Refactor out of plugin

This commit is contained in:
Tom Moor committed 2025-04-03 21:08:28 -04:00
1 parent db0deb6997
commit 24eaeca47e
36 files changed
+468 -251

No files matched your search

+2 -3
View File
@@ -11,9 +11,8 @@ export const createOAuthClient = createAction({
section: SettingsSection,
icon: <PlusIcon />,
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();
+7 -3
View File
@@ -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() {
<Route exact path="/create" component={Login} />
<Route exact path="/logout" component={Logout} />
<Route exact path="/desktop-redirect" component={DesktopRedirect} />
<Route exact path="/oauth/authorize" component={OAuthAuthorize} />
<Redirect exact from="/share/:shareId" to="/s/:shareId" />
<Route exact path="/s/:shareId" component={SharedDocument} />
@@ -61,7 +62,10 @@ export default function Routes() {
/>
<Authenticated>
<AuthenticatedRoutes />
<Switch>
<Route exact path="/oauth/authorize" component={OAuthAuthorize} />
<AuthenticatedRoutes />
</Switch>
</Authenticated>
</Switch>
)}
@@ -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) {
<Background>
<BackButton />
<ChangeLanguage locale={detectLanguage()} />
<Centered align="center" justify="center" column auto>
<Centered>
<PageTitle title={t("Login")} />
<Heading centered>{t("Error")}</Heading>
<Note>
@@ -144,7 +144,7 @@ function Login({ children }: Props) {
<Background>
<BackButton config={config} />
<ChangeLanguage locale={detectLanguage()} />
<Centered align="center" justify="center" column auto>
<Centered>
<PageTitle title={t("Custom domain setup")} />
<Heading centered>{t("Almost there")}…</Heading>
<Note>
@@ -163,14 +163,7 @@ function Login({ children }: Props) {
<BackButton config={config} />
<ChangeLanguage locale={detectLanguage()} />
<Centered
as="form"
onSubmit={handleGoSubdomain}
align="center"
justify="center"
column
auto
>
<Centered as="form" onSubmit={handleGoSubdomain}>
<Heading centered>{t("Choose workspace")}</Heading>
<Note>
{t(
@@ -207,7 +200,7 @@ function Login({ children }: Props) {
return (
<Background>
<BackButton config={config} />
<Centered align="center" justify="center" column auto>
<Centered>
<PageTitle title={t("Check your email")} />
<CheckEmailIcon size={38} />
<Heading centered>{t("Check your email")}</Heading>
@@ -244,7 +237,7 @@ function Login({ children }: Props) {
<BackButton config={config} />
<ChangeLanguage locale={detectLanguage()} />
<Centered align="center" justify="center" gap={12} column auto>
<Centered gap={12}>
<PageTitle
title={config.name ? `${config.name} – ${t("Login")}` : t("Login")}
/>
@@ -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);
+86
View File
@@ -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 (
<Background>
<ChangeLanguage locale={detectLanguage()} />
<Centered>
<h1>{t("Error")}</h1>
<p>{t("Unable to load OAuth client")}</p>
</Centered>
</Background>
);
}
if (!data) {
// TODO
return null;
}
return (
<Background>
<ChangeLanguage locale={detectLanguage()} />
<Centered gap={12}>
<TeamLogo model={team} size={24} alt={t("Logo")} /> {team.name}
<h1>{data.data.name}</h1>
<p>{data.data.developerName}</p>
<p>{data.data.developerUrl}</p>
<p>{data.data.description}</p>
<form method="POST" action="/oauth/authorize" style={{ width: "100%" }}>
<input type="hidden" name="client_id" value={clientId ?? ""} />
<input
type="hidden"
name="client_secret"
value={clientSecret ?? ""}
/>
<input type="hidden" name="redirect_uri" value={redirectUri ?? ""} />
<input
type="hidden"
name="response_type"
value={responseType ?? "code"}
/>
<input type="hidden" name="state" value={state ?? ""} />
<input type="hidden" name="scope" value={scope ?? ""} />
<Button type="submit" fullwidth>
{t("Authorize")}
</Button>
</form>
</Centered>
</Background>
);
}
export default Authorize;
+1 -1
View File
@@ -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;
@@ -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()}
`;
+15
View File
@@ -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;
`;
+1 -1
View File
@@ -123,7 +123,7 @@ function Message({ notice }: { notice: string }) {
}
}
export default function Notices() {
export function Notices() {
const query = useQuery();
const notice = query.get("notice");
+3
View File
@@ -0,0 +1,3 @@
import Login from "./Login";
export default Login;
-24
View File
@@ -1,24 +0,0 @@
import React from "react";
import CenteredContent from "~/components/CenteredContent";
function Authorize() {
return (
<CenteredContent>
<form
method="POST"
action="/oauth/authorize"
style={{ display: "flex", flexDirection: "column", gap: 10 }}
>
<input type="text" name="client_id" placeholder="Client ID" />
<input type="text" name="client_secret" placeholder="Client Secret" />
<input type="text" name="redirect_uri" placeholder="Redirect URI" />
<input type="text" name="response_type" value="code" />
<input type="text" name="scope" value="read" />
<input type="text" name="state" value="123" />
<button type="submit">Authorize</button>
</form>
</CenteredContent>
);
}
export default Authorize;
-6
View File
@@ -1,6 +0,0 @@
{
"id": "oauth",
"name": "OAuth Provider",
"priority": 10,
"description": "Adds an OAuth2 compatible authentication provider"
}
-37
View File
@@ -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<T.OAuthClientsCreateReq>) => {
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;
-32
View File
@@ -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,
},
]);
@@ -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,
};
}
+34 -2
View File
@@ -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;
@@ -173,6 +173,10 @@ module.exports = {
type: Sequelize.DATE,
allowNull: false
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false
},
deletedAt: {
type: Sequelize.DATE,
allowNull: true
+2 -16
View File
@@ -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);
};
}
@@ -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 === "*")
);
});
};
}
+6
View File
@@ -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";
@@ -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<OAuthAuthentication>,
Partial<InferCreationAttributes<OAuthAuthentication>>
> {
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.
*
@@ -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<OAuthAuthorizationCode>,
Partial<InferCreationAttributes<OAuthAuthorizationCode>>
> {
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,
});
}
}
@@ -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",
+2 -1
View File
@@ -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";
+36
View File
@@ -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)
)
);
+3
View File
@@ -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,
+30
View File
@@ -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,
};
}
+2
View File
@@ -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());
+1
View File
@@ -0,0 +1 @@
export { default } from "./oauthClients";
@@ -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<T.OAuthClientsCreateReq>) => {
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<T.OAuthClientsInfoReq>) => {
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;
@@ -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<typeof OAuthClientsCreateSchema>;
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<typeof OAuthClientsInfoSchema>;
@@ -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());
+2 -6
View File
@@ -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));
-6
View File
@@ -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") &&
+1
View File
@@ -41,6 +41,7 @@ import type {
export enum AuthenticationType {
API = "api",
APP = "app",
OAUTH = "oauth",
}
export type AuthenticationResult = AccountProvisionerResult & {
-6
View File
@@ -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<any>;
[Hook.Uninstall]: UninstallSignature;
[Hook.UnfurlProvider]: { unfurl: UnfurlSignature; cacheExpiry: number };
[Hook.Model]: typeof BaseModel;
[Hook.Route]: { path: string; app: Koa };
};
export type Plugin<T extends Hook> = {
@@ -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<OAuthClient> = {
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,