debugging

This commit is contained in:
Tom Moor committed 2025-04-02 09:45:56 -04:00
1 parent 9f21e57335
commit db0deb6997
14 files changed
+394 -17

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
import { PlusIcon } from "outline-icons";
import * as React from "react";
import stores from "~/stores";
import OAuthClientNew from "~/scenes/OAuthClientNew";
import { createAction } from "..";
import { SettingsSection } from "../sections";
export const createOAuthClient = createAction({
name: ({ t }) => t("New App"),
analyticsName: "New App",
section: SettingsSection,
icon: <PlusIcon />,
keywords: "create",
// TODO
// visible: () =>
// stores.policies.abilities(stores.auth.team?.id || "").createOAuthClient,
perform: ({ t, event }) => {
event?.preventDefault();
event?.stopPropagation();
stores.dialogs.openModal({
title: t("New App"),
content: <OAuthClientNew onSubmit={stores.dialogs.closeAllModals} />,
});
},
});
+9
View File
@@ -29,6 +29,7 @@ import useCurrentUser from "./useCurrentUser";
import usePolicy from "./usePolicy";
const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys"));
const Applications = lazy(() => import("~/scenes/Settings/Applications"));
const PersonalApiKeys = lazy(() => import("~/scenes/Settings/PersonalApiKeys"));
const Details = lazy(() => import("~/scenes/Settings/Details"));
const Export = lazy(() => import("~/scenes/Settings/Export"));
@@ -152,6 +153,14 @@ const useSettingsConfig = () => {
group: t("Workspace"),
icon: CodeIcon,
},
{
name: t("Applications"),
path: settingsPath("applications"),
component: Applications,
enabled: true, // can.listApiKeys, TODO
group: t("Workspace"),
icon: CodeIcon,
},
{
name: t("Shared Links"),
path: settingsPath("shares"),
+59
View File
@@ -0,0 +1,59 @@
import { observable } from "mobx";
import User from "./User";
import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
class OAuthClient extends ParanoidModel {
static modelName = "OAuthClient";
/** The human-readable name of this app */
@Field
@observable
name: string;
/** A short description of this app */
@Field
@observable
description: string | null;
/** The name of the developer of this app */
@Field
@observable
developerName: string | null;
/** The URL of the developer of this app */
@Field
@observable
developerUrl: string | null;
/** The URL of the avatar of the developer of this app */
@Field
@observable
avatarUrl: string | null;
/** The developer facing ID of this app */
@Field
clientId: string;
/** The developer facing secret of this app */
@Field
clientSecret: string;
/** Whether this app is published (available to other workspaces) */
@Field
@observable
published: boolean;
/** A list of valid redirect URIs for this app */
@Field
@observable
redirectUris: string[];
@Relation(() => User)
createdBy: User;
createdById: string;
}
export default OAuthClient;
+3 -2
View File
@@ -12,8 +12,9 @@ function Authorize() {
<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" placeholder="Response Type" />
<input type="text" name="scope" placeholder="Scope" />
<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>
+73
View File
@@ -0,0 +1,73 @@
import { observer } from "mobx-react";
import { CodeIcon } from "outline-icons";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import OAuthClient from "~/models/OAuthClient";
import { Action } from "~/components/Actions";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import PaginatedList from "~/components/PaginatedList";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import { createOAuthClient } from "~/actions/definitions/oauthClients";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import OAuthClientListItem from "./components/OAuthClientListItem";
function Applications() {
const team = useCurrentTeam();
const { t } = useTranslation();
const { oauthClients } = useStores();
const can = usePolicy(team);
const context = useActionContext();
return (
<Scene
title={t("Applications")}
icon={<CodeIcon />}
actions={
<>
{can.createApiKey && (
<Action>
<Button
type="submit"
value={`${t("New App")}…`}
action={createOAuthClient}
context={context}
/>
</Action>
)}
</>
}
>
<Heading>{t("Applications")}</Heading>
<Text as="p" type="secondary">
<Trans
defaults="OAuth apps can be used to authenticate with the API and programatically control
your workspace's data. For more details see the <em>developer documentation</em>."
components={{
em: (
<a
href="https://www.getoutline.com/developers"
target="_blank"
rel="noreferrer"
/>
),
}}
/>
</Text>
<PaginatedList
fetch={oauthClients.fetchPage}
items={oauthClients.orderedData}
heading={<h2>{t("All")}</h2>}
renderItem={(oauthClient: OAuthClient) => (
<OAuthClientListItem key={oauthClient.id} oauthClient={oauthClient} />
)}
/>
</Scene>
);
}
export default observer(Applications);
@@ -0,0 +1,80 @@
import { observer } from "mobx-react";
import { CopyIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import OAuthClient from "~/models/OAuthClient";
import Button from "~/components/Button";
import CopyToClipboard from "~/components/CopyToClipboard";
import Flex from "~/components/Flex";
import ListItem from "~/components/List/Item";
import Text from "~/components/Text";
import Time from "~/components/Time";
import useCurrentUser from "~/hooks/useCurrentUser";
type Props = {
oauthClient: OAuthClient;
};
const OAuthClientListItem = ({ oauthClient }: Props) => {
const { t } = useTranslation();
const user = useCurrentUser();
const subtitle = (
<>
<Text type="tertiary">
{t(`Created`)} <Time dateTime={oauthClient.createdAt} addSuffix />{" "}
{oauthClient.createdById === user.id
? ""
: t(`by {{ name }}`, { name: user.name })}
</Text>
</>
);
const [copied, setCopied] = React.useState<boolean>(false);
const copyTimeoutIdRef = React.useRef<ReturnType<typeof setTimeout>>();
const handleCopy = React.useCallback(() => {
if (copyTimeoutIdRef.current) {
clearTimeout(copyTimeoutIdRef.current);
}
setCopied(true);
copyTimeoutIdRef.current = setTimeout(() => {
setCopied(false);
}, 3000);
toast.message(t("Client secret copied to clipboard"));
}, [t]);
return (
<ListItem
key={oauthClient.id}
title={oauthClient.name}
subtitle={subtitle}
actions={
<Flex align="center" gap={8}>
{oauthClient.clientSecret && handleCopy && (
<CopyToClipboard
text={oauthClient.clientSecret}
onCopy={handleCopy}
>
<Button type="button" icon={<CopyIcon />} neutral borderOnHover>
{copied ? t("Copied") : t("Copy")}
</Button>
</CopyToClipboard>
)}
<Text
type="tertiary"
size="xsmall"
style={{ marginRight: 8 }}
monospace
>
***
</Text>
{/* <OAuthClientMenu oauthClient={oauthClient} /> */}
</Flex>
}
/>
);
};
export default observer(OAuthClientListItem);
+16
View File
@@ -0,0 +1,16 @@
import OAuthClient from "~/models/OAuthClient";
import RootStore from "./RootStore";
import Store, { RPCAction } from "./base/Store";
export default class OAuthClientsStore extends Store<OAuthClient> {
actions = [
RPCAction.List,
RPCAction.Create,
RPCAction.Update,
RPCAction.Delete,
];
constructor(rootStore: RootStore) {
super(rootStore, OAuthClient);
}
}
+3
View File
@@ -18,6 +18,7 @@ import ImportsStore from "./ImportsStore";
import IntegrationsStore from "./IntegrationsStore";
import MembershipsStore from "./MembershipsStore";
import NotificationsStore from "./NotificationsStore";
import OAuthClientsStore from "./OAuthClientsStore";
import PinsStore from "./PinsStore";
import PoliciesStore from "./PoliciesStore";
import RevisionsStore from "./RevisionsStore";
@@ -48,6 +49,7 @@ export default class RootStore {
integrations: IntegrationsStore;
memberships: MembershipsStore;
notifications: NotificationsStore;
oauthClients: OAuthClientsStore;
presence: DocumentPresenceStore;
pins: PinsStore;
policies: PoliciesStore;
@@ -78,6 +80,7 @@ export default class RootStore {
this.registerStore(IntegrationsStore);
this.registerStore(MembershipsStore);
this.registerStore(NotificationsStore);
this.registerStore(OAuthClientsStore);
this.registerStore(PinsStore);
this.registerStore(PoliciesStore);
this.registerStore(RevisionsStore);
+37
View File
@@ -0,0 +1,37 @@
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;
+35
View File
@@ -0,0 +1,35 @@
import { BaseSchema } from "@server/routes/api/schema";
import { z } from "zod";
export const OAuthClientsCreateSchema = BaseSchema.extend({
body: z.object({
/** OAuth client name */
name: z.string(),
/** OAuth client description */
description: z.string().nullish(),
/** OAuth client developer name */
developerName: z.string().nullish(),
/** OAuth client developer url */
developerUrl: z.string().nullish(),
/** OAuth client avatar url */
avatarUrl: z.string().nullish(),
/** OAuth client redirect uri */
redirectUris: z
.array(z.string().url())
.min(1, { message: "At least one redirect uri is required" })
.max(10, { message: "A maximum of 10 redirect uris are allowed" })
.refine((uris) => uris.every((uri) => uri.length <= 255), {
message: "Redirect uri must be less than 255 characters",
}),
/** OAuth client published */
published: z.boolean().default(false),
}),
});
export type OAuthClientsCreateReq = z.infer<typeof OAuthClientsCreateSchema>;
+5
View File
@@ -1,4 +1,5 @@
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";
@@ -24,4 +25,8 @@ PluginManager.add([
app: oauth,
},
},
{
type: Hook.API,
value: oauthClients,
},
]);
+21 -13
View File
@@ -1,4 +1,18 @@
import { ArrayNotEmpty, ArrayUnique, IsUrl } from "class-validator";
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,
ArrayNotEmpty,
ArrayUnique,
IsUrl,
} from "class-validator";
import rs from "randomstring";
import { InferAttributes, InferCreationAttributes } from "sequelize";
import {
@@ -11,14 +25,6 @@ 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",
@@ -29,7 +35,7 @@ class OAuthClient extends ParanoidModel<
InferAttributes<OAuthClient>,
Partial<InferCreationAttributes<OAuthClient>>
> {
public static secretPrefix = "ol_secret_";
public static clientSecretPrefix = "ol_sk_";
@NotContainsUrl
@Length({ max: OAuthClientValidation.maxNameLength })
@@ -72,7 +78,8 @@ class OAuthClient extends ParanoidModel<
@ArrayNotEmpty()
@ArrayUnique()
@Length({ max: OAuthClientValidation.maxRedirectUriLength })
@ArrayMinSize(1)
@ArrayMaxSize(10)
@IsUrl(
{
require_tld: false,
@@ -106,10 +113,11 @@ class OAuthClient extends ParanoidModel<
@BeforeCreate
public static async generateCredentials(model: OAuthClient) {
model.clientId = rs.generate({
length: 32,
length: 20,
charset: "alphanumeric",
capitalization: "lowercase",
});
model.clientSecret = `${OAuthClient.secretPrefix}${rs.generate(32)}`;
model.clientSecret = `${OAuthClient.clientSecretPrefix}${rs.generate(32)}`;
}
}
+9 -2
View File
@@ -1,8 +1,8 @@
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 auth from "@server/middlewares/authentication";
import { OAuthInterface } from "./interface";
const app = new Koa();
@@ -17,7 +17,14 @@ router.post("/authorize", auth(), async (ctx) => {
const request = new OAuth2Server.Request(ctx.request);
const response = new OAuth2Server.Response(ctx.response);
const authorizationCode = await oauth.authorize(request, response);
const authorizationCode = await oauth.authorize(request, response, {
authenticateHandler: {
handle: async () => {
const { user } = ctx.state.auth;
return user;
},
},
});
ctx.body = { code: authorizationCode };
});
@@ -0,0 +1,18 @@
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,
};
}