From 97e4c2dfd6504405cc21457a2c717435f56d46d3 Mon Sep 17 00:00:00 2001 From: hmacr Date: Thu, 6 Mar 2025 01:10:56 +0530 Subject: [PATCH] exchange code for access_token and persist --- plugins/notion/server/api/notion.ts | 102 +++++++++++++++++++++++++++ plugins/notion/server/api/schema.ts | 17 +++++ plugins/notion/server/index.ts | 16 +++++ plugins/notion/server/oauth.ts | 40 +++++++++++ plugins/notion/shared/NotionUtils.ts | 15 ++-- shared/types.ts | 3 + 6 files changed, 189 insertions(+), 4 deletions(-) create mode 100644 plugins/notion/server/api/notion.ts create mode 100644 plugins/notion/server/api/schema.ts create mode 100644 plugins/notion/server/index.ts create mode 100644 plugins/notion/server/oauth.ts diff --git a/plugins/notion/server/api/notion.ts b/plugins/notion/server/api/notion.ts new file mode 100644 index 0000000000..7239a925d4 --- /dev/null +++ b/plugins/notion/server/api/notion.ts @@ -0,0 +1,102 @@ +import Router from "koa-router"; +import { IntegrationService, IntegrationType } from "@shared/types"; +import { parseDomain } from "@shared/utils/domains"; +import Logger from "@server/logging/Logger"; +import auth from "@server/middlewares/authentication"; +import { transaction } from "@server/middlewares/transaction"; +import validate from "@server/middlewares/validate"; +import { Integration, IntegrationAuthentication, Team } from "@server/models"; +import { APIContext } from "@server/types"; +import { NotionOAuth } from "../oauth"; +import * as T from "./schema"; +import { NotionUtils } from "plugins/notion/shared/NotionUtils"; + +const router = new Router(); + +router.get( + "notion.callback", + auth({ optional: true }), + validate(T.NotionCallbackSchema), + transaction(), + async (ctx: APIContext) => { + const { code, state, error } = ctx.input.query; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + if (error) { + ctx.redirect(NotionUtils.errorUrl(error)); + return; + } + + let parsedState; + try { + parsedState = NotionUtils.parseState(state); + } catch { + ctx.redirect(NotionUtils.errorUrl("invalid_state")); + return; + } + + const { teamId } = parsedState; + + // This code block accounts for the root domain being unable to access authentication for subdomains. + // We must forward to the appropriate subdomain to complete the oauth flow + if (!user) { + if (teamId) { + try { + const team = await Team.findByPk(teamId, { + rejectOnEmpty: true, + transaction, + }); + + return parseDomain(ctx.host).teamSubdomain === team.subdomain + ? ctx.redirect("/") + : ctx.redirectOnClient( + NotionUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }) + ); + } catch (err) { + Logger.error(`Error fetching team for teamId: ${teamId}!`, err); + return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); + } + } else { + return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); + } + } + + // validation middleware ensures that code is non-null at this point. + const data = await NotionOAuth.oauthAccess(code!); + + const authentication = await IntegrationAuthentication.create( + { + service: IntegrationService.Notion, + userId: user.id, + teamId: user.teamId, + token: data.access_token, + }, + { transaction } + ); + await Integration.create( + { + service: IntegrationService.Notion, + type: IntegrationType.Import, + userId: user.id, + teamId: user.teamId, + authenticationId: authentication.id, + settings: { + externalWorkspace: { + id: data.workspace_id, + name: data.workspace_name ?? undefined, + iconUrl: data.workspace_icon ?? undefined, + }, + }, + }, + { transaction } + ); + + ctx.redirect(NotionUtils.settingsUrl); + } +); + +export default router; diff --git a/plugins/notion/server/api/schema.ts b/plugins/notion/server/api/schema.ts new file mode 100644 index 0000000000..f6eabc2a4e --- /dev/null +++ b/plugins/notion/server/api/schema.ts @@ -0,0 +1,17 @@ +import isEmpty from "lodash/isEmpty"; +import { z } from "zod"; +import { BaseSchema } from "@server/routes/api/schema"; + +export const NotionCallbackSchema = BaseSchema.extend({ + query: z + .object({ + code: z.string().nullish(), + state: z.string(), + error: z.string().nullish(), + }) + .refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), { + message: "one of code or error is required", + }), +}); + +export type NotionCallbackReq = z.infer; diff --git a/plugins/notion/server/index.ts b/plugins/notion/server/index.ts new file mode 100644 index 0000000000..5f56c19b8e --- /dev/null +++ b/plugins/notion/server/index.ts @@ -0,0 +1,16 @@ +import { Hook, PluginManager } from "@server/utils/PluginManager"; +import config from "../plugin.json"; +import router from "./api/notion"; +import env from "./env"; + +const enabled = !!env.NOTION_CLIENT_ID && !!env.NOTION_CLIENT_SECRET; + +if (enabled) { + PluginManager.add([ + { + ...config, + type: Hook.API, + value: router, + }, + ]); +} diff --git a/plugins/notion/server/oauth.ts b/plugins/notion/server/oauth.ts new file mode 100644 index 0000000000..3dcfa0da45 --- /dev/null +++ b/plugins/notion/server/oauth.ts @@ -0,0 +1,40 @@ +import { z } from "zod"; +import fetch from "@server/utils/fetch"; +import { NotionUtils } from "../shared/NotionUtils"; +import env from "./env"; + +export class NotionOAuth { + private static tokenUrl = "https://api.notion.com/v1/oauth/token"; + private static credentials = Buffer.from( + `${env.NOTION_CLIENT_ID}:${env.NOTION_CLIENT_SECRET}` + ).toString("base64"); + + private static resSchema = z.object({ + access_token: z.string(), + bot_id: z.string(), + workspace_id: z.string(), + workspace_name: z.string().nullish(), + workspace_icon: z.string().url().nullish(), + }); + + static async oauthAccess(code: string) { + const headers = { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Basic ${this.credentials}`, + }; + const body = { + grant_type: "authorization_code", + code, + redirect_uri: NotionUtils.callbackUrl(), + }; + + const res = await fetch(this.tokenUrl, { + method: "POST", + headers, + body: JSON.stringify(body), + }); + + return this.resSchema.parse(await res.json()); + } +} diff --git a/plugins/notion/shared/NotionUtils.ts b/plugins/notion/shared/NotionUtils.ts index 81755e2420..58c8f57f31 100644 --- a/plugins/notion/shared/NotionUtils.ts +++ b/plugins/notion/shared/NotionUtils.ts @@ -1,20 +1,27 @@ import queryString from "query-string"; import env from "@shared/env"; +import { settingsPath } from "@shared/utils/routeHelpers"; export type OAuthState = { teamId: string; }; export class NotionUtils { - // private static clientId = "eda3ac5b-39fa-4d79-a99d-b70bc5ded123"; - private static clientId = env.NOTION_CLIENT_ID; - private static clientSecret = env.NOTION_CLIENT_SECRET; private static authBaseUrl = "https://api.notion.com/v1/oauth/authorize"; + static settingsUrl = settingsPath("import"); static parseState(state: string): OAuthState { return JSON.parse(state); } + static errorUrl(error: string) { + const params = { + type: "notion", + error, + }; + return `${this.settingsUrl}?${queryString.stringify(params)}`; + } + static callbackUrl( { baseUrl, params }: { baseUrl: string; params?: string } = { // baseUrl: `${env.URL}`, @@ -29,7 +36,7 @@ export class NotionUtils { static authUrl({ state }: { state: OAuthState }) { const params = { - client_id: this.clientId, + client_id: env.NOTION_CLIENT_ID, redirect_uri: this.callbackUrl(), state: JSON.stringify(state), response_type: "code", diff --git a/shared/types.ts b/shared/types.ts index dc45116750..431639ebad 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -86,6 +86,7 @@ export enum IntegrationType { Analytics = "analytics", /** An integration that maps an Outline user to an external service. */ LinkedAccount = "linkedAccount", + Import = "import", } export enum IntegrationService { @@ -96,6 +97,7 @@ export enum IntegrationService { Matomo = "matomo", Umami = "umami", GitHub = "github", + Notion = "notion", } export type UserCreatableIntegrationService = Extract< @@ -157,6 +159,7 @@ export type IntegrationSettings = T extends IntegrationType.Embed | { serviceTeamId: string } | { measurementId: string } | { slack: { serviceTeamId: string; serviceUserId: string } } + | { externalWorkspace: { id: string; name?: string; iconUrl?: string } } | undefined; export enum UserPreference {