mirror of
https://github.com/outline/outline.git
synced 2026-12-01 17:32:49 +03:00
feat: Extract a chat provider interface from the Slack plugin
This commit is contained in:
40 files changed
+3187
-974
No files matched your search
@@ -3,6 +3,7 @@ import * as React from "react";
|
||||
import { useTranslation, Trans } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import { ChatUtils } from "@shared/utils/ChatUtils";
|
||||
import type Collection from "~/models/Collection";
|
||||
import type Integration from "~/models/Integration";
|
||||
import { ConnectedButton } from "~/scenes/Settings/components/ConnectedButton";
|
||||
@@ -20,7 +21,6 @@ import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useQuery from "~/hooks/useQuery";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { SlackUtils } from "../shared/SlackUtils";
|
||||
import SlackIcon from "./Icon";
|
||||
import SlackButton from "./components/SlackButton";
|
||||
import SlackListItem from "./components/SlackListItem";
|
||||
@@ -103,7 +103,7 @@ function Slack() {
|
||||
<SlackButton
|
||||
type={IntegrationType.LinkedAccount}
|
||||
state={{ teamId: team.id }}
|
||||
redirectUri={SlackUtils.connectUrl()}
|
||||
redirectUri={ChatUtils.connectUrl(IntegrationService.Slack)}
|
||||
label={t("Connect")}
|
||||
/>
|
||||
)}
|
||||
@@ -142,7 +142,7 @@ function Slack() {
|
||||
type={IntegrationType.Command}
|
||||
scopes={["commands", "links:read", "links:write"]}
|
||||
state={{ teamId: team.id }}
|
||||
redirectUri={SlackUtils.connectUrl()}
|
||||
redirectUri={ChatUtils.connectUrl(IntegrationService.Slack)}
|
||||
icon={<SlackIcon />}
|
||||
/>
|
||||
)}
|
||||
@@ -185,7 +185,9 @@ function Slack() {
|
||||
teamId: team.id,
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
redirectUri={SlackUtils.connectUrl()}
|
||||
redirectUri={ChatUtils.connectUrl(
|
||||
IntegrationService.Slack
|
||||
)}
|
||||
label={t("Connect")}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { IntegrationType } from "@shared/types";
|
||||
import { IntegrationService, type IntegrationType } from "@shared/types";
|
||||
import { ChatUtils } from "@shared/utils/ChatUtils";
|
||||
import Button from "~/components/Button";
|
||||
import { generateOAuthStateNonce } from "~/utils/oauth";
|
||||
import { redirectTo } from "~/utils/urls";
|
||||
import { SlackOAuthNonceCookie, SlackUtils } from "../../shared/SlackUtils";
|
||||
import { SlackUtils } from "../../shared/SlackUtils";
|
||||
|
||||
type Props = {
|
||||
type: IntegrationType;
|
||||
@@ -26,9 +27,11 @@ function SlackButton({
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleClick = () => {
|
||||
const nonce = generateOAuthStateNonce(SlackOAuthNonceCookie);
|
||||
const nonce = generateOAuthStateNonce(
|
||||
ChatUtils.nonceCookie(IntegrationService.Slack)
|
||||
);
|
||||
const { teamId, ...rest } = stateData;
|
||||
const state = SlackUtils.createState(teamId, type, { nonce, ...rest });
|
||||
const state = ChatUtils.createState(teamId, type, { nonce, ...rest });
|
||||
redirectTo(SlackUtils.authUrl(state, scopes, redirectUri));
|
||||
};
|
||||
|
||||
|
||||
+53
-2
@@ -1,7 +1,9 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { randomString } from "@shared/random";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import type { Document, User } from "@server/models";
|
||||
import { IntegrationAuthentication, SearchQuery } from "@server/models";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
@@ -9,9 +11,10 @@ import {
|
||||
buildTeam,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { server as mswServer } from "@server/test/msw";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
import env from "../env";
|
||||
import * as Slack from "../slack";
|
||||
import env from "./env";
|
||||
import * as Slack from "./slack";
|
||||
|
||||
const server = getTestServer();
|
||||
|
||||
@@ -43,6 +46,10 @@ describe("#hooks.unfurl", () => {
|
||||
type,
|
||||
authenticationId: authentication.id,
|
||||
createdAt,
|
||||
// A real install stores the Slack workspace that it was installed in.
|
||||
settings: {
|
||||
serviceTeamId: user.team.authenticationProviders[0].providerId,
|
||||
},
|
||||
});
|
||||
return { integration, authentication };
|
||||
};
|
||||
@@ -516,3 +523,47 @@ describe("#hooks.interactive", () => {
|
||||
expect(res.status).toEqual(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("#hooks.interactive block actions", () => {
|
||||
it("should post the answer through the response URL", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const searchQuery = await SearchQuery.create({
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
source: SearchQuerySource.Slack,
|
||||
query: "what is this?",
|
||||
answer: "It is **this**",
|
||||
results: 1,
|
||||
});
|
||||
const responseUrl = "https://hooks.slack.com/actions/test";
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
mswServer.use(
|
||||
http.post(responseUrl, async ({ request }) => {
|
||||
bodies.push((await request.json()) as Record<string, unknown>);
|
||||
return HttpResponse.text("ok");
|
||||
})
|
||||
);
|
||||
|
||||
const payload = JSON.stringify({
|
||||
type: "block_actions",
|
||||
token: env.SLACK_VERIFICATION_TOKEN,
|
||||
user: { id: user.authentications[0].providerId },
|
||||
team: { id: team.authenticationProviders[0].providerId },
|
||||
actions: [{ action_id: "post_answer_to_channel", value: searchQuery.id }],
|
||||
response_url: responseUrl,
|
||||
});
|
||||
const res = await server.post("/api/hooks.interactive", {
|
||||
body: { payload },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(bodies).toHaveLength(2);
|
||||
expect(bodies[0]).toMatchObject({
|
||||
response_type: "in_channel",
|
||||
replace_original: false,
|
||||
text: "It is *this*",
|
||||
});
|
||||
expect(bodies[1]).toEqual({ delete_original: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import { IntegrationService, type IntegrationType } from "@shared/types";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { BaseChatProvider } from "@server/chat/BaseChatProvider";
|
||||
import type {
|
||||
ChatCapabilities,
|
||||
ChatEvent,
|
||||
ChatInstall,
|
||||
ChatMessage,
|
||||
ChatRequest,
|
||||
ChatResult,
|
||||
ChatVisibility,
|
||||
} from "@server/chat/types";
|
||||
import {
|
||||
AuthenticationError,
|
||||
InvalidRequestError,
|
||||
ValidationError,
|
||||
} from "@server/errors";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { validateRequest } from "@server/middlewares/validate";
|
||||
import type { Integration } from "@server/models";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import fetch from "@server/utils/fetch";
|
||||
import env from "./env";
|
||||
import * as T from "./schema";
|
||||
import { SlackMessageHelper } from "./SlackMessageHelper";
|
||||
import * as Slack from "./slack";
|
||||
|
||||
/** The data needed to reply to a Slack event. */
|
||||
export interface SlackReplyTarget {
|
||||
/** The response URL sent with commands and interactions. */
|
||||
responseUrl?: string;
|
||||
/** True for Block Kit actions, which ignore the HTTP response body. */
|
||||
isBlockAction?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects Slack to the shared chat logic.
|
||||
*/
|
||||
export class SlackChatProvider extends BaseChatProvider<SlackReplyTarget> {
|
||||
public readonly service = IntegrationService.Slack;
|
||||
|
||||
public readonly name = "Slack";
|
||||
|
||||
public readonly searchSource = SearchQuerySource.Slack;
|
||||
|
||||
public readonly authProviderName = "slack";
|
||||
|
||||
public readonly capabilities: ChatCapabilities = {
|
||||
messageActions: env.SLACK_MESSAGE_ACTIONS,
|
||||
};
|
||||
|
||||
public readonly webhookPaths = [
|
||||
"hooks.unfurl",
|
||||
"hooks.interactive",
|
||||
"hooks.slack",
|
||||
];
|
||||
|
||||
public async parseRequest(
|
||||
ctx: APIContext,
|
||||
path: string
|
||||
): Promise<ChatRequest<SlackReplyTarget>> {
|
||||
switch (path) {
|
||||
case "hooks.unfurl":
|
||||
return this.parseUnfurl(ctx);
|
||||
case "hooks.interactive":
|
||||
return this.parseInteractive(ctx);
|
||||
case "hooks.slack":
|
||||
return this.parseCommand(ctx);
|
||||
default:
|
||||
throw InvalidRequestError(`Unknown webhook path ${path}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async respond(
|
||||
ctx: APIContext,
|
||||
event: ChatEvent<SlackReplyTarget>,
|
||||
result: ChatResult
|
||||
): Promise<void> {
|
||||
switch (result.type) {
|
||||
case "message":
|
||||
case "deferred":
|
||||
if (event.type === "action" && event.replyTarget.isBlockAction) {
|
||||
await this.respondToBlockAction(event.replyTarget, result.message);
|
||||
ctx.body = { ok: true };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
response_type: this.responseType(result.message.visibility),
|
||||
...(event.type === "action" ? { replace_original: false } : {}),
|
||||
...SlackMessageHelper.toPayload(result.message),
|
||||
};
|
||||
return;
|
||||
|
||||
case "linkPreviews": {
|
||||
if (event.type !== "linksShared") {
|
||||
return;
|
||||
}
|
||||
|
||||
await Slack.post("chat.unfurl", {
|
||||
token: result.authentication.token,
|
||||
channel: event.conversation.channelId,
|
||||
ts: event.messageId,
|
||||
unfurls: Object.fromEntries(
|
||||
Array.from(result.cards, ([url, card]) => [
|
||||
url,
|
||||
SlackMessageHelper.toUnfurl(card),
|
||||
])
|
||||
),
|
||||
});
|
||||
ctx.body = { success: true };
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
public async reply(
|
||||
target: SlackReplyTarget,
|
||||
message: ChatMessage
|
||||
): Promise<void> {
|
||||
if (!target.responseUrl) {
|
||||
throw InvalidRequestError("Missing response_url");
|
||||
}
|
||||
|
||||
await this.send(target.responseUrl, {
|
||||
replace_original: true,
|
||||
response_type: this.responseType(message.visibility),
|
||||
...SlackMessageHelper.toPayload(message),
|
||||
});
|
||||
}
|
||||
|
||||
public async exchangeCode(
|
||||
code: string,
|
||||
redirectUri: string
|
||||
): Promise<ChatInstall> {
|
||||
const data = T.OAuthAccessSchema.parse(
|
||||
await Slack.oauthAccess(code, redirectUri)
|
||||
);
|
||||
|
||||
return {
|
||||
token: data.access_token,
|
||||
scopes: data.scope.split(","),
|
||||
serviceTeamId: data.team_id,
|
||||
serviceUserId: data.user_id,
|
||||
channel: data.incoming_webhook
|
||||
? {
|
||||
id: data.incoming_webhook.channel_id,
|
||||
name: data.incoming_webhook.channel,
|
||||
webhookUrl: data.incoming_webhook.url,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
public async postMessage(
|
||||
integration: Integration<IntegrationType.Post>,
|
||||
message: ChatMessage
|
||||
): Promise<void> {
|
||||
await this.send(
|
||||
integration.settings.url,
|
||||
SlackMessageHelper.toPayload(message)
|
||||
);
|
||||
}
|
||||
|
||||
private async respondToBlockAction(
|
||||
target: SlackReplyTarget,
|
||||
message: ChatMessage
|
||||
) {
|
||||
if (!target.responseUrl) {
|
||||
throw InvalidRequestError("Missing response_url");
|
||||
}
|
||||
|
||||
await this.send(target.responseUrl, {
|
||||
replace_original: false,
|
||||
response_type: this.responseType(message.visibility),
|
||||
...SlackMessageHelper.toPayload(message),
|
||||
});
|
||||
|
||||
// Remove the ephemeral message so that the button cannot be used again.
|
||||
await this.send(target.responseUrl, { delete_original: true });
|
||||
}
|
||||
|
||||
private parseUnfurl(ctx: APIContext): ChatRequest<SlackReplyTarget> {
|
||||
const { body } = validateRequest(T.HooksUnfurlSchema, ctx);
|
||||
|
||||
// See URL verification handshake documentation on this page:
|
||||
// https://api.slack.com/apis/connections/events-api
|
||||
if ("challenge" in body) {
|
||||
return { type: "handshake", body: { challenge: body.challenge } };
|
||||
}
|
||||
|
||||
this.verifyToken(body.token);
|
||||
|
||||
return {
|
||||
type: "linksShared",
|
||||
installation: { serviceTeamId: body.team_id },
|
||||
actor: { serviceTeamId: body.team_id, serviceUserId: body.event.user },
|
||||
conversation: { channelId: body.event.channel },
|
||||
messageId: body.event.message_ts,
|
||||
urls: body.event.links.map((link) => link.url),
|
||||
replyTarget: {},
|
||||
};
|
||||
}
|
||||
|
||||
private parseInteractive(ctx: APIContext): ChatRequest<SlackReplyTarget> {
|
||||
const { body } = validateRequest(T.HooksInteractiveSchema, ctx);
|
||||
|
||||
// https://api.slack.com/interactivity/handling#payloads
|
||||
let parsed;
|
||||
try {
|
||||
parsed = T.InteractivePayloadSchema.parse(JSON.parse(body.payload));
|
||||
} catch (err) {
|
||||
Logger.error("Failed to parse Slack interactive payload", toError(err), {
|
||||
payload: body.payload,
|
||||
});
|
||||
throw ValidationError("Invalid payload");
|
||||
}
|
||||
|
||||
this.verifyToken(parsed.token);
|
||||
|
||||
const { user, team } = parsed;
|
||||
if (!user || !team) {
|
||||
throw ValidationError("Invalid payload");
|
||||
}
|
||||
|
||||
const blockAction = parsed.actions?.[0];
|
||||
const action =
|
||||
parsed.type === "block_actions" && blockAction?.action_id
|
||||
? SlackMessageHelper.actionFromId(blockAction.action_id)
|
||||
: "postDocument";
|
||||
const value =
|
||||
parsed.type === "block_actions" ? blockAction?.value : parsed.callback_id;
|
||||
|
||||
if (!action || !value) {
|
||||
throw InvalidRequestError("Invalid callback_id");
|
||||
}
|
||||
|
||||
return {
|
||||
type: "action",
|
||||
installation: { serviceTeamId: team.id },
|
||||
actor: { serviceTeamId: user.team_id ?? team.id, serviceUserId: user.id },
|
||||
action,
|
||||
value,
|
||||
replyTarget: {
|
||||
responseUrl: parsed.response_url,
|
||||
isBlockAction: parsed.type === "block_actions",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private parseCommand(ctx: APIContext): ChatRequest<SlackReplyTarget> {
|
||||
const { body } = validateRequest(T.HooksSlackCommandSchema, ctx);
|
||||
this.verifyToken(body.token);
|
||||
|
||||
return {
|
||||
type: "command",
|
||||
installation: { serviceTeamId: body.team_id },
|
||||
actor: { serviceTeamId: body.team_id, serviceUserId: body.user_id },
|
||||
text: body.text,
|
||||
replyTarget: { responseUrl: body.response_url },
|
||||
};
|
||||
}
|
||||
|
||||
private verifyToken(token: string) {
|
||||
if (!env.SLACK_VERIFICATION_TOKEN) {
|
||||
throw AuthenticationError(
|
||||
"SLACK_VERIFICATION_TOKEN is not present in environment"
|
||||
);
|
||||
}
|
||||
|
||||
if (!safeEqual(env.SLACK_VERIFICATION_TOKEN, token)) {
|
||||
throw AuthenticationError("Invalid token");
|
||||
}
|
||||
}
|
||||
|
||||
private responseType(visibility: ChatVisibility) {
|
||||
return visibility === "conversation" ? "in_channel" : "ephemeral";
|
||||
}
|
||||
|
||||
private async send(url: string, payload: Record<string, unknown>) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw InvalidRequestError(
|
||||
`Slack responded with status ${response.status}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { ChatMessageHelper } from "@server/chat/ChatMessageHelper";
|
||||
import { SlackMessageHelper } from "./SlackMessageHelper";
|
||||
|
||||
describe("SlackMessageHelper", () => {
|
||||
it.each([
|
||||
["a **b** c", "a *b* c"],
|
||||
[
|
||||
"[Link your account](https://a.com/b)",
|
||||
"<https://a.com/b|Link your account>",
|
||||
],
|
||||
[ChatMessageHelper.escape("a *b* [c](d)"), "a *b* [c](d)"],
|
||||
[
|
||||
ChatMessageHelper.escape("<!channel> & <https://a.com|b>"),
|
||||
"<!channel> & <https://a.com|b>",
|
||||
],
|
||||
["[a>b](https://a.com/x|y z>)", "<https://a.com/x%7Cy%20z%3E|a>b>"],
|
||||
])("toMrkdwn(%j)", (input, expected) => {
|
||||
expect(SlackMessageHelper.toMrkdwn(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
describe("toPayload", () => {
|
||||
it("should include blocks, actions and attachments", () => {
|
||||
const payload = SlackMessageHelper.toPayload({
|
||||
context: "Answer",
|
||||
text: "**Yes**",
|
||||
visibility: "ephemeral",
|
||||
cards: [
|
||||
{
|
||||
title: "Doc",
|
||||
url: "https://a.com/doc",
|
||||
text: "Summary",
|
||||
timestamp: new Date(2000),
|
||||
},
|
||||
],
|
||||
actions: [{ id: "postAnswer", label: "Post", value: "123" }],
|
||||
});
|
||||
|
||||
expect(payload.text).toEqual("*Yes*");
|
||||
expect(payload.blocks).toHaveLength(3);
|
||||
expect(payload.blocks?.[2]).toMatchObject({
|
||||
type: "actions",
|
||||
elements: [{ action_id: "post_answer_to_channel", value: "123" }],
|
||||
});
|
||||
expect(payload.attachments?.[0]).toMatchObject({
|
||||
title: "Doc",
|
||||
title_link: "https://a.com/doc",
|
||||
text: "Summary",
|
||||
ts: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("should omit empty blocks and attachments", () => {
|
||||
const payload = SlackMessageHelper.toPayload({
|
||||
text: "",
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
});
|
||||
|
||||
expect(payload.blocks).toBeUndefined();
|
||||
expect(payload.attachments).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["at the limit", "a".repeat(3001), ["a".repeat(3000), "a"]],
|
||||
[
|
||||
"at a line break",
|
||||
`${"a".repeat(2500)}\n${"b".repeat(1000)}`,
|
||||
["a".repeat(2500), "b".repeat(1000)],
|
||||
],
|
||||
[
|
||||
"before a link",
|
||||
`${"a".repeat(2990)}<https://a.com/doc|Document>`,
|
||||
["a".repeat(2990), "<https://a.com/doc|Document>"],
|
||||
],
|
||||
[
|
||||
"before an entity",
|
||||
`${"a".repeat(2997)}&b`,
|
||||
["a".repeat(2997), "&b"],
|
||||
],
|
||||
])("splitMrkdwn should split %s", (_name, input, expected) => {
|
||||
expect(SlackMessageHelper.splitMrkdwn(input, 3000)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should keep every section within the Slack limit", () => {
|
||||
const payload = SlackMessageHelper.toPayload({
|
||||
context: "c".repeat(3500),
|
||||
text: "word ".repeat(1500),
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
});
|
||||
|
||||
const blocks: {
|
||||
type: string;
|
||||
text?: { text: string };
|
||||
elements?: { text: string }[];
|
||||
}[] = JSON.parse(JSON.stringify(payload.blocks));
|
||||
const texts = blocks.map(
|
||||
(block) => block.text?.text ?? block.elements?.[0].text ?? ""
|
||||
);
|
||||
|
||||
expect(texts.every((text) => text.length <= 3000)).toBe(true);
|
||||
expect(blocks.filter((block) => block.type === "section")).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import type {
|
||||
ChatAction,
|
||||
ChatCard,
|
||||
ChatMarkdown,
|
||||
ChatMessage,
|
||||
} from "@server/chat/types";
|
||||
|
||||
/** The maximum length of a Block Kit text object. */
|
||||
const maxBlockTextLength = 3000;
|
||||
|
||||
/** The Slack action IDs for each chat action. */
|
||||
const actionIds: Record<ChatAction["id"], string> = {
|
||||
postDocument: "post",
|
||||
postAnswer: "post_answer_to_channel",
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts neutral chat messages to Slack message payloads.
|
||||
*/
|
||||
export class SlackMessageHelper {
|
||||
/**
|
||||
* Returns the chat action for a Slack block action ID.
|
||||
*
|
||||
* @param actionId the Slack action ID.
|
||||
* @returns the chat action, if known.
|
||||
*/
|
||||
public static actionFromId(actionId: string): ChatAction["id"] | undefined {
|
||||
switch (actionId) {
|
||||
case actionIds.postDocument:
|
||||
return "postDocument";
|
||||
case actionIds.postAnswer:
|
||||
return "postAnswer";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a message to a Slack message payload.
|
||||
*
|
||||
* @param message the message.
|
||||
* @returns the Slack payload.
|
||||
*/
|
||||
public static toPayload(message: ChatMessage) {
|
||||
const text = this.toMrkdwn(message.text);
|
||||
const blocks = [];
|
||||
|
||||
if (message.context) {
|
||||
blocks.push({
|
||||
type: "context",
|
||||
elements: [
|
||||
{
|
||||
type: "plain_text",
|
||||
text: this.truncate(message.context, maxBlockTextLength),
|
||||
emoji: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
for (const chunk of this.splitMrkdwn(text, maxBlockTextLength)) {
|
||||
blocks.push({ type: "section", text: { type: "mrkdwn", text: chunk } });
|
||||
}
|
||||
if (message.actions?.length) {
|
||||
blocks.push({
|
||||
type: "actions",
|
||||
elements: message.actions.map((action) => ({
|
||||
type: "button",
|
||||
text: { type: "plain_text", text: action.label },
|
||||
action_id: actionIds[action.id],
|
||||
value: action.value,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
text: text || message.context || "",
|
||||
blocks: blocks.length ? blocks : undefined,
|
||||
attachments: message.cards.length
|
||||
? message.cards.map((card) => this.toAttachment(card))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a card to a Slack link unfurl.
|
||||
*
|
||||
* @param card the card.
|
||||
* @returns the Slack unfurl.
|
||||
*/
|
||||
public static toUnfurl(card: ChatCard) {
|
||||
return {
|
||||
title: card.title,
|
||||
text: card.text ? this.toMrkdwn(card.text) : undefined,
|
||||
color: card.color,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Markdown to Slack mrkdwn. Supports bold, links and backslash
|
||||
* escapes; other text is escaped so that it cannot form Slack controls.
|
||||
*
|
||||
* @param markdown the Markdown.
|
||||
* @returns the Slack mrkdwn.
|
||||
*/
|
||||
public static toMrkdwn(markdown: ChatMarkdown): string {
|
||||
let output = "";
|
||||
let index = 0;
|
||||
|
||||
while (index < markdown.length) {
|
||||
const char = markdown[index];
|
||||
|
||||
if (char === "\\" && index + 1 < markdown.length) {
|
||||
output += this.escapeText(markdown[index + 1]);
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (markdown.startsWith("**", index)) {
|
||||
output += "*";
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "[") {
|
||||
const link = this.parseLink(markdown, index);
|
||||
if (link) {
|
||||
output += `<${this.escapeUrl(link.url)}|${this.toMrkdwn(link.text)}>`;
|
||||
index = link.end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
output += this.escapeText(char);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits Slack mrkdwn into parts no longer than the limit. Parts end at a
|
||||
* line break or space where possible, and never inside a link or entity.
|
||||
*
|
||||
* @param text the Slack mrkdwn.
|
||||
* @param limit the maximum length of each part.
|
||||
* @returns the parts.
|
||||
*/
|
||||
public static splitMrkdwn(text: string, limit: number): string[] {
|
||||
const parts: string[] = [];
|
||||
let remaining = text;
|
||||
|
||||
while (remaining.length > limit) {
|
||||
let index = remaining.lastIndexOf("\n", limit);
|
||||
if (index < limit / 2) {
|
||||
index = remaining.lastIndexOf(" ", limit);
|
||||
}
|
||||
if (index < limit / 2) {
|
||||
index = limit;
|
||||
}
|
||||
|
||||
// Do not split inside a <link|label> or an &entity;.
|
||||
const linkStart = remaining.lastIndexOf("<", index - 1);
|
||||
if (linkStart > remaining.lastIndexOf(">", index - 1)) {
|
||||
index = linkStart;
|
||||
}
|
||||
const entityStart = remaining.lastIndexOf("&", index - 1);
|
||||
if (
|
||||
entityStart > remaining.lastIndexOf(";", index - 1) &&
|
||||
index - entityStart < 8
|
||||
) {
|
||||
index = entityStart;
|
||||
}
|
||||
if (index <= 0) {
|
||||
index = limit;
|
||||
}
|
||||
|
||||
const part = remaining.slice(0, index).trimEnd();
|
||||
if (part) {
|
||||
parts.push(part);
|
||||
}
|
||||
remaining = remaining.slice(index).trimStart();
|
||||
}
|
||||
|
||||
if (remaining) {
|
||||
parts.push(remaining);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static truncate(text: string, limit: number) {
|
||||
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
||||
}
|
||||
|
||||
private static toAttachment(card: ChatCard) {
|
||||
const postDocument = card.actions?.find(
|
||||
(action) => action.id === "postDocument"
|
||||
);
|
||||
|
||||
return {
|
||||
color: card.color,
|
||||
title: card.title,
|
||||
title_link: card.url,
|
||||
footer: card.footer,
|
||||
callback_id: postDocument?.value,
|
||||
text: card.text ? this.toMrkdwn(card.text) : undefined,
|
||||
ts: card.timestamp
|
||||
? Math.round(card.timestamp.getTime() / 1000)
|
||||
: undefined,
|
||||
actions: card.actions?.map((action) => ({
|
||||
name: actionIds[action.id],
|
||||
text: action.label,
|
||||
type: "button",
|
||||
value: action.value,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private static parseLink(markdown: string, start: number) {
|
||||
let index = start + 1;
|
||||
while (index < markdown.length && markdown[index] !== "]") {
|
||||
index += markdown[index] === "\\" ? 2 : 1;
|
||||
}
|
||||
if (markdown[index] !== "]" || markdown[index + 1] !== "(") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const end = markdown.indexOf(")", index + 2);
|
||||
if (end === -1) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
text: markdown.slice(start + 1, index),
|
||||
url: markdown.slice(index + 2, end),
|
||||
end: end + 1,
|
||||
};
|
||||
}
|
||||
|
||||
private static escapeText(text: string) {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
private static escapeUrl(url: string) {
|
||||
return url.replace(/[<>| ]/g, (char) => encodeURIComponent(char));
|
||||
}
|
||||
}
|
||||
@@ -1,460 +0,0 @@
|
||||
import { t } from "i18next";
|
||||
import Router from "@koa/router";
|
||||
import { escapeRegExp } from "es-toolkit/compat";
|
||||
import queryString from "query-string";
|
||||
import { z } from "zod";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
|
||||
import { AuthenticationError, ValidationError } from "@server/errors";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import {
|
||||
UserAuthentication,
|
||||
Document,
|
||||
User,
|
||||
Team,
|
||||
SearchQuery,
|
||||
Integration,
|
||||
AuthenticationProvider,
|
||||
Comment,
|
||||
} from "@server/models";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import SearchProviderManager from "@server/utils/SearchProviderManager";
|
||||
import { can } from "@server/policies";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import { opts } from "@server/utils/i18n";
|
||||
import env from "../env";
|
||||
import { presentMessageAttachment } from "../presenters/messageAttachment";
|
||||
import { presentUserNotLinkedBlocks } from "../presenters/userNotLinkedBlocks";
|
||||
import * as Slack from "../slack";
|
||||
import * as T from "./schema";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
// triggered by a user posting a getoutline.com link in Slack
|
||||
router.post(
|
||||
"hooks.unfurl",
|
||||
validate(T.HooksUnfurlSchema),
|
||||
async (ctx: APIContext<T.HooksUnfurlReq>) => {
|
||||
// See URL verification handshake documentation on this page:
|
||||
// https://api.slack.com/apis/connections/events-api
|
||||
if ("challenge" in ctx.input.body) {
|
||||
ctx.body = {
|
||||
challenge: ctx.input.body.challenge,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const { token, team_id, event } = ctx.input.body;
|
||||
verifySlackToken(token);
|
||||
|
||||
const user = await findUserForRequest(team_id, event.user);
|
||||
if (!user) {
|
||||
Logger.debug("plugins", "No user found for Slack user ID", {
|
||||
providerId: event.user,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const integration = await Integration.scope("withAuthentication").findOne({
|
||||
where: {
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Command,
|
||||
teamId: user.teamId,
|
||||
},
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
if (!integration) {
|
||||
Logger.debug("plugins", "No Slack command integration found for team", {
|
||||
teamId: user.teamId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// get content for unfurled links
|
||||
const unfurls: Record<
|
||||
string,
|
||||
{ title: string; text: string; color?: string | undefined }
|
||||
> = {};
|
||||
|
||||
for (const link of event.links) {
|
||||
const documentId = parseDocumentSlug(link.url);
|
||||
if (documentId) {
|
||||
const doc = await Document.findByPk(documentId, { userId: user.id });
|
||||
|
||||
if (doc && can(user, "read", doc)) {
|
||||
const commentId = queryString.parse(
|
||||
link.url.split("?")[1]
|
||||
)?.commentId;
|
||||
|
||||
if (commentId) {
|
||||
const comment = await Comment.findByPk(commentId as string);
|
||||
if (!comment || comment.documentId !== doc.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
unfurls[link.url] = {
|
||||
title: t("Comment by {{ author }} on “{{ title }}”", {
|
||||
author: comment.createdBy.name,
|
||||
title: doc.title,
|
||||
...opts(user),
|
||||
}),
|
||||
text: comment.toPlainText(),
|
||||
};
|
||||
} else {
|
||||
unfurls[link.url] = {
|
||||
title: doc.title,
|
||||
text: doc.getSummary(),
|
||||
color: doc.collection?.color ?? undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Slack.post("chat.unfurl", {
|
||||
token: integration.authentication.token,
|
||||
channel: event.channel,
|
||||
ts: event.message_ts,
|
||||
unfurls,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
// triggered by interactions with actions, dialogs, message buttons in Slack
|
||||
router.post(
|
||||
"hooks.interactive",
|
||||
validate(T.HooksInteractiveSchema),
|
||||
async (ctx: APIContext<T.HooksInteractiveReq>) => {
|
||||
const { payload } = ctx.input.body;
|
||||
let parsed;
|
||||
|
||||
try {
|
||||
// https://api.slack.com/interactivity/handling#payloads
|
||||
const data = JSON.parse(payload);
|
||||
|
||||
parsed = z
|
||||
.object({
|
||||
type: z.string(),
|
||||
callback_id: z.string(),
|
||||
token: z.string(),
|
||||
user: z.object({ id: z.string() }).optional(),
|
||||
team: z.object({ id: z.string() }).optional(),
|
||||
})
|
||||
.parse(data);
|
||||
} catch (err) {
|
||||
Logger.error("Failed to parse Slack interactive payload", toError(err), {
|
||||
payload,
|
||||
});
|
||||
throw ValidationError("Invalid payload");
|
||||
}
|
||||
|
||||
verifySlackToken(parsed.token);
|
||||
|
||||
if (!parsed.user || !parsed.team) {
|
||||
throw ValidationError("Payload must include user and team");
|
||||
}
|
||||
|
||||
const user = await findUserForRequest(parsed.team.id, parsed.user.id);
|
||||
if (!user) {
|
||||
ctx.body = {
|
||||
response_type: "ephemeral",
|
||||
replace_original: false,
|
||||
blocks: presentUserNotLinkedBlocks(
|
||||
await findTeamForRequest(parsed.team.id)
|
||||
),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const document = await Document.findByPk(parsed.callback_id, {
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
if (!document || !can(user, "read", document)) {
|
||||
ctx.body = {
|
||||
response_type: "ephemeral",
|
||||
replace_original: false,
|
||||
text: t("You do not have access to this document", opts(user)),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// respond with a public message that will be posted in the original channel
|
||||
ctx.body = {
|
||||
response_type: "in_channel",
|
||||
replace_original: false,
|
||||
attachments: [
|
||||
presentMessageAttachment(
|
||||
document,
|
||||
user.team,
|
||||
document.collection,
|
||||
document.getSummary()
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
// triggered by the /outline command in Slack
|
||||
router.post(
|
||||
"hooks.slack",
|
||||
validate(T.HooksSlackCommandSchema),
|
||||
async (ctx: APIContext<T.HooksSlackCommandReq>) => {
|
||||
const { token, team_id, user_id, text } = ctx.input.body;
|
||||
verifySlackToken(token);
|
||||
|
||||
const user = await findUserForRequest(team_id, user_id);
|
||||
|
||||
// Handle "help" command or no input
|
||||
if (text.trim() === "help" || !text.trim()) {
|
||||
ctx.body = {
|
||||
response_type: "ephemeral",
|
||||
text: t("How to use {{ command }}", {
|
||||
command: "/outline",
|
||||
...opts(user),
|
||||
}),
|
||||
attachments: [
|
||||
{
|
||||
text: t(
|
||||
"To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.",
|
||||
{
|
||||
command: `/outline keyword`,
|
||||
command2: `/outline`,
|
||||
...opts(user),
|
||||
}
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const options = {
|
||||
query: text,
|
||||
limit: 5,
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
const team = await findTeamForRequest(team_id);
|
||||
|
||||
ctx.body = {
|
||||
response_type: "ephemeral",
|
||||
blocks: presentUserNotLinkedBlocks(team),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const { results, total } =
|
||||
await SearchProviderManager.getProvider().searchForUser(user, options);
|
||||
|
||||
await SearchQuery.create({
|
||||
userId: user ? user.id : null,
|
||||
teamId: user.teamId,
|
||||
source: SearchQuerySource.Slack,
|
||||
query: text,
|
||||
results: total,
|
||||
});
|
||||
|
||||
// Map search results to the format expected by the Slack API
|
||||
if (results.length) {
|
||||
const attachments = [];
|
||||
|
||||
for (const result of results) {
|
||||
const queryIsInTitle = !!result.document.title
|
||||
.toLowerCase()
|
||||
.match(escapeRegExp(text.toLowerCase()));
|
||||
attachments.push(
|
||||
presentMessageAttachment(
|
||||
result.document,
|
||||
user.team,
|
||||
result.document.collection,
|
||||
queryIsInTitle ? undefined : result.context,
|
||||
env.SLACK_MESSAGE_ACTIONS
|
||||
? [
|
||||
{
|
||||
name: "post",
|
||||
text: t("Post to Channel", opts(user)),
|
||||
type: "button",
|
||||
value: result.document.id,
|
||||
},
|
||||
]
|
||||
: undefined
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
text: t("This is what we found for “{{ term }}”", {
|
||||
...opts(user),
|
||||
term: text,
|
||||
}),
|
||||
attachments,
|
||||
};
|
||||
} else {
|
||||
ctx.body = {
|
||||
text: t("No results for “{{ term }}”", {
|
||||
...opts(user),
|
||||
term: text,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
function verifySlackToken(token: string) {
|
||||
if (!env.SLACK_VERIFICATION_TOKEN) {
|
||||
throw AuthenticationError(
|
||||
"SLACK_VERIFICATION_TOKEN is not present in environment"
|
||||
);
|
||||
}
|
||||
|
||||
if (!safeEqual(env.SLACK_VERIFICATION_TOKEN, token)) {
|
||||
throw AuthenticationError("Invalid token");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a matching team for the given Slack team ID
|
||||
*
|
||||
* @param serviceTeamId The Slack team ID
|
||||
* @returns A promise resolving to a matching team, if found
|
||||
*/
|
||||
async function findTeamForRequest(
|
||||
serviceTeamId: string
|
||||
): Promise<Team | undefined> {
|
||||
const authenticationProvider = await AuthenticationProvider.findOne({
|
||||
where: {
|
||||
name: "slack",
|
||||
providerId: serviceTeamId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
required: true,
|
||||
model: Team,
|
||||
as: "team",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (authenticationProvider) {
|
||||
return authenticationProvider.team;
|
||||
}
|
||||
|
||||
const integration = await Integration.findOne({
|
||||
where: {
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
settings: {
|
||||
slack: {
|
||||
serviceTeamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: Team,
|
||||
as: "team",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (integration) {
|
||||
return integration.team;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a matching user for the given Slack team and user ID
|
||||
*
|
||||
* @param serviceTeamId The Slack team ID
|
||||
* @param serviceUserId The Slack user ID
|
||||
* @returns A promise resolving to a matching user, if found
|
||||
*/
|
||||
async function findUserForRequest(
|
||||
serviceTeamId: string,
|
||||
serviceUserId: string
|
||||
): Promise<User | undefined> {
|
||||
// Prefer explicit linked account
|
||||
const integration = await Integration.findOne({
|
||||
where: {
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
settings: {
|
||||
slack: {
|
||||
serviceTeamId,
|
||||
serviceUserId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
as: "user",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
model: Team,
|
||||
as: "team",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
if (integration) {
|
||||
integration.user.team = integration.team;
|
||||
return integration.user;
|
||||
}
|
||||
|
||||
// Fallback to authentication provider if the user has Slack sign-in.
|
||||
// Scoped via AuthenticationProvider to the matching Slack workspace so a
|
||||
// colliding providerId from another team/provider cannot resolve.
|
||||
const authentication = await UserAuthentication.findOne({
|
||||
where: {
|
||||
providerId: serviceUserId,
|
||||
},
|
||||
order: [["createdAt", "DESC"]],
|
||||
include: [
|
||||
{
|
||||
model: AuthenticationProvider,
|
||||
as: "authenticationProvider",
|
||||
required: true,
|
||||
where: {
|
||||
name: "slack",
|
||||
providerId: serviceTeamId,
|
||||
},
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "user",
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: Team,
|
||||
as: "team",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (authentication?.user) {
|
||||
return authentication.user;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
export default router;
|
||||
@@ -1,45 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const HooksUnfurlSchema = z.object({
|
||||
body: z
|
||||
.object({
|
||||
challenge: z.string(),
|
||||
})
|
||||
.or(
|
||||
z.object({
|
||||
token: z.string(),
|
||||
team_id: z.string(),
|
||||
event: z.object({
|
||||
channel: z.string(),
|
||||
message_ts: z.string(),
|
||||
links: z.array(
|
||||
z.object({
|
||||
url: z.string(),
|
||||
})
|
||||
),
|
||||
user: z.string(),
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type HooksUnfurlReq = z.infer<typeof HooksUnfurlSchema>;
|
||||
|
||||
export const HooksSlackCommandSchema = z.object({
|
||||
body: z.object({
|
||||
token: z.string(),
|
||||
team_id: z.string(),
|
||||
user_id: z.string(),
|
||||
text: z.string().prefault(""),
|
||||
}),
|
||||
});
|
||||
|
||||
export type HooksSlackCommandReq = z.infer<typeof HooksSlackCommandSchema>;
|
||||
|
||||
export const HooksInteractiveSchema = z.object({
|
||||
body: z.object({
|
||||
payload: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type HooksInteractiveReq = z.infer<typeof HooksInteractiveSchema>;
|
||||
@@ -4,23 +4,10 @@ import Router from "@koa/router";
|
||||
import type { Profile } from "passport";
|
||||
import { Strategy as SlackStrategy } from "passport-slack-oauth2";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import accountProvisioner from "@server/commands/accountProvisioner";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import apexAuthRedirect from "@server/middlewares/apexAuthRedirect";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import passportMiddleware from "@server/middlewares/passport";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import type { User } from "@server/models";
|
||||
import {
|
||||
IntegrationAuthentication,
|
||||
Integration,
|
||||
Collection,
|
||||
} from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext, AuthenticationResult } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import type { AuthenticationResult } from "@server/types";
|
||||
import {
|
||||
getClientFromOAuthState,
|
||||
getTeamFromContext,
|
||||
@@ -31,12 +18,7 @@ import {
|
||||
} from "@server/utils/passport";
|
||||
import { parseEmail } from "@shared/utils/email";
|
||||
import env from "../env";
|
||||
import * as Slack from "../slack";
|
||||
import * as T from "./schema";
|
||||
import {
|
||||
SlackUtils,
|
||||
SlackOAuthNonceCookie,
|
||||
} from "plugins/slack/shared/SlackUtils";
|
||||
import { SlackUtils } from "plugins/slack/shared/SlackUtils";
|
||||
import { createContext } from "@server/context";
|
||||
|
||||
type SlackProfile = Profile & {
|
||||
@@ -142,143 +124,6 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) {
|
||||
|
||||
router.get("slack", startOAuthFlow, passport.authenticate(providerName));
|
||||
router.get("slack.callback", passportMiddleware(providerName));
|
||||
|
||||
router.get(
|
||||
"slack.post",
|
||||
auth({ optional: true }),
|
||||
validate(T.SlackPostSchema),
|
||||
apexAuthRedirect<T.SlackPostReq>({
|
||||
getTeamId: (ctx) => SlackUtils.parseState(ctx.input.query.state)?.teamId,
|
||||
getRedirectPath: (ctx, team) =>
|
||||
SlackUtils.connectUrl({
|
||||
baseUrl: team.url,
|
||||
params: ctx.request.querystring,
|
||||
}),
|
||||
getErrorPath: () => SlackUtils.errorUrl("unauthenticated"),
|
||||
}),
|
||||
async (ctx: APIContext<T.SlackPostReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(SlackUtils.errorUrl(error));
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedState = SlackUtils.parseState(state);
|
||||
if (!parsedState) {
|
||||
throw ValidationError("Invalid state");
|
||||
}
|
||||
|
||||
verifyOAuthStateNonce(ctx, SlackOAuthNonceCookie, parsedState.nonce);
|
||||
|
||||
const { collectionId, type } = parsedState;
|
||||
|
||||
switch (type) {
|
||||
case IntegrationType.Post: {
|
||||
if (!collectionId) {
|
||||
throw ValidationError("collectionId is required");
|
||||
}
|
||||
const collection = await Collection.findByPk(collectionId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "read", collection);
|
||||
authorize(user, "update", user.team);
|
||||
|
||||
// validation middleware ensures that code is non-null at this point
|
||||
const data = await Slack.oauthAccess(code!, SlackUtils.connectUrl());
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: IntegrationService.Slack,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: data.access_token,
|
||||
scopes: data.scope.split(","),
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Integration.create<Integration<IntegrationType.Post>>(
|
||||
{
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
collectionId,
|
||||
events: ["documents.update", "documents.publish"],
|
||||
settings: {
|
||||
url: data.incoming_webhook.url,
|
||||
channel: data.incoming_webhook.channel,
|
||||
channelId: data.incoming_webhook.channel_id,
|
||||
},
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case IntegrationType.Command: {
|
||||
authorize(user, "update", user.team);
|
||||
|
||||
// validation middleware ensures that code is non-null at this point
|
||||
const data = await Slack.oauthAccess(code!, SlackUtils.connectUrl());
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: IntegrationService.Slack,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: data.access_token,
|
||||
scopes: data.scope.split(","),
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Integration.create<Integration<IntegrationType.Command>>(
|
||||
{
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Command,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: {
|
||||
serviceTeamId: data.team_id,
|
||||
},
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case IntegrationType.LinkedAccount: {
|
||||
// validation middleware ensures that code is non-null at this point
|
||||
const data = await Slack.oauthAccess(code!, SlackUtils.connectUrl());
|
||||
await Integration.create<Integration<IntegrationType.LinkedAccount>>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
settings: {
|
||||
slack: {
|
||||
serviceUserId: data.user_id,
|
||||
serviceTeamId: data.team_id,
|
||||
},
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw ValidationError("Invalid integration type");
|
||||
}
|
||||
|
||||
ctx.redirect(SlackUtils.url);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export default router;
|
||||
@@ -1,9 +1,8 @@
|
||||
import { PluginManager, Hook } from "@server/utils/PluginManager";
|
||||
import config from "../plugin.json";
|
||||
import hooks from "./api/hooks";
|
||||
import router from "./auth/slack";
|
||||
import env from "./env";
|
||||
import SlackProcessor from "./processors/SlackProcessor";
|
||||
import { SlackChatProvider } from "./SlackChatProvider";
|
||||
|
||||
const enabled = !!env.SLACK_CLIENT_ID && !!env.SLACK_CLIENT_SECRET;
|
||||
|
||||
@@ -16,12 +15,8 @@ if (enabled) {
|
||||
},
|
||||
{
|
||||
...config,
|
||||
type: Hook.API,
|
||||
value: hooks,
|
||||
},
|
||||
{
|
||||
type: Hook.Processor,
|
||||
value: SlackProcessor,
|
||||
type: Hook.ChatProvider,
|
||||
value: new SlackChatProvider(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { Document, Collection, Team } from "@server/models";
|
||||
|
||||
type Action = {
|
||||
type: string;
|
||||
text: string;
|
||||
name: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export function presentMessageAttachment(
|
||||
document: Document,
|
||||
team: Team,
|
||||
collection?: Collection | null,
|
||||
context?: string,
|
||||
actions?: Action[]
|
||||
) {
|
||||
// the context contains <b> tags around search terms, we convert them here
|
||||
// to the markdown format that slack expects to receive.
|
||||
const text = context
|
||||
? context.replace(/<\/?b>/g, "*").replace(/\n/g, "")
|
||||
: document.getSummary();
|
||||
|
||||
return {
|
||||
color: collection?.color,
|
||||
title: document.displayTitle,
|
||||
title_link: `${team.url}${document.url}`,
|
||||
footer: collection?.name,
|
||||
callback_id: document.id,
|
||||
text,
|
||||
ts: document.getTimestamp(),
|
||||
actions,
|
||||
};
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { t } from "i18next";
|
||||
import type { Team } from "@server/models";
|
||||
import { opts } from "@server/utils/i18n";
|
||||
import env from "../env";
|
||||
|
||||
export function presentUserNotLinkedBlocks(team?: Team) {
|
||||
const appName = env.APP_NAME;
|
||||
|
||||
return [
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text:
|
||||
t(
|
||||
`It looks like you haven’t linked your {{ appName }} account to Slack yet`,
|
||||
{
|
||||
...opts(),
|
||||
appName,
|
||||
}
|
||||
) +
|
||||
". " +
|
||||
(team
|
||||
? `<${team.url}/settings/integrations/slack|${t(
|
||||
"Link your account",
|
||||
opts()
|
||||
)}>`
|
||||
: t(
|
||||
"Link your account in {{ appName }} settings to search from Slack",
|
||||
{
|
||||
...opts(),
|
||||
appName,
|
||||
}
|
||||
)),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { differenceInMilliseconds } from "date-fns";
|
||||
import { Op } from "sequelize";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import { Minute } from "@shared/utils/time";
|
||||
import { Document, Integration, Collection, Team } from "@server/models";
|
||||
import BaseProcessor from "@server/queues/processors/BaseProcessor";
|
||||
import type {
|
||||
DocumentEvent,
|
||||
IntegrationEvent,
|
||||
RevisionEvent,
|
||||
Event,
|
||||
} from "@server/types";
|
||||
import fetch from "@server/utils/fetch";
|
||||
import { sleep } from "@shared/utils/timers";
|
||||
import env from "../env";
|
||||
import { presentMessageAttachment } from "../presenters/messageAttachment";
|
||||
|
||||
export default class SlackProcessor extends BaseProcessor {
|
||||
static applicableEvents: Event["name"][] = [
|
||||
"documents.publish",
|
||||
"revisions.create",
|
||||
"integrations.create",
|
||||
];
|
||||
|
||||
async perform(event: Event) {
|
||||
switch (event.name) {
|
||||
case "documents.publish":
|
||||
case "revisions.create":
|
||||
// wait a few seconds to give the document summary chance to be generated
|
||||
await sleep(5000);
|
||||
return this.documentUpdated(event);
|
||||
|
||||
case "integrations.create":
|
||||
return this.integrationCreated(event);
|
||||
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
async integrationCreated(event: IntegrationEvent) {
|
||||
const integration = (await Integration.findOne({
|
||||
where: {
|
||||
id: event.modelId,
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: Collection,
|
||||
required: true,
|
||||
as: "collection",
|
||||
},
|
||||
],
|
||||
})) as Integration<IntegrationType.Post>;
|
||||
if (!integration) {
|
||||
return;
|
||||
}
|
||||
|
||||
const collection = integration.collection;
|
||||
if (!collection) {
|
||||
return;
|
||||
}
|
||||
|
||||
await fetch(integration.settings.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: `👋 Hey there! When documents are published or updated in the *${collection.name}* collection on ${env.APP_NAME} they will be posted to this channel!`,
|
||||
attachments: [
|
||||
{
|
||||
color: collection.color,
|
||||
title: collection.name,
|
||||
title_link: `${env.URL}${collection.path}`,
|
||||
text: collection.description,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async documentUpdated(event: DocumentEvent | RevisionEvent) {
|
||||
// never send notifications when batch importing documents
|
||||
if (event.name === "documents.publish" && event.data?.source === "import") {
|
||||
return;
|
||||
}
|
||||
const [document, team] = await Promise.all([
|
||||
Document.findByPk(event.documentId),
|
||||
Team.findByPk(event.teamId),
|
||||
]);
|
||||
if (!document || !team) {
|
||||
return;
|
||||
}
|
||||
|
||||
// never send notifications for draft documents
|
||||
if (!document.publishedAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the document was published less than a minute ago, don't send a
|
||||
// separate notification.
|
||||
if (
|
||||
event.name === "revisions.create" &&
|
||||
differenceInMilliseconds(document.updatedAt, document.publishedAt) <
|
||||
Minute.ms
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const integration = (await Integration.findOne({
|
||||
where: {
|
||||
teamId: document.teamId,
|
||||
collectionId: document.collectionId,
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
events: {
|
||||
[Op.contains]: [
|
||||
event.name === "revisions.create" ? "documents.update" : event.name,
|
||||
],
|
||||
},
|
||||
},
|
||||
})) as Integration<IntegrationType.Post>;
|
||||
if (!integration) {
|
||||
return;
|
||||
}
|
||||
let text = `${document.updatedBy.name} updated "${document.displayTitle}"`;
|
||||
|
||||
if (event.name === "documents.publish") {
|
||||
text = `${document.createdBy.name} published "${document.displayTitle}"`;
|
||||
}
|
||||
|
||||
await fetch(integration.settings.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text,
|
||||
attachments: [
|
||||
presentMessageAttachment(document, team, document.collection),
|
||||
],
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const HooksUnfurlSchema = z.object({
|
||||
body: z
|
||||
.object({
|
||||
challenge: z.string(),
|
||||
})
|
||||
.or(
|
||||
z.object({
|
||||
token: z.string(),
|
||||
team_id: z.string(),
|
||||
event: z.object({
|
||||
channel: z.string(),
|
||||
message_ts: z.string(),
|
||||
links: z.array(
|
||||
z.object({
|
||||
url: z.string(),
|
||||
})
|
||||
),
|
||||
user: z.string(),
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const HooksSlackCommandSchema = z.object({
|
||||
body: z.object({
|
||||
token: z.string(),
|
||||
team_id: z.string(),
|
||||
user_id: z.string(),
|
||||
response_url: z.string().optional(),
|
||||
text: z.string().prefault(""),
|
||||
}),
|
||||
});
|
||||
|
||||
export const HooksInteractiveSchema = z.object({
|
||||
body: z.object({
|
||||
payload: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
/** The JSON payload of an interactive request. */
|
||||
export const InteractivePayloadSchema = z.object({
|
||||
type: z.string(),
|
||||
token: z.string(),
|
||||
callback_id: z.string().optional(),
|
||||
user: z.object({ id: z.string(), team_id: z.string().optional() }).optional(),
|
||||
team: z.object({ id: z.string() }).optional(),
|
||||
actions: z
|
||||
.array(
|
||||
z.object({
|
||||
action_id: z.string().optional(),
|
||||
value: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
response_url: z.string().optional(),
|
||||
});
|
||||
|
||||
/** The response of the Slack oauth.access method. */
|
||||
export const OAuthAccessSchema = z.object({
|
||||
access_token: z.string(),
|
||||
scope: z.string(),
|
||||
team_id: z.string(),
|
||||
user_id: z.string(),
|
||||
incoming_webhook: z
|
||||
.object({
|
||||
url: z.string(),
|
||||
channel: z.string(),
|
||||
channel_id: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
@@ -1,49 +1,14 @@
|
||||
import env from "@shared/env";
|
||||
import type { IntegrationType } from "@shared/types";
|
||||
import { integrationSettingsPath } from "@shared/utils/routeHelpers";
|
||||
|
||||
export const SlackOAuthNonceCookie = "slackOAuthNonce";
|
||||
|
||||
export type OAuthState = {
|
||||
teamId: string;
|
||||
type: IntegrationType;
|
||||
nonce: string;
|
||||
collectionId?: string;
|
||||
};
|
||||
|
||||
export class SlackUtils {
|
||||
private static authBaseUrl = "https://slack.com/oauth/authorize";
|
||||
|
||||
/**
|
||||
* Create a state string for use in OAuth flows
|
||||
* Returns the callback URL for Slack sign in.
|
||||
*
|
||||
* @param teamId The team ID
|
||||
* @param type The integration type
|
||||
* @param data Additional data to include in the state
|
||||
* @returns A state string
|
||||
* @param options the base URL and optional query string.
|
||||
* @returns the callback URL.
|
||||
*/
|
||||
static createState(
|
||||
teamId: string,
|
||||
type: IntegrationType,
|
||||
data?: Record<string, unknown>
|
||||
) {
|
||||
return JSON.stringify({ type, teamId, ...data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a state string from an OAuth flow
|
||||
*
|
||||
* @param state The state string
|
||||
* @returns The parsed state
|
||||
*/
|
||||
static parseState(state: string): OAuthState | undefined {
|
||||
try {
|
||||
return JSON.parse(state);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
static callbackUrl(
|
||||
{ baseUrl, params }: { baseUrl: string; params?: string } = {
|
||||
baseUrl: env.URL,
|
||||
@@ -55,25 +20,14 @@ export class SlackUtils {
|
||||
: `${baseUrl}/auth/slack.callback`;
|
||||
}
|
||||
|
||||
static connectUrl(
|
||||
{ baseUrl, params }: { baseUrl: string; params?: string } = {
|
||||
baseUrl: env.URL,
|
||||
params: undefined,
|
||||
}
|
||||
) {
|
||||
return params
|
||||
? `${baseUrl}/auth/slack.post?${params}`
|
||||
: `${baseUrl}/auth/slack.post`;
|
||||
}
|
||||
|
||||
static errorUrl(err: string) {
|
||||
return integrationSettingsPath(`slack?error=${err}`);
|
||||
}
|
||||
|
||||
static get url() {
|
||||
return integrationSettingsPath("slack");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Slack OAuth authorization URL.
|
||||
*
|
||||
* @param state the OAuth state.
|
||||
* @param scopes the scopes to request.
|
||||
* @param redirectUri the URL that Slack redirects to.
|
||||
* @returns the authorization URL.
|
||||
*/
|
||||
static authUrl(
|
||||
state: string,
|
||||
scopes: string[] = [
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { ChatIntegrationService, IntegrationType } from "@shared/types";
|
||||
import type { Integration } from "@server/models";
|
||||
import type { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type {
|
||||
ChatCapabilities,
|
||||
ChatEvent,
|
||||
ChatInstall,
|
||||
ChatMessage,
|
||||
ChatRequest,
|
||||
ChatResult,
|
||||
} from "./types";
|
||||
|
||||
/**
|
||||
* Base class for chat platform adapters. A provider converts platform
|
||||
* requests to neutral events, and neutral messages to platform messages. The
|
||||
* shared logic in `ChatService` does all lookups and permission checks.
|
||||
*
|
||||
* @template TTarget the data that the provider needs to reply to an event.
|
||||
*/
|
||||
export abstract class BaseChatProvider<TTarget = unknown> {
|
||||
/** The integration service of the platform. */
|
||||
public abstract readonly service: ChatIntegrationService;
|
||||
|
||||
/** The display name of the platform. */
|
||||
public abstract readonly name: string;
|
||||
|
||||
/** The source recorded on search queries from the platform. */
|
||||
public abstract readonly searchSource: SearchQuerySource;
|
||||
|
||||
/** The features that the provider supports. */
|
||||
public abstract readonly capabilities: ChatCapabilities;
|
||||
|
||||
/** The paths under /api that receive requests from the platform. */
|
||||
public abstract readonly webhookPaths: string[];
|
||||
|
||||
/**
|
||||
* The name of the matching authentication provider, if the platform also
|
||||
* supports sign in. Used to find users that have not linked an account.
|
||||
*/
|
||||
public readonly authProviderName?: string;
|
||||
|
||||
/**
|
||||
* Verifies and parses an inbound request.
|
||||
*
|
||||
* @param ctx the request context.
|
||||
* @param path the webhook path that received the request.
|
||||
* @returns the parsed request.
|
||||
* @throws {AuthenticationError} if the request is not from the platform.
|
||||
* @throws {ValidationError} if the request is not valid.
|
||||
*/
|
||||
public abstract parseRequest(
|
||||
ctx: APIContext,
|
||||
path: string
|
||||
): Promise<ChatRequest<TTarget>>;
|
||||
|
||||
/**
|
||||
* Sends the result of an event to the platform, as the HTTP response or
|
||||
* with an API call.
|
||||
*
|
||||
* @param ctx the request context.
|
||||
* @param event the event.
|
||||
* @param result the result of the event.
|
||||
*/
|
||||
public abstract respond(
|
||||
ctx: APIContext,
|
||||
event: ChatEvent<TTarget>,
|
||||
result: ChatResult
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Sends a message after the HTTP response. Where the platform allows it, the
|
||||
* message replaces the deferred message.
|
||||
*
|
||||
* @param target the reply target of the event.
|
||||
* @param message the message to send.
|
||||
*/
|
||||
public abstract reply(target: TTarget, message: ChatMessage): Promise<void>;
|
||||
|
||||
/**
|
||||
* Exchanges an OAuth code from the install flow for an access token.
|
||||
*
|
||||
* @param code the OAuth code.
|
||||
* @param redirectUri the redirect URI used in the install flow.
|
||||
* @returns the result of the install.
|
||||
*/
|
||||
public abstract exchangeCode(
|
||||
code: string,
|
||||
redirectUri: string
|
||||
): Promise<ChatInstall>;
|
||||
|
||||
/**
|
||||
* Posts a message to the channel of a post integration.
|
||||
*
|
||||
* @param integration the post integration.
|
||||
* @param message the message to post.
|
||||
*/
|
||||
public abstract postMessage(
|
||||
integration: Integration<IntegrationType.Post>,
|
||||
message: ChatMessage
|
||||
): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { AuthenticationType, IntegrationType } from "@shared/types";
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
AuthenticationProvider,
|
||||
Integration,
|
||||
Team,
|
||||
User,
|
||||
UserAuthentication,
|
||||
} from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { BaseChatProvider } from "./BaseChatProvider";
|
||||
import type { ChatInstallationRef, ChatUserRef } from "./types";
|
||||
|
||||
/** The Outline teams connected to an installation, and the actor's contexts. */
|
||||
export interface ChatAccounts {
|
||||
/** All teams connected to the installation, oldest first. */
|
||||
teams: Team[];
|
||||
/** A context for each team in which the actor has an account. */
|
||||
contexts: APIContext[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the Outline teams and users that match chat platform accounts. One
|
||||
* chat workspace can be connected to several Outline teams, so every user
|
||||
* lookup is scoped to one team.
|
||||
*/
|
||||
export class ChatAccountHelper {
|
||||
/**
|
||||
* Finds the teams connected to an installation, and creates a context for
|
||||
* each team in which the actor has an account. Each context holds the user
|
||||
* and, if installed, the command integration of that team.
|
||||
*
|
||||
* @param ctx the context of the inbound request.
|
||||
* @param provider the chat provider.
|
||||
* @param installation the installation that received the event.
|
||||
* @param actor the user on the chat platform.
|
||||
* @returns the connected teams and the actor's contexts.
|
||||
*/
|
||||
public static async findAccounts(
|
||||
ctx: APIContext,
|
||||
provider: BaseChatProvider,
|
||||
installation: ChatInstallationRef,
|
||||
actor: ChatUserRef
|
||||
): Promise<ChatAccounts> {
|
||||
const [teams, integrations] = await Promise.all([
|
||||
this.findTeams(provider, installation),
|
||||
Integration.scope("withAuthentication").findAll({
|
||||
where: {
|
||||
service: provider.service,
|
||||
type: IntegrationType.Command,
|
||||
settings: { serviceTeamId: installation.serviceTeamId },
|
||||
},
|
||||
order: [["createdAt", "DESC"]],
|
||||
}),
|
||||
]);
|
||||
|
||||
const contexts: APIContext[] = [];
|
||||
for (const team of teams) {
|
||||
const user = await this.findUser(provider, installation, actor, team);
|
||||
if (!user) {
|
||||
continue;
|
||||
}
|
||||
|
||||
contexts.push(
|
||||
createContext({
|
||||
user,
|
||||
authType: AuthenticationType.CHAT,
|
||||
ip: ctx.context.ip,
|
||||
integration: integrations.find((i) => i.teamId === team.id),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return { teams, contexts };
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all Outline teams connected to an installation: teams that
|
||||
* installed the app, sign in with the workspace, or have linked accounts.
|
||||
*
|
||||
* @param provider the chat provider.
|
||||
* @param installation the installation that received the event.
|
||||
* @returns the teams, oldest first.
|
||||
*/
|
||||
private static async findTeams(
|
||||
provider: BaseChatProvider,
|
||||
installation: ChatInstallationRef
|
||||
): Promise<Team[]> {
|
||||
const { serviceTeamId } = installation;
|
||||
const [installs, linkedAccounts, authenticationProviders] =
|
||||
await Promise.all([
|
||||
Integration.findAll({
|
||||
attributes: ["teamId"],
|
||||
where: {
|
||||
service: provider.service,
|
||||
type: IntegrationType.Command,
|
||||
settings: { serviceTeamId },
|
||||
},
|
||||
}),
|
||||
Integration.findAll({
|
||||
attributes: ["teamId"],
|
||||
where: {
|
||||
service: provider.service,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
settings: { [provider.service]: { serviceTeamId } },
|
||||
},
|
||||
}),
|
||||
provider.authProviderName
|
||||
? AuthenticationProvider.findAll({
|
||||
attributes: ["teamId"],
|
||||
where: {
|
||||
name: provider.authProviderName,
|
||||
providerId: serviceTeamId,
|
||||
},
|
||||
})
|
||||
: [],
|
||||
]);
|
||||
|
||||
const teamIds = new Set(
|
||||
[...installs, ...linkedAccounts, ...authenticationProviders].map(
|
||||
(model) => model.teamId
|
||||
)
|
||||
);
|
||||
if (!teamIds.size) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Team.findAll({
|
||||
where: { id: Array.from(teamIds) },
|
||||
order: [["createdAt", "ASC"]],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the actor's user in one team. A linked account is used first, then
|
||||
* a sign in with the workspace of the installation.
|
||||
*
|
||||
* @param provider the chat provider.
|
||||
* @param installation the installation that received the event.
|
||||
* @param actor the user on the chat platform.
|
||||
* @param team the team to search in.
|
||||
* @returns the user with the team loaded, if found.
|
||||
*/
|
||||
private static async findUser(
|
||||
provider: BaseChatProvider,
|
||||
installation: ChatInstallationRef,
|
||||
actor: ChatUserRef,
|
||||
team: Team
|
||||
): Promise<User | undefined> {
|
||||
const integration = await Integration.findOne({
|
||||
where: {
|
||||
service: provider.service,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
teamId: team.id,
|
||||
settings: {
|
||||
[provider.service]: {
|
||||
serviceTeamId: actor.serviceTeamId,
|
||||
serviceUserId: actor.serviceUserId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
as: "user",
|
||||
required: true,
|
||||
where: { teamId: team.id },
|
||||
},
|
||||
],
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
let user = integration?.user;
|
||||
|
||||
if (!user && provider.authProviderName) {
|
||||
const authentication = await UserAuthentication.findOne({
|
||||
where: {
|
||||
providerId: actor.serviceUserId,
|
||||
},
|
||||
order: [["createdAt", "DESC"]],
|
||||
include: [
|
||||
{
|
||||
model: AuthenticationProvider,
|
||||
as: "authenticationProvider",
|
||||
required: true,
|
||||
where: {
|
||||
name: provider.authProviderName,
|
||||
providerId: installation.serviceTeamId,
|
||||
teamId: team.id,
|
||||
},
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "user",
|
||||
required: true,
|
||||
where: { teamId: team.id },
|
||||
},
|
||||
],
|
||||
});
|
||||
user = authentication?.user;
|
||||
}
|
||||
|
||||
if (user) {
|
||||
user.team = team;
|
||||
}
|
||||
return user ?? undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Document } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { ChatMarkdown } from "./types";
|
||||
|
||||
/** An answer to a question, with the documents that it came from. */
|
||||
export interface ChatAnswer {
|
||||
/** The answer, or an empty string if no answer was found. */
|
||||
answer: ChatMarkdown;
|
||||
/** The documents that the answer came from. */
|
||||
documents: Document[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers questions asked from a chat platform. Register an implementation
|
||||
* with `Hook.ChatAnswerProvider` to answer questions in place of a search.
|
||||
*/
|
||||
export interface ChatAnswerProvider {
|
||||
/**
|
||||
* Returns true if the text is a question that the provider can answer.
|
||||
*
|
||||
* @param ctx the context of the user that asked, for one team.
|
||||
* @param text the text that the user typed.
|
||||
* @returns true if the provider can answer.
|
||||
*/
|
||||
canAnswer(ctx: APIContext, text: string): boolean;
|
||||
|
||||
/**
|
||||
* Answers a question with the permissions of the user in the context.
|
||||
*
|
||||
* @param ctx the context of the user that asked, for one team.
|
||||
* @param question the question.
|
||||
* @returns the answer and its source documents.
|
||||
*/
|
||||
answer(ctx: APIContext, question: string): Promise<ChatAnswer>;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { AuthenticationType, IntegrationType } from "@shared/types";
|
||||
import { createContext } from "@server/context";
|
||||
import { Event, Integration } from "@server/models";
|
||||
import { TestChatProvider } from "@server/test/ChatHelper";
|
||||
import { buildAdmin, buildCollection, buildUser } from "@server/test/factories";
|
||||
import { ChatInstallHelper } from "./ChatInstallHelper";
|
||||
|
||||
describe("ChatInstallHelper", () => {
|
||||
it("should create a post integration and record the event with the actor", async () => {
|
||||
const user = await buildAdmin();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const ctx = createContext({ user, ip: "10.0.0.1" });
|
||||
|
||||
await ChatInstallHelper.install(
|
||||
ctx,
|
||||
new TestChatProvider(),
|
||||
{
|
||||
type: IntegrationType.Post,
|
||||
teamId: user.teamId,
|
||||
nonce: "nonce",
|
||||
collectionId: collection.id,
|
||||
},
|
||||
"code"
|
||||
);
|
||||
|
||||
const integration = await Integration.scope("withAuthentication").findOne({
|
||||
where: { collectionId: collection.id, type: IntegrationType.Post },
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
expect(integration.settings).toEqual({
|
||||
url: "https://a.com/hook",
|
||||
channel: "general",
|
||||
channelId: "C1",
|
||||
});
|
||||
expect(integration.authentication.token).toEqual("token");
|
||||
|
||||
const event = await Event.findOne({
|
||||
where: { name: "integrations.create", modelId: integration.id },
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
expect(event.actorId).toEqual(user.id);
|
||||
expect(event.ip).toEqual("10.0.0.1");
|
||||
expect(event.authType).toEqual(AuthenticationType.APP);
|
||||
});
|
||||
|
||||
it("should not create a command integration for a member", async () => {
|
||||
const user = await buildUser();
|
||||
const ctx = createContext({ user });
|
||||
|
||||
await expect(
|
||||
ChatInstallHelper.install(
|
||||
ctx,
|
||||
new TestChatProvider(),
|
||||
{ type: IntegrationType.Command, teamId: user.teamId, nonce: "nonce" },
|
||||
"code"
|
||||
)
|
||||
).rejects.toThrow();
|
||||
expect(
|
||||
await Integration.count({
|
||||
where: { teamId: user.teamId, type: IntegrationType.Command },
|
||||
})
|
||||
).toEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { Transaction } from "sequelize";
|
||||
import { IntegrationType } from "@shared/types";
|
||||
import type { ChatOAuthState } from "@shared/utils/ChatUtils";
|
||||
import { ChatUtils } from "@shared/utils/ChatUtils";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import {
|
||||
Collection,
|
||||
Integration,
|
||||
IntegrationAuthentication,
|
||||
} from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import { createContext } from "@server/context";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import type { APIContext } from "@server/types";
|
||||
import type { BaseChatProvider } from "./BaseChatProvider";
|
||||
|
||||
/**
|
||||
* Creates integrations when a chat platform is connected.
|
||||
*/
|
||||
export class ChatInstallHelper {
|
||||
/**
|
||||
* Completes an install flow and creates the matching integration. The
|
||||
* code is exchanged before the transaction starts, so that no transaction
|
||||
* stays open during the request to the platform.
|
||||
*
|
||||
* @param ctx the context of the user that started the install.
|
||||
* @param provider the chat provider.
|
||||
* @param state the parsed OAuth state.
|
||||
* @param code the OAuth code from the platform.
|
||||
* @throws {AuthorizationError} if the user cannot create the integration.
|
||||
* @throws {ValidationError} if the state or the install result is not valid.
|
||||
*/
|
||||
public static async install(
|
||||
ctx: APIContext,
|
||||
provider: BaseChatProvider,
|
||||
state: ChatOAuthState,
|
||||
code: string
|
||||
): Promise<void> {
|
||||
const { user } = ctx.context.auth;
|
||||
const redirectUri = ChatUtils.connectUrl(provider.service);
|
||||
|
||||
switch (state.type) {
|
||||
case IntegrationType.Post: {
|
||||
if (!state.collectionId) {
|
||||
throw ValidationError("collectionId is required");
|
||||
}
|
||||
const collection = await Collection.findByPk(state.collectionId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "read", collection);
|
||||
authorize(user, "update", user.team);
|
||||
|
||||
const install = await provider.exchangeCode(code, redirectUri);
|
||||
const { channel } = install;
|
||||
if (!channel) {
|
||||
throw ValidationError("No channel was selected");
|
||||
}
|
||||
|
||||
await this.transaction(ctx, async (txCtx, transaction) => {
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: provider.service,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: install.token,
|
||||
scopes: install.scopes,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Integration.createWithCtx<Integration<IntegrationType.Post>>(
|
||||
txCtx,
|
||||
{
|
||||
service: provider.service,
|
||||
type: IntegrationType.Post,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
collectionId: collection.id,
|
||||
events: ["documents.update", "documents.publish"],
|
||||
settings: {
|
||||
url: channel.webhookUrl,
|
||||
channel: channel.name,
|
||||
channelId: channel.id,
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case IntegrationType.Command: {
|
||||
authorize(user, "update", user.team);
|
||||
|
||||
const install = await provider.exchangeCode(code, redirectUri);
|
||||
|
||||
await this.transaction(ctx, async (txCtx, transaction) => {
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: provider.service,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: install.token,
|
||||
scopes: install.scopes,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Integration.createWithCtx<Integration<IntegrationType.Command>>(
|
||||
txCtx,
|
||||
{
|
||||
service: provider.service,
|
||||
type: IntegrationType.Command,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: {
|
||||
serviceTeamId: install.serviceTeamId,
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case IntegrationType.LinkedAccount: {
|
||||
const install = await provider.exchangeCode(code, redirectUri);
|
||||
|
||||
await this.transaction(ctx, (txCtx) =>
|
||||
Integration.createWithCtx<Integration<IntegrationType.LinkedAccount>>(
|
||||
txCtx,
|
||||
{
|
||||
service: provider.service,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
settings: {
|
||||
[provider.service]: {
|
||||
serviceUserId: install.serviceUserId,
|
||||
serviceTeamId: install.serviceTeamId,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
throw ValidationError("Invalid integration type");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a callback in a transaction, with a copy of the context that holds
|
||||
* the transaction.
|
||||
*
|
||||
* @param ctx the context of the request.
|
||||
* @param callback the callback to run.
|
||||
* @returns the result of the callback.
|
||||
*/
|
||||
private static transaction<T>(
|
||||
ctx: APIContext,
|
||||
callback: (txCtx: APIContext, transaction: Transaction) => Promise<T>
|
||||
): Promise<T> {
|
||||
return sequelize.transaction((transaction) =>
|
||||
callback(
|
||||
createContext({
|
||||
user: ctx.context.auth.user,
|
||||
authType: ctx.context.auth.type,
|
||||
ip: ctx.context.ip,
|
||||
transaction,
|
||||
}),
|
||||
transaction
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ChatMessageHelper } from "./ChatMessageHelper";
|
||||
|
||||
describe("ChatMessageHelper", () => {
|
||||
it.each([
|
||||
["a *b* [c](d) <e>", "a \\*b\\* \\[c\\]\\(d\\) \\<e\\>"],
|
||||
["Hello “world”", "Hello “world”"],
|
||||
])("escape(%j)", (input, expected) => {
|
||||
expect(ChatMessageHelper.escape(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"This title <b>contains</b> a\nsearch term",
|
||||
"This title **contains** asearch term",
|
||||
],
|
||||
["a*b <b>c_d</b> [e]", "a\\*b **c\\_d** \\[e\\]"],
|
||||
])("fromSearchContext(%j)", (input, expected) => {
|
||||
expect(ChatMessageHelper.fromSearchContext(input)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Collection, Document, Team } from "@server/models";
|
||||
import type { ChatAction, ChatCard, ChatMarkdown } from "./types";
|
||||
|
||||
/**
|
||||
* Helpers to build neutral chat messages.
|
||||
*/
|
||||
export class ChatMessageHelper {
|
||||
/**
|
||||
* Escapes a string so that it shows as plain text in Markdown.
|
||||
*
|
||||
* @param text the untrusted text.
|
||||
* @returns the escaped Markdown.
|
||||
*/
|
||||
public static escape(text: string): ChatMarkdown {
|
||||
return text.replace(/[\\`*_~[\]()<>|#]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a search result context, which marks matches with `<b>` tags, to
|
||||
* Markdown on one line.
|
||||
*
|
||||
* @param context the search result context.
|
||||
* @returns the context as Markdown with the matches in bold.
|
||||
*/
|
||||
public static fromSearchContext(context: string): ChatMarkdown {
|
||||
return context
|
||||
.replace(/\n/g, "")
|
||||
.split(/(<b>.*?<\/b>)/g)
|
||||
.map((part) => {
|
||||
const match = part.match(/^<b>(.*?)<\/b>$/);
|
||||
if (match) {
|
||||
return match[1] ? `**${this.escape(match[1])}**` : "";
|
||||
}
|
||||
return this.escape(part.replace(/<\/?b>/g, ""));
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a card that previews a document.
|
||||
*
|
||||
* @param document the document.
|
||||
* @param team the team of the document.
|
||||
* @param collection the collection of the document, if any.
|
||||
* @param text the body of the card, defaults to the document summary.
|
||||
* @param actions actions shown on the card.
|
||||
* @returns the card.
|
||||
*/
|
||||
public static documentCard(
|
||||
document: Document,
|
||||
team: Team,
|
||||
collection?: Collection | null,
|
||||
text?: ChatMarkdown,
|
||||
actions?: ChatAction[]
|
||||
): ChatCard {
|
||||
return {
|
||||
title: document.displayTitle,
|
||||
url: `${team.url}${document.url}`,
|
||||
text: text ?? this.escape(document.getSummary()),
|
||||
color: collection?.color ?? undefined,
|
||||
footer: collection?.name,
|
||||
timestamp: document.updatedAt,
|
||||
actions,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import Router from "@koa/router";
|
||||
import { ChatUtils } from "@shared/utils/ChatUtils";
|
||||
import { createContext } from "@server/context";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import apexAuthRedirect from "@server/middlewares/apexAuthRedirect";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { verifyOAuthStateNonce } from "@server/utils/oauth";
|
||||
import type { BaseChatProvider } from "./BaseChatProvider";
|
||||
import { ChatInstallHelper } from "./ChatInstallHelper";
|
||||
import { ChatService } from "./ChatService";
|
||||
import * as T from "./schema";
|
||||
|
||||
/**
|
||||
* Creates the routes for chat providers.
|
||||
*/
|
||||
export class ChatRouter {
|
||||
/**
|
||||
* Creates the routes, mounted under /api, that receive requests from the
|
||||
* chat platform.
|
||||
*
|
||||
* @param provider the chat provider.
|
||||
* @returns the router.
|
||||
*/
|
||||
public static createWebhookRouter<TTarget>(
|
||||
provider: BaseChatProvider<TTarget>
|
||||
): Router {
|
||||
const router = new Router();
|
||||
|
||||
for (const path of provider.webhookPaths) {
|
||||
router.post(path, async (ctx: APIContext) => {
|
||||
const request = await provider.parseRequest(ctx, path);
|
||||
|
||||
if (request.type === "handshake") {
|
||||
ctx.body = request.body;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, request);
|
||||
await provider.respond(ctx, request, result);
|
||||
});
|
||||
}
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the route, mounted under /auth, that completes the install flow.
|
||||
*
|
||||
* @param provider the chat provider.
|
||||
* @returns the router.
|
||||
*/
|
||||
public static createInstallRouter(provider: BaseChatProvider): Router {
|
||||
const router = new Router();
|
||||
const { service } = provider;
|
||||
|
||||
router.get(
|
||||
`${service}.post`,
|
||||
auth({ optional: true }),
|
||||
validate(T.ChatInstallSchema),
|
||||
apexAuthRedirect<T.ChatInstallReq>({
|
||||
getTeamId: (ctx) => ChatUtils.parseState(ctx.input.query.state)?.teamId,
|
||||
getRedirectPath: (ctx, team) =>
|
||||
ChatUtils.connectUrl(service, {
|
||||
baseUrl: team.url,
|
||||
params: ctx.request.querystring,
|
||||
}),
|
||||
getErrorPath: () => ChatUtils.errorPath(service, "unauthenticated"),
|
||||
}),
|
||||
async (ctx: APIContext<T.ChatInstallReq>) => {
|
||||
const { code, error, state } = ctx.input.query;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(ChatUtils.errorPath(service, error));
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedState = ChatUtils.parseState(state);
|
||||
if (!parsedState) {
|
||||
throw ValidationError("Invalid state");
|
||||
}
|
||||
|
||||
verifyOAuthStateNonce(
|
||||
ctx,
|
||||
ChatUtils.nonceCookie(service),
|
||||
parsedState.nonce
|
||||
);
|
||||
|
||||
if (!code) {
|
||||
throw ValidationError("code is required");
|
||||
}
|
||||
|
||||
// The auth app has no apiContext middleware, so build the context here.
|
||||
const { user, type } = ctx.state.auth;
|
||||
await ChatInstallHelper.install(
|
||||
createContext({ user, authType: type, ip: ctx.request.ip }),
|
||||
provider,
|
||||
parsedState,
|
||||
code
|
||||
);
|
||||
ctx.redirect(ChatUtils.settingsPath(service));
|
||||
}
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import {
|
||||
AuthenticationType,
|
||||
IntegrationService,
|
||||
IntegrationType,
|
||||
} from "@shared/types";
|
||||
import { randomString } from "@shared/random";
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
Integration,
|
||||
IntegrationAuthentication,
|
||||
SearchQuery,
|
||||
} from "@server/models";
|
||||
import type { Team, User } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import { TestChatProvider, type TestChatTarget } from "@server/test/ChatHelper";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
buildTeam,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
import { Hook, PluginManager } from "@server/utils/PluginManager";
|
||||
import type { ChatAnswerProvider } from "./ChatAnswerProvider";
|
||||
import { ChatService } from "./ChatService";
|
||||
import type { ChatEvent } from "./types";
|
||||
|
||||
// Starts the app, which loads translations.
|
||||
getTestServer();
|
||||
|
||||
const mockAnswerProvider = (answerProvider: ChatAnswerProvider) => {
|
||||
const getHooks = PluginManager.getHooks.bind(PluginManager);
|
||||
vi.spyOn(PluginManager, "getHooks").mockImplementation(((type: Hook) =>
|
||||
type === Hook.ChatAnswerProvider
|
||||
? [{ type, value: answerProvider }]
|
||||
: getHooks(type)) as typeof PluginManager.getHooks);
|
||||
};
|
||||
|
||||
const ctx = createContext({ ip: "127.0.0.1" });
|
||||
|
||||
const actorOf = (team: Team, user: User) => {
|
||||
const serviceTeamId = team.authenticationProviders[0].providerId;
|
||||
return {
|
||||
installation: { serviceTeamId },
|
||||
actor: { serviceTeamId, serviceUserId: user.authentications[0].providerId },
|
||||
replyTarget: { id: randomString(8) },
|
||||
};
|
||||
};
|
||||
|
||||
const commandEvent = async (text: string) => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const event: ChatEvent<TestChatTarget> = {
|
||||
type: "command",
|
||||
...actorOf(team, user),
|
||||
text,
|
||||
};
|
||||
return { team, user, event };
|
||||
};
|
||||
|
||||
/** Installs the app in a team, and returns the install token. */
|
||||
const install = async (team: Team, user: User, serviceTeamId: string) => {
|
||||
const authentication = await IntegrationAuthentication.create({
|
||||
service: IntegrationService.Slack,
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
token: randomString(32),
|
||||
});
|
||||
await Integration.create<Integration<IntegrationType.Command>>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Command,
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
authenticationId: authentication.id,
|
||||
settings: { serviceTeamId },
|
||||
});
|
||||
return authentication.token;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates two Outline teams that sign in with the same Slack workspace, and a
|
||||
* person with an account in each, linked to the same Slack user.
|
||||
*/
|
||||
const twoTeamsOneWorkspace = async () => {
|
||||
const serviceTeamId = randomString(16);
|
||||
const serviceUserId = randomString(16);
|
||||
const teams = [
|
||||
await buildTeam({
|
||||
authenticationProviders: [{ name: "slack", providerId: serviceTeamId }],
|
||||
}),
|
||||
await buildTeam({
|
||||
authenticationProviders: [{ name: "slack", providerId: serviceTeamId }],
|
||||
}),
|
||||
];
|
||||
const users = [];
|
||||
for (const team of teams) {
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
await Integration.create<Integration<IntegrationType.LinkedAccount>>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
settings: { slack: { serviceTeamId, serviceUserId } },
|
||||
});
|
||||
users.push(user);
|
||||
}
|
||||
const ref = {
|
||||
installation: { serviceTeamId },
|
||||
actor: { serviceTeamId, serviceUserId },
|
||||
replyTarget: { id: randomString(8) },
|
||||
};
|
||||
return { teams, users, ref, serviceTeamId };
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("ChatService", () => {
|
||||
describe("command", () => {
|
||||
it("should reply later with an answer when the answer provider can answer", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { user, event } = await commandEvent("what is this?");
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const answer = vi.fn(async (_ctx: APIContext, _question: string) => ({
|
||||
answer: "**It is**",
|
||||
documents: [document],
|
||||
}));
|
||||
mockAnswerProvider({ canAnswer: () => true, answer });
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, event);
|
||||
expect(result.type).toEqual("deferred");
|
||||
|
||||
const [answerCtx, question] = answer.mock.calls[0];
|
||||
expect(question).toEqual("what is this?");
|
||||
expect(answerCtx.context.auth.user.id).toEqual(user.id);
|
||||
expect(answerCtx.context.auth.type).toEqual(AuthenticationType.CHAT);
|
||||
|
||||
await vi.waitFor(() => expect(provider.replies).toHaveLength(1));
|
||||
const [reply] = provider.replies;
|
||||
expect(reply.text).toEqual("**It is**");
|
||||
expect(reply.cards[0].title).toEqual(document.displayTitle);
|
||||
|
||||
const searchQuery = await SearchQuery.findOne({
|
||||
where: { userId: user.id },
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
expect(searchQuery.answer).toEqual("**It is**");
|
||||
expect(reply.actions).toEqual([
|
||||
expect.objectContaining({ id: "postAnswer", value: searchQuery.id }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should reply later with search results when there is no answer", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { event } = await commandEvent("what is this?");
|
||||
mockAnswerProvider({
|
||||
canAnswer: () => true,
|
||||
answer: async () => ({ answer: "", documents: [] }),
|
||||
});
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, event);
|
||||
expect(result.type).toEqual("deferred");
|
||||
|
||||
await vi.waitFor(() => expect(provider.replies).toHaveLength(1));
|
||||
expect(provider.replies[0].text).toContain("No results for");
|
||||
});
|
||||
});
|
||||
|
||||
describe("action", () => {
|
||||
it("should not post the answer of another user", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { team, user } = await commandEvent("");
|
||||
const other = await buildUser({ teamId: team.id });
|
||||
const searchQuery = await SearchQuery.create({
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
source: SearchQuerySource.Slack,
|
||||
query: "what is this?",
|
||||
answer: "It is",
|
||||
results: 1,
|
||||
});
|
||||
|
||||
await expect(
|
||||
ChatService.handle(ctx, provider, {
|
||||
type: "action",
|
||||
action: "postAnswer",
|
||||
value: searchQuery.id,
|
||||
...actorOf(team, other),
|
||||
})
|
||||
).rejects.toThrow("Invalid search query");
|
||||
});
|
||||
|
||||
it("should not post a document that the actor cannot read", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { team, user } = await commandEvent("");
|
||||
const owner = await buildUser({ teamId: team.id });
|
||||
const collection = await buildCollection({
|
||||
teamId: team.id,
|
||||
userId: owner.id,
|
||||
permission: null,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: team.id,
|
||||
userId: owner.id,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, {
|
||||
type: "action",
|
||||
action: "postDocument",
|
||||
value: document.id,
|
||||
...actorOf(team, user),
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
type: "message",
|
||||
message: { visibility: "ephemeral", cards: [] },
|
||||
});
|
||||
if (result.type === "message") {
|
||||
expect(result.message.text).toContain("do not have access");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("several teams on one workspace", () => {
|
||||
it("should search every team that the actor is linked in", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { teams, users, ref } = await twoTeamsOneWorkspace();
|
||||
for (const [index, team] of teams.entries()) {
|
||||
await buildDocument({
|
||||
title: `Roadmap ${index}`,
|
||||
teamId: team.id,
|
||||
userId: users[index].id,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, {
|
||||
type: "command",
|
||||
...ref,
|
||||
text: "roadmap",
|
||||
});
|
||||
|
||||
expect(result.type).toEqual("message");
|
||||
if (result.type === "message") {
|
||||
const footers = result.message.cards.map((card) => card.footer);
|
||||
expect(result.message.cards).toHaveLength(2);
|
||||
expect(footers[0]).toContain(teams[0].name);
|
||||
expect(footers[1]).toContain(teams[1].name);
|
||||
}
|
||||
expect(
|
||||
await SearchQuery.count({
|
||||
where: { query: "roadmap", teamId: teams.map((team) => team.id) },
|
||||
})
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("should search, not answer, when the actor is linked in several teams", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { ref } = await twoTeamsOneWorkspace();
|
||||
mockAnswerProvider({
|
||||
canAnswer: () => true,
|
||||
answer: async () => ({ answer: "unused", documents: [] }),
|
||||
});
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, {
|
||||
type: "command",
|
||||
...ref,
|
||||
text: "what is this?",
|
||||
});
|
||||
|
||||
expect(result.type).toEqual("message");
|
||||
});
|
||||
|
||||
it("should preview links with the account and token of the document's team", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { teams, users, ref, serviceTeamId } = await twoTeamsOneWorkspace();
|
||||
await install(teams[0], users[0], serviceTeamId);
|
||||
const token = await install(teams[1], users[1], serviceTeamId);
|
||||
const document = await buildDocument({
|
||||
teamId: teams[1].id,
|
||||
userId: users[1].id,
|
||||
});
|
||||
const otherTeamDocument = await buildDocument();
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, {
|
||||
type: "linksShared",
|
||||
...ref,
|
||||
conversation: { channelId: "C1" },
|
||||
messageId: "1",
|
||||
urls: [document.url, otherTeamDocument.url],
|
||||
});
|
||||
|
||||
expect(result.type).toEqual("linkPreviews");
|
||||
if (result.type === "linkPreviews") {
|
||||
expect(Array.from(result.cards.keys())).toEqual([document.url]);
|
||||
expect(result.authentication.token).toEqual(token);
|
||||
}
|
||||
});
|
||||
|
||||
it("should list a link for each team when the actor is not linked", async () => {
|
||||
const provider = new TestChatProvider();
|
||||
const { teams, ref } = await twoTeamsOneWorkspace();
|
||||
|
||||
const result = await ChatService.handle(ctx, provider, {
|
||||
type: "command",
|
||||
...ref,
|
||||
actor: { ...ref.actor, serviceUserId: "unknown" },
|
||||
text: "roadmap",
|
||||
});
|
||||
|
||||
expect(result.type).toEqual("message");
|
||||
if (result.type === "message") {
|
||||
expect(result.message.text).toContain(teams[0].url);
|
||||
expect(result.message.text).toContain(teams[1].url);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,551 @@
|
||||
import { t } from "i18next";
|
||||
import httpErrors from "http-errors";
|
||||
import { escapeRegExp } from "es-toolkit/compat";
|
||||
import queryString from "query-string";
|
||||
import type { IntegrationService } from "@shared/types";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
|
||||
import { ChatUtils } from "@shared/utils/ChatUtils";
|
||||
import env from "@server/env";
|
||||
import documentLoader from "@server/commands/documentLoader";
|
||||
import { InvalidRequestError, NotFoundError } from "@server/errors";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { Comment, Document, SearchQuery } from "@server/models";
|
||||
import type { IntegrationAuthentication, Team, User } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { opts } from "@server/utils/i18n";
|
||||
import { Hook, PluginManager } from "@server/utils/PluginManager";
|
||||
import SearchProviderManager from "@server/utils/SearchProviderManager";
|
||||
import type { BaseChatProvider } from "./BaseChatProvider";
|
||||
import { type ChatAccounts, ChatAccountHelper } from "./ChatAccountHelper";
|
||||
import type { ChatAnswerProvider } from "./ChatAnswerProvider";
|
||||
import { ChatMessageHelper } from "./ChatMessageHelper";
|
||||
import type { ChatCard, ChatEvent, ChatMessage, ChatResult } from "./types";
|
||||
|
||||
/** The command that users type to use Outline from a chat platform. */
|
||||
const command = "/outline";
|
||||
|
||||
/**
|
||||
* Handles events from chat platforms. All lookups and permission checks for
|
||||
* chat providers are done here. One chat workspace can be connected to
|
||||
* several Outline teams, so each lookup uses a context for one team.
|
||||
*/
|
||||
export class ChatService {
|
||||
/**
|
||||
* Returns all registered chat providers.
|
||||
*
|
||||
* @returns the chat providers.
|
||||
*/
|
||||
public static getProviders(): BaseChatProvider[] {
|
||||
return PluginManager.getHooks(Hook.ChatProvider).map((hook) => hook.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the chat provider for a service.
|
||||
*
|
||||
* @param service the integration service.
|
||||
* @returns the chat provider, if registered.
|
||||
*/
|
||||
public static getProvider(
|
||||
service: IntegrationService
|
||||
): BaseChatProvider | undefined {
|
||||
return this.getProviders().find((provider) => provider.service === service);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an event from a chat platform.
|
||||
*
|
||||
* @param ctx the context of the inbound request.
|
||||
* @param provider the chat provider that received the event.
|
||||
* @param event the event.
|
||||
* @returns the result to send to the platform.
|
||||
*/
|
||||
public static async handle<TTarget>(
|
||||
ctx: APIContext,
|
||||
provider: BaseChatProvider<TTarget>,
|
||||
event: ChatEvent<TTarget>
|
||||
): Promise<ChatResult> {
|
||||
const accounts = await ChatAccountHelper.findAccounts(
|
||||
ctx,
|
||||
provider,
|
||||
event.installation,
|
||||
event.actor
|
||||
);
|
||||
|
||||
switch (event.type) {
|
||||
case "command":
|
||||
return this.handleCommand(provider, event, accounts);
|
||||
case "linksShared":
|
||||
return this.handleLinksShared(provider, event, accounts);
|
||||
case "action":
|
||||
return this.handleAction(provider, event, accounts);
|
||||
default:
|
||||
return { type: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
private static getAnswerProvider(): ChatAnswerProvider | undefined {
|
||||
return PluginManager.getHooks(Hook.ChatAnswerProvider)[0]?.value;
|
||||
}
|
||||
|
||||
private static userOf(ctx: APIContext): User {
|
||||
return ctx.context.auth.user;
|
||||
}
|
||||
|
||||
private static async handleCommand<TTarget>(
|
||||
provider: BaseChatProvider<TTarget>,
|
||||
event: Extract<ChatEvent<TTarget>, { type: "command" }>,
|
||||
{ teams, contexts }: ChatAccounts
|
||||
): Promise<ChatResult> {
|
||||
const user = contexts.length ? this.userOf(contexts[0]) : undefined;
|
||||
const query = event.text;
|
||||
|
||||
if (query.trim() === "help" || !query.trim()) {
|
||||
return {
|
||||
type: "message",
|
||||
message: {
|
||||
text: [
|
||||
t("How to use {{ command }}", { command, ...opts(user) }),
|
||||
t(
|
||||
"To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.",
|
||||
{
|
||||
command: `${command} keyword`,
|
||||
command2: command,
|
||||
...opts(user),
|
||||
}
|
||||
),
|
||||
].join("\n"),
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
type: "message",
|
||||
message: this.notLinkedMessage(provider, teams),
|
||||
};
|
||||
}
|
||||
|
||||
// An answer needs one team, so it is only used when there is no choice.
|
||||
const answerProvider = this.getAnswerProvider();
|
||||
if (
|
||||
contexts.length === 1 &&
|
||||
answerProvider?.canAnswer(contexts[0], query)
|
||||
) {
|
||||
void this.replyWithAnswer(
|
||||
contexts[0],
|
||||
provider,
|
||||
event.replyTarget,
|
||||
answerProvider,
|
||||
query
|
||||
);
|
||||
|
||||
return {
|
||||
type: "deferred",
|
||||
message: {
|
||||
text: "",
|
||||
context: t("Looking for answers", opts(user)) + "…",
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "message",
|
||||
message: await this.search(provider, contexts, query),
|
||||
};
|
||||
}
|
||||
|
||||
private static async handleLinksShared<TTarget>(
|
||||
provider: BaseChatProvider<TTarget>,
|
||||
event: Extract<ChatEvent<TTarget>, { type: "linksShared" }>,
|
||||
{ contexts }: ChatAccounts
|
||||
): Promise<ChatResult> {
|
||||
if (!contexts.length) {
|
||||
Logger.debug("plugins", "No user found for chat user ID", {
|
||||
service: provider.service,
|
||||
providerId: event.actor.serviceUserId,
|
||||
});
|
||||
return { type: "none" };
|
||||
}
|
||||
|
||||
const cards = new Map<string, ChatCard>();
|
||||
let authentication: IntegrationAuthentication | undefined;
|
||||
|
||||
for (const url of event.urls) {
|
||||
const documentId = parseDocumentSlug(url);
|
||||
if (!documentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const found = await this.tryLoadDocument(contexts, documentId);
|
||||
if (!found) {
|
||||
continue;
|
||||
}
|
||||
const { ctx, document } = found;
|
||||
const user = this.userOf(ctx);
|
||||
authentication ??= ctx.state.integration?.authentication;
|
||||
|
||||
const commentId = queryString.parse(url.split("?")[1])?.commentId;
|
||||
if (commentId) {
|
||||
if (typeof commentId !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const comment = await Comment.findByPk(commentId);
|
||||
if (!comment || comment.documentId !== document.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cards.set(url, {
|
||||
title: t("Comment by {{ author }} on “{{ title }}”", {
|
||||
author: comment.createdBy.name,
|
||||
title: document.title,
|
||||
...opts(user),
|
||||
}),
|
||||
url,
|
||||
text: ChatMessageHelper.escape(comment.toPlainText()),
|
||||
});
|
||||
} else {
|
||||
cards.set(url, {
|
||||
title: document.title,
|
||||
url,
|
||||
text: ChatMessageHelper.escape(document.getSummary()),
|
||||
color: document.collection?.color ?? undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Tokens of one app in one workspace are interchangeable, so any
|
||||
// installed team can send previews for the others.
|
||||
authentication ??= contexts
|
||||
.map((ctx) => ctx.state.integration?.authentication)
|
||||
.find(Boolean);
|
||||
if (!authentication) {
|
||||
Logger.debug("plugins", "No chat integration authentication found", {
|
||||
service: provider.service,
|
||||
serviceTeamId: event.installation.serviceTeamId,
|
||||
});
|
||||
return { type: "none" };
|
||||
}
|
||||
|
||||
return { type: "linkPreviews", cards, authentication };
|
||||
}
|
||||
|
||||
private static async handleAction<TTarget>(
|
||||
provider: BaseChatProvider<TTarget>,
|
||||
event: Extract<ChatEvent<TTarget>, { type: "action" }>,
|
||||
{ teams, contexts }: ChatAccounts
|
||||
): Promise<ChatResult> {
|
||||
switch (event.action) {
|
||||
case "postDocument": {
|
||||
if (!contexts.length) {
|
||||
return {
|
||||
type: "message",
|
||||
message: this.notLinkedMessage(provider, teams),
|
||||
};
|
||||
}
|
||||
|
||||
const found = await this.tryLoadDocument(contexts, event.value);
|
||||
if (!found) {
|
||||
return {
|
||||
type: "message",
|
||||
message: {
|
||||
text: ChatMessageHelper.escape(
|
||||
t(
|
||||
"You do not have access to this document",
|
||||
opts(this.userOf(contexts[0]))
|
||||
)
|
||||
),
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
const user = this.userOf(found.ctx);
|
||||
|
||||
return {
|
||||
type: "message",
|
||||
message: {
|
||||
text: "",
|
||||
visibility: "conversation",
|
||||
cards: [
|
||||
ChatMessageHelper.documentCard(
|
||||
found.document,
|
||||
user.team,
|
||||
found.document.collection
|
||||
),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "postAnswer": {
|
||||
const searchQuery = await SearchQuery.findByPk(event.value);
|
||||
const ctx = contexts.find(
|
||||
(context) => this.userOf(context).id === searchQuery?.userId
|
||||
);
|
||||
if (!searchQuery || !ctx) {
|
||||
throw InvalidRequestError("Invalid search query");
|
||||
}
|
||||
|
||||
return {
|
||||
type: "message",
|
||||
message: {
|
||||
context: t("Answer to “{{ query }}”", {
|
||||
query: searchQuery.query,
|
||||
...opts(this.userOf(ctx)),
|
||||
}),
|
||||
text: searchQuery.answer,
|
||||
visibility: "conversation",
|
||||
cards: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return { type: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a document for the actor. The document decides the team, and the
|
||||
* actor's user in that team must be able to read it.
|
||||
*
|
||||
* @param contexts the actor's contexts.
|
||||
* @param documentId the ID or URL ID of the document.
|
||||
* @returns the document and the context of the user that loaded it.
|
||||
* @throws {NotFoundError} if the actor has no account in the team.
|
||||
* @throws {AuthorizationError} if the user cannot read the document.
|
||||
*/
|
||||
private static async loadDocument(
|
||||
contexts: APIContext[],
|
||||
documentId: string
|
||||
): Promise<{ ctx: APIContext; document: Document }> {
|
||||
// This lookup excludes deleted documents, which documentLoader returns to
|
||||
// users that can restore them.
|
||||
const found = await Document.findByPk(documentId);
|
||||
const ctx = contexts.find(
|
||||
(context) => this.userOf(context).teamId === found?.teamId
|
||||
);
|
||||
if (!found || !ctx) {
|
||||
throw NotFoundError();
|
||||
}
|
||||
|
||||
const document = await documentLoader({
|
||||
id: found.id,
|
||||
user: this.userOf(ctx),
|
||||
});
|
||||
return { ctx, document };
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a document for the actor, or returns undefined if the document is
|
||||
* missing or the actor cannot read it.
|
||||
*
|
||||
* @param contexts the actor's contexts.
|
||||
* @param documentId the ID or URL ID of the document.
|
||||
* @returns the document and the context of the user that loaded it, if any.
|
||||
*/
|
||||
private static async tryLoadDocument(
|
||||
contexts: APIContext[],
|
||||
documentId: string
|
||||
): Promise<{ ctx: APIContext; document: Document } | undefined> {
|
||||
try {
|
||||
return await this.loadDocument(contexts, documentId);
|
||||
} catch (err) {
|
||||
if (httpErrors.isHttpError(err) && err.status < 500) {
|
||||
return undefined;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private static notLinkedMessage(
|
||||
provider: BaseChatProvider,
|
||||
teams: Team[]
|
||||
): ChatMessage {
|
||||
const appName = env.APP_NAME;
|
||||
const prefix = ChatMessageHelper.escape(
|
||||
t(
|
||||
"It looks like you haven’t linked your {{ appName }} account to {{ serviceName }} yet",
|
||||
{ appName, serviceName: provider.name, ...opts() }
|
||||
) + ". "
|
||||
);
|
||||
const settingsPath = ChatUtils.settingsPath(provider.service);
|
||||
const linkLabel = ChatMessageHelper.escape(t("Link your account", opts()));
|
||||
|
||||
let suffix: string;
|
||||
if (teams.length === 1) {
|
||||
suffix = `[${linkLabel}](${teams[0].url}${settingsPath})`;
|
||||
} else if (teams.length > 1) {
|
||||
suffix = `${linkLabel}: ${teams
|
||||
.map(
|
||||
(team) =>
|
||||
`[${ChatMessageHelper.escape(team.name)}](${team.url}${settingsPath})`
|
||||
)
|
||||
.join(" · ")}`;
|
||||
} else {
|
||||
suffix = ChatMessageHelper.escape(
|
||||
t(
|
||||
"Link your account in {{ appName }} settings to search from {{ serviceName }}",
|
||||
{ appName, serviceName: provider.name, ...opts() }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
text: prefix + suffix,
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
};
|
||||
}
|
||||
|
||||
private static async search(
|
||||
provider: BaseChatProvider,
|
||||
contexts: APIContext[],
|
||||
query: string
|
||||
): Promise<ChatMessage> {
|
||||
const user = this.userOf(contexts[0]);
|
||||
const cards: ChatCard[] = [];
|
||||
|
||||
for (const ctx of contexts) {
|
||||
cards.push(
|
||||
...(await this.searchTeam(ctx, provider, query, contexts.length > 1))
|
||||
);
|
||||
}
|
||||
|
||||
if (!cards.length) {
|
||||
return {
|
||||
text: ChatMessageHelper.escape(
|
||||
t("No results for “{{ term }}”", { term: query, ...opts(user) })
|
||||
),
|
||||
visibility: "ephemeral",
|
||||
cards: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
text: ChatMessageHelper.escape(
|
||||
t("This is what we found for “{{ term }}”", {
|
||||
term: query,
|
||||
...opts(user),
|
||||
})
|
||||
),
|
||||
visibility: "ephemeral",
|
||||
cards,
|
||||
};
|
||||
}
|
||||
|
||||
private static async searchTeam(
|
||||
ctx: APIContext,
|
||||
provider: BaseChatProvider,
|
||||
query: string,
|
||||
showTeam: boolean
|
||||
): Promise<ChatCard[]> {
|
||||
const user = this.userOf(ctx);
|
||||
const { results, total } =
|
||||
await SearchProviderManager.getProvider().searchForUser(user, {
|
||||
query,
|
||||
limit: 5,
|
||||
});
|
||||
|
||||
await SearchQuery.create({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
source: provider.searchSource,
|
||||
query,
|
||||
results: total,
|
||||
});
|
||||
|
||||
return results.map((result) => {
|
||||
const queryIsInTitle = !!result.document.title
|
||||
.toLowerCase()
|
||||
.match(escapeRegExp(query.toLowerCase()));
|
||||
|
||||
const card = ChatMessageHelper.documentCard(
|
||||
result.document,
|
||||
user.team,
|
||||
result.document.collection,
|
||||
queryIsInTitle || !result.context
|
||||
? undefined
|
||||
: ChatMessageHelper.fromSearchContext(result.context),
|
||||
provider.capabilities.messageActions
|
||||
? [
|
||||
{
|
||||
id: "postDocument",
|
||||
label: t("Post to Channel", opts(user)),
|
||||
value: result.document.id,
|
||||
},
|
||||
]
|
||||
: undefined
|
||||
);
|
||||
|
||||
return showTeam
|
||||
? {
|
||||
...card,
|
||||
footer: [user.team.name, card.footer].filter(Boolean).join(" · "),
|
||||
}
|
||||
: card;
|
||||
});
|
||||
}
|
||||
|
||||
private static async replyWithAnswer<TTarget>(
|
||||
ctx: APIContext,
|
||||
provider: BaseChatProvider<TTarget>,
|
||||
target: TTarget,
|
||||
answerProvider: ChatAnswerProvider,
|
||||
query: string
|
||||
) {
|
||||
const user = this.userOf(ctx);
|
||||
|
||||
try {
|
||||
const { answer, documents } = await answerProvider.answer(ctx, query);
|
||||
if (!answer) {
|
||||
await provider.reply(target, await this.search(provider, [ctx], query));
|
||||
return;
|
||||
}
|
||||
|
||||
const searchQuery = await SearchQuery.create({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
source: provider.searchSource,
|
||||
query,
|
||||
answer,
|
||||
results: documents.length,
|
||||
});
|
||||
|
||||
await provider.reply(target, {
|
||||
context: t("Answer to “{{ query }}”", { query, ...opts(user) }),
|
||||
text: answer,
|
||||
visibility: "ephemeral",
|
||||
cards: documents
|
||||
.slice(0, 1)
|
||||
.map((document) =>
|
||||
ChatMessageHelper.documentCard(
|
||||
document,
|
||||
user.team,
|
||||
document.collection
|
||||
)
|
||||
),
|
||||
actions: provider.capabilities.messageActions
|
||||
? [
|
||||
{
|
||||
id: "postAnswer",
|
||||
label: t("Post to channel", opts(user)),
|
||||
value: searchQuery.id,
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
Logger.error("Failed to answer chat question", toError(err), {
|
||||
service: provider.service,
|
||||
userId: user.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { isEmpty } from "es-toolkit/compat";
|
||||
import { z } from "zod";
|
||||
import { BaseSchema } from "@server/routes/api/schema";
|
||||
|
||||
export const SlackPostSchema = BaseSchema.extend({
|
||||
export const ChatInstallSchema = BaseSchema.extend({
|
||||
query: z
|
||||
.object({
|
||||
code: z.string().nullish(),
|
||||
@@ -17,4 +17,4 @@ export const SlackPostSchema = BaseSchema.extend({
|
||||
}),
|
||||
});
|
||||
|
||||
export type SlackPostReq = z.infer<typeof SlackPostSchema>;
|
||||
export type ChatInstallReq = z.infer<typeof ChatInstallSchema>;
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { IntegrationAuthentication } from "@server/models";
|
||||
|
||||
/**
|
||||
* Markdown text. Providers convert it to the format of their platform. Use
|
||||
* `ChatMessageHelper.escape` for untrusted strings.
|
||||
*/
|
||||
export type ChatMarkdown = string;
|
||||
|
||||
/** The installation of the app that received an event. */
|
||||
export interface ChatInstallationRef {
|
||||
/** The ID of the workspace that the app is installed in, e.g. a Slack team ID. */
|
||||
serviceTeamId: string;
|
||||
}
|
||||
|
||||
/** A reference to a user on a chat platform. */
|
||||
export interface ChatUserRef {
|
||||
/**
|
||||
* The ID of the home workspace of the user. In shared channels this can
|
||||
* differ from the installation.
|
||||
*/
|
||||
serviceTeamId: string;
|
||||
/** The ID of the user on the chat platform. */
|
||||
serviceUserId: string;
|
||||
}
|
||||
|
||||
/** A reference to a channel, direct message or thread on a chat platform. */
|
||||
export interface ChatConversationRef {
|
||||
/** The ID of the channel or direct message. */
|
||||
channelId: string;
|
||||
}
|
||||
|
||||
/** An action that a user can take on a message. */
|
||||
export interface ChatAction {
|
||||
/** The type of action. */
|
||||
id: "postDocument" | "postAnswer";
|
||||
/** The button label. */
|
||||
label: string;
|
||||
/** The ID of the item that the action applies to. */
|
||||
value: string;
|
||||
}
|
||||
|
||||
/** A preview of an item in Outline, shown with a message. */
|
||||
export interface ChatCard {
|
||||
/** Plain text title. */
|
||||
title: string;
|
||||
/** The URL that the title links to. */
|
||||
url: string;
|
||||
/** The body of the card. */
|
||||
text?: ChatMarkdown;
|
||||
/** An accent color as a hex string. */
|
||||
color?: string;
|
||||
/** Plain text shown below the card. */
|
||||
footer?: string;
|
||||
/** The time shown in the footer. */
|
||||
timestamp?: Date;
|
||||
/** Actions shown on the card. */
|
||||
actions?: ChatAction[];
|
||||
}
|
||||
|
||||
/** Who can see a message. */
|
||||
export type ChatVisibility = "ephemeral" | "conversation";
|
||||
|
||||
/** A message in a neutral format, rendered by each provider. */
|
||||
export interface ChatMessage {
|
||||
/** Plain text shown above the message in a smaller font. */
|
||||
context?: string;
|
||||
/** The body of the message. */
|
||||
text: ChatMarkdown;
|
||||
/** Who can see the message. */
|
||||
visibility: ChatVisibility;
|
||||
/** Previews shown with the message. */
|
||||
cards: ChatCard[];
|
||||
/** Actions shown below the message. */
|
||||
actions?: ChatAction[];
|
||||
}
|
||||
|
||||
/** An event received from a chat platform. */
|
||||
export type ChatEvent<TTarget> = {
|
||||
/** The installation that received the event. */
|
||||
installation: ChatInstallationRef;
|
||||
/** The user that caused the event. */
|
||||
actor: ChatUserRef;
|
||||
/** Where to send a later reply. Must serialize to JSON. */
|
||||
replyTarget: TTarget;
|
||||
} & (
|
||||
| {
|
||||
type: "command";
|
||||
/** The text that the user typed after the command. */
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "linksShared";
|
||||
conversation: ChatConversationRef;
|
||||
/** The ID of the message that contains the links. */
|
||||
messageId: string;
|
||||
urls: string[];
|
||||
}
|
||||
| {
|
||||
type: "action";
|
||||
action: ChatAction["id"];
|
||||
value: string;
|
||||
}
|
||||
);
|
||||
|
||||
/** The result of parsing an inbound request. */
|
||||
export type ChatRequest<TTarget> =
|
||||
| ChatEvent<TTarget>
|
||||
| {
|
||||
/** A verification request from the platform, answered with the body. */
|
||||
type: "handshake";
|
||||
body: Record<string, string>;
|
||||
};
|
||||
|
||||
/** The result of handling an event. */
|
||||
export type ChatResult =
|
||||
| { type: "message"; message: ChatMessage }
|
||||
| {
|
||||
/** A message to show now, replaced later with `BaseChatProvider.reply`. */
|
||||
type: "deferred";
|
||||
message: ChatMessage;
|
||||
}
|
||||
| {
|
||||
type: "linkPreviews";
|
||||
cards: Map<string, ChatCard>;
|
||||
authentication: IntegrationAuthentication;
|
||||
}
|
||||
| { type: "none" };
|
||||
|
||||
/** The features that a chat provider supports. */
|
||||
export interface ChatCapabilities {
|
||||
/** Buttons on messages. */
|
||||
messageActions: boolean;
|
||||
}
|
||||
|
||||
/** The result of an install flow on a chat platform. */
|
||||
export interface ChatInstall {
|
||||
/** The access token for the platform API. */
|
||||
token: string;
|
||||
/** The scopes that the token has. */
|
||||
scopes: string[];
|
||||
/** The ID of the workspace on the chat platform. */
|
||||
serviceTeamId: string;
|
||||
/** The ID of the user that did the install. */
|
||||
serviceUserId: string;
|
||||
/** The channel selected for notifications, if any. */
|
||||
channel?: { id: string; name: string; webhookUrl: string };
|
||||
}
|
||||
+4
-1
@@ -1,5 +1,5 @@
|
||||
import type { Transaction } from "sequelize";
|
||||
import type { User } from "@server/models";
|
||||
import type { Integration, User } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
|
||||
@@ -11,17 +11,20 @@ export function createContext({
|
||||
authType = AuthenticationType.APP,
|
||||
ip,
|
||||
transaction,
|
||||
integration,
|
||||
}: {
|
||||
user?: User;
|
||||
authType?: AuthenticationType | null;
|
||||
ip?: string | null;
|
||||
transaction?: Transaction;
|
||||
integration?: Integration;
|
||||
}) {
|
||||
const auth = { user, type: authType };
|
||||
return {
|
||||
state: {
|
||||
auth,
|
||||
transaction,
|
||||
integration,
|
||||
},
|
||||
context: {
|
||||
auth,
|
||||
|
||||
@@ -16,15 +16,39 @@ export default function validate<T extends z.ZodType<Record<string, unknown>>>(
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
const { path, message } = err.issues[0];
|
||||
const errMessage =
|
||||
path.length > 0
|
||||
? `${String(path[path.length - 1])}: ${message}`
|
||||
: message;
|
||||
throw ValidationError(errMessage);
|
||||
throw toValidationError(err);
|
||||
}
|
||||
ctx.throw(toError(err));
|
||||
}
|
||||
return next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the request of the given context with a schema.
|
||||
*
|
||||
* @param schema the schema to parse the request with.
|
||||
* @param ctx the request context.
|
||||
* @returns the parsed request.
|
||||
* @throws {ValidationError} if the request does not match the schema.
|
||||
*/
|
||||
export function validateRequest<T extends z.ZodType<Record<string, unknown>>>(
|
||||
schema: T,
|
||||
ctx: APIContext
|
||||
): z.infer<T> {
|
||||
try {
|
||||
return schema.parse(ctx.request);
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
throw toValidationError(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function toValidationError(err: ZodError) {
|
||||
const { path, message } = err.issues[0];
|
||||
const errMessage =
|
||||
path.length > 0 ? `${String(path[path.length - 1])}: ${message}` : message;
|
||||
return ValidationError(errMessage);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import * as timers from "@shared/utils/timers";
|
||||
import { ChatService } from "@server/chat/ChatService";
|
||||
import type { BaseChatProvider } from "@server/chat/BaseChatProvider";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { Integration } from "@server/models";
|
||||
import { AuthenticationType } from "@server/types";
|
||||
import ChatNotificationsProcessor from "./ChatNotificationsProcessor";
|
||||
|
||||
const ip = "127.0.0.1";
|
||||
|
||||
/** Stubs the wait for summaries and spies on the Slack provider's postMessage. */
|
||||
const spyOnPostMessage = () => {
|
||||
vi.spyOn(timers, "sleep").mockResolvedValue(undefined);
|
||||
const provider = ChatService.getProvider(IntegrationService.Slack);
|
||||
if (!provider) {
|
||||
throw new Error("Slack provider is not registered");
|
||||
}
|
||||
return vi
|
||||
.spyOn(provider as BaseChatProvider, "postMessage")
|
||||
.mockResolvedValue(undefined);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("ChatNotificationsProcessor", () => {
|
||||
it("should post to every connected channel and continue after a failure", async () => {
|
||||
const postMessage = spyOnPostMessage().mockRejectedValueOnce(
|
||||
new Error("Channel archived")
|
||||
);
|
||||
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
for (const channel of ["one", "two"]) {
|
||||
await Integration.create<Integration<IntegrationType.Post>>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
events: ["documents.publish"],
|
||||
settings: {
|
||||
url: `https://hooks.slack.com/${channel}`,
|
||||
channel,
|
||||
channelId: channel,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await new ChatNotificationsProcessor().perform({
|
||||
name: "documents.publish",
|
||||
documentId: document.id,
|
||||
collectionId: collection.id,
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
data: {},
|
||||
authType: AuthenticationType.APP,
|
||||
ip,
|
||||
});
|
||||
|
||||
expect(postMessage).toHaveBeenCalledTimes(2);
|
||||
const channels = postMessage.mock.calls.map(
|
||||
([integration]) => integration.settings.channel
|
||||
);
|
||||
expect(channels.sort()).toEqual(["one", "two"]);
|
||||
expect(postMessage.mock.calls[0][1].cards[0].title).toEqual(
|
||||
document.displayTitle
|
||||
);
|
||||
});
|
||||
|
||||
it("should not post drafts", async () => {
|
||||
const postMessage = spyOnPostMessage();
|
||||
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
publishedAt: null,
|
||||
});
|
||||
await Integration.create<Integration<IntegrationType.Post>>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
collectionId: document.collectionId,
|
||||
events: ["documents.publish"],
|
||||
settings: {
|
||||
url: "https://hooks.slack.com/x",
|
||||
channel: "x",
|
||||
channelId: "x",
|
||||
},
|
||||
});
|
||||
|
||||
await new ChatNotificationsProcessor().perform({
|
||||
name: "documents.publish",
|
||||
documentId: document.id,
|
||||
collectionId: document.collectionId!,
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
data: {},
|
||||
authType: AuthenticationType.APP,
|
||||
ip,
|
||||
});
|
||||
|
||||
expect(postMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should post a welcome message when a channel is connected", async () => {
|
||||
const postMessage = spyOnPostMessage();
|
||||
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await Integration.create<
|
||||
Integration<IntegrationType.Post>
|
||||
>({
|
||||
service: IntegrationService.Slack,
|
||||
type: IntegrationType.Post,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
events: ["documents.publish"],
|
||||
settings: {
|
||||
url: "https://hooks.slack.com/x",
|
||||
channel: "x",
|
||||
channelId: "x",
|
||||
},
|
||||
});
|
||||
|
||||
await new ChatNotificationsProcessor().perform({
|
||||
name: "integrations.create",
|
||||
modelId: integration.id,
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
authType: AuthenticationType.APP,
|
||||
ip,
|
||||
});
|
||||
|
||||
expect(postMessage).toHaveBeenCalledTimes(1);
|
||||
expect(postMessage.mock.calls[0][1].text).toContain("Hey there");
|
||||
expect(postMessage.mock.calls[0][1].cards[0].title).toEqual(
|
||||
collection.name
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { differenceInMilliseconds } from "date-fns";
|
||||
import { Op } from "sequelize";
|
||||
import { IntegrationType } from "@shared/types";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { Minute } from "@shared/utils/time";
|
||||
import { sleep } from "@shared/utils/timers";
|
||||
import { ChatMessageHelper } from "@server/chat/ChatMessageHelper";
|
||||
import { ChatService } from "@server/chat/ChatService";
|
||||
import type { ChatMessage } from "@server/chat/types";
|
||||
import env from "@server/env";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { Collection, Document, Integration, Team } from "@server/models";
|
||||
import type {
|
||||
DocumentEvent,
|
||||
Event,
|
||||
IntegrationEvent,
|
||||
RevisionEvent,
|
||||
} from "@server/types";
|
||||
import BaseProcessor from "./BaseProcessor";
|
||||
|
||||
/**
|
||||
* Posts document changes to the chat channels that are connected to a
|
||||
* collection, on every registered chat platform.
|
||||
*/
|
||||
export default class ChatNotificationsProcessor extends BaseProcessor {
|
||||
static applicableEvents: Event["name"][] = [
|
||||
"documents.publish",
|
||||
"revisions.create",
|
||||
"integrations.create",
|
||||
];
|
||||
|
||||
async perform(event: Event) {
|
||||
const services = ChatService.getProviders().map(
|
||||
(provider) => provider.service
|
||||
);
|
||||
if (!services.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.name) {
|
||||
case "documents.publish":
|
||||
case "revisions.create":
|
||||
// wait a few seconds to give the document summary chance to be generated
|
||||
await sleep(5000);
|
||||
return this.documentUpdated(event, services);
|
||||
|
||||
case "integrations.create":
|
||||
return this.integrationCreated(event, services);
|
||||
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
private async integrationCreated(
|
||||
event: IntegrationEvent,
|
||||
services: string[]
|
||||
) {
|
||||
const integration = (await Integration.findOne({
|
||||
where: {
|
||||
id: event.modelId,
|
||||
service: services,
|
||||
type: IntegrationType.Post,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: Collection,
|
||||
required: true,
|
||||
as: "collection",
|
||||
},
|
||||
],
|
||||
})) as Integration<IntegrationType.Post> | null;
|
||||
const collection = integration?.collection;
|
||||
if (!integration || !collection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = ChatService.getProvider(integration.service);
|
||||
if (!provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
await provider.postMessage(integration, {
|
||||
text: `👋 Hey there! When documents are published or updated in the **${ChatMessageHelper.escape(
|
||||
collection.name
|
||||
)}** collection on ${ChatMessageHelper.escape(
|
||||
env.APP_NAME
|
||||
)} they will be posted to this channel!`,
|
||||
visibility: "conversation",
|
||||
cards: [
|
||||
{
|
||||
title: collection.name,
|
||||
url: `${env.URL}${collection.path}`,
|
||||
text: collection.description ?? undefined,
|
||||
color: collection.color ?? undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async documentUpdated(
|
||||
event: DocumentEvent | RevisionEvent,
|
||||
services: string[]
|
||||
) {
|
||||
// never send notifications when batch importing documents
|
||||
if (event.name === "documents.publish" && event.data?.source === "import") {
|
||||
return;
|
||||
}
|
||||
const [document, team] = await Promise.all([
|
||||
Document.findByPk(event.documentId),
|
||||
Team.findByPk(event.teamId),
|
||||
]);
|
||||
if (!document || !team) {
|
||||
return;
|
||||
}
|
||||
|
||||
// never send notifications for draft documents
|
||||
if (!document.publishedAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the document was published less than a minute ago, don't send a
|
||||
// separate notification.
|
||||
if (
|
||||
event.name === "revisions.create" &&
|
||||
differenceInMilliseconds(document.updatedAt, document.publishedAt) <
|
||||
Minute.ms
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const integrations = (await Integration.findAll({
|
||||
where: {
|
||||
teamId: document.teamId,
|
||||
collectionId: document.collectionId,
|
||||
service: services,
|
||||
type: IntegrationType.Post,
|
||||
events: {
|
||||
[Op.contains]: [
|
||||
event.name === "revisions.create" ? "documents.update" : event.name,
|
||||
],
|
||||
},
|
||||
},
|
||||
})) as Integration<IntegrationType.Post>[];
|
||||
if (!integrations.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text =
|
||||
event.name === "documents.publish"
|
||||
? `${document.createdBy.name} published "${document.displayTitle}"`
|
||||
: `${document.updatedBy.name} updated "${document.displayTitle}"`;
|
||||
const message: ChatMessage = {
|
||||
text: ChatMessageHelper.escape(text),
|
||||
visibility: "conversation",
|
||||
cards: [
|
||||
ChatMessageHelper.documentCard(document, team, document.collection),
|
||||
],
|
||||
};
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
integrations.map(async (integration) => {
|
||||
const provider = ChatService.getProvider(integration.service);
|
||||
if (provider) {
|
||||
await provider.postMessage(integration, message);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === "rejected") {
|
||||
Logger.error(
|
||||
"Failed to post chat notification",
|
||||
toError(result.reason),
|
||||
{ integrationId: integrations[index].id }
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import bodyParser from "koa-body";
|
||||
import Router from "@koa/router";
|
||||
import type { UserAgentContext } from "koa-useragent";
|
||||
import userAgent from "koa-useragent";
|
||||
import { ChatRouter } from "@server/chat/ChatRouter";
|
||||
import { ChatService } from "@server/chat/ChatService";
|
||||
import env from "@server/env";
|
||||
import { NotFoundError } from "@server/errors";
|
||||
import { apiContext } from "@server/middlewares/apiContext";
|
||||
@@ -87,6 +89,9 @@ api.use(verifyCSRFToken());
|
||||
PluginManager.getHooks(Hook.API).forEach((hook) =>
|
||||
router.use("/", hook.value.routes())
|
||||
);
|
||||
ChatService.getProviders().forEach((provider) =>
|
||||
router.use("/", ChatRouter.createWebhookRouter(provider).routes())
|
||||
);
|
||||
|
||||
// routes
|
||||
router.use("/", auth.routes());
|
||||
|
||||
@@ -3,6 +3,8 @@ import { addMonths } from "date-fns";
|
||||
import Koa from "koa";
|
||||
import bodyParser from "koa-body";
|
||||
import Router from "@koa/router";
|
||||
import { ChatRouter } from "@server/chat/ChatRouter";
|
||||
import { ChatService } from "@server/chat/ChatService";
|
||||
import { AuthenticationError } from "@server/errors";
|
||||
import authMiddleware from "@server/middlewares/authentication";
|
||||
import coalesceBody from "@server/middlewares/coaleseBody";
|
||||
@@ -32,6 +34,9 @@ void (async () => {
|
||||
router.use("/", resolvedRouter.routes());
|
||||
}
|
||||
}
|
||||
for (const provider of ChatService.getProviders()) {
|
||||
router.use("/", ChatRouter.createInstallRouter(provider).routes());
|
||||
}
|
||||
})();
|
||||
|
||||
router.get(
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { IntegrationService } from "@shared/types";
|
||||
import { BaseChatProvider } from "@server/chat/BaseChatProvider";
|
||||
import type { ChatInstall, ChatMessage, ChatRequest } from "@server/chat/types";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
|
||||
/** The reply target of the test provider. */
|
||||
export interface TestChatTarget {
|
||||
id: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A chat provider for tests. It records replies and returns a fixed install.
|
||||
*/
|
||||
export class TestChatProvider extends BaseChatProvider<TestChatTarget> {
|
||||
public readonly service = IntegrationService.Slack;
|
||||
public readonly name = "Test";
|
||||
public readonly searchSource = SearchQuerySource.Slack;
|
||||
public readonly authProviderName = "slack";
|
||||
public readonly webhookPaths = [];
|
||||
public readonly capabilities = { messageActions: true };
|
||||
|
||||
/** The messages sent with `reply`. */
|
||||
public replies: ChatMessage[] = [];
|
||||
|
||||
/** The result of `exchangeCode`. */
|
||||
public install: ChatInstall = {
|
||||
token: "token",
|
||||
scopes: ["incoming-webhook"],
|
||||
serviceTeamId: "T1",
|
||||
serviceUserId: "U1",
|
||||
channel: { id: "C1", name: "general", webhookUrl: "https://a.com/hook" },
|
||||
};
|
||||
|
||||
public async parseRequest(): Promise<ChatRequest<TestChatTarget>> {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
public async respond() {}
|
||||
|
||||
public async reply(_target: TestChatTarget, message: ChatMessage) {
|
||||
this.replies.push(message);
|
||||
}
|
||||
|
||||
public async exchangeCode(): Promise<ChatInstall> {
|
||||
return this.install;
|
||||
}
|
||||
|
||||
public async postMessage() {}
|
||||
}
|
||||
@@ -76,6 +76,8 @@ export type AppState = {
|
||||
pagination: Pagination;
|
||||
/** The teams authorized to receive an inbound webhook. */
|
||||
webhookTeamIds?: string[];
|
||||
/** The integration that the request was received through, if any. */
|
||||
integration?: Integration;
|
||||
oauthClient?: OAuthClient;
|
||||
oauthIntent?: OAuthIntent;
|
||||
oauthState?: OAuthState;
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
import { glob } from "glob";
|
||||
import type Router from "@koa/router";
|
||||
import { isArray, sortBy } from "es-toolkit/compat";
|
||||
import type { BaseChatProvider } from "@server/chat/BaseChatProvider";
|
||||
import type { ChatAnswerProvider } from "@server/chat/ChatAnswerProvider";
|
||||
import type BaseEmail from "@server/emails/templates/BaseEmail";
|
||||
import env from "@server/env";
|
||||
import Logger from "@server/logging/Logger";
|
||||
@@ -34,6 +36,8 @@ export enum PluginPriority {
|
||||
export enum Hook {
|
||||
API = "api",
|
||||
AuthProvider = "authProvider",
|
||||
ChatAnswerProvider = "chatAnswerProvider",
|
||||
ChatProvider = "chatProvider",
|
||||
EmailTemplate = "emailTemplate",
|
||||
IssueProvider = "issueProvider",
|
||||
Processor = "processor",
|
||||
@@ -52,6 +56,8 @@ export enum Hook {
|
||||
type PluginValueMap = {
|
||||
[Hook.API]: Router;
|
||||
[Hook.AuthProvider]: { router: Router | Promise<Router>; id: string };
|
||||
[Hook.ChatAnswerProvider]: ChatAnswerProvider;
|
||||
[Hook.ChatProvider]: BaseChatProvider;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- typeof BaseEmail<EmailProps> isn't assignable from BaseEmail<Subtype>; plugins register heterogeneous template Props.
|
||||
[Hook.EmailTemplate]: typeof BaseEmail<any>;
|
||||
[Hook.IssueProvider]: BaseIssueProvider;
|
||||
|
||||
@@ -1747,16 +1747,6 @@
|
||||
"Get rich previews of {{ appName }} links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat.": "Get rich previews of {{ appName }} links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat.",
|
||||
"This will remove the Outline slash command from your Slack workspace. Are you sure?": "This will remove the Outline slash command from your Slack workspace. Are you sure?",
|
||||
"Connect {{appName}} collections to Slack channels. Messages will be automatically posted to Slack when documents are published or updated.": "Connect {{appName}} collections to Slack channels. Messages will be automatically posted to Slack when documents are published or updated.",
|
||||
"Comment by {{ author }} on “{{ title }}”": "Comment by {{ author }} on “{{ title }}”",
|
||||
"You do not have access to this document": "You do not have access to this document",
|
||||
"How to use {{ command }}": "How to use {{ command }}",
|
||||
"To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.": "To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.",
|
||||
"Post to Channel": "Post to Channel",
|
||||
"This is what we found for “{{ term }}”": "This is what we found for “{{ term }}”",
|
||||
"No results for “{{ term }}”": "No results for “{{ term }}”",
|
||||
"It looks like you haven’t linked your {{ appName }} account to Slack yet": "It looks like you haven’t linked your {{ appName }} account to Slack yet",
|
||||
"Link your account": "Link your account",
|
||||
"Link your account in {{ appName }} settings to search from Slack": "Link your account in {{ appName }} settings to search from Slack",
|
||||
"Configure a Umami installation to send views and analytics from the workspace to your own Umami instance.": "Configure a Umami installation to send views and analytics from the workspace to your own Umami instance.",
|
||||
"The URL of your Umami instance. If you are using Umami Cloud it will begin with {{ url }}": "The URL of your Umami instance. If you are using Umami Cloud it will begin with {{ url }}",
|
||||
"Script name": "Script name",
|
||||
@@ -1783,6 +1773,17 @@
|
||||
"Webhooks": "Webhooks",
|
||||
"Webhooks can be used to notify your application when events happen in {{appName}}. Events are sent as an HTTPS request with a JSON payload in near real-time.": "Webhooks can be used to notify your application when events happen in {{appName}}. Events are sent as an HTTPS request with a JSON payload in near real-time.",
|
||||
"Zapier is a platform that allows {{appName}} to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.": "Zapier is a platform that allows {{appName}} to easily integrate with thousands of other business tools. Automate your workflows, sync data, and more.",
|
||||
"How to use {{ command }}": "How to use {{ command }}",
|
||||
"To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.": "To search your workspace use {{ command }}.\nType {{ command2 }} help to display this help text.",
|
||||
"Comment by {{ author }} on “{{ title }}”": "Comment by {{ author }} on “{{ title }}”",
|
||||
"You do not have access to this document": "You do not have access to this document",
|
||||
"It looks like you haven’t linked your {{ appName }} account to {{ serviceName }} yet": "It looks like you haven’t linked your {{ appName }} account to {{ serviceName }} yet",
|
||||
"Link your account": "Link your account",
|
||||
"Link your account in {{ appName }} settings to search from {{ serviceName }}": "Link your account in {{ appName }} settings to search from {{ serviceName }}",
|
||||
"No results for “{{ term }}”": "No results for “{{ term }}”",
|
||||
"This is what we found for “{{ term }}”": "This is what we found for “{{ term }}”",
|
||||
"Post to Channel": "Post to Channel",
|
||||
"Post to channel": "Post to channel",
|
||||
"Delayed notification": "Delayed notification",
|
||||
"“{{ collectionName }}” created": "“{{ collectionName }}” created",
|
||||
"{{ userName }} created a collection": "{{ userName }} created a collection",
|
||||
|
||||
@@ -17,6 +17,7 @@ export enum Scope {
|
||||
export enum AuthenticationType {
|
||||
API = "api",
|
||||
APP = "app",
|
||||
CHAT = "chat",
|
||||
MCP = "mcp",
|
||||
OAUTH = "oauth",
|
||||
}
|
||||
|
||||
@@ -67,6 +67,25 @@ export const IssueTrackerIntegrationService = {
|
||||
Linear: IntegrationService.Linear,
|
||||
} as const;
|
||||
|
||||
/** Integration services that are chat platforms. */
|
||||
export type ChatIntegrationService = Extract<
|
||||
IntegrationService,
|
||||
IntegrationService.Slack
|
||||
>;
|
||||
|
||||
/** Runtime values of `ChatIntegrationService`. */
|
||||
export const ChatIntegrationService = {
|
||||
Slack: IntegrationService.Slack,
|
||||
} as const;
|
||||
|
||||
/** A link between an Outline user and a user on a chat platform. */
|
||||
export interface ChatAccountSettings {
|
||||
/** The ID of the workspace on the chat platform. */
|
||||
serviceTeamId: string;
|
||||
/** The ID of the user on the chat platform. */
|
||||
serviceUserId: string;
|
||||
}
|
||||
|
||||
/** Integration services that can be created through the API. */
|
||||
export type UserCreatableIntegrationService = Extract<
|
||||
IntegrationService,
|
||||
@@ -124,7 +143,8 @@ export type IntegrationSettings<T> = T extends IntegrationType.Embed
|
||||
}
|
||||
: T extends IntegrationType.LinkedAccount
|
||||
? {
|
||||
slack?: { serviceTeamId: string; serviceUserId: string };
|
||||
[S in ChatIntegrationService]?: ChatAccountSettings;
|
||||
} & {
|
||||
figma?: {
|
||||
account: {
|
||||
id: string;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import env from "../env";
|
||||
import type { ChatIntegrationService, IntegrationType } from "../types";
|
||||
import { integrationSettingsPath } from "./routeHelpers";
|
||||
|
||||
/** The state passed through the OAuth flow when a chat integration is installed. */
|
||||
export interface ChatOAuthState {
|
||||
/** The ID of the Outline team. */
|
||||
teamId: string;
|
||||
/** The type of integration to create. */
|
||||
type: IntegrationType;
|
||||
/** A one-time value that is compared with a cookie on callback. */
|
||||
nonce: string;
|
||||
/** The collection to connect, for post integrations. */
|
||||
collectionId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers for the install flow of chat integrations, shared by client and server.
|
||||
*/
|
||||
export class ChatUtils {
|
||||
/**
|
||||
* Returns the name of the cookie that holds the OAuth nonce for a service.
|
||||
*
|
||||
* @param service the chat service.
|
||||
* @returns the cookie name.
|
||||
*/
|
||||
public static nonceCookie(service: ChatIntegrationService) {
|
||||
return `${service}OAuthNonce`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a state string for use in OAuth flows.
|
||||
*
|
||||
* @param teamId the ID of the Outline team.
|
||||
* @param type the integration type.
|
||||
* @param data additional data to include in the state.
|
||||
* @returns a state string.
|
||||
*/
|
||||
public static createState(
|
||||
teamId: string,
|
||||
type: IntegrationType,
|
||||
data?: { nonce?: string; collectionId?: string }
|
||||
) {
|
||||
return JSON.stringify({ type, teamId, ...data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a state string from an OAuth flow.
|
||||
*
|
||||
* @param state the state string.
|
||||
* @returns the parsed state, or undefined if the state is not valid JSON.
|
||||
*/
|
||||
public static parseState(state: string): ChatOAuthState | undefined {
|
||||
try {
|
||||
return JSON.parse(state);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL that the chat platform redirects to after install.
|
||||
*
|
||||
* @param service the chat service.
|
||||
* @param options the base URL and optional query string.
|
||||
* @returns the install callback URL.
|
||||
*/
|
||||
public static connectUrl(
|
||||
service: ChatIntegrationService,
|
||||
{ baseUrl, params }: { baseUrl: string; params?: string } = {
|
||||
baseUrl: env.URL,
|
||||
params: undefined,
|
||||
}
|
||||
) {
|
||||
return params
|
||||
? `${baseUrl}/auth/${service}.post?${params}`
|
||||
: `${baseUrl}/auth/${service}.post`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the settings path for a service.
|
||||
*
|
||||
* @param service the chat service.
|
||||
* @returns the settings path.
|
||||
*/
|
||||
public static settingsPath(service: ChatIntegrationService) {
|
||||
return integrationSettingsPath(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the settings path for a service with an error code.
|
||||
*
|
||||
* @param service the chat service.
|
||||
* @param error the error code.
|
||||
* @returns the settings path.
|
||||
*/
|
||||
public static errorPath(service: ChatIntegrationService, error: string) {
|
||||
return integrationSettingsPath(`${service}?error=${error}`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user