From fa6b83382b1fa89dd33dbb8f86f8a1cc4a0e4cc3 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 1 Apr 2025 22:13:26 -0400 Subject: [PATCH] Add interface --- plugins/oauth/server/index.ts | 5 + plugins/oauth/server/interface.ts | 195 ++++++++++++++++++ .../server/models/OAuthAuthentication.ts | 56 +++-- .../server/models/OAuthAuthorizationCode.ts | 42 +++- plugins/oauth/server/oauth.ts | 27 +++ server/routes/index.ts | 6 + server/utils/PluginManager.ts | 6 +- 7 files changed, 309 insertions(+), 28 deletions(-) create mode 100644 plugins/oauth/server/interface.ts diff --git a/plugins/oauth/server/index.ts b/plugins/oauth/server/index.ts index f0e3ff9b46..0a0ba71e20 100644 --- a/plugins/oauth/server/index.ts +++ b/plugins/oauth/server/index.ts @@ -2,6 +2,7 @@ import { PluginManager, Hook } from "@server/utils/PluginManager"; import OAuthAuthentication from "./models/OAuthAuthentication"; import OAuthAuthorizationCode from "./models/OAuthAuthorizationCode"; import OAuthClient from "./models/OAuthClient"; +import oauth from "./oauth"; PluginManager.add([ { @@ -16,4 +17,8 @@ PluginManager.add([ type: Hook.Model, value: OAuthAuthorizationCode, }, + { + type: Hook.Route, + value: oauth, + }, ]); diff --git a/plugins/oauth/server/interface.ts b/plugins/oauth/server/interface.ts new file mode 100644 index 0000000000..72deaf0e11 --- /dev/null +++ b/plugins/oauth/server/interface.ts @@ -0,0 +1,195 @@ +import { + RefreshTokenModel, + AuthorizationCodeModel, +} from "@node-oauth/oauth2-server"; +import rs from "randomstring"; +import { WhereOptions } from "sequelize"; +import OAuthAuthentication from "./models/OAuthAuthentication"; +import OAuthAuthorizationCode from "./models/OAuthAuthorizationCode"; +import OAuthClient from "./models/OAuthClient"; + +interface Config { + accessTokenPrefix: string; + refreshTokenPrefix: string; + clientSecretPrefix: string; + authorizationCodePrefix: string; + grants: string[]; +} + +export const OAuthInterface: RefreshTokenModel & + AuthorizationCodeModel & + Config = { + accessTokenPrefix: "ol_at_", + refreshTokenPrefix: "ol_rt_", + clientSecretPrefix: "ol_sk_", + authorizationCodePrefix: "ol_ac_", + grants: ["authorization_code", "refresh_token"], + + async generateAccessToken() { + return `${this.accessTokenPrefix}${rs.generate(32)}`; + }, + + async generateRefreshToken() { + return `${this.refreshTokenPrefix}${rs.generate(32)}`; + }, + + async generateAuthorizationCode() { + return `${this.authorizationCodePrefix}${rs.generate(32)}`; + }, + + async getAccessToken(accessToken: string) { + const authentication = await OAuthAuthentication.findByAccessToken( + accessToken + ); + + return { + accessToken, + accessTokenExpiresAt: authentication.accessTokenExpiresAt, + scope: authentication.scope, + client: { + id: authentication.oauthClientId, + grants: this.grants, + }, + user: authentication.user, + }; + }, + + async getRefreshToken(refreshToken: string) { + const authentication = await OAuthAuthentication.findByRefreshToken( + refreshToken + ); + + return { + refreshToken, + refreshTokenExpiresAt: authentication.refreshTokenExpiresAt, + scope: authentication.scope, + client: { + id: authentication.oauthClientId, + grants: this.grants, + }, + user: authentication.user, + }; + }, + + async getAuthorizationCode(authorizationCode: string) { + const code = await OAuthAuthorizationCode.findByCode(authorizationCode); + + return { + authorizationCode, + expiresAt: code.expiresAt, + scope: code.scope, + redirectUri: code.redirectUri, + client: { + id: code.oauthClientId, + grants: this.grants, + }, + user: code.user, + }; + }, + + async getClient(clientId: string, clientSecret: string) { + const where: WhereOptions = { + clientId, + }; + if (clientSecret) { + where.clientSecret = clientSecret; + } + const client = await OAuthClient.findOne({ + where, + }); + if (!client) { + return null; + } + + return { + id: client.clientId, + redirectUris: client.redirectUris, + databaseId: client.id, + grants: this.grants, + }; + }, + + async saveToken(token, client, user) { + const accessToken = token.accessToken; + const refreshToken = token.refreshToken; + const accessTokenExpiresAt = token.accessTokenExpiresAt; + const refreshTokenExpiresAt = token.refreshTokenExpiresAt; + + const authentication = await OAuthAuthentication.create({ + accessToken, + refreshToken, + accessTokenExpiresAt, + refreshTokenExpiresAt, + scope: token.scope, + oauthClientId: client.databaseId, + userId: user.id, + }); + + return { + accessToken, + accessTokenExpiresAt, + refreshToken, + refreshTokenExpiresAt, + scope: token.scope, + client: { + id: client.databaseId, + grants: this.grants, + }, + user: authentication.user, + }; + }, + + async saveAuthorizationCode(code, client, user) { + const authorizationCode = code.authorizationCode; + const expiresAt = code.expiresAt; + const redirectUri = code.redirectUri; + + const authCode = await OAuthAuthorizationCode.create({ + authorizationCodeHash: OAuthAuthorizationCode.hash(authorizationCode), + expiresAt, + scope: code.scope, + redirectUri, + oauthClientId: client.databaseId, + userId: user.id, + }); + + return { + authorizationCode, + expiresAt, + scope: code.scope, + redirectUri, + client: { + id: client.databaseId, + grants: this.grants, + }, + user: authCode.user, + }; + }, + + async revokeToken(token) { + const auth = await OAuthAuthentication.findByRefreshToken( + token.refreshToken + ); + if (auth) { + await auth.destroy(); + return true; + } + return false; + }, + + async revokeAuthorizationCode(code) { + const authCode = await OAuthAuthorizationCode.findByCode( + code.authorizationCode + ); + if (authCode) { + await authCode.destroy(); + return true; + } + return false; + }, + + async validateRedirectUri() { + // TODO + return true; + }, +}; diff --git a/plugins/oauth/server/models/OAuthAuthentication.ts b/plugins/oauth/server/models/OAuthAuthentication.ts index 82af137f68..bb696fec60 100644 --- a/plugins/oauth/server/models/OAuthAuthentication.ts +++ b/plugins/oauth/server/models/OAuthAuthentication.ts @@ -1,7 +1,10 @@ import crypto from "crypto"; +import User from "@server/models/User"; +import ParanoidModel from "@server/models/base/ParanoidModel"; +import { SkipChangeset } from "@server/models/decorators/Changeset"; +import Fix from "@server/models/decorators/Fix"; import { Matches } from "class-validator"; -import { addDays, addHours, subMinutes } from "date-fns"; -import rs from "randomstring"; +import { subMinutes } from "date-fns"; import { InferAttributes, InferCreationAttributes } from "sequelize"; import { Column, @@ -13,10 +16,6 @@ import { IsDate, Unique, } from "sequelize-typescript"; -import User from "@server/models/User"; -import ParanoidModel from "@server/models/base/ParanoidModel"; -import { SkipChangeset } from "@server/models/decorators/Changeset"; -import Fix from "@server/models/decorators/Fix"; import OAuthClient from "./OAuthClient"; @Table({ @@ -101,19 +100,6 @@ class OAuthAuthentication extends ParanoidModel< // hooks - @BeforeCreate - static async generateTokens(model: OAuthAuthentication) { - const accessToken = `${this.accessTokenPrefix}${rs.generate(32)}`; - model.accessToken = accessToken; - model.accessTokenHash = this.hash(accessToken); - model.accessTokenExpiresAt = addHours(new Date(), 1); - - const refreshToken = `${this.refreshTokenPrefix}${rs.generate(32)}`; - model.refreshToken = refreshToken; - model.refreshTokenHash = this.hash(refreshToken); - model.refreshTokenExpiresAt = addDays(new Date(), 30); - } - @BeforeCreate static async setLastActiveAt(model: OAuthAuthentication) { model.lastActiveAt = new Date(); @@ -132,9 +118,9 @@ class OAuthAuthentication extends ParanoidModel< } /** - * Finds an OAuthAuthentication by the given input string. + * Finds an OAuthAuthentication by the given access token. * - * @param input The input string to search for + * @param input The access token to search for * @returns The OAuthAuthentication if found */ public static findByAccessToken(input: string) { @@ -142,6 +128,34 @@ class OAuthAuthentication extends ParanoidModel< where: { accessTokenHash: this.hash(input), }, + include: [ + { + association: "user", + required: true, + }, + ], + rejectOnEmpty: true, + }); + } + + /** + * Finds an OAuthAuthentication by the given refresh token. + * + * @param input The refresh token to search for + * @returns The OAuthAuthentication if found + */ + public static findByRefreshToken(input: string) { + return this.findOne({ + where: { + refreshTokenHash: this.hash(input), + }, + include: [ + { + association: "user", + required: true, + }, + ], + rejectOnEmpty: true, }); } } diff --git a/plugins/oauth/server/models/OAuthAuthorizationCode.ts b/plugins/oauth/server/models/OAuthAuthorizationCode.ts index ced8f52d05..a8b5e9c994 100644 --- a/plugins/oauth/server/models/OAuthAuthorizationCode.ts +++ b/plugins/oauth/server/models/OAuthAuthorizationCode.ts @@ -1,3 +1,9 @@ +import crypto from "crypto"; +import User from "@server/models/User"; +import IdModel from "@server/models/base/IdModel"; +import { SkipChangeset } from "@server/models/decorators/Changeset"; +import Fix from "@server/models/decorators/Fix"; +import { OAuthClientValidation } from "@shared/validations"; import { Matches } from "class-validator"; import { InferAttributes, InferCreationAttributes } from "sequelize"; import { @@ -8,11 +14,6 @@ import { Table, Length, } from "sequelize-typescript"; -import { OAuthClientValidation } from "@shared/validations"; -import User from "@server/models/User"; -import IdModel from "@server/models/base/IdModel"; -import { SkipChangeset } from "@server/models/decorators/Changeset"; -import Fix from "@server/models/decorators/Fix"; import OAuthClient from "./OAuthClient"; @Table({ @@ -58,6 +59,37 @@ class OAuthAuthorizationCode extends IdModel< @ForeignKey(() => User) @Column(DataType.UUID) userId: string; + + /** + * Generates a hashed token for the given input. + * + * @param key The input string to hash + * @returns The hashed input + */ + public static hash(key: string) { + return crypto.createHash("sha256").update(key).digest("hex"); + } + + /** + * Finds an OAuthAuthorizationCode by the given code. + * + * @param input The code to search for + * @returns The OAuthAuthentication if found + */ + public static findByCode(input: string) { + return this.findOne({ + where: { + authorizationCodeHash: this.hash(input), + }, + include: [ + { + association: "user", + required: true, + }, + ], + rejectOnEmpty: true, + }); + } } export default OAuthAuthorizationCode; diff --git a/plugins/oauth/server/oauth.ts b/plugins/oauth/server/oauth.ts index e69de29bb2..19eb554e90 100644 --- a/plugins/oauth/server/oauth.ts +++ b/plugins/oauth/server/oauth.ts @@ -0,0 +1,27 @@ +import OAuth2Server from "@node-oauth/oauth2-server"; +import Router from "koa-router"; +import { OAuthInterface } from "./interface"; + +const router = new Router(); + +const oauth = new OAuth2Server({ + model: OAuthInterface, +}); + +router.get("/oauth/authorize", async (ctx) => { + const request = new OAuth2Server.Request(ctx.request); + const response = new OAuth2Server.Response(ctx.response); + + const authorizationCode = await oauth.authorize(request, response); + ctx.body = { code: authorizationCode }; +}); + +router.post("/oauth/token", async (ctx) => { + const request = new OAuth2Server.Request(ctx.request); + const response = new OAuth2Server.Response(ctx.response); + + const token = await oauth.token(request, response); + ctx.body = { token }; +}); + +export default router; diff --git a/server/routes/index.ts b/server/routes/index.ts index 5273ae81db..3bf7eab2c8 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -13,6 +13,7 @@ import env from "@server/env"; import { NotFoundError } from "@server/errors"; import shareDomains from "@server/middlewares/shareDomains"; import { Integration } from "@server/models"; +import { Hook, PluginManager } from "@server/utils/PluginManager"; import { opensearchResponse } from "@server/utils/opensearch"; import { getTeamFromContext } from "@server/utils/passport"; import { robotsResponse } from "@server/utils/robots"; @@ -26,6 +27,11 @@ const router = new Router(); koa.use(userAgent); +// Register routes before others to allow for overrides +PluginManager.getHooks(Hook.Route).forEach((hook) => + router.use("/", hook.value.routes()) +); + // serve public assets router.use(["/images/*", "/email/*", "/fonts/*"], async (ctx, next) => { let done; diff --git a/server/utils/PluginManager.ts b/server/utils/PluginManager.ts index 67e29ed52c..515ae8a82e 100644 --- a/server/utils/PluginManager.ts +++ b/server/utils/PluginManager.ts @@ -6,7 +6,7 @@ import sortBy from "lodash/sortBy"; import type BaseEmail from "@server/emails/templates/BaseEmail"; import env from "@server/env"; import Logger from "@server/logging/Logger"; -import Model from "@server/models/base/Model"; +import BaseModel from "@server/models/base/Model"; import type BaseProcessor from "@server/queues/processors/BaseProcessor"; import type BaseTask from "@server/queues/tasks/BaseTask"; import { UnfurlSignature, UninstallSignature } from "@server/types"; @@ -26,6 +26,7 @@ export enum Hook { API = "api", AuthProvider = "authProvider", EmailTemplate = "emailTemplate", + Route = "route", Model = "model", Processor = "processor", Task = "task", @@ -45,7 +46,8 @@ type PluginValueMap = { [Hook.Task]: typeof BaseTask; [Hook.Uninstall]: UninstallSignature; [Hook.UnfurlProvider]: { unfurl: UnfurlSignature; cacheExpiry: number }; - [Hook.Model]: typeof Model; + [Hook.Model]: typeof BaseModel; + [Hook.Route]: Router; }; export type Plugin = {