diff --git a/app/actions/definitions/oauthClients.tsx b/app/actions/definitions/oauthClients.tsx index db0fbc61ae..7999aa57ea 100644 --- a/app/actions/definitions/oauthClients.tsx +++ b/app/actions/definitions/oauthClients.tsx @@ -11,9 +11,8 @@ export const createOAuthClient = createAction({ section: SettingsSection, icon: , keywords: "create", - // TODO - // visible: () => - // stores.policies.abilities(stores.auth.team?.id || "").createOAuthClient, + visible: () => + stores.policies.abilities(stores.auth.team?.id || "").createOAuthClient, perform: ({ t, event }) => { event?.preventDefault(); event?.stopPropagation(); diff --git a/app/routes/index.tsx b/app/routes/index.tsx index cad0547c76..3c4b240cb0 100644 --- a/app/routes/index.tsx +++ b/app/routes/index.tsx @@ -14,7 +14,9 @@ const AuthenticatedRoutes = lazyWithRetry(() => import("./authenticated")); const SharedDocument = lazyWithRetry(() => import("~/scenes/Document/Shared")); const Login = lazyWithRetry(() => import("~/scenes/Login")); const Logout = lazyWithRetry(() => import("~/scenes/Logout")); -const OAuthAuthorize = lazyWithRetry(() => import("~/scenes/OAuth/Authorize")); +const OAuthAuthorize = lazyWithRetry( + () => import("~/scenes/Login/OAuthAuthorize") +); export default function Routes() { useQueryNotices(); @@ -44,7 +46,6 @@ export default function Routes() { - @@ -61,7 +62,10 @@ export default function Routes() { /> - + + + + )} diff --git a/app/scenes/Login/index.tsx b/app/scenes/Login/Login.tsx similarity index 92% rename from app/scenes/Login/index.tsx rename to app/scenes/Login/Login.tsx index 96a356abe2..e35a35c48c 100644 --- a/app/scenes/Login/index.tsx +++ b/app/scenes/Login/Login.tsx @@ -13,7 +13,6 @@ import { Config } from "~/stores/AuthStore"; import { AvatarSize } from "~/components/Avatar"; import ButtonLarge from "~/components/ButtonLarge"; import ChangeLanguage from "~/components/ChangeLanguage"; -import Fade from "~/components/Fade"; import Flex from "~/components/Flex"; import Heading from "~/components/Heading"; import OutlineIcon from "~/components/Icons/OutlineIcon"; @@ -30,14 +29,15 @@ import { } from "~/hooks/useLastVisitedPath"; import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; -import { draggableOnDesktop } from "~/styles"; import Desktop from "~/utils/Desktop"; import isCloudHosted from "~/utils/isCloudHosted"; import { detectLanguage } from "~/utils/language"; import { homePath } from "~/utils/routeHelpers"; import AuthenticationProvider from "./components/AuthenticationProvider"; -import BackButton from "./components/BackButton"; -import Notices from "./components/Notices"; +import { BackButton } from "./components/BackButton"; +import { Background } from "./components/Background"; +import { Centered } from "./components/Centered"; +import { Notices } from "./components/Notices"; import { getRedirectUrl, navigateToSubdomain } from "./urls"; type Props = { @@ -112,7 +112,7 @@ function Login({ children }: Props) { - + {t("Error")} @@ -144,7 +144,7 @@ function Login({ children }: Props) { - + {t("Almost there")}… @@ -163,14 +163,7 @@ function Login({ children }: Props) { - + {t("Choose workspace")} {t( @@ -207,7 +200,7 @@ function Login({ children }: Props) { return ( - + {t("Check your email")} @@ -244,7 +237,7 @@ function Login({ children }: Props) { - + @@ -336,14 +329,6 @@ const CheckEmailIcon = styled(EmailIcon)` margin-bottom: -1.5em; `; -const Background = styled(Fade)` - width: 100vw; - height: 100%; - background: ${s("background")}; - display: flex; - ${draggableOnDesktop()} -`; - const Logo = styled.div` margin-bottom: -4px; `; @@ -389,12 +374,4 @@ const Or = styled.hr` } `; -const Centered = styled(Flex)` - user-select: none; - width: 90vw; - height: 100%; - max-width: 320px; - margin: 0 auto; -`; - export default observer(Login); diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx new file mode 100644 index 0000000000..8cb06cfad2 --- /dev/null +++ b/app/scenes/Login/OAuthAuthorize.tsx @@ -0,0 +1,86 @@ +import React from "react"; +import { useTranslation } from "react-i18next"; +import Button from "~/components/Button"; +import ChangeLanguage from "~/components/ChangeLanguage"; +import TeamLogo from "~/components/TeamLogo"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useQuery from "~/hooks/useQuery"; +import useRequest from "~/hooks/useRequest"; +import { client } from "~/utils/ApiClient"; +import { detectLanguage } from "~/utils/language"; +import { Background } from "./components/Background"; +import { Centered } from "./components/Centered"; + +function Authorize() { + const team = useCurrentTeam(); + const params = useQuery(); + const { t } = useTranslation(); + const clientId = params.get("client_id"); + const clientSecret = params.get("client_secret"); + const redirectUri = params.get("redirect_uri"); + const responseType = params.get("response_type"); + const state = params.get("state"); + const scope = params.get("scope"); + // const [scopes] = React.useState(() => scope?.split(" ") ?? []); + const { error, data, request } = useRequest(() => + client.post("/oauthClients.info", { clientId }) + ); + + React.useEffect(() => { + if (clientId) { + void request(); + } + }, []); + + if (error) { + return ( + + + +

{t("Error")}

+

{t("Unable to load OAuth client")}

+
+
+ ); + } + + if (!data) { + // TODO + return null; + } + + return ( + + + + + {team.name} +

{data.data.name}

+

{data.data.developerName}

+

{data.data.developerUrl}

+

{data.data.description}

+
+ + + + + + + +
+
+
+ ); +} + +export default Authorize; diff --git a/app/scenes/Login/components/BackButton.tsx b/app/scenes/Login/components/BackButton.tsx index 28ce8aa6b2..bf60efb344 100644 --- a/app/scenes/Login/components/BackButton.tsx +++ b/app/scenes/Login/components/BackButton.tsx @@ -12,7 +12,7 @@ type Props = { config?: Config; }; -export default function BackButton({ config }: Props) { +export function BackButton({ config }: Props) { const { t } = useTranslation(); const isSubdomain = !!config?.hostname; diff --git a/app/scenes/Login/components/Background.tsx b/app/scenes/Login/components/Background.tsx new file mode 100644 index 0000000000..532d6e9841 --- /dev/null +++ b/app/scenes/Login/components/Background.tsx @@ -0,0 +1,12 @@ +import styled from "styled-components"; +import { s } from "@shared/styles"; +import Fade from "~/components/Fade"; +import { draggableOnDesktop } from "~/styles"; + +export const Background = styled(Fade)` + width: 100vw; + height: 100%; + background: ${s("background")}; + display: flex; + ${draggableOnDesktop()} +`; diff --git a/app/scenes/Login/components/Centered.tsx b/app/scenes/Login/components/Centered.tsx new file mode 100644 index 0000000000..4c84301af1 --- /dev/null +++ b/app/scenes/Login/components/Centered.tsx @@ -0,0 +1,15 @@ +import styled from "styled-components"; +import Flex from "@shared/components/Flex"; + +export const Centered = styled(Flex).attrs({ + align: "center", + justify: "center", + column: true, + auto: true, +})` + user-select: none; + width: 90vw; + height: 100%; + max-width: 320px; + margin: 0 auto; +`; diff --git a/app/scenes/Login/components/Notices.tsx b/app/scenes/Login/components/Notices.tsx index 0a752b3f37..a434e7b1a6 100644 --- a/app/scenes/Login/components/Notices.tsx +++ b/app/scenes/Login/components/Notices.tsx @@ -123,7 +123,7 @@ function Message({ notice }: { notice: string }) { } } -export default function Notices() { +export function Notices() { const query = useQuery(); const notice = query.get("notice"); diff --git a/app/scenes/Login/index.ts b/app/scenes/Login/index.ts new file mode 100644 index 0000000000..04230a1bd9 --- /dev/null +++ b/app/scenes/Login/index.ts @@ -0,0 +1,3 @@ +import Login from "./Login"; + +export default Login; diff --git a/app/scenes/OAuth/Authorize.tsx b/app/scenes/OAuth/Authorize.tsx deleted file mode 100644 index 7ff8de56cb..0000000000 --- a/app/scenes/OAuth/Authorize.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import React from "react"; -import CenteredContent from "~/components/CenteredContent"; - -function Authorize() { - return ( - -
- - - - - - - -
-
- ); -} - -export default Authorize; diff --git a/plugins/oauth/plugin.json b/plugins/oauth/plugin.json deleted file mode 100644 index df0d6b5587..0000000000 --- a/plugins/oauth/plugin.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "id": "oauth", - "name": "OAuth Provider", - "priority": 10, - "description": "Adds an OAuth2 compatible authentication provider" -} \ No newline at end of file diff --git a/plugins/oauth/server/api/oauthClients.ts b/plugins/oauth/server/api/oauthClients.ts deleted file mode 100644 index efa27881e2..0000000000 --- a/plugins/oauth/server/api/oauthClients.ts +++ /dev/null @@ -1,37 +0,0 @@ -import auth from "@server/middlewares/authentication"; -import { transaction } from "@server/middlewares/transaction"; -import validate from "@server/middlewares/validate"; -import { authorize } from "@server/policies"; -import { APIContext } from "@server/types"; -import Router from "koa-router"; -import OAuthClient from "../models/OAuthClient"; -import presentOAuthClient from "../presenters/oauthClient"; -import * as T from "./schema"; - -const router = new Router(); - -router.post( - "oauthClients.create", - auth(), - validate(T.OAuthClientsCreateSchema), - transaction(), - async (ctx: APIContext) => { - const input = ctx.input.body; - const { user } = ctx.state.auth; - - // TODO: Switch policy - authorize(user, "createApiKey", user.team); - - const oauthClient = await OAuthClient.createWithCtx(ctx, { - ...input, - teamId: user.teamId, - createdById: user.id, - }); - - ctx.body = { - data: presentOAuthClient(oauthClient), - }; - } -); - -export default router; diff --git a/plugins/oauth/server/index.ts b/plugins/oauth/server/index.ts deleted file mode 100644 index a00b439d94..0000000000 --- a/plugins/oauth/server/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { PluginManager, Hook } from "@server/utils/PluginManager"; -import oauthClients from "./api/oauthClients"; -import OAuthAuthentication from "./models/OAuthAuthentication"; -import OAuthAuthorizationCode from "./models/OAuthAuthorizationCode"; -import OAuthClient from "./models/OAuthClient"; -import oauth from "./oauth"; - -PluginManager.add([ - { - type: Hook.Model, - value: OAuthClient, - }, - { - type: Hook.Model, - value: OAuthAuthentication, - }, - { - type: Hook.Model, - value: OAuthAuthorizationCode, - }, - { - type: Hook.Route, - value: { - path: "/oauth", - app: oauth, - }, - }, - { - type: Hook.API, - value: oauthClients, - }, -]); diff --git a/plugins/oauth/server/presenters/oauthClient.ts b/plugins/oauth/server/presenters/oauthClient.ts deleted file mode 100644 index 48dbb72928..0000000000 --- a/plugins/oauth/server/presenters/oauthClient.ts +++ /dev/null @@ -1,18 +0,0 @@ -import OAuthClient from "../models/OAuthClient"; - -export default function presentOAuthClient(apiKey: OAuthClient) { - return { - id: apiKey.id, - name: apiKey.name, - description: apiKey.description, - developerName: apiKey.developerName, - developerUrl: apiKey.developerUrl, - avatarUrl: apiKey.avatarUrl, - clientId: apiKey.clientId, - clientSecret: apiKey.clientSecret, - redirectUris: apiKey.redirectUris, - published: apiKey.published, - createdAt: apiKey.createdAt, - updatedAt: apiKey.updatedAt, - }; -} diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index bc3fa6c3bc..d3c95ab395 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -7,7 +7,7 @@ import tracer, { addTags, getRootSpanFromRequestContext, } from "@server/logging/tracer"; -import { User, Team, ApiKey } from "@server/models"; +import { User, Team, ApiKey, OAuthAuthentication } from "@server/models"; import { AppContext, AuthenticationType } from "@server/types"; import { getUserForJWT } from "@server/utils/jwt"; import { @@ -65,7 +65,39 @@ export default function auth(options: AuthenticationOptions = {}) { let user: User | null; let type: AuthenticationType; - if (ApiKey.match(String(token))) { + if (OAuthAuthentication.match(String(token))) { + type = AuthenticationType.OAUTH; + + let authentication; + try { + authentication = await OAuthAuthentication.findByAccessToken(token); + } catch (err) { + throw AuthenticationError("Invalid access token"); + } + if (authentication.accessTokenExpiresAt < new Date()) { + throw AuthenticationError("Access token is expired"); + } + if (!authentication.canAccess(ctx.request.url)) { + throw AuthenticationError( + "Access token does not have access to this resource" + ); + } + + user = await User.findByPk(authentication.userId, { + include: [ + { + model: Team, + as: "team", + required: true, + }, + ], + }); + if (!user) { + throw AuthenticationError("Invalid access token"); + } + + await authentication.updateActiveAt(); + } else if (ApiKey.match(String(token))) { type = AuthenticationType.API; let apiKey; diff --git a/server/migrations/20250331231413-add-oauth-server-models.js b/server/migrations/20250331231413-add-oauth-server-models.js index f62f640194..e28c612889 100644 --- a/server/migrations/20250331231413-add-oauth-server-models.js +++ b/server/migrations/20250331231413-add-oauth-server-models.js @@ -173,6 +173,10 @@ module.exports = { type: Sequelize.DATE, allowNull: false }, + updatedAt: { + type: Sequelize.DATE, + allowNull: false + }, deletedAt: { type: Sequelize.DATE, allowNull: true diff --git a/server/models/ApiKey.ts b/server/models/ApiKey.ts index 0406b68c6d..397add70e8 100644 --- a/server/models/ApiKey.ts +++ b/server/models/ApiKey.ts @@ -20,6 +20,7 @@ import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; import { SkipChangeset } from "./decorators/Changeset"; import Fix from "./decorators/Fix"; +import AuthenticationHelper from "./helpers/AuthenticationHelper"; import Length from "./validators/Length"; @Table({ tableName: "apiKeys", modelName: "apiKey" }) @@ -174,22 +175,7 @@ class ApiKey extends ParanoidModel< return true; } - // strip any query string from the path - path = path.split("?")[0]; - - const resource = path.split("/").pop() ?? ""; - const [namespace, method] = resource.split("."); - - return this.scope.some((scope) => { - const [scopeNamespace, scopeMethod] = scope - .replace("/api/", "") - .split("."); - return ( - scope.startsWith("/api/") && - (namespace === scopeNamespace || scopeNamespace === "*") && - (method === scopeMethod || scopeMethod === "*") - ); - }); + return AuthenticationHelper.canAccess(path, this.scope); }; } diff --git a/server/models/helpers/AuthenticationHelper.ts b/server/models/helpers/AuthenticationHelper.ts index 6e85bbd80a..69fddf174e 100644 --- a/server/models/helpers/AuthenticationHelper.ts +++ b/server/models/helpers/AuthenticationHelper.ts @@ -52,4 +52,23 @@ export default class AuthenticationHelper { ); }); } + + public static canAccess = (path: string, scopes: string[]) => { + // strip any query string from the path + path = path.split("?")[0]; + + const resource = path.split("/").pop() ?? ""; + const [namespace, method] = resource.split("."); + + return scopes.some((scope) => { + const [scopeNamespace, scopeMethod] = scope + .replace("/api/", "") + .split("."); + return ( + scope.startsWith("/api/") && + (namespace === scopeNamespace || scopeNamespace === "*") && + (method === scopeMethod || scopeMethod === "*") + ); + }); + }; } diff --git a/server/models/index.ts b/server/models/index.ts index a7a773f2d6..486e3c8b4f 100644 --- a/server/models/index.ts +++ b/server/models/index.ts @@ -34,6 +34,12 @@ export { default as IntegrationAuthentication } from "./IntegrationAuthenticatio export { default as Notification } from "./Notification"; +export { default as OAuthAuthentication } from "./oauth/OAuthAuthentication"; + +export { default as OAuthAuthorizationCode } from "./oauth/OAuthAuthorizationCode"; + +export { default as OAuthClient } from "./oauth/OAuthClient"; + export { default as Pin } from "./Pin"; export { default as Reaction } from "./Reaction"; diff --git a/plugins/oauth/server/models/OAuthAuthentication.ts b/server/models/oauth/OAuthAuthentication.ts similarity index 84% rename from plugins/oauth/server/models/OAuthAuthentication.ts rename to server/models/oauth/OAuthAuthentication.ts index bb696fec60..e21107befb 100644 --- a/plugins/oauth/server/models/OAuthAuthentication.ts +++ b/server/models/oauth/OAuthAuthentication.ts @@ -1,8 +1,4 @@ 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 { subMinutes } from "date-fns"; import { InferAttributes, InferCreationAttributes } from "sequelize"; @@ -16,6 +12,11 @@ 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 AuthenticationHelper from "@server/models/helpers/AuthenticationHelper"; import OAuthClient from "./OAuthClient"; @Table({ @@ -27,8 +28,8 @@ class OAuthAuthentication extends ParanoidModel< InferAttributes, Partial> > { - public static accessTokenPrefix = "ol_atx_"; - public static refreshTokenPrefix = "ol_rtx_"; + public static accessTokenPrefix = "ol_at_"; + public static refreshTokenPrefix = "ol_rt_"; @Unique @Column @@ -105,8 +106,25 @@ class OAuthAuthentication extends ParanoidModel< model.lastActiveAt = new Date(); } + // instance methods + + /** Checks if the authentication has access to the given path */ + canAccess = (path: string) => + AuthenticationHelper.canAccess(path, this.scope); + // static methods + /** + * Validates that the input text _could_ be an OAuth token, this does not check + * that the key actually exists in the database. + * + * @param text The text to validate + * @returns True if likely an OAuth token + */ + public static match(text: string) { + return !!text.startsWith(this.accessTokenPrefix); + } + /** * Generates a hashed token for the given input. * diff --git a/plugins/oauth/server/models/OAuthAuthorizationCode.ts b/server/models/oauth/OAuthAuthorizationCode.ts similarity index 94% rename from plugins/oauth/server/models/OAuthAuthorizationCode.ts rename to server/models/oauth/OAuthAuthorizationCode.ts index a8b5e9c994..b77b5d60d4 100644 --- a/plugins/oauth/server/models/OAuthAuthorizationCode.ts +++ b/server/models/oauth/OAuthAuthorizationCode.ts @@ -1,9 +1,4 @@ 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 { @@ -14,6 +9,11 @@ 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({ @@ -26,6 +26,8 @@ class OAuthAuthorizationCode extends IdModel< InferAttributes, Partial> > { + public static authorizationCodePrefix = "ol_ac_"; + @Column @SkipChangeset authorizationCodeHash: string; @@ -77,9 +79,11 @@ class OAuthAuthorizationCode extends IdModel< * @returns The OAuthAuthentication if found */ public static findByCode(input: string) { + const authorizationCodeHash = this.hash(input); + return this.findOne({ where: { - authorizationCodeHash: this.hash(input), + authorizationCodeHash, }, include: [ { @@ -87,7 +91,6 @@ class OAuthAuthorizationCode extends IdModel< required: true, }, ], - rejectOnEmpty: true, }); } } diff --git a/plugins/oauth/server/models/OAuthClient.ts b/server/models/oauth/OAuthClient.ts similarity index 100% rename from plugins/oauth/server/models/OAuthClient.ts rename to server/models/oauth/OAuthClient.ts index 722fb29913..427ea509a3 100644 --- a/plugins/oauth/server/models/OAuthClient.ts +++ b/server/models/oauth/OAuthClient.ts @@ -1,11 +1,3 @@ -import Team from "@server/models/Team"; -import User from "@server/models/User"; -import ParanoidModel from "@server/models/base/ParanoidModel"; -import Encrypted from "@server/models/decorators/Encrypted"; -import Fix from "@server/models/decorators/Fix"; -import IsUrlOrRelativePath from "@server/models/validators/IsUrlOrRelativePath"; -import NotContainsUrl from "@server/models/validators/NotContainsUrl"; -import { OAuthClientValidation } from "@shared/validations"; import { ArrayMaxSize, ArrayMinSize, @@ -25,6 +17,14 @@ import { BeforeCreate, AllowNull, } from "sequelize-typescript"; +import { OAuthClientValidation } from "@shared/validations"; +import Team from "@server/models/Team"; +import User from "@server/models/User"; +import ParanoidModel from "@server/models/base/ParanoidModel"; +import Encrypted from "@server/models/decorators/Encrypted"; +import Fix from "@server/models/decorators/Fix"; +import IsUrlOrRelativePath from "@server/models/validators/IsUrlOrRelativePath"; +import NotContainsUrl from "@server/models/validators/NotContainsUrl"; @Table({ tableName: "oauth_clients", diff --git a/server/policies/index.ts b/server/policies/index.ts index ebcf04f9ab..d7d60b3823 100644 --- a/server/policies/index.ts +++ b/server/policies/index.ts @@ -11,6 +11,8 @@ import "./document"; import "./fileOperation"; import "./import"; import "./integration"; +import "./notification"; +import "./oauthClient"; import "./pins"; import "./reaction"; import "./revision"; @@ -22,5 +24,4 @@ import "./user"; import "./team"; import "./group"; import "./webhookSubscription"; -import "./notification"; import "./userMembership"; diff --git a/server/policies/oauthClient.ts b/server/policies/oauthClient.ts new file mode 100644 index 0000000000..6dfebc3b00 --- /dev/null +++ b/server/policies/oauthClient.ts @@ -0,0 +1,36 @@ +import { TeamPreference } from "@shared/types"; +import { Team, User, OAuthClient } from "@server/models"; +import { allow } from "./cancan"; +import { or, isTeamModel, isTeamMutable, and, isOwner } from "./utils"; + +allow(User, "createOAuthClient", Team, (actor, team) => + and( + isTeamModel(actor, team), + isTeamMutable(actor), + !actor.isViewer, + !actor.isGuest, + !actor.isSuspended, + actor.isAdmin || + !!team?.getPreference(TeamPreference.MembersCanCreateApiKey) + ) +); + +allow(User, "listOAuthClients", Team, (actor, team) => + and( + // + isTeamModel(actor, team), + actor.isAdmin + ) +); + +allow(User, "read", OAuthClient, (actor, oauthClient) => + or(isTeamModel(actor, oauthClient), !!oauthClient?.published) +); + +allow(User, ["update", "delete"], OAuthClient, (actor, oauthClient) => + and( + isOwner(actor, oauthClient), + actor.isAdmin || + !!actor.team?.getPreference(TeamPreference.MembersCanCreateApiKey) + ) +); diff --git a/server/presenters/index.ts b/server/presenters/index.ts index 563e3657e5..f3fb962ce9 100644 --- a/server/presenters/index.ts +++ b/server/presenters/index.ts @@ -13,6 +13,7 @@ import presentGroupUser from "./groupUser"; import presentImport from "./import"; import presentIntegration from "./integration"; import presentMembership from "./membership"; +import presentOAuthClient, { presentPublishedOAuthClient } from "./oauthClient"; import presentPin from "./pin"; import presentPolicies from "./policy"; import presentProviderConfig from "./providerConfig"; @@ -43,6 +44,8 @@ export { presentImport, presentIntegration, presentMembership, + presentOAuthClient, + presentPublishedOAuthClient, presentPublicTeam, presentPin, presentPolicies, diff --git a/server/presenters/oauthClient.ts b/server/presenters/oauthClient.ts new file mode 100644 index 0000000000..5148f0d7d5 --- /dev/null +++ b/server/presenters/oauthClient.ts @@ -0,0 +1,30 @@ +import { OAuthClient } from "@server/models"; + +export default function presentOAuthClient(oauthClient: OAuthClient) { + return { + id: oauthClient.id, + name: oauthClient.name, + description: oauthClient.description, + developerName: oauthClient.developerName, + developerUrl: oauthClient.developerUrl, + avatarUrl: oauthClient.avatarUrl, + clientId: oauthClient.clientId, + clientSecret: oauthClient.clientSecret, + redirectUris: oauthClient.redirectUris, + published: oauthClient.published, + createdAt: oauthClient.createdAt, + updatedAt: oauthClient.updatedAt, + }; +} + +export function presentPublishedOAuthClient(oauthClient: OAuthClient) { + return { + name: oauthClient.name, + description: oauthClient.description, + developerName: oauthClient.developerName, + developerUrl: oauthClient.developerUrl, + avatarUrl: oauthClient.avatarUrl, + clientId: oauthClient.clientId, + published: oauthClient.published, + }; +} diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index de12822684..0d6a7fb8b2 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -28,6 +28,7 @@ import apiResponse from "./middlewares/apiResponse"; import apiTracer from "./middlewares/apiTracer"; import editor from "./middlewares/editor"; import notifications from "./notifications"; +import oauthClients from "./oauthClients"; import pins from "./pins"; import reactions from "./reactions"; import revisions from "./revisions"; @@ -90,6 +91,7 @@ router.use("/", suggestions.routes()); router.use("/", teams.routes()); router.use("/", integrations.routes()); router.use("/", notifications.routes()); +router.use("/", oauthClients.routes()); router.use("/", attachments.routes()); router.use("/", cron.routes()); router.use("/", groups.routes()); diff --git a/server/routes/api/oauthClients/index.ts b/server/routes/api/oauthClients/index.ts new file mode 100644 index 0000000000..1428e5aa23 --- /dev/null +++ b/server/routes/api/oauthClients/index.ts @@ -0,0 +1 @@ +export { default } from "./oauthClients"; diff --git a/server/routes/api/oauthClients/oauthClients.ts b/server/routes/api/oauthClients/oauthClients.ts new file mode 100644 index 0000000000..2b60935831 --- /dev/null +++ b/server/routes/api/oauthClients/oauthClients.ts @@ -0,0 +1,66 @@ +import Router from "koa-router"; +import auth from "@server/middlewares/authentication"; +import { transaction } from "@server/middlewares/transaction"; +import validate from "@server/middlewares/validate"; +import { OAuthClient } from "@server/models"; +import { authorize } from "@server/policies"; +import { + presentPolicies, + presentOAuthClient, + presentPublishedOAuthClient, +} from "@server/presenters"; +import { APIContext } from "@server/types"; +import * as T from "./schema"; + +const router = new Router(); + +router.post( + "oauthClients.create", + auth(), + validate(T.OAuthClientsCreateSchema), + transaction(), + async (ctx: APIContext) => { + const input = ctx.input.body; + const { user } = ctx.state.auth; + + authorize(user, "createOAuthClient", user.team); + + const oauthClient = await OAuthClient.createWithCtx(ctx, { + ...input, + teamId: user.teamId, + createdById: user.id, + }); + + ctx.body = { + data: presentOAuthClient(oauthClient), + policies: presentPolicies(user, [oauthClient]), + }; + } +); + +router.post( + "oauthClients.info", + auth(), + validate(T.OAuthClientsInfoSchema), + async (ctx: APIContext) => { + const { id, clientId } = ctx.input.body; + const { user } = ctx.state.auth; + + const oauthClient = await OAuthClient.findOne({ + where: clientId ? { clientId } : { id }, + rejectOnEmpty: true, + }); + authorize(user, "read", oauthClient); + + const internal = oauthClient.teamId === user.teamId; + + ctx.body = { + data: internal + ? presentOAuthClient(oauthClient) + : presentPublishedOAuthClient(oauthClient), + policies: internal ? presentPolicies(user, [oauthClient]) : [], + }; + } +); + +export default router; diff --git a/plugins/oauth/server/api/schema.ts b/server/routes/api/oauthClients/schema.ts similarity index 71% rename from plugins/oauth/server/api/schema.ts rename to server/routes/api/oauthClients/schema.ts index 224f6518dc..28aaf74ccd 100644 --- a/plugins/oauth/server/api/schema.ts +++ b/server/routes/api/oauthClients/schema.ts @@ -1,5 +1,5 @@ -import { BaseSchema } from "@server/routes/api/schema"; import { z } from "zod"; +import { BaseSchema } from "@server/routes/api/schema"; export const OAuthClientsCreateSchema = BaseSchema.extend({ body: z.object({ @@ -33,3 +33,19 @@ export const OAuthClientsCreateSchema = BaseSchema.extend({ }); export type OAuthClientsCreateReq = z.infer; + +export const OAuthClientsInfoSchema = BaseSchema.extend({ + body: z + .object({ + /** OAuth client id */ + id: z.string().uuid().optional(), + + /** OAuth clientId */ + clientId: z.string().optional(), + }) + .refine((data) => data.id || data.clientId, { + message: "Either id or clientId is required", + }), +}); + +export type OAuthClientsInfoReq = z.infer; diff --git a/plugins/oauth/server/oauth.ts b/server/routes/oauth/index.ts similarity index 63% rename from plugins/oauth/server/oauth.ts rename to server/routes/oauth/index.ts index dfe78e23d8..991e87a699 100644 --- a/plugins/oauth/server/oauth.ts +++ b/server/routes/oauth/index.ts @@ -1,9 +1,9 @@ import OAuth2Server from "@node-oauth/oauth2-server"; -import auth from "@server/middlewares/authentication"; import Koa from "koa"; import bodyParser from "koa-body"; import Router from "koa-router"; -import { OAuthInterface } from "./interface"; +import auth from "@server/middlewares/authentication"; +import { OAuthInterface } from "@server/utils/oauth/OAuthInterface"; const app = new Koa(); @@ -25,6 +25,15 @@ router.post("/authorize", auth(), async (ctx) => { }, }, }); + + if (response.status === 302 && response.headers?.location) { + const location = response.headers.location; + delete response.headers.location; + ctx.set(response.headers); + ctx.redirect(location); + return; + } + ctx.body = { code: authorizationCode }; }); @@ -33,7 +42,16 @@ router.post("/token", async (ctx) => { const response = new OAuth2Server.Response(ctx.response); const token = await oauth.token(request, response); - ctx.body = { token }; + + ctx.body = { + access_token: token.accessToken, + refresh_token: token.refreshToken, + expires_in: token.accessTokenExpiresAt + ? Math.round((token.accessTokenExpiresAt.getTime() - Date.now()) / 1000) + : undefined, + token_type: "Bearer", + scope: token.scope?.join(" "), + }; }); app.use(bodyParser()); diff --git a/server/services/web.ts b/server/services/web.ts index 1a052550bd..f75eeb5700 100644 --- a/server/services/web.ts +++ b/server/services/web.ts @@ -17,12 +17,12 @@ import { Second } from "@shared/utils/time"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; -import { Hook, PluginManager } from "@server/utils/PluginManager"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; import { initI18n } from "@server/utils/i18n"; import routes from "../routes"; import api from "../routes/api"; import auth from "../routes/auth"; +import oauth from "../routes/oauth"; // Construct scripts CSP based on services in use by this installation const defaultSrc = ["'self'"]; @@ -76,11 +76,7 @@ export default function init(app: Koa = new Koa(), server?: Server) { app.use(compress()); - // Register routes before others to allow for overrides - PluginManager.getHooks(Hook.Route).forEach((hook) => - app.use(mount(hook.value.path, hook.value.app)) - ); - + app.use(mount("/oauth", oauth)); app.use(mount("/auth", auth)); app.use(mount("/api", api)); diff --git a/server/storage/database.ts b/server/storage/database.ts index b6ccbfdbeb..61e0f0a0fb 100644 --- a/server/storage/database.ts +++ b/server/storage/database.ts @@ -4,7 +4,6 @@ import { Sequelize } from "sequelize-typescript"; import { Umzug, SequelizeStorage, MigrationError } from "umzug"; import env from "@server/env"; import Model from "@server/models/base/Model"; -import { Hook, PluginManager } from "@server/utils/PluginManager"; import Logger from "../logging/Logger"; import * as baseModels from "../models"; @@ -26,11 +25,6 @@ export function createDatabaseInstance( const models = Object.values(input); try { - // Collect any additional models from plugins - PluginManager.getHooks(Hook.Model).forEach((plugin) => { - models.push(plugin.value); - }); - return new Sequelize(databaseUrl, { logging: (msg) => process.env.DEBUG?.includes("database") && diff --git a/server/types.ts b/server/types.ts index a0d1c44493..1ee93e49a7 100644 --- a/server/types.ts +++ b/server/types.ts @@ -41,6 +41,7 @@ import type { export enum AuthenticationType { API = "api", APP = "app", + OAUTH = "oauth", } export type AuthenticationResult = AccountProvisionerResult & { diff --git a/server/utils/PluginManager.ts b/server/utils/PluginManager.ts index 08edaa2c92..2db8d7010a 100644 --- a/server/utils/PluginManager.ts +++ b/server/utils/PluginManager.ts @@ -1,13 +1,11 @@ import path from "path"; import { glob } from "glob"; -import type Koa from "koa"; import type Router from "koa-router"; import isArray from "lodash/isArray"; 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 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"; @@ -27,8 +25,6 @@ export enum Hook { API = "api", AuthProvider = "authProvider", EmailTemplate = "emailTemplate", - Route = "route", - Model = "model", Processor = "processor", Task = "task", UnfurlProvider = "unfurl", @@ -47,8 +43,6 @@ type PluginValueMap = { [Hook.Task]: typeof BaseTask; [Hook.Uninstall]: UninstallSignature; [Hook.UnfurlProvider]: { unfurl: UnfurlSignature; cacheExpiry: number }; - [Hook.Model]: typeof BaseModel; - [Hook.Route]: { path: string; app: Koa }; }; export type Plugin = { diff --git a/plugins/oauth/server/interface.ts b/server/utils/oauth/OAuthInterface.ts similarity index 75% rename from plugins/oauth/server/interface.ts rename to server/utils/oauth/OAuthInterface.ts index 72deaf0e11..e97fa7f099 100644 --- a/plugins/oauth/server/interface.ts +++ b/server/utils/oauth/OAuthInterface.ts @@ -3,38 +3,34 @@ import { 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"; +import { + OAuthClient, + OAuthAuthentication, + OAuthAuthorizationCode, +} from "@server/models"; +import { safeEqual } from "@server/utils/crypto"; 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)}`; + return `${OAuthAuthentication.accessTokenPrefix}${rs.generate(32)}`; }, async generateRefreshToken() { - return `${this.refreshTokenPrefix}${rs.generate(32)}`; + return `${OAuthAuthentication.refreshTokenPrefix}${rs.generate(32)}`; }, async generateAuthorizationCode() { - return `${this.authorizationCodePrefix}${rs.generate(32)}`; + return `${OAuthAuthorizationCode.authorizationCodePrefix}${rs.generate( + 32 + )}`; }, async getAccessToken(accessToken: string) { @@ -71,8 +67,15 @@ export const OAuthInterface: RefreshTokenModel & }; }, - async getAuthorizationCode(authorizationCode: string) { + async getAuthorizationCode(authorizationCode) { const code = await OAuthAuthorizationCode.findByCode(authorizationCode); + if (!code) { + return null; + } + + const oauthClient = await OAuthClient.findByPk(code.oauthClientId, { + rejectOnEmpty: true, + }); return { authorizationCode, @@ -80,7 +83,7 @@ export const OAuthInterface: RefreshTokenModel & scope: code.scope, redirectUri: code.redirectUri, client: { - id: code.oauthClientId, + id: oauthClient.clientId, grants: this.grants, }, user: code.user, @@ -88,19 +91,23 @@ export const OAuthInterface: RefreshTokenModel & }, async getClient(clientId: string, clientSecret: string) { - const where: WhereOptions = { - clientId, - }; - if (clientSecret) { - where.clientSecret = clientSecret; - } const client = await OAuthClient.findOne({ - where, + where: { + clientId, + }, }); if (!client) { return null; } + if ( + clientSecret && + client && + !safeEqual(client.clientSecret, clientSecret) + ) { + return null; + } + return { id: client.clientId, redirectUris: client.redirectUris, @@ -114,10 +121,14 @@ export const OAuthInterface: RefreshTokenModel & const refreshToken = token.refreshToken; const accessTokenExpiresAt = token.accessTokenExpiresAt; const refreshTokenExpiresAt = token.refreshTokenExpiresAt; + const accessTokenHash = OAuthAuthentication.hash(accessToken); + const refreshTokenHash = refreshToken + ? OAuthAuthentication.hash(refreshToken) + : undefined; - const authentication = await OAuthAuthentication.create({ - accessToken, - refreshToken, + await OAuthAuthentication.create({ + accessTokenHash, + refreshTokenHash, accessTokenExpiresAt, refreshTokenExpiresAt, scope: token.scope, @@ -132,10 +143,10 @@ export const OAuthInterface: RefreshTokenModel & refreshTokenExpiresAt, scope: token.scope, client: { - id: client.databaseId, + id: client.id, grants: this.grants, }, - user: authentication.user, + user, }; }, @@ -143,11 +154,12 @@ export const OAuthInterface: RefreshTokenModel & const authorizationCode = code.authorizationCode; const expiresAt = code.expiresAt; const redirectUri = code.redirectUri; + const scope = code.scope; const authCode = await OAuthAuthorizationCode.create({ authorizationCodeHash: OAuthAuthorizationCode.hash(authorizationCode), expiresAt, - scope: code.scope, + scope, redirectUri, oauthClientId: client.databaseId, userId: user.id, @@ -156,10 +168,10 @@ export const OAuthInterface: RefreshTokenModel & return { authorizationCode, expiresAt, - scope: code.scope, + scope, redirectUri, client: { - id: client.databaseId, + id: client.id, grants: this.grants, }, user: authCode.user,