refactor: simplified Deno KV OAuth plugin (#1808)
This commit is contained in:
+95
-190
@@ -1,206 +1,111 @@
|
||||
import { handleCallback, signIn, signOut } from "./kv_oauth/plugin_deps.ts";
|
||||
import { OAuth2Client } from "./kv_oauth/plugin_deps.ts";
|
||||
import type { Plugin } from "../server.ts";
|
||||
import {
|
||||
createAuth0OAuthConfig,
|
||||
createDiscordOAuthConfig,
|
||||
createDropboxOAuthConfig,
|
||||
createFacebookOAuthConfig,
|
||||
createGitHubOAuthConfig,
|
||||
createGitLabOAuthConfig,
|
||||
createGoogleOAuthConfig,
|
||||
createNotionOAuthConfig,
|
||||
createOktaOAuthConfig,
|
||||
createPatreonOAuthConfig,
|
||||
createSlackOAuthConfig,
|
||||
createSpotifyOAuthConfig,
|
||||
createTwitterOAuthConfig,
|
||||
handleCallback,
|
||||
signIn,
|
||||
signOut,
|
||||
} from "https://deno.land/x/deno_kv_oauth@v0.7.0/mod.ts";
|
||||
import type { OAuth2ClientConfig } from "https://deno.land/x/oauth2_client@v1.0.2/mod.ts";
|
||||
import { Handler } from "$fresh/server.ts";
|
||||
|
||||
export {
|
||||
createAuth0OAuthConfig,
|
||||
createDiscordOAuthConfig,
|
||||
createDropboxOAuthConfig,
|
||||
createFacebookOAuthConfig,
|
||||
createGitHubOAuthConfig,
|
||||
createGitLabOAuthConfig,
|
||||
createGoogleOAuthConfig,
|
||||
createNotionOAuthConfig,
|
||||
createOktaOAuthConfig,
|
||||
createPatreonOAuthConfig,
|
||||
createSlackOAuthConfig,
|
||||
createSpotifyOAuthConfig,
|
||||
createTwitterOAuthConfig,
|
||||
};
|
||||
|
||||
/**
|
||||
* This is a helper type to infer the routes created by the `kvOAuthPlugin` function.
|
||||
* Creates the following routes, based on Deno KV OAuth's request handlers:
|
||||
* - `GET <oauthPath>/signin` for the sign-in page
|
||||
* - `GET <oauthPath>/callback` for the callback page
|
||||
* - `GET <oauthPath>/signout` for the sign-out page
|
||||
*
|
||||
* Use a KV OAuth plugin instance to infer the routes paths.
|
||||
*
|
||||
* @example
|
||||
* @example Single provider
|
||||
* ```ts
|
||||
* // main.ts
|
||||
* import { start } from "$fresh/server.ts";
|
||||
* import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
|
||||
* import { kvOAuthPlugin } from "https://deno.land/x/deno_kv_oauth@$VERSION/fresh.ts";
|
||||
* import { createRoutes, createGitHubOAuthConfig } from "$fresh/plugins/kv_oauth.ts";
|
||||
* import manifest from "./fresh.gen.ts";
|
||||
*
|
||||
* const kvOAuth = kvOAuthPlugin({
|
||||
* github: createGitHubOAuth2Client(),
|
||||
* await start(manifest, {
|
||||
* plugins: [{
|
||||
* name: "kv-oauth",
|
||||
* routes: createRoutes(createGitHubOAuthConfig())
|
||||
* }]
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* export type KVOAuthRoutes = InferOAuthProviders<typeof kvOAuth>;
|
||||
* // ^? type Foo = "/oauth/github/signin" | "/oauth/github/callback" | "/oauth/github/signout"
|
||||
* @example Multiple providers
|
||||
* ```ts
|
||||
* // main.ts
|
||||
* import { start } from "$fresh/server.ts";
|
||||
* import {
|
||||
* createRoutes,
|
||||
* createGitHubOAuthConfig,
|
||||
* createGoogleOAuthConfig,
|
||||
* } from "$fresh/plugins/kv_oauth.ts";
|
||||
* import manifest from "./fresh.gen.ts";
|
||||
*
|
||||
* await start(manifest, {
|
||||
* plugins: [kvOAuth],
|
||||
* plugins: [{
|
||||
* name: "kv-oauth-github",
|
||||
* routes: createRoutes(createGitHubOAuthConfig(), "/oauth/github"),
|
||||
* }, {
|
||||
* name: "kv-oauth-google",
|
||||
* routes: createRoutes(createGoogleOAuthConfig(), "/oauth/google"),
|
||||
* }]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export type InferOAuthProviders<T, U = T extends Plugin<infer U> ? U : never> =
|
||||
{
|
||||
[K in keyof U]: K extends string ?
|
||||
| `/oauth/${K}/signin`
|
||||
| `/oauth/${K}/callback`
|
||||
| `/oauth/${K}/signout`
|
||||
: never;
|
||||
}[keyof U];
|
||||
|
||||
export interface KvOAuthPluginOptions {
|
||||
/**
|
||||
* Sign-in page path
|
||||
*
|
||||
* @default {"/oauth/signin"}
|
||||
*/
|
||||
signInPath?: string;
|
||||
/**
|
||||
* Callback page path
|
||||
*
|
||||
* @default {"/oauth/callback"}
|
||||
*/
|
||||
callbackPath?: string;
|
||||
/**
|
||||
* Sign-out page path
|
||||
*
|
||||
* @default {"/oauth/signout"}
|
||||
*/
|
||||
signOutPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* This creates handlers for the following routes:
|
||||
* - `GET /oauth/signin` for the sign-in page
|
||||
* - `GET /oauth/callback` for the callback page
|
||||
* - `GET /oauth/signout` for the sign-out page
|
||||
*
|
||||
* ```ts
|
||||
* // main.ts
|
||||
* import { start } from "$fresh/server.ts";
|
||||
* import kvOAuthPlugin from "$fresh/plugins/kv_oauth.ts";
|
||||
* import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
|
||||
* import manifest from "./fresh.gen.ts";
|
||||
*
|
||||
* await start(manifest, {
|
||||
* plugins: [
|
||||
* kvOAuthPlugin(createGitHubOAuth2Client())
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function kvOAuthPlugin(
|
||||
oauth2Client: OAuth2Client,
|
||||
options?: KvOAuthPluginOptions,
|
||||
): Plugin;
|
||||
|
||||
/**
|
||||
* This creates handlers for the following routes:
|
||||
* - `GET /oauth/[PROVIDER_SLUG]/signin` for the sign-in page
|
||||
* - `GET /oauth/[PROVIDER_SLUG]/callback` for the callback page
|
||||
* - `GET /oauth/[PROVIDER_SLUG]/signout` for the sign-out page
|
||||
*
|
||||
* ```ts
|
||||
* // main.ts
|
||||
* import { start } from "$fresh/server.ts";
|
||||
* import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
|
||||
* import { kvOAuthPlugin } from "https://deno.land/x/deno_kv_oauth@$VERSION/fresh.ts";
|
||||
* import manifest from "./fresh.gen.ts";
|
||||
*
|
||||
* await start(manifest, {
|
||||
* plugins: [
|
||||
* kvOAuthPlugin({
|
||||
* github: createGitHubOAuth2Client(),
|
||||
* })
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function kvOAuthPlugin<
|
||||
const TProviders extends Record<string, OAuth2Client>,
|
||||
>(providers: TProviders): Plugin<TProviders>;
|
||||
|
||||
/**
|
||||
* This creates handlers for the following routes:
|
||||
* - `GET /oauth/signin` for the sign-in page
|
||||
* - `GET /oauth/callback` for the callback page
|
||||
* - `GET /oauth/signout` for the sign-out page
|
||||
*
|
||||
* ```ts
|
||||
* // main.ts
|
||||
* import { start } from "$fresh/server.ts";
|
||||
* import kvOAuthPlugin from "$fresh/plugins/kv_oauth.ts";
|
||||
* import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
|
||||
* import manifest from "./fresh.gen.ts";
|
||||
*
|
||||
* await start(manifest, {
|
||||
* plugins: [
|
||||
* kvOAuthPlugin(createGitHubOAuth2Client())
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export default function kvOAuthPlugin<
|
||||
const TProviders extends Record<string, OAuth2Client>,
|
||||
>(
|
||||
...args: [
|
||||
oauth2Client: OAuth2Client,
|
||||
options?: KvOAuthPluginOptions,
|
||||
] | [
|
||||
providers: TProviders,
|
||||
]
|
||||
): Plugin<Record<keyof TProviders, unknown>> {
|
||||
const routes: Plugin["routes"] = [];
|
||||
|
||||
if (args.length >= 3 || args.length <= 0) {
|
||||
throw new Error(
|
||||
`Unable to initialise kv-oauth plugin with. Expected 1-2 arguments, got ${args.length}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const [providersOrOAuth2Client] = args;
|
||||
|
||||
if (providersOrOAuth2Client instanceof OAuth2Client) {
|
||||
const [_, options] = args;
|
||||
routes.push(
|
||||
{
|
||||
path: options?.signInPath ?? "/oauth/signin",
|
||||
handler: async (req) => await signIn(req, providersOrOAuth2Client),
|
||||
},
|
||||
{
|
||||
path: options?.callbackPath ?? "/oauth/callback",
|
||||
handler: async (req) => {
|
||||
// Return object also includes `accessToken` and `sessionId` properties.
|
||||
const { response } = await handleCallback(
|
||||
req,
|
||||
providersOrOAuth2Client,
|
||||
);
|
||||
return response;
|
||||
},
|
||||
},
|
||||
{
|
||||
path: options?.signOutPath ?? "/oauth/signout",
|
||||
handler: signOut,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
Object.entries(providersOrOAuth2Client).forEach((
|
||||
[providerName, oauth2Client],
|
||||
) =>
|
||||
routes.push(
|
||||
{
|
||||
path: `/oauth/${providerName}/signin`,
|
||||
handler: async (req) => await signIn(req, oauth2Client),
|
||||
},
|
||||
{
|
||||
path: `/oauth/${providerName}/callback`,
|
||||
handler: async (req) => {
|
||||
// Return object also includes `accessToken` and `sessionId` properties.
|
||||
const { response } = await handleCallback(
|
||||
req,
|
||||
oauth2Client,
|
||||
);
|
||||
return response;
|
||||
},
|
||||
},
|
||||
{
|
||||
path: `/oauth/${providerName}/signout`,
|
||||
handler: signOut,
|
||||
},
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
name: "kv-oauth",
|
||||
routes,
|
||||
};
|
||||
export function createRoutes<T extends string = "/oauth">(
|
||||
oauthConfig: OAuth2ClientConfig,
|
||||
/** Parent path for sign-in, callback and sign-out pages. */
|
||||
oauthPath = "/oauth" as T,
|
||||
): [
|
||||
{ path: `${T}/signin`; handler: Handler },
|
||||
{ path: `${T}/callback`; handler: Handler },
|
||||
{ path: `${T}/signout`; handler: Handler },
|
||||
] {
|
||||
return [
|
||||
{
|
||||
path: `${oauthPath}/signin`,
|
||||
handler: async (req) => await signIn(req, oauthConfig),
|
||||
},
|
||||
{
|
||||
path: `${oauthPath}/callback`,
|
||||
handler: async (req) => {
|
||||
// Return object also includes `accessToken` and `sessionId` properties.
|
||||
const { response } = await handleCallback(
|
||||
req,
|
||||
oauthConfig,
|
||||
);
|
||||
return response;
|
||||
},
|
||||
},
|
||||
{
|
||||
path: `${oauthPath}/signout`,
|
||||
handler: signOut,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
export {
|
||||
handleCallback,
|
||||
signIn,
|
||||
signOut,
|
||||
} from "https://deno.land/x/deno_kv_oauth@v0.6.1/mod.ts";
|
||||
export { OAuth2Client } from "https://deno.land/x/oauth2_client@v1.0.2/mod.ts";
|
||||
@@ -1,71 +0,0 @@
|
||||
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
|
||||
import {
|
||||
assert,
|
||||
assertArrayIncludes,
|
||||
assertNotEquals,
|
||||
} from "$std/testing/asserts.ts";
|
||||
import { colors } from "$fresh/src/server/deps.ts";
|
||||
|
||||
// @ts-ignore openKv is only available with --unstable
|
||||
const hasKVEnabled = typeof Deno.openKv === "function";
|
||||
if (!hasKVEnabled) {
|
||||
console.log(
|
||||
colors.yellow(`Skipping Deno KV tests. Pass "--unstable" to run them.`),
|
||||
);
|
||||
}
|
||||
|
||||
Deno.test(
|
||||
{
|
||||
name: "kvOAuthPlugin() works correctly",
|
||||
ignore: !hasKVEnabled,
|
||||
sanitizeResources: false,
|
||||
fn: async (test) => {
|
||||
const { oauth2Client } = await import("./plugin_test_utils.ts");
|
||||
const kvOAuthPlugin =
|
||||
(await import("$fresh/plugins/kv_oauth.ts")).default;
|
||||
|
||||
await test.step("with default values", () => {
|
||||
const plugin = kvOAuthPlugin(oauth2Client);
|
||||
assertNotEquals(plugin.routes, undefined);
|
||||
assert(plugin.routes!.every((route) => route.handler !== undefined));
|
||||
assertArrayIncludes(plugin.routes!.map((route) => route.path), [
|
||||
"/oauth/signin",
|
||||
"/oauth/callback",
|
||||
"/oauth/signout",
|
||||
]);
|
||||
});
|
||||
|
||||
await test.step("with defined values", () => {
|
||||
const signInPath = "/signin";
|
||||
const callbackPath = "/callback";
|
||||
const signOutPath = "/signout";
|
||||
const plugin = kvOAuthPlugin(oauth2Client, {
|
||||
signInPath,
|
||||
callbackPath,
|
||||
signOutPath,
|
||||
});
|
||||
assertNotEquals(plugin.routes, undefined);
|
||||
assert(plugin.routes!.every((route) => route.handler !== undefined));
|
||||
assertArrayIncludes(plugin.routes!.map((route) => route.path), [
|
||||
signInPath,
|
||||
callbackPath,
|
||||
signOutPath,
|
||||
]);
|
||||
});
|
||||
|
||||
await test.step("with mapped providers", () => {
|
||||
const providerKey = "customProvider";
|
||||
const plugin = kvOAuthPlugin({
|
||||
[providerKey]: oauth2Client,
|
||||
});
|
||||
assertNotEquals(plugin.routes, undefined);
|
||||
assert(plugin.routes!.every((route) => route.handler !== undefined));
|
||||
assertArrayIncludes(plugin.routes!.map((route) => route.path), [
|
||||
`/oauth/${providerKey}/signin`,
|
||||
`/oauth/${providerKey}/callback`,
|
||||
`/oauth/${providerKey}/signout`,
|
||||
]);
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -1,2 +0,0 @@
|
||||
export type { Tokens } from "https://deno.land/x/oauth2_client@v1.0.2/mod.ts";
|
||||
export type { OAuthSession } from "https://deno.land/x/deno_kv_oauth@v0.6.1/src/core.ts";
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
|
||||
import { OAuth2Client } from "./plugin_deps.ts";
|
||||
import type { OAuthSession, Tokens } from "./plugin_test_deps.ts";
|
||||
|
||||
// Dummy OAuth 2.0 client for testing only.
|
||||
export const oauth2Client = new OAuth2Client({
|
||||
clientId: crypto.randomUUID(),
|
||||
clientSecret: crypto.randomUUID(),
|
||||
authorizationEndpointUri: "https://example.com/authorize",
|
||||
tokenUri: "https://example.com/token",
|
||||
});
|
||||
|
||||
export function genOAuthSession(): OAuthSession {
|
||||
return {
|
||||
state: crypto.randomUUID(),
|
||||
codeVerifier: crypto.randomUUID(),
|
||||
};
|
||||
}
|
||||
|
||||
export function genTokens(): Tokens {
|
||||
return {
|
||||
accessToken: crypto.randomUUID(),
|
||||
tokenType: crypto.randomUUID(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
|
||||
import { assertArrayIncludes } from "$std/testing/asserts.ts";
|
||||
import { colors } from "$fresh/src/server/deps.ts";
|
||||
import { createRoutes } from "$fresh/plugins/kv_oauth.ts";
|
||||
|
||||
function randomOAuthConfig() {
|
||||
return {
|
||||
clientId: crypto.randomUUID(),
|
||||
clientSecret: crypto.randomUUID(),
|
||||
authorizationEndpointUri: `http://${crypto.randomUUID()}.com/authorize`,
|
||||
tokenUri: `http://${crypto.randomUUID()}.com/token`,
|
||||
};
|
||||
}
|
||||
|
||||
// @ts-ignore openKv is only available with --unstable
|
||||
const isKvEnabled = typeof Deno.openKv === "function";
|
||||
if (!isKvEnabled) {
|
||||
console.log(
|
||||
colors.yellow(`Skipping Deno KV tests. Pass "--unstable" to run them.`),
|
||||
);
|
||||
}
|
||||
|
||||
Deno.test({
|
||||
name: "createRoutes() has all handlers defined with default OAuth path",
|
||||
ignore: !isKvEnabled,
|
||||
fn: () => {
|
||||
const routes = createRoutes(randomOAuthConfig());
|
||||
assertArrayIncludes(routes.map((route) => route.path), [
|
||||
"/oauth/signin",
|
||||
"/oauth/callback",
|
||||
"/oauth/signout",
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "createRoutes() has all handlers defined with set OAuth path",
|
||||
ignore: !isKvEnabled,
|
||||
fn: () => {
|
||||
const oauthPath = "/" + crypto.randomUUID();
|
||||
const routes = createRoutes(randomOAuthConfig(), oauthPath);
|
||||
assertArrayIncludes(routes.map((route) => route.path), [
|
||||
oauthPath + "/signin",
|
||||
oauthPath + "/callback",
|
||||
oauthPath + "/signout",
|
||||
]);
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user