mirror of
https://github.com/outline/outline.git
synced 2026-12-06 03:05:08 +03:00
feat: Granola integration (#14906)
* wip * fix: Address review feedback on Granola integration - Limit the size of Granola API responses - Load the team when authorizing notes into personal collections - Add the user's connection from granola.list to the integrations store * feat: Connect Granola from a dialog * fix: Accept Granola webhook test events * Copy pass * Copy pass
This commit is contained in:
1 parent
e23a9566fb
commit
ba2d9888cc
28 files changed
+2287
-31
No files matched your search
@@ -18,6 +18,7 @@ GITHUB_CLIENT_ID=123;
|
||||
GITHUB_CLIENT_SECRET=123;
|
||||
GITHUB_APP_NAME=outline-test;
|
||||
GITHUB_APP_ID=123
|
||||
GITHUB_WEBHOOK_SECRET=test-webhook-secret
|
||||
GITHUB_APP_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA\n-----END RSA PRIVATE KEY-----"
|
||||
|
||||
GITLAB_CLIENT_ID=123
|
||||
|
||||
@@ -93,6 +93,8 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
fileName?: string;
|
||||
/** The id of the document this document was duplicated from. */
|
||||
originalDocumentId?: string;
|
||||
/** A link to the document in the external source. */
|
||||
externalUrl?: string;
|
||||
};
|
||||
|
||||
@computed
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
import { stringToColor } from "@shared/utils/color";
|
||||
import { sanitizeUrl } from "@shared/utils/urls";
|
||||
import type User from "~/models/User";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import Flex from "~/components/Flex";
|
||||
@@ -20,6 +21,7 @@ type Props = {
|
||||
function Insights({ document }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
const sourceUrl = sanitizeUrl(document?.sourceMetadata?.externalUrl);
|
||||
|
||||
// Move focus into the modal to account for lazy-loading
|
||||
useLayoutEffect(() => {
|
||||
@@ -60,6 +62,17 @@ function Insights({ document }: Props) {
|
||||
})}
|
||||
</li>
|
||||
)}
|
||||
{sourceUrl && (
|
||||
<li>
|
||||
<a
|
||||
href={sourceUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{t("View original")}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
</List>
|
||||
</Text>
|
||||
</Flex>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import crypto from "node:crypto";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import { Integration } from "@server/models";
|
||||
import {
|
||||
@@ -8,8 +9,9 @@ import {
|
||||
buildUser,
|
||||
buildViewer,
|
||||
} from "@server/test/factories";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
import { getTestServer, mockTaskSchedule } from "@server/test/support";
|
||||
import { GitHub, InstallationAccess } from "../github";
|
||||
import env from "../env";
|
||||
import { SetupAction } from "./schema";
|
||||
|
||||
const server = getTestServer();
|
||||
@@ -200,3 +202,40 @@ describe("#integrations.list", () => {
|
||||
expect(body.data[0].settings).toEqual({ url: "https://example.com" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("#github.webhooks", () => {
|
||||
const schedule = mockTaskSchedule();
|
||||
|
||||
// Spaces and non-ASCII text are not kept when the parsed body is stringified again.
|
||||
const body = '{ "action": "opened", "title": "Caf\\u00e9 ☕" }';
|
||||
|
||||
const deliver = (signedBody: string) =>
|
||||
server.post("/api/github.webhooks", {
|
||||
body,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-hub-signature-256": `sha256=${crypto
|
||||
.createHmac("sha256", env.GITHUB_WEBHOOK_SECRET!)
|
||||
.update(signedBody)
|
||||
.digest("hex")}`,
|
||||
},
|
||||
});
|
||||
|
||||
it("accepts a signature of the raw body", async () => {
|
||||
const res = await deliver(body);
|
||||
|
||||
expect(res.status).toEqual(202);
|
||||
expect(schedule).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payload: { action: "opened", title: "Café ☕" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a signature of the parsed body", async () => {
|
||||
const res = await deliver(JSON.stringify(JSON.parse(body)));
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
type Props = {
|
||||
/** The size of the icon, 24px is default to match standard icons */
|
||||
size?: number;
|
||||
/** The color of the icon, defaults to the current text color */
|
||||
fill?: string;
|
||||
};
|
||||
|
||||
/** The Granola brand mark, sized to match the other integration icons. */
|
||||
export default function Icon({ size = 24, fill = "currentColor" }: Props) {
|
||||
return (
|
||||
// The view box centers the mark at 16 of 24px, like the Figma icon.
|
||||
<svg fill={fill} width={size} height={size} viewBox="-85 -75 1500 1500">
|
||||
<path d="M1033.8,1021.6c-21.6,24.2-40.1,38.9-50.3,45.9 c-4.8,3.2-7.8,7.7-12,11.5 c-22.2,19.1-46.3,24.8-63.1,38.2 c-22.8,17.9-108,39.1-132.2,46.5 c-41,9.3-87,12.7-137.4,10.8c-10.9,0-21-0-30.3-0.7 c-3.8-0.3-7.5,0.7-11.3,0.7c-0.1,0-0.3,0-0.4,0 c-0.4,0-1.1-0.3-2-0.9c-1.1-0.6-2.3-1.1-3.5-1.1 c-0.3,0-0.7-0-1-0.1c-5.1-0.7-7.8,1.1-9.7,2.1 c-1.5,0.8-3.1,0.1-4.5-0.8c-4.4-2.8-14.3-9.1-17.7-10.2 c-3.3-1-3.6,0.4-5.4,0.7c-1.2,0.2-2.4-0.2-3.3-1 c-1-0.9-2.1-2.2-4.5-3.5c-4.5-2.4-6.9,3-13.5-3 c-1-0.9-1.5-2.6-2.8-2.7c-0.3-0-0.6-0-0.9-0.1 c-6.7-1.3-18.9-3.8-27.1-6.3c-9.6-2.6-6.6-4.5-10.8-6.4 c-56.4-21-136.8-62.5-166.2-91.9 c-10.8-10.8-23.4-35.7-31.2-42.1 c-6-5.1-18-15.3-21-20.4c-2.4-4.5-0-12.8-4.2-18.5 c-5.4-7-16.2-10.8-26.4-26.8 c-11.4-17.9-18-41.5-29.4-65.7 C202,854.9,175,786,175,660.4c0-84.2,39-200.9,55.8-216.9 c10.8-10.2,9.6-32.5,17.4-43.4 c89-123.7,244.8-214.8,430.2-224.4 c7.5-0.4,15.1-0.6,22.6-0.7c45.7-0.5,91.6,4.5,136,15.3 c44.4,10.8,86.9,27.7,128.3,47c0,0,4.9,0.4,6.2,1 c2.2,1.1,3.1,3,5.2,4.1c2.2,1.1,5.3,0.2,7.6,0.6 c7.8,1.6,9.2,6.2,10.6,8c1.7,2.2,3.8,3.1,7.8,4.2 c10.3,3,11.7,6.4,13.1,7.9c1.1,1.3,1.6,2.9,2.2,4.3 c0.6,1.5,1.7,2.8,3.3,3.2c3.4,0.8,8.1,5,9,10.7 c0.6,3.7,4.6,5.3,3.6,12.3c-0.4,2.3,2,5.6-10.6,18.1 s-39.2,20.3-55.3,14.1c-55.9-21.4-64.1-25.5-86.6-31.6 c-41-11.2-75.9-18.8-118.4-18 c-67.8,1.3-121.2,7.7-185.4,30 c-28.1,10-81.3,37.1-107.9,58.2 c-26.7,21.1-65.3,50.3-81.2,77.3 c-5.6,9.5-11.9,18.5-25.1,33.2 c-19.2,21-41.4,81.9-48.6,111.3 c-1.8,6.4,3,13.4,0.6,19.8c-2.4,7-13.8,10.2-15,16 c-4.8,20.4-3.6,46.6-3.6,68.9c0,12.1,3.6,28.7,7.8,38.3 c3,6.4,12.6,10.8,13.8,17.2c0.6,4.5-5.4,9.6-5.4,13.4 c0,3.2,5.4,46.6,8.4,53c4.2,7.7,17.4,17.2,21,26.1 c2.4,6.4-4.2,12.8,0.6,19.1c3,3.8,12.6,3.8,16.2,8.9 c4.8,6.4,15,24.9,19.8,30.6c3.6,4.5,10.2,6.4,13.2,8.3 c9,6.4,1.2,12.1,9.6,21.7c26.4,30,67.2,67,106.2,83.6 c6,2.6,67.8,26.1,71.4,26.1 c87,12.8,184.8,11.6,269.4-35.6 c19.8-10.8,132-88.8,150.6-181.3 c4.2-18.5,9.6-63.2,7.2-81 c-9.6-66.3-50.5-161.8-125.4-197.1 c-39.9-18.8-70.2-18.5-78-17.2 c-22.8,4.5-30.6-8.9-51.6-7 c-64.2,5.1-127.2,23-176.4,74.6 c-45,47.8-54,109.1-31.2,148 c2.4,5.1,1.2,11.5-3.6,14.7c-2.1,1.3-4,2.9-4.9,4.5 c-1.8,3.3,3.4,5.1,7,6.4c25,8.7,34,50.8,67,49.1 h7.2c0,0,13.8-0,19.2-6.4c4.4-5.2,4.4-11.3,1.3-14.1 c-1.4-1.2-3.2-1.9-3.6-3.7c-0.5-2-0.7-4.6-0.7-5.8 c0-1.3,1.8-1.9,1.8-3.2c-0-3.8-4.2-7-3.6-10.8 c0.4-2,3.2-4.9,5.2-7c1.5-1.6,1.5-3.6,0.5-5.6 c-0-0.1-0.1-0.1-0.1-0.2c-1-2-1.1-4.3-0.5-6.4 c0.4-1.2,0.8-2.5,0.8-3.8c0.6-5.7-1.8-8.3-2.4-12.8 c0-1.6,8.5-5.3,11.6-7.7c0.9-0.7,1-1.8,0.7-2.9 c-0.6-2.3-1.5-3-1.5-7.3c0-1,0.9-2.4,1.9-3.8 c2.1-2.7,4-5.6,4.9-8.9l1.7-5.8 c0.7-2.4,2.5-4.3,4.9-5.1c4.1-1.4,2.2-8.1,6.2-10 c1.1-0.5,4,0.1,8.6-0.8c9.6-1.9,3-5.1,4.8-10.2 c0.8-3.1,3.4-2.8,6-2.6c2,0.2,4-0.5,5.4-1.9 c1.4-1.4,2.9-3,4.8-3.8c2.4-1,8.8-1.2,13.4-1.3 c1.9-0,3.7-0.3,5.6-0.5c5.1-0.6,12.3-0.2,15.8-0.8 c4.2-0.6,6.6-4.5,10.2-4.5c3,0,7.2,5.1,10.2,5.1 c3-0,6-2.6,9-2.6c1.8,0,2.4,3.2,5.4,3.2 h1.2c0,0,27.6,0.6,56.4,18.5c19.8,12.1,34.2,41.5,34.2,41.5 c13.8,23.6-1.5,47.9-1.5,69.6c0,8.9,3,16.6,1.2,24.9 c-1.2,6.4-6,11.5-7.8,16.6c-1.8,4.5-1.8,10.2-7.8,18.5 c-4.8,7-7.2,7-8.4,8.3c-1.8,1.9-17.3,25.4-27.5,34.3 c-27,24.2-52,31.3-88.6,32c-16.2,0.6-18,3.8-20.4,3.8 c-8.4,0.6-46.8-1.3-58.8-3.2c0,0-53.4-10.2-74.4-20.4 c-11.4-5.1-86.4-60.6-103.2-91.9 c-52.2-98.2-40.2-202.8,13.8-273 c39-51,103.2-117.4,255.6-130.1 c77.4-6.4,146.4,3.8,200.4,29.3 c76.2,35.7,132,98.9,166.8,173.5 C1154.8,743.3,1151.4,887.6,1033.8,1021.6z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { EditIcon, PlusIcon, TrashIcon } from "outline-icons";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation, Trans } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import Button from "~/components/Button";
|
||||
import Flex from "~/components/Flex";
|
||||
import Heading from "~/components/Heading";
|
||||
import List from "~/components/List";
|
||||
import ListItem from "~/components/List/Item";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import Text from "~/components/Text";
|
||||
import Time from "~/components/Time";
|
||||
import env from "~/env";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useRequest from "~/hooks/useRequest";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import type Integration from "~/models/Integration";
|
||||
import type Policy from "~/models/Policy";
|
||||
import type User from "~/models/User";
|
||||
import { ConnectedButton } from "~/scenes/Settings/components/ConnectedButton";
|
||||
import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene";
|
||||
import type { PartialExcept } from "~/types";
|
||||
import { client } from "~/utils/ApiClient";
|
||||
import type { GranolaRule } from "../shared/types";
|
||||
import GranolaIcon from "./Icon";
|
||||
import { GranolaConnectButton } from "./components/GranolaButton";
|
||||
import RuleDialog from "./components/RuleDialog";
|
||||
|
||||
interface Connection {
|
||||
id: string;
|
||||
userId: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface ListResponse {
|
||||
data: Connection[];
|
||||
users: PartialExcept<User, "id">[];
|
||||
policies: Policy[];
|
||||
}
|
||||
|
||||
function Granola() {
|
||||
const { integrations, users } = useStores();
|
||||
const user = useCurrentUser();
|
||||
const { t } = useTranslation();
|
||||
const appName = env.APP_NAME;
|
||||
|
||||
const integration = integrations.find({
|
||||
type: IntegrationType.LinkedAccount,
|
||||
service: IntegrationService.Granola,
|
||||
userId: user.id,
|
||||
}) as Integration<IntegrationType.LinkedAccount> | undefined;
|
||||
const settings = integration?.settings?.granola;
|
||||
|
||||
const fetchConnections = useCallback(async () => {
|
||||
const res = await client.post<ListResponse>("/granola.list");
|
||||
res.users.forEach((item) => users.add(item));
|
||||
// The rules come from the store, and another tab can change the connection.
|
||||
res.data
|
||||
.filter((item) => item.userId === user.id)
|
||||
.forEach((item) => integrations.add(item));
|
||||
integrations.addPolicies(res.policies);
|
||||
return res.data;
|
||||
}, [users, integrations, user.id]);
|
||||
const { data: connections, request: refresh } = useRequest(
|
||||
fetchConnections,
|
||||
true
|
||||
);
|
||||
|
||||
const handleDisconnect = useCallback(
|
||||
async (id: string) => {
|
||||
await client.post("/integrations.delete", { id });
|
||||
if (integrations.get(id)) {
|
||||
integrations.remove(id);
|
||||
}
|
||||
await refresh();
|
||||
},
|
||||
[integrations, refresh]
|
||||
);
|
||||
|
||||
return (
|
||||
<IntegrationScene title="Granola" icon={<GranolaIcon />}>
|
||||
<Heading>Granola</Heading>
|
||||
<Text as="p">
|
||||
<Trans>
|
||||
Link your Granola account to {{ appName }} and your meeting notes will
|
||||
show up as documents as soon as they’re ready. Everyone connects their
|
||||
own account and chooses where their notes go.
|
||||
</Trans>
|
||||
</Text>
|
||||
|
||||
{connections &&
|
||||
(connections.length ? (
|
||||
<>
|
||||
<Heading as="h2">
|
||||
<Flex justify="space-between" auto>
|
||||
{t("Connected")}
|
||||
{!integration && (
|
||||
<GranolaConnectButton
|
||||
icon={<PlusIcon />}
|
||||
onConnect={refresh}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
</Heading>
|
||||
<List>
|
||||
{connections.map((connection) => (
|
||||
<ConnectionItem
|
||||
key={connection.id}
|
||||
connection={connection}
|
||||
onDisconnect={handleDisconnect}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
<GranolaConnectButton icon={<GranolaIcon />} onConnect={refresh} />
|
||||
</p>
|
||||
))}
|
||||
|
||||
{integration && settings ? (
|
||||
<Rules integration={integration} rules={settings.rules} />
|
||||
) : null}
|
||||
</IntegrationScene>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConnectionItemProps {
|
||||
connection: Connection;
|
||||
onDisconnect: (id: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const ConnectionItem = observer(function ConnectionItem({
|
||||
connection,
|
||||
onDisconnect,
|
||||
}: ConnectionItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { users, policies } = useStores();
|
||||
const user = useCurrentUser();
|
||||
const owner = users.get(connection.userId);
|
||||
const canDelete = policies.abilities(connection.id).delete;
|
||||
const isOwn = connection.userId === user.id;
|
||||
|
||||
return (
|
||||
<ListItem
|
||||
small
|
||||
title={
|
||||
isOwn
|
||||
? t("{{ userName }} (you)", { userName: owner?.name })
|
||||
: (owner?.name ?? t("Unknown user"))
|
||||
}
|
||||
subtitle={
|
||||
<>
|
||||
<Trans>Connected on</Trans>{" "}
|
||||
<Time
|
||||
dateTime={connection.createdAt}
|
||||
relative={false}
|
||||
format={{ en_US: "MMMM d, y" }}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
image={owner ? <Avatar model={owner} size={AvatarSize.Large} /> : null}
|
||||
actions={
|
||||
canDelete ? (
|
||||
<ConnectedButton
|
||||
onClick={() => onDisconnect(connection.id)}
|
||||
confirmationMessage={
|
||||
isOwn
|
||||
? t(
|
||||
"Disconnecting will stop creating documents from your new meeting notes. Are you sure?"
|
||||
)
|
||||
: t(
|
||||
"Disconnecting will stop creating documents from new meeting notes by {{ userName }}. Are you sure?",
|
||||
{ userName: owner?.name }
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
interface RulesProps {
|
||||
integration: Integration<IntegrationType.LinkedAccount>;
|
||||
rules: GranolaRule[];
|
||||
}
|
||||
|
||||
const Rules = observer(function Rules({ integration, rules }: RulesProps) {
|
||||
const { t } = useTranslation();
|
||||
const { collections, documents, dialogs, integrations } = useStores();
|
||||
|
||||
const save = useCallback(
|
||||
async (next: GranolaRule[]) => {
|
||||
try {
|
||||
const res = await client.post("/granola.update", {
|
||||
id: integration.id,
|
||||
rules: next,
|
||||
});
|
||||
integrations.add(res.data);
|
||||
} catch (err) {
|
||||
toast.error(errToString(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
[integration.id, integrations]
|
||||
);
|
||||
|
||||
const openDialog = (index?: number) => {
|
||||
const rule = index === undefined ? undefined : rules[index];
|
||||
dialogs.openModal({
|
||||
title: rule ? t("Edit rule") : t("Add rule"),
|
||||
content: (
|
||||
<RuleDialog
|
||||
integrationId={integration.id}
|
||||
rule={rule}
|
||||
usedFolderIds={rules
|
||||
.filter((_, i) => i !== index)
|
||||
.map((other) => other.folderId)}
|
||||
onSubmit={async (updated) => {
|
||||
await save(
|
||||
index === undefined
|
||||
? [...rules, updated]
|
||||
: rules.map((other, i) => (i === index ? updated : other))
|
||||
);
|
||||
dialogs.closeAllModals();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const locationName = (rule: GranolaRule) =>
|
||||
(rule.documentId && documents.get(rule.documentId)?.title) ||
|
||||
(rule.collectionId && collections.get(rule.collectionId)?.name) ||
|
||||
rule.locationName ||
|
||||
t("Unknown location");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Heading as="h2">
|
||||
<Flex justify="space-between" auto>
|
||||
{t("Rules")}
|
||||
<Button icon={<PlusIcon />} onClick={() => openDialog()} neutral>
|
||||
{t("Add rule")}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Heading>
|
||||
{rules.length ? (
|
||||
<List>
|
||||
{rules.map((rule, index) => (
|
||||
<ListItem
|
||||
key={rule.folderId ?? "*"}
|
||||
small
|
||||
title={
|
||||
rule.folderId === null
|
||||
? t("All other notes")
|
||||
: (rule.folderName ?? rule.folderId)
|
||||
}
|
||||
subtitle={locationName(rule)}
|
||||
actions={
|
||||
<Flex gap={4}>
|
||||
<Tooltip content={t("Edit")}>
|
||||
<NudeButton
|
||||
aria-label={t("Edit")}
|
||||
onClick={() => openDialog(index)}
|
||||
>
|
||||
<EditIcon />
|
||||
</NudeButton>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("Remove")}>
|
||||
<NudeButton
|
||||
aria-label={t("Remove")}
|
||||
onClick={() =>
|
||||
save(rules.filter((_, i) => i !== index)).catch(
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
>
|
||||
<TrashIcon />
|
||||
</NudeButton>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
) : (
|
||||
<Text as="p" type="secondary">
|
||||
<Trans>
|
||||
Add a rule to choose where your notes are saved. Notes that don’t
|
||||
match a rule won’t be added.
|
||||
</Trans>
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default observer(Granola);
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Button, { type Props as ButtonProps } from "~/components/Button";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { GranolaConnectDialog } from "./GranolaConnectDialog";
|
||||
|
||||
interface Props extends ButtonProps<"button"> {
|
||||
/** Called after the account is connected. */
|
||||
onConnect: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Button that opens a dialog to connect a Granola account.
|
||||
*/
|
||||
export function GranolaConnectButton({ onConnect, ...rest }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { dialogs } = useStores();
|
||||
|
||||
const handleClick = () => {
|
||||
dialogs.openModal({
|
||||
title: t("Connect Granola"),
|
||||
content: <GranolaConnectDialog onConnect={onConnect} />,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Button onClick={handleClick} neutral {...rest}>
|
||||
{t("Connect")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import * as React from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation, Trans } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import Button from "~/components/Button";
|
||||
import Flex from "~/components/Flex";
|
||||
import Input from "~/components/Input";
|
||||
import Text from "~/components/Text";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { client } from "~/utils/ApiClient";
|
||||
|
||||
interface FormData {
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** Called after the account is connected. */
|
||||
onConnect: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dialog that connects the current user's Granola account with an API key.
|
||||
*/
|
||||
export function GranolaConnectDialog({ onConnect }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { dialogs, integrations } = useStores();
|
||||
const { register, handleSubmit, formState } = useForm<FormData>({
|
||||
defaultValues: { apiKey: "" },
|
||||
});
|
||||
|
||||
const handleFormSubmit = React.useCallback(
|
||||
async (data: FormData) => {
|
||||
try {
|
||||
const res = await client.post("/granola.connect", {
|
||||
apiKey: data.apiKey.trim(),
|
||||
});
|
||||
integrations.add(res.data);
|
||||
integrations.addPolicies(res.policies);
|
||||
dialogs.closeAllModals();
|
||||
await onConnect();
|
||||
} catch (err) {
|
||||
toast.error(errToString(err));
|
||||
}
|
||||
},
|
||||
[dialogs, integrations, onConnect]
|
||||
);
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<Flex column gap={12}>
|
||||
<Text as="p" type="secondary">
|
||||
<Trans>
|
||||
You can create a personal API key in Granola under Settings →
|
||||
Connectors → API keys. API keys are only available on Granola
|
||||
Business and Enterprise plans.
|
||||
</Trans>
|
||||
</Text>
|
||||
<Input
|
||||
label={t("API key")}
|
||||
type="password"
|
||||
placeholder="grn_…"
|
||||
autoComplete="off"
|
||||
{...register("apiKey")}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Flex justify="flex-end">
|
||||
<Button type="submit" disabled={formState.isSubmitting}>
|
||||
{formState.isSubmitting ? `${t("Connecting")}…` : t("Connect")}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { breakpoint } from "@shared/styles/breakpoint";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
import { NavigationNodeType } from "@shared/types";
|
||||
import Button from "~/components/Button";
|
||||
import DocumentExplorer from "~/components/DocumentExplorer";
|
||||
import {
|
||||
FlexContainer,
|
||||
Footer,
|
||||
} from "~/components/DocumentExplorer/Components";
|
||||
import type { Option } from "~/components/InputSelect";
|
||||
import { LabelText } from "~/components/Input";
|
||||
import { InputSelect } from "~/components/InputSelect";
|
||||
import Text from "~/components/Text";
|
||||
import useCollectionTrees from "~/hooks/useCollectionTrees";
|
||||
import useRequest from "~/hooks/useRequest";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { client } from "~/utils/ApiClient";
|
||||
import type { GranolaRule } from "../../shared/types";
|
||||
|
||||
interface Folder {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** The ID of the Granola integration. */
|
||||
integrationId: string;
|
||||
/** The rule to edit, if any. */
|
||||
rule?: GranolaRule;
|
||||
/** Folder IDs that the other rules use, null is the rule for all other notes. */
|
||||
usedFolderIds: (string | null)[];
|
||||
/** Called with the new rule. */
|
||||
onSubmit: (rule: GranolaRule) => Promise<void>;
|
||||
}
|
||||
|
||||
const OtherNotes = "*";
|
||||
|
||||
/**
|
||||
* Dialog that chooses a Granola folder and the Outline location that its notes
|
||||
* go to.
|
||||
*/
|
||||
function RuleDialog({ integrationId, rule, usedFolderIds, onSubmit }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { policies } = useStores();
|
||||
const collectionTrees = useCollectionTrees();
|
||||
const [folderId, setFolderId] = useState<string | undefined>(
|
||||
rule ? (rule.folderId ?? OtherNotes) : undefined
|
||||
);
|
||||
const [location, setLocation] = useState<NavigationNode | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const fetchFolders = useCallback(async () => {
|
||||
const res = await client.post<{ data: Folder[] }>("/granola.folders", {
|
||||
id: integrationId,
|
||||
});
|
||||
return res.data;
|
||||
}, [integrationId]);
|
||||
const { data: folders, loading } = useRequest(fetchFolders, true);
|
||||
|
||||
const folderOptions = useMemo((): Option[] => {
|
||||
const isAvailable = (id: string | null) => !usedFolderIds.includes(id);
|
||||
|
||||
return [
|
||||
...(isAvailable(null)
|
||||
? [
|
||||
{
|
||||
type: "item" as const,
|
||||
label: t("All other notes"),
|
||||
value: OtherNotes,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(folders ?? [])
|
||||
.filter((folder) => isAvailable(folder.id))
|
||||
.map((folder) => ({
|
||||
type: "item" as const,
|
||||
label: folder.name,
|
||||
value: folder.id,
|
||||
})),
|
||||
];
|
||||
}, [folders, usedFolderIds, t]);
|
||||
|
||||
// Only offer collections the user can create documents in.
|
||||
const items = useMemo(
|
||||
() =>
|
||||
collectionTrees.filter((node) =>
|
||||
node.collectionId
|
||||
? policies.get(node.collectionId)?.abilities.createDocument
|
||||
: true
|
||||
),
|
||||
[policies, collectionTrees]
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!folderId || !location) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSubmit({
|
||||
folderId: folderId === OtherNotes ? null : folderId,
|
||||
folderName: folders?.find((folder) => folder.id === folderId)?.name,
|
||||
...(location.type === NavigationNodeType.Collection
|
||||
? { collectionId: location.id }
|
||||
: { documentId: location.id }),
|
||||
locationName: location.title,
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout column>
|
||||
<FolderSelect>
|
||||
<InputSelect
|
||||
label={t("Granola folder")}
|
||||
options={folderOptions}
|
||||
value={folderId}
|
||||
onChange={setFolderId}
|
||||
// The default placeholder lowercases the label, which would read "granola".
|
||||
displayValue={(option) => option?.label ?? t("Choose a folder")}
|
||||
disabled={loading}
|
||||
/>
|
||||
</FolderSelect>
|
||||
<LocationLabel>{t("Location")}</LocationLabel>
|
||||
<ExplorerFill>
|
||||
<DocumentExplorer
|
||||
items={items}
|
||||
defaultValue={rule?.documentId ?? rule?.collectionId}
|
||||
onSelect={setLocation}
|
||||
onSubmit={setLocation}
|
||||
/>
|
||||
</ExplorerFill>
|
||||
<Footer justify="space-between" align="center" gap={8}>
|
||||
<Text ellipsis type="secondary">
|
||||
{location
|
||||
? location.title || t("Untitled")
|
||||
: t("Choose where these notes are saved")}
|
||||
</Text>
|
||||
<Button
|
||||
disabled={!folderId || !location || saving}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
{saving ? `${t("Saving")}…` : t("Save")}
|
||||
</Button>
|
||||
</Footer>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
// Matches the height of the document move dialog, so the folder select takes
|
||||
// its space from the explorer list rather than pushing the footer out.
|
||||
const Layout = styled(FlexContainer)`
|
||||
height: calc(65vh + 76px);
|
||||
|
||||
${breakpoint("tablet")`
|
||||
height: max(calc(40vh + 76px), 340px);
|
||||
`}
|
||||
`;
|
||||
|
||||
const FolderSelect = styled.div`
|
||||
flex-shrink: 0;
|
||||
padding: 0 24px 12px;
|
||||
`;
|
||||
|
||||
const LocationLabel = styled(LabelText)`
|
||||
flex-shrink: 0;
|
||||
padding: 0 24px 4px;
|
||||
`;
|
||||
|
||||
// The explorer sizes its list to the viewport, here it fills the space left.
|
||||
const ExplorerFill = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
> div {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
> div > :first-child {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
> div > div:last-child {
|
||||
flex: 1;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export default observer(RuleDialog);
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createLazyComponent } from "~/components/LazyLoad";
|
||||
import { Hook, PluginManager } from "~/utils/PluginManager";
|
||||
import config from "../plugin.json";
|
||||
import Icon from "./Icon";
|
||||
|
||||
PluginManager.add([
|
||||
{
|
||||
...config,
|
||||
type: Hook.Settings,
|
||||
value: {
|
||||
group: "Integrations",
|
||||
icon: Icon,
|
||||
description:
|
||||
"Connect your Granola account to Outline to automatically turn your meeting notes into documents.",
|
||||
component: createLazyComponent(() => import("./Settings")),
|
||||
enabled: (_team, user) => !user.isGuest && !user.isViewer,
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"id": "granola",
|
||||
"name": "Granola",
|
||||
"priority": 15,
|
||||
"description": "Adds a Granola integration that publishes meeting notes as documents.",
|
||||
"after": "figma"
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import crypto from "node:crypto";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import env from "@server/env";
|
||||
import { Integration, IntegrationAuthentication } from "@server/models";
|
||||
import type { User } from "@server/models";
|
||||
import {
|
||||
buildAdmin,
|
||||
buildCollection,
|
||||
buildGuestUser,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { getTestServer, mockTaskSchedule } from "@server/test/support";
|
||||
import { Granola, GranolaApiError } from "../granola";
|
||||
|
||||
const server = getTestServer();
|
||||
const schedule = mockTaskSchedule();
|
||||
const signingKey = Buffer.from("secret-key");
|
||||
const signingSecret = `whsec_${signingKey.toString("base64")}`;
|
||||
|
||||
async function buildIntegration(user: User) {
|
||||
const authentication = await IntegrationAuthentication.create({
|
||||
service: IntegrationService.Granola,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: "grn_key",
|
||||
clientSecret: signingSecret,
|
||||
});
|
||||
return Integration.create<Integration<IntegrationType.LinkedAccount>>({
|
||||
service: IntegrationService.Granola,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: { granola: { webhookEndpointId: "whe_1", rules: [] } },
|
||||
});
|
||||
}
|
||||
|
||||
function deliver(
|
||||
integrationId: string,
|
||||
payload: object | string,
|
||||
key = signingKey
|
||||
) {
|
||||
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
||||
const id = "msg_1";
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
const signature = crypto
|
||||
.createHmac("sha256", key)
|
||||
.update(`${id}.${timestamp}.${body}`)
|
||||
.digest("base64");
|
||||
|
||||
return server.post(`/api/granola.webhooks?id=${integrationId}`, {
|
||||
body,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"webhook-id": id,
|
||||
"webhook-timestamp": timestamp,
|
||||
"webhook-signature": `v1,${signature}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("#granola.webhooks", () => {
|
||||
it("schedules a task for a generated note", async () => {
|
||||
const integration = await buildIntegration(await buildUser());
|
||||
const res = await deliver(integration.id, {
|
||||
event_id: "msg_1",
|
||||
event_type: "note.generated",
|
||||
note_id: "not_1",
|
||||
occurred_at: "2026-01-27T15:30:00Z",
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(202);
|
||||
expect(schedule).toHaveBeenCalledWith({
|
||||
integrationId: integration.id,
|
||||
noteId: "not_1",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a body that is not compact JSON", async () => {
|
||||
const integration = await buildIntegration(await buildUser());
|
||||
const res = await deliver(
|
||||
integration.id,
|
||||
'{\n "event_type": "note.generated",\n "note_id": "not_1",\n "title": "Café"\n}'
|
||||
);
|
||||
|
||||
expect(res.status).toEqual(202);
|
||||
expect(schedule).toHaveBeenCalledWith({
|
||||
integrationId: integration.id,
|
||||
noteId: "not_1",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores other events", async () => {
|
||||
const integration = await buildIntegration(await buildUser());
|
||||
const res = await deliver(integration.id, {
|
||||
event_type: "note.edited",
|
||||
note_id: "not_1",
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(202);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a test event without a note", async () => {
|
||||
const integration = await buildIntegration(await buildUser());
|
||||
const res = await deliver(integration.id, { event_type: "webhook.test" });
|
||||
|
||||
expect(res.status).toEqual(202);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an invalid signature", async () => {
|
||||
const integration = await buildIntegration(await buildUser());
|
||||
const res = await deliver(
|
||||
integration.id,
|
||||
{ event_type: "note.generated", note_id: "not_1" },
|
||||
Buffer.from("other-key")
|
||||
);
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("#granola.list", () => {
|
||||
it("lists every connection with the user that connected it", async () => {
|
||||
const user = await buildUser();
|
||||
const other = await buildUser({ teamId: user.teamId });
|
||||
const admin = await buildAdmin({ teamId: user.teamId });
|
||||
const mine = await buildIntegration(user);
|
||||
const theirs = await buildIntegration(other);
|
||||
await buildIntegration(await buildUser());
|
||||
|
||||
const res = await server.post("/api/granola.list", user);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.map((item: { id: string }) => item.id)).toEqual([
|
||||
mine.id,
|
||||
theirs.id,
|
||||
]);
|
||||
expect(body.data[0].settings.granola.webhookEndpointId).toEqual("whe_1");
|
||||
expect(body.data[1].settings).toBeUndefined();
|
||||
expect(body.users.map((item: { name: string }) => item.name)).toEqual([
|
||||
user.name,
|
||||
other.name,
|
||||
]);
|
||||
expect(body.users[1].email).toBeUndefined();
|
||||
|
||||
const abilities = (id: string) =>
|
||||
body.policies.find((policy: { id: string }) => policy.id === id)
|
||||
.abilities;
|
||||
expect(abilities(mine.id).delete).toBe(true);
|
||||
expect(abilities(theirs.id).delete).toBe(false);
|
||||
expect(abilities(mine.id).update).toBe(true);
|
||||
expect(abilities(theirs.id).update).toBe(false);
|
||||
|
||||
const adminRes = await server.post("/api/granola.list", admin);
|
||||
const adminBody = await adminRes.json();
|
||||
// Admins can disconnect any account but only change their own.
|
||||
expect(
|
||||
adminBody.policies.map(
|
||||
(policy: { abilities: { delete: boolean; update: boolean } }) => [
|
||||
policy.abilities.delete,
|
||||
policy.abilities.update,
|
||||
]
|
||||
)
|
||||
).toEqual([
|
||||
[true, false],
|
||||
[true, false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects a guest", async () => {
|
||||
const res = await server.post("/api/granola.list", await buildGuestUser());
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("#granola.connect", () => {
|
||||
it("creates a linked account with a webhook endpoint", async () => {
|
||||
const user = await buildUser();
|
||||
const create = vi
|
||||
.spyOn(Granola, "createWebhookEndpoint")
|
||||
.mockResolvedValue({
|
||||
id: "whe_1",
|
||||
signing_secret: signingSecret,
|
||||
created_by: { name: "Ada", email: "ada@example.com" },
|
||||
});
|
||||
|
||||
const res = await server.post("/api/granola.connect", user, {
|
||||
body: { apiKey: "grn_key" },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(create).toHaveBeenCalledWith(
|
||||
"grn_key",
|
||||
expect.stringContaining(`/api/granola.webhooks?id=${body.data.id}`)
|
||||
);
|
||||
expect(body.data.settings.granola.account.email).toEqual("ada@example.com");
|
||||
|
||||
const integration = await Integration.scope("withAuthentication").findByPk(
|
||||
body.data.id,
|
||||
{ rejectOnEmpty: true }
|
||||
);
|
||||
expect(integration.type).toEqual(IntegrationType.LinkedAccount);
|
||||
expect(integration.authentication.token).toEqual("grn_key");
|
||||
expect(integration.authentication.clientSecret).toEqual(signingSecret);
|
||||
|
||||
const again = await server.post("/api/granola.connect", user, {
|
||||
body: { apiKey: "grn_key" },
|
||||
});
|
||||
expect(again.status).toEqual(400);
|
||||
});
|
||||
|
||||
it("rejects a server that is not public HTTPS", async () => {
|
||||
env.URL = "http://localhost:3000";
|
||||
const user = await buildUser();
|
||||
const create = vi.spyOn(Granola, "createWebhookEndpoint");
|
||||
|
||||
const res = await server.post("/api/granola.connect", user, {
|
||||
body: { apiKey: "grn_key" },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(400);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an invalid API key", async () => {
|
||||
const user = await buildUser();
|
||||
vi.spyOn(Granola, "createWebhookEndpoint").mockRejectedValue(
|
||||
new GranolaApiError(401, "Invalid API key")
|
||||
);
|
||||
|
||||
const res = await server.post("/api/granola.connect", user, {
|
||||
body: { apiKey: "grn_bad" },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(400);
|
||||
expect(
|
||||
await Integration.count({
|
||||
where: { userId: user.id, service: IntegrationService.Granola },
|
||||
})
|
||||
).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("#granola.update", () => {
|
||||
it("saves rules for a collection the owner can use", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await buildIntegration(user);
|
||||
const rules = [{ folderId: null, collectionId: collection.id }];
|
||||
|
||||
const res = await server.post("/api/granola.update", user, {
|
||||
body: { id: integration.id, rules },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
await integration.reload();
|
||||
expect(integration.settings.granola?.rules).toEqual(rules);
|
||||
expect(integration.settings.granola?.webhookEndpointId).toEqual("whe_1");
|
||||
});
|
||||
|
||||
it("rejects a collection the owner cannot use", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
permission: null,
|
||||
});
|
||||
const integration = await buildIntegration(user);
|
||||
|
||||
const res = await server.post("/api/granola.update", user, {
|
||||
body: {
|
||||
id: integration.id,
|
||||
rules: [{ folderId: null, collectionId: collection.id }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("rejects another user, even an admin", async () => {
|
||||
const user = await buildUser();
|
||||
const member = await buildUser({ teamId: user.teamId });
|
||||
const admin = await buildAdmin({ teamId: user.teamId });
|
||||
const integration = await buildIntegration(user);
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: admin.id,
|
||||
});
|
||||
const rules = [{ folderId: null, collectionId: collection.id }];
|
||||
|
||||
for (const actor of [member, admin]) {
|
||||
const res = await server.post("/api/granola.update", actor, {
|
||||
body: { id: integration.id, rules },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
}
|
||||
|
||||
// The generic route must not change another user's rules either.
|
||||
const res = await server.post("/api/integrations.update", admin, {
|
||||
body: { id: integration.id, settings: { url: "https://example.com" } },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
|
||||
await integration.reload();
|
||||
expect(integration.settings).toEqual({
|
||||
granola: { webhookEndpointId: "whe_1", rules: [] },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import Router from "@koa/router";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { IntegrationService, IntegrationType, UserRole } from "@shared/types";
|
||||
import { authorizeDocumentCreate } from "@server/commands/documentCreator";
|
||||
import env from "@server/env";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { rateLimiter } from "@server/middlewares/rateLimiter";
|
||||
import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Integration, IntegrationAuthentication, User } from "@server/models";
|
||||
import { authorize } from "@server/policies";
|
||||
import {
|
||||
presentIntegration,
|
||||
presentPolicies,
|
||||
presentUser,
|
||||
} from "@server/presenters";
|
||||
import type { Context } from "@server/types";
|
||||
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
||||
import { Granola, GranolaApiError } from "../granola";
|
||||
import GranolaNoteTask from "../tasks/GranolaNoteTask";
|
||||
import * as T from "./schema";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
router.post(
|
||||
"granola.connect",
|
||||
rateLimiter(RateLimiterStrategy.TenPerMinute),
|
||||
auth({ role: UserRole.Member }),
|
||||
validate(T.GranolaConnectSchema),
|
||||
transaction(),
|
||||
async (ctx: Context<T.GranolaConnectReq>) => {
|
||||
const { apiKey } = ctx.input.body;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const existing = await Integration.count({
|
||||
where: {
|
||||
userId: user.id,
|
||||
service: IntegrationService.Granola,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
if (existing) {
|
||||
throw ValidationError("Your Granola account is already connected");
|
||||
}
|
||||
|
||||
const { protocol, hostname } = new URL(env.URL);
|
||||
if (protocol !== "https:" || hostname === "localhost") {
|
||||
throw ValidationError(
|
||||
"Granola needs to reach this server over HTTPS from the internet to send notes"
|
||||
);
|
||||
}
|
||||
|
||||
// The webhook URL contains the integration ID, so it is chosen first.
|
||||
const id = uuidv4();
|
||||
let endpoint;
|
||||
try {
|
||||
endpoint = await Granola.createWebhookEndpoint(
|
||||
apiKey,
|
||||
Granola.webhookUrl(id)
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof GranolaApiError) {
|
||||
throw ValidationError(
|
||||
err.status === 401
|
||||
? "That API key didn’t work. Check that you copied the whole key from Granola."
|
||||
: `Granola: ${err.message}`
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: IntegrationService.Granola,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: apiKey,
|
||||
// The signing secret verifies webhook deliveries, it is stored encrypted.
|
||||
clientSecret: endpoint.signing_secret,
|
||||
scopes: [],
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
const integration = await Integration.createWithCtx<
|
||||
Integration<IntegrationType.LinkedAccount>
|
||||
>(ctx, {
|
||||
id,
|
||||
service: IntegrationService.Granola,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: {
|
||||
granola: {
|
||||
webhookEndpointId: endpoint.id,
|
||||
account: endpoint.created_by
|
||||
? {
|
||||
name: endpoint.created_by.name ?? null,
|
||||
email: endpoint.created_by.email,
|
||||
}
|
||||
: undefined,
|
||||
rules: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
data: presentIntegration(ctx, integration),
|
||||
policies: presentPolicies(user, [integration]),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"granola.list",
|
||||
auth({ role: UserRole.Member }),
|
||||
async (ctx: Context) => {
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const integrations = await Integration.findAll({
|
||||
where: {
|
||||
teamId: user.teamId,
|
||||
service: IntegrationService.Granola,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
},
|
||||
include: [{ model: User, as: "user", required: true }],
|
||||
order: [["createdAt", "ASC"]],
|
||||
});
|
||||
|
||||
// Settings are only presented to the owner, other users see who connected.
|
||||
ctx.body = {
|
||||
data: integrations.map((integration) =>
|
||||
presentIntegration(ctx, integration)
|
||||
),
|
||||
users: integrations.map((integration) => presentUser(integration.user)),
|
||||
policies: presentPolicies(user, integrations),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"granola.folders",
|
||||
auth(),
|
||||
validate(T.GranolaFoldersSchema),
|
||||
async (ctx: Context<T.GranolaFoldersReq>) => {
|
||||
const { id } = ctx.input.body;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const integration = await Integration.scope("withAuthentication").findOne({
|
||||
where: { id, service: IntegrationService.Granola },
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
authorize(user, "read", integration);
|
||||
|
||||
let folders;
|
||||
try {
|
||||
folders = await Granola.listFolders(integration.authentication.token);
|
||||
} catch (err) {
|
||||
if (err instanceof GranolaApiError) {
|
||||
throw ValidationError(`Granola: ${err.message}`);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: folders.map((folder) => ({
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
parentFolderId: folder.parent_folder_id ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"granola.update",
|
||||
auth(),
|
||||
validate(T.GranolaUpdateSchema),
|
||||
transaction(),
|
||||
async (ctx: Context<T.GranolaUpdateReq>) => {
|
||||
const { id, rules } = ctx.input.body;
|
||||
const { user } = ctx.auth;
|
||||
const { transaction } = ctx;
|
||||
|
||||
const integration = (await Integration.findOne({
|
||||
where: { id, service: IntegrationService.Granola },
|
||||
rejectOnEmpty: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.NO_KEY_UPDATE,
|
||||
})) as Integration<IntegrationType.LinkedAccount>;
|
||||
authorize(user, "update", integration);
|
||||
|
||||
for (const rule of rules) {
|
||||
await authorizeDocumentCreate(ctx, {
|
||||
collectionId: rule.collectionId,
|
||||
parentDocumentId: rule.documentId,
|
||||
});
|
||||
}
|
||||
|
||||
const settings = integration.settings?.granola;
|
||||
if (!settings) {
|
||||
throw ValidationError("Your Granola account isn’t connected");
|
||||
}
|
||||
integration.settings = { granola: { ...settings, rules } };
|
||||
await integration.saveWithCtx(ctx);
|
||||
|
||||
ctx.body = {
|
||||
data: presentIntegration(ctx, integration),
|
||||
policies: presentPolicies(user, [integration]),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"granola.webhooks",
|
||||
validate(T.GranolaWebhookSchema),
|
||||
async (ctx: Context<T.GranolaWebhookReq>) => {
|
||||
const { id } = ctx.input.query;
|
||||
const { event_type: eventType, note_id: noteId } = ctx.input.body;
|
||||
const header = (name: string) => {
|
||||
const value = ctx.request.headers[name];
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
};
|
||||
|
||||
const integration = await Integration.scope("withAuthentication").findOne({
|
||||
where: { id, service: IntegrationService.Granola },
|
||||
});
|
||||
const secret = integration?.authentication.clientSecret;
|
||||
const webhookId = header("webhook-id");
|
||||
const timestamp = header("webhook-timestamp");
|
||||
const signature = header("webhook-signature");
|
||||
const { rawBody } = ctx.request;
|
||||
|
||||
if (
|
||||
!integration ||
|
||||
!secret ||
|
||||
!webhookId ||
|
||||
!timestamp ||
|
||||
!signature ||
|
||||
rawBody === undefined ||
|
||||
!Granola.verifySignature({
|
||||
secret,
|
||||
id: webhookId,
|
||||
timestamp,
|
||||
signature,
|
||||
body: rawBody,
|
||||
})
|
||||
) {
|
||||
ctx.status = 401;
|
||||
ctx.body = "Invalid signature";
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType === "note.generated" && noteId) {
|
||||
await new GranolaNoteTask().schedule({
|
||||
integrationId: integration.id,
|
||||
noteId,
|
||||
});
|
||||
}
|
||||
|
||||
ctx.status = 202;
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { z } from "zod";
|
||||
import { BaseSchema } from "@server/routes/api/schema";
|
||||
|
||||
export const GranolaConnectSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
/** A personal Granola API key. */
|
||||
apiKey: z.string().trim().min(1).max(255),
|
||||
}),
|
||||
});
|
||||
|
||||
export type GranolaConnectReq = z.infer<typeof GranolaConnectSchema>;
|
||||
|
||||
export const GranolaFoldersSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
/** The ID of the Granola integration. */
|
||||
id: z.uuid(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type GranolaFoldersReq = z.infer<typeof GranolaFoldersSchema>;
|
||||
|
||||
const RuleSchema = z
|
||||
.object({
|
||||
folderId: z.string().min(1).max(255).nullable(),
|
||||
folderName: z.string().max(255).optional(),
|
||||
collectionId: z.uuid().optional(),
|
||||
documentId: z.uuid().optional(),
|
||||
locationName: z.string().max(255).optional(),
|
||||
})
|
||||
.refine((rule) => !rule.collectionId !== !rule.documentId, {
|
||||
message: "One of collectionId or documentId is required",
|
||||
});
|
||||
|
||||
export const GranolaUpdateSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
/** The ID of the Granola integration. */
|
||||
id: z.uuid(),
|
||||
/** The rules that choose where notes go. */
|
||||
rules: z
|
||||
.array(RuleSchema)
|
||||
.max(50)
|
||||
.refine(
|
||||
(rules) =>
|
||||
new Set(rules.map((rule) => rule.folderId)).size === rules.length,
|
||||
{ message: "Each Granola folder can have only one rule" }
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
export type GranolaUpdateReq = z.infer<typeof GranolaUpdateSchema>;
|
||||
|
||||
export const GranolaWebhookSchema = BaseSchema.extend({
|
||||
query: z.object({
|
||||
/** The ID of the Granola integration that the webhook belongs to. */
|
||||
id: z.uuid(),
|
||||
}),
|
||||
body: z.object({
|
||||
event_type: z.string(),
|
||||
/** Missing on events that are not about a note, such as webhook.test. */
|
||||
note_id: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type GranolaWebhookReq = z.infer<typeof GranolaWebhookSchema>;
|
||||
@@ -0,0 +1,136 @@
|
||||
import crypto from "node:crypto";
|
||||
import { DocumentValidation } from "@shared/validations";
|
||||
import { buildUser } from "@server/test/factories";
|
||||
import { Granola } from "./granola";
|
||||
|
||||
const secret = `whsec_${Buffer.from("secret-key").toString("base64")}`;
|
||||
|
||||
function sign(id: string, timestamp: string, body: string) {
|
||||
return crypto
|
||||
.createHmac("sha256", Buffer.from("secret-key"))
|
||||
.update(`${id}.${timestamp}.${body}`)
|
||||
.digest("base64");
|
||||
}
|
||||
|
||||
describe("Granola.verifySignature", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const timestamp = String(now / 1000);
|
||||
const body = JSON.stringify({ note_id: "not_1" });
|
||||
|
||||
it("accepts a valid signature", () => {
|
||||
expect(
|
||||
Granola.verifySignature({
|
||||
secret,
|
||||
id: "msg_1",
|
||||
timestamp,
|
||||
signature: `v1,${sign("msg_1", timestamp, body)}`,
|
||||
body,
|
||||
now,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts one valid signature in a list", () => {
|
||||
expect(
|
||||
Granola.verifySignature({
|
||||
secret,
|
||||
id: "msg_1",
|
||||
timestamp,
|
||||
signature: `v1,invalid v1,${sign("msg_1", timestamp, body)}`,
|
||||
body,
|
||||
now,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a changed body", () => {
|
||||
expect(
|
||||
Granola.verifySignature({
|
||||
secret,
|
||||
id: "msg_1",
|
||||
timestamp,
|
||||
signature: `v1,${sign("msg_1", timestamp, body)}`,
|
||||
body: JSON.stringify({ note_id: "not_2" }),
|
||||
now,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an old timestamp", () => {
|
||||
expect(
|
||||
Granola.verifySignature({
|
||||
secret,
|
||||
id: "msg_1",
|
||||
timestamp,
|
||||
signature: `v1,${sign("msg_1", timestamp, body)}`,
|
||||
body,
|
||||
now: now + 10 * 60 * 1000,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Granola.findRule", () => {
|
||||
const folderRule = { folderId: "fol_1", collectionId: "a" };
|
||||
const otherRule = { folderId: null, collectionId: "b" };
|
||||
|
||||
it("prefers a folder rule", () => {
|
||||
expect(Granola.findRule([otherRule, folderRule], ["fol_1"])).toBe(
|
||||
folderRule
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the rule for other notes", () => {
|
||||
expect(Granola.findRule([folderRule, otherRule], ["fol_2"])).toBe(
|
||||
otherRule
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined when no rule matches", () => {
|
||||
expect(Granola.findRule([folderRule], [])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Granola.toDocument", () => {
|
||||
it("includes the metadata and summary", async () => {
|
||||
const user = await buildUser();
|
||||
const { title, text, createdAt, externalUrl } = Granola.toDocument(
|
||||
{
|
||||
id: "not_1",
|
||||
title: null,
|
||||
web_url: "https://notes.granola.ai/d/1",
|
||||
created_at: "2026-01-27T15:30:00Z",
|
||||
calendar_event: { event_title: "Weekly sync" },
|
||||
attendees: [
|
||||
{ name: "Ada", email: "ada@example.com" },
|
||||
{ email: "b@example.com" },
|
||||
],
|
||||
summary_markdown:
|
||||
"## Decisions\n\n- Ship it\n\n---\n\nChat with meeting transcript: <https://notes.granola.ai/t/1>",
|
||||
},
|
||||
user
|
||||
);
|
||||
|
||||
expect(title).toEqual("Weekly sync");
|
||||
expect(createdAt.toISOString()).toEqual("2026-01-27T15:30:00.000Z");
|
||||
expect(text).toContain("Ada, b@example.com");
|
||||
expect(text).not.toContain("notes.granola.ai");
|
||||
expect(externalUrl).toEqual("https://notes.granola.ai/d/1");
|
||||
expect(text).not.toContain("Date");
|
||||
expect(text.endsWith("- Ship it")).toBe(true);
|
||||
});
|
||||
|
||||
it("truncates a long title", async () => {
|
||||
const user = await buildUser();
|
||||
const { title } = Granola.toDocument(
|
||||
{
|
||||
id: "not_1",
|
||||
title: "a".repeat(200),
|
||||
created_at: "2026-01-27T15:30:00Z",
|
||||
},
|
||||
user
|
||||
);
|
||||
|
||||
expect(title).toHaveLength(DocumentValidation.maxTitleLength);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
import crypto from "node:crypto";
|
||||
import { truncate } from "es-toolkit/compat";
|
||||
import { t } from "i18next";
|
||||
import { z } from "zod";
|
||||
import { DocumentValidation } from "@shared/validations";
|
||||
import env from "@server/env";
|
||||
import type { User } from "@server/models";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import fetch from "@server/utils/fetch";
|
||||
import { opts } from "@server/utils/i18n";
|
||||
import type { GranolaRule } from "../shared/types";
|
||||
|
||||
const FolderSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
parent_folder_id: z.string().nullish(),
|
||||
});
|
||||
|
||||
const FoldersResponseSchema = z.object({
|
||||
folders: z.array(FolderSchema),
|
||||
hasMore: z.boolean(),
|
||||
cursor: z.string().nullish(),
|
||||
});
|
||||
|
||||
const NoteSchema = z.object({
|
||||
id: z.string(),
|
||||
title: z.string().nullish(),
|
||||
web_url: z.string().nullish(),
|
||||
created_at: z.string(),
|
||||
calendar_event: z
|
||||
.object({
|
||||
event_title: z.string().nullish(),
|
||||
scheduled_start_time: z.string().nullish(),
|
||||
})
|
||||
.nullish(),
|
||||
attendees: z
|
||||
.array(
|
||||
z.object({ name: z.string().nullish(), email: z.string().nullish() })
|
||||
)
|
||||
.nullish(),
|
||||
folder_membership: z.array(z.object({ id: z.string() })).nullish(),
|
||||
summary_markdown: z.string().nullish(),
|
||||
summary_text: z.string().nullish(),
|
||||
});
|
||||
|
||||
const WebhookEndpointSchema = z.object({
|
||||
id: z.string(),
|
||||
signing_secret: z.string(),
|
||||
created_by: z
|
||||
.object({ name: z.string().nullish(), email: z.string() })
|
||||
.nullish(),
|
||||
});
|
||||
|
||||
/** A note returned by the Granola API. */
|
||||
export type GranolaNote = z.infer<typeof NoteSchema>;
|
||||
|
||||
/** A folder returned by the Granola API. */
|
||||
export type GranolaFolder = z.infer<typeof FolderSchema>;
|
||||
|
||||
/** An error response from the Granola API. */
|
||||
export class GranolaApiError extends Error {
|
||||
public status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
// Granola ends summaries with a divider and a link to chat with the transcript.
|
||||
const transcriptFooter =
|
||||
/(\s*\n-{3,})?\s*\n+Chat with meeting transcript:[^\n]*\s*$/;
|
||||
|
||||
/** A client for the Granola public API. */
|
||||
export class Granola {
|
||||
public static baseUrl = "https://public-api.granola.ai/v1";
|
||||
|
||||
/** The age in seconds after which a webhook delivery is rejected. */
|
||||
public static webhookTolerance = 5 * 60;
|
||||
|
||||
/** The largest Granola API response to read, in bytes. */
|
||||
public static maxResponseSize = 5 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Returns the URL that Granola sends webhooks for an integration to.
|
||||
*
|
||||
* @param integrationId the ID of the integration.
|
||||
* @returns the webhook URL.
|
||||
*/
|
||||
public static webhookUrl(integrationId: string) {
|
||||
return `${env.URL}/api/granola.webhooks?id=${integrationId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all folders that the API key can access.
|
||||
*
|
||||
* @param apiKey the Granola API key.
|
||||
* @returns the folders.
|
||||
*/
|
||||
public static async listFolders(apiKey: string): Promise<GranolaFolder[]> {
|
||||
const folders: GranolaFolder[] = [];
|
||||
let cursor: string | null | undefined;
|
||||
|
||||
// shortcut: stops at 20 pages (600 folders), add search if users have more.
|
||||
for (let page = 0; page < 20; page++) {
|
||||
const query = new URLSearchParams({ page_size: "30" });
|
||||
if (cursor) {
|
||||
query.set("cursor", cursor);
|
||||
}
|
||||
const res = FoldersResponseSchema.parse(
|
||||
await this.request(apiKey, `/folders?${query}`)
|
||||
);
|
||||
folders.push(...res.folders);
|
||||
cursor = res.cursor;
|
||||
if (!res.hasMore || !cursor) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return folders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a note.
|
||||
*
|
||||
* @param apiKey the Granola API key.
|
||||
* @param noteId the ID of the note.
|
||||
* @returns the note.
|
||||
* @throws GranolaApiError when the note cannot be loaded.
|
||||
*/
|
||||
public static async getNote(apiKey: string, noteId: string) {
|
||||
return NoteSchema.parse(
|
||||
await this.request(apiKey, `/notes/${encodeURIComponent(noteId)}`)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a webhook endpoint for newly generated notes.
|
||||
*
|
||||
* @param apiKey the Granola API key.
|
||||
* @param url the URL that Granola sends events to.
|
||||
* @returns the endpoint, including its signing secret.
|
||||
* @throws GranolaApiError when the endpoint cannot be created.
|
||||
*/
|
||||
public static async createWebhookEndpoint(apiKey: string, url: string) {
|
||||
return WebhookEndpointSchema.parse(
|
||||
await this.request(apiKey, "/webhook-endpoints", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
scopes: ["personal"],
|
||||
events: ["note.generated"],
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a webhook endpoint.
|
||||
*
|
||||
* @param apiKey the Granola API key.
|
||||
* @param id the ID of the endpoint.
|
||||
*/
|
||||
public static async deleteWebhookEndpoint(apiKey: string, id: string) {
|
||||
await this.request(apiKey, `/webhook-endpoints/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies a webhook delivery that uses the Standard Webhooks scheme.
|
||||
*
|
||||
* @param params the signing secret, delivery headers, and raw body.
|
||||
* @returns true when the signature is valid and the timestamp is recent.
|
||||
*/
|
||||
public static verifySignature({
|
||||
secret,
|
||||
id,
|
||||
timestamp,
|
||||
signature,
|
||||
body,
|
||||
now = Date.now(),
|
||||
}: {
|
||||
secret: string;
|
||||
id: string;
|
||||
timestamp: string;
|
||||
signature: string;
|
||||
body: string;
|
||||
now?: number;
|
||||
}): boolean {
|
||||
const seconds = Number(timestamp);
|
||||
if (
|
||||
!Number.isFinite(seconds) ||
|
||||
Math.abs(now / 1000 - seconds) > this.webhookTolerance
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
|
||||
const expected = crypto
|
||||
.createHmac("sha256", key)
|
||||
.update(`${id}.${timestamp}.${body}`)
|
||||
.digest("base64");
|
||||
|
||||
return signature.split(" ").some((candidate) => {
|
||||
const [version, value] = candidate.split(",");
|
||||
return version === "v1" && safeEqual(value, expected);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the rule for a note. A rule for one of the note's folders comes
|
||||
* before the rule that matches all other notes.
|
||||
*
|
||||
* @param rules the rules of the integration.
|
||||
* @param folderIds the folders that contain the note.
|
||||
* @returns the matching rule, if any.
|
||||
*/
|
||||
public static findRule(
|
||||
rules: GranolaRule[],
|
||||
folderIds: string[]
|
||||
): GranolaRule | undefined {
|
||||
// shortcut: matches direct folders only, add folder ancestry if users ask for subfolders.
|
||||
return (
|
||||
rules.find(
|
||||
(rule) => rule.folderId && folderIds.includes(rule.folderId)
|
||||
) ?? rules.find((rule) => rule.folderId === null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a note to a document title, Markdown text, creation date, and
|
||||
* source link.
|
||||
*
|
||||
* @param note the note to convert.
|
||||
* @param user the user that the document is written for.
|
||||
* @returns the title, text, creation date, and source link.
|
||||
*/
|
||||
public static toDocument(note: GranolaNote, user: User) {
|
||||
const { lng } = opts(user);
|
||||
const title = truncate(
|
||||
note.title ||
|
||||
note.calendar_event?.event_title ||
|
||||
t("Meeting notes", { lng }),
|
||||
{ length: DocumentValidation.maxTitleLength }
|
||||
);
|
||||
const attendees = (note.attendees ?? [])
|
||||
.map((attendee) => attendee.name || attendee.email)
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
const lines = [
|
||||
attendees ? `**${t("Attendees", { lng })}:** ${attendees}` : undefined,
|
||||
(note.summary_markdown ?? note.summary_text ?? "").replace(
|
||||
transcriptFooter,
|
||||
""
|
||||
),
|
||||
];
|
||||
|
||||
return {
|
||||
title,
|
||||
text: lines.filter((line) => line !== undefined).join("\n\n"),
|
||||
createdAt: new Date(note.created_at),
|
||||
// Only an https link is stored, it is rendered as a link to the source.
|
||||
externalUrl: note.web_url?.startsWith("https://")
|
||||
? note.web_url
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private static async request(
|
||||
apiKey: string,
|
||||
path: string,
|
||||
init: { method?: string; body?: string } = {}
|
||||
): Promise<unknown> {
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
...init,
|
||||
size: this.maxResponseSize,
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => undefined)) as
|
||||
| { message?: unknown }
|
||||
| undefined;
|
||||
throw new GranolaApiError(
|
||||
res.status,
|
||||
typeof body?.message === "string"
|
||||
? body.message
|
||||
: `Granola API request failed with status ${res.status}`
|
||||
);
|
||||
}
|
||||
|
||||
return res.status === 204 ? undefined : res.json();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { toError } from "@shared/utils/error";
|
||||
import type { IntegrationType } from "@shared/types";
|
||||
import { IntegrationService } from "@shared/types";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import type { Integration } from "@server/models";
|
||||
import { PluginManager, Hook } from "@server/utils/PluginManager";
|
||||
import config from "../plugin.json";
|
||||
import router from "./api/granola";
|
||||
import { Granola } from "./granola";
|
||||
import GranolaNoteTask from "./tasks/GranolaNoteTask";
|
||||
|
||||
PluginManager.add([
|
||||
{
|
||||
...config,
|
||||
type: Hook.API,
|
||||
value: router,
|
||||
},
|
||||
{
|
||||
type: Hook.IntegrationSettings,
|
||||
value: {
|
||||
service: IntegrationService.Granola,
|
||||
keys: ["granola"],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: Hook.Task,
|
||||
value: GranolaNoteTask,
|
||||
},
|
||||
{
|
||||
type: Hook.Uninstall,
|
||||
value: async (integration: Integration) => {
|
||||
if (integration.service !== IntegrationService.Granola) {
|
||||
return;
|
||||
}
|
||||
|
||||
const settings = (
|
||||
integration as Integration<IntegrationType.LinkedAccount>
|
||||
).settings?.granola;
|
||||
const authentication = await integration.$get("authentication");
|
||||
if (!settings || !authentication) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await Granola.deleteWebhookEndpoint(
|
||||
authentication.token,
|
||||
settings.webhookEndpointId
|
||||
);
|
||||
} catch (err) {
|
||||
// Best effort, Granola disables the endpoint when deliveries fail.
|
||||
Logger.error("Failed to delete Granola webhook endpoint", toError(err));
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,196 @@
|
||||
import {
|
||||
IntegrationService,
|
||||
IntegrationType,
|
||||
TeamPreference,
|
||||
} from "@shared/types";
|
||||
import {
|
||||
Document,
|
||||
Integration,
|
||||
IntegrationAuthentication,
|
||||
} from "@server/models";
|
||||
import type { User } from "@server/models";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
buildPersonalCollection,
|
||||
buildTeam,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import type { GranolaRule } from "../../shared/types";
|
||||
import { Granola, GranolaApiError } from "../granola";
|
||||
import GranolaNoteTask from "./GranolaNoteTask";
|
||||
|
||||
async function buildIntegration(user: User, rules: GranolaRule[]) {
|
||||
const authentication = await IntegrationAuthentication.create({
|
||||
service: IntegrationService.Granola,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: "grn_key",
|
||||
clientSecret: "whsec_secret",
|
||||
});
|
||||
return Integration.create<Integration<IntegrationType.LinkedAccount>>({
|
||||
service: IntegrationService.Granola,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: { granola: { webhookEndpointId: "whe_1", rules } },
|
||||
});
|
||||
}
|
||||
|
||||
const note = {
|
||||
id: "not_1d3tmYTlCICgjy",
|
||||
title: "Weekly sync",
|
||||
web_url: "https://notes.granola.ai/d/1",
|
||||
created_at: "2026-01-27T15:30:00Z",
|
||||
attendees: [],
|
||||
folder_membership: [{ id: "fol_1" }],
|
||||
summary_markdown: "Summary text",
|
||||
};
|
||||
|
||||
describe("GranolaNoteTask", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("creates a published document in the collection of the rule", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: null, collectionId: collection.id },
|
||||
]);
|
||||
const getNote = vi.spyOn(Granola, "getNote").mockResolvedValue(note);
|
||||
|
||||
const task = new GranolaNoteTask();
|
||||
await task.perform({ integrationId: integration.id, noteId: note.id });
|
||||
await task.perform({ integrationId: integration.id, noteId: note.id });
|
||||
|
||||
const documents = await Document.findAll({
|
||||
where: { collectionId: collection.id },
|
||||
});
|
||||
expect(documents).toHaveLength(1);
|
||||
expect(documents[0].title).toEqual("Weekly sync");
|
||||
expect(documents[0].publishedAt).toBeTruthy();
|
||||
expect(documents[0].createdById).toEqual(user.id);
|
||||
expect(documents[0].createdAt.toISOString()).toEqual(
|
||||
"2026-01-27T15:30:00.000Z"
|
||||
);
|
||||
expect(documents[0].sourceMetadata?.externalId).toEqual(note.id);
|
||||
expect(documents[0].sourceMetadata?.externalUrl).toEqual(note.web_url);
|
||||
expect(getNote).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates a document in a personal collection", async () => {
|
||||
const team = await buildTeam();
|
||||
team.setPreference(TeamPreference.PersonalDocs, true);
|
||||
await team.save();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const collection = await buildPersonalCollection(user);
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: null, collectionId: collection.id },
|
||||
]);
|
||||
vi.spyOn(Granola, "getNote").mockResolvedValue(note);
|
||||
|
||||
await new GranolaNoteTask().perform({
|
||||
integrationId: integration.id,
|
||||
noteId: note.id,
|
||||
});
|
||||
|
||||
expect(
|
||||
await Document.count({ where: { collectionId: collection.id } })
|
||||
).toEqual(1);
|
||||
});
|
||||
|
||||
it("nests the document under the document of a folder rule", async () => {
|
||||
const user = await buildUser();
|
||||
const parent = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const other = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: null, collectionId: other.id },
|
||||
{ folderId: "fol_1", documentId: parent.id },
|
||||
]);
|
||||
vi.spyOn(Granola, "getNote").mockResolvedValue(note);
|
||||
|
||||
await new GranolaNoteTask().perform({
|
||||
integrationId: integration.id,
|
||||
noteId: note.id,
|
||||
});
|
||||
|
||||
const document = await Document.findOne({
|
||||
where: { parentDocumentId: parent.id },
|
||||
});
|
||||
expect(document?.collectionId).toEqual(parent.collectionId);
|
||||
});
|
||||
|
||||
it("does not create a document when no rule matches", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: "fol_2", collectionId: collection.id },
|
||||
]);
|
||||
vi.spyOn(Granola, "getNote").mockResolvedValue(note);
|
||||
|
||||
await new GranolaNoteTask().perform({
|
||||
integrationId: integration.id,
|
||||
noteId: note.id,
|
||||
});
|
||||
|
||||
expect(
|
||||
await Document.count({ where: { collectionId: collection.id } })
|
||||
).toEqual(0);
|
||||
});
|
||||
|
||||
it("does not create a document when the user lost access", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
permission: null,
|
||||
});
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: null, collectionId: collection.id },
|
||||
]);
|
||||
vi.spyOn(Granola, "getNote").mockResolvedValue(note);
|
||||
|
||||
await new GranolaNoteTask().perform({
|
||||
integrationId: integration.id,
|
||||
noteId: note.id,
|
||||
});
|
||||
|
||||
expect(
|
||||
await Document.count({ where: { collectionId: collection.id } })
|
||||
).toEqual(0);
|
||||
});
|
||||
|
||||
it("ignores a note that the key cannot read", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const integration = await buildIntegration(user, [
|
||||
{ folderId: null, collectionId: collection.id },
|
||||
]);
|
||||
vi.spyOn(Granola, "getNote").mockRejectedValue(
|
||||
new GranolaApiError(404, "Not found")
|
||||
);
|
||||
|
||||
await expect(
|
||||
new GranolaNoteTask().perform({
|
||||
integrationId: integration.id,
|
||||
noteId: note.id,
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import httpErrors from "http-errors";
|
||||
import type { IntegrationType } from "@shared/types";
|
||||
import documentCreator, {
|
||||
authorizeDocumentCreate,
|
||||
} from "@server/commands/documentCreator";
|
||||
import { createContext } from "@server/context";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { Document, Integration, User } from "@server/models";
|
||||
import { BaseTask } from "@server/queues/tasks/base/BaseTask";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import { Granola, GranolaApiError } from "../granola";
|
||||
|
||||
interface Props {
|
||||
/** The Granola integration that received the note. */
|
||||
integrationId: string;
|
||||
/** The ID of the Granola note. */
|
||||
noteId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a document from a Granola note in the location that the
|
||||
* integration's rules choose.
|
||||
*/
|
||||
export default class GranolaNoteTask extends BaseTask<Props> {
|
||||
public async perform({ integrationId, noteId }: Props) {
|
||||
const integration = (await Integration.scope("withAuthentication").findByPk(
|
||||
integrationId
|
||||
)) as Integration<IntegrationType.LinkedAccount> | null;
|
||||
const rules = integration?.settings?.granola?.rules;
|
||||
if (!integration || !rules?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Personal collections need the team to authorize.
|
||||
const user = await User.scope("withTeam").findByPk(integration.userId);
|
||||
if (!user || user.isSuspended) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Granola retries deliveries, so a note can arrive more than one time.
|
||||
const existing = await Document.unscoped().findOne({
|
||||
attributes: ["id"],
|
||||
where: {
|
||||
teamId: user.teamId,
|
||||
createdById: user.id,
|
||||
sourceMetadata: { externalId: noteId },
|
||||
},
|
||||
paranoid: false,
|
||||
});
|
||||
if (existing) {
|
||||
return;
|
||||
}
|
||||
|
||||
let note;
|
||||
try {
|
||||
note = await Granola.getNote(integration.authentication.token, noteId);
|
||||
} catch (err) {
|
||||
if (err instanceof GranolaApiError && err.status === 404) {
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const rule = Granola.findRule(
|
||||
rules,
|
||||
(note.folder_membership ?? []).map((folder) => folder.id)
|
||||
);
|
||||
if (!rule) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = createContext({ user });
|
||||
let location;
|
||||
try {
|
||||
location = await authorizeDocumentCreate(ctx, {
|
||||
collectionId: rule.collectionId,
|
||||
parentDocumentId: rule.documentId,
|
||||
});
|
||||
} catch (err) {
|
||||
if (httpErrors.isHttpError(err) && err.status === 403) {
|
||||
Logger.info("task", "Granola note destination is not available", {
|
||||
integrationId,
|
||||
noteId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const { title, text, createdAt, externalUrl } = Granola.toDocument(
|
||||
note,
|
||||
user
|
||||
);
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
ctx.transaction = transaction;
|
||||
await documentCreator(ctx, {
|
||||
title,
|
||||
text,
|
||||
createdAt,
|
||||
collectionId: location.collection?.id,
|
||||
parentDocumentId: location.parentDocument?.id,
|
||||
publish: true,
|
||||
sourceMetadata: { externalId: note.id, externalUrl },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected jobId({ integrationId, noteId }: Props) {
|
||||
return `GranolaNoteTask-${integrationId}-${noteId}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** A rule that sends Granola notes to a location in Outline. */
|
||||
// A type alias, so rules are assignable to JSON values.
|
||||
export type GranolaRule = {
|
||||
/** The Granola folder the rule matches, null matches notes that no other rule matches. */
|
||||
folderId: string | null;
|
||||
/** The name of the Granola folder, for display. */
|
||||
folderName?: string;
|
||||
/** The collection to create documents in. */
|
||||
collectionId?: string;
|
||||
/** The document to nest new documents under. */
|
||||
documentId?: string;
|
||||
/** The name of the location when the rule was saved, for display. */
|
||||
locationName?: string;
|
||||
};
|
||||
|
||||
declare module "@shared/types" {
|
||||
interface LinkedAccountIntegrationSettings {
|
||||
granola?: {
|
||||
account?: { name: string | null; email: string };
|
||||
webhookEndpointId: string;
|
||||
rules: GranolaRule[];
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export default function validateWebhook({
|
||||
hmacSign?: boolean;
|
||||
}) {
|
||||
return async function validateWebhookMiddleware(ctx: Context, next: Next) {
|
||||
const { body } = ctx.request;
|
||||
const { rawBody } = ctx.request;
|
||||
const signatureFromHeader = getSignatureFromHeader(ctx);
|
||||
|
||||
if (!signatureFromHeader) {
|
||||
@@ -31,12 +31,19 @@ export default function validateWebhook({
|
||||
return;
|
||||
}
|
||||
|
||||
const computedSignature = hmacSign
|
||||
? crypto
|
||||
.createHmac("sha256", key)
|
||||
.update(JSON.stringify(body))
|
||||
.digest("hex")
|
||||
: key;
|
||||
let computedSignature = key;
|
||||
if (hmacSign) {
|
||||
// The signature covers the exact bytes sent, not the parsed body.
|
||||
if (rawBody === undefined) {
|
||||
ctx.status = 401;
|
||||
ctx.body = "Invalid signature";
|
||||
return;
|
||||
}
|
||||
computedSignature = crypto
|
||||
.createHmac("sha256", key)
|
||||
.update(rawBody)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
if (!safeEqual(computedSignature, signatureFromHeader)) {
|
||||
ctx.status = 401;
|
||||
|
||||
@@ -23,7 +23,20 @@ allow(User, "read", Integration, (actor, integration) =>
|
||||
)
|
||||
);
|
||||
|
||||
allow(User, ["update", "delete"], Integration, (actor, integration) =>
|
||||
// A linked account acts as its owner, so only the owner may change it.
|
||||
allow(User, "update", Integration, (actor, integration) =>
|
||||
and(
|
||||
isTeamModel(actor, integration),
|
||||
isTeamMutable(actor),
|
||||
!actor.isGuest,
|
||||
!actor.isViewer,
|
||||
integration?.type === IntegrationType.LinkedAccount
|
||||
? isOwner(actor, integration)
|
||||
: actor.isAdmin
|
||||
)
|
||||
);
|
||||
|
||||
allow(User, "delete", Integration, (actor, integration) =>
|
||||
and(
|
||||
isTeamModel(actor, integration),
|
||||
isTeamMutable(actor),
|
||||
|
||||
@@ -152,6 +152,7 @@ async function presentDocument(
|
||||
createdByName: document.sourceMetadata.createdByName,
|
||||
fileName: document.sourceMetadata?.fileName,
|
||||
originalDocumentId: document.sourceMetadata?.originalDocumentId,
|
||||
externalUrl: document.sourceMetadata?.externalUrl,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+24
-12
@@ -57,18 +57,30 @@ const router = new Router();
|
||||
|
||||
// middlewares
|
||||
api.use(requestContextMiddleware());
|
||||
api.use(
|
||||
bodyParser({
|
||||
multipart: true,
|
||||
formidable: {
|
||||
maxFileSize: Math.max(
|
||||
env.FILE_STORAGE_UPLOAD_MAX_SIZE,
|
||||
env.FILE_STORAGE_IMPORT_MAX_SIZE
|
||||
),
|
||||
maxFieldsSize: 10 * 1024 * 1024,
|
||||
},
|
||||
jsonLimit: 5 * 1024 * 1024, // 5MB limit for JSON payloads
|
||||
})
|
||||
const bodyParserOptions = {
|
||||
multipart: true,
|
||||
formidable: {
|
||||
maxFileSize: Math.max(
|
||||
env.FILE_STORAGE_UPLOAD_MAX_SIZE,
|
||||
env.FILE_STORAGE_IMPORT_MAX_SIZE
|
||||
),
|
||||
maxFieldsSize: 10 * 1024 * 1024,
|
||||
},
|
||||
jsonLimit: 5 * 1024 * 1024, // 5MB limit for JSON payloads
|
||||
};
|
||||
const defaultBodyParser = bodyParser(bodyParserOptions);
|
||||
|
||||
// Webhook signatures cover the exact bytes sent, so only these routes keep the raw body.
|
||||
const webhookBodyParser = bodyParser({
|
||||
...bodyParserOptions,
|
||||
includeUnparsed: true,
|
||||
});
|
||||
const webhookPath = /\.webhooks$/;
|
||||
|
||||
api.use((ctx, next) =>
|
||||
webhookPath.test(ctx.path)
|
||||
? webhookBodyParser(ctx, next)
|
||||
: defaultBodyParser(ctx, next)
|
||||
);
|
||||
api.use(cleanupMultipartFiles());
|
||||
api.use(coalesceBody());
|
||||
|
||||
@@ -33,6 +33,26 @@ describe("#integrations.update", () => {
|
||||
expect(integration.events).toEqual(events);
|
||||
});
|
||||
|
||||
it("should not allow an admin to update another user's linked account", async () => {
|
||||
const user = await buildUser();
|
||||
const admin = await buildAdmin({ teamId: user.teamId });
|
||||
const integration = await buildIntegration({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
service: IntegrationService.Figma,
|
||||
type: IntegrationType.LinkedAccount,
|
||||
settings: {},
|
||||
});
|
||||
|
||||
const res = await server.post("/api/integrations.update", admin, {
|
||||
body: { id: integration.id, settings: { url: "https://example.com" } },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
await integration.reload();
|
||||
expect(integration.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("should allow updating integration events", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildAdmin({ teamId: team.id });
|
||||
|
||||
@@ -1108,6 +1108,7 @@
|
||||
"Source": "Source",
|
||||
"Created": "Created",
|
||||
"Imported from {{ source }}": "Imported from {{ source }}",
|
||||
"View original": "View original",
|
||||
"Contributors": "Contributors",
|
||||
"Creator": "Creator",
|
||||
"Last edited": "Last edited",
|
||||
@@ -1805,6 +1806,25 @@
|
||||
"Add a Google Analytics 4 measurement ID to send document views and analytics from the workspace to your own Google Analytics account.": "Add a Google Analytics 4 measurement ID to send document views and analytics from the workspace to your own Google Analytics account.",
|
||||
"Measurement ID": "Measurement ID",
|
||||
"Create a “Web” stream in your Google Analytics admin dashboard and copy the measurement ID from the generated code snippet to install.": "Create a “Web” stream in your Google Analytics admin dashboard and copy the measurement ID from the generated code snippet to install.",
|
||||
"Connect Granola": "Connect Granola",
|
||||
"You can create a personal API key in Granola under Settings → Connectors → API keys. API keys are only available on Granola Business and Enterprise plans.": "You can create a personal API key in Granola under Settings → Connectors → API keys. API keys are only available on Granola Business and Enterprise plans.",
|
||||
"All other notes": "All other notes",
|
||||
"Granola folder": "Granola folder",
|
||||
"Choose a folder": "Choose a folder",
|
||||
"Choose where these notes are saved": "Choose where these notes are saved",
|
||||
"Link your Granola account to {{appName}} and your meeting notes will show up as documents as soon as they’re ready. Everyone connects their own account and chooses where their notes go.": "Link your Granola account to {{appName}} and your meeting notes will show up as documents as soon as they’re ready. Everyone connects their own account and chooses where their notes go.",
|
||||
"{{ userName }} (you)": "{{ userName }} (you)",
|
||||
"Unknown user": "Unknown user",
|
||||
"Connected on": "Connected on",
|
||||
"Disconnecting will stop creating documents from your new meeting notes. Are you sure?": "Disconnecting will stop creating documents from your new meeting notes. Are you sure?",
|
||||
"Disconnecting will stop creating documents from new meeting notes by {{ userName }}. Are you sure?": "Disconnecting will stop creating documents from new meeting notes by {{ userName }}. Are you sure?",
|
||||
"Edit rule": "Edit rule",
|
||||
"Add rule": "Add rule",
|
||||
"Unknown location": "Unknown location",
|
||||
"Rules": "Rules",
|
||||
"Add a rule to choose where your notes are saved. Notes that don’t match a rule won’t be added.": "Add a rule to choose where your notes are saved. Notes that don’t match a rule won’t be added.",
|
||||
"Meeting notes": "Meeting notes",
|
||||
"Attendees": "Attendees",
|
||||
"Whoops, you need to accept the permissions in Linear to connect {{appName}} to your workspace. Try again?": "Whoops, you need to accept the permissions in Linear to connect {{appName}} to your workspace. Try again?",
|
||||
"Enable previews of Linear issues in documents by connecting a Linear workspace to {{appName}}.": "Enable previews of Linear issues in documents by connecting a Linear workspace to {{appName}}.",
|
||||
"Disconnecting will prevent previewing Linear links from this workspace in documents. Are you sure?": "Disconnecting will prevent previewing Linear links from this workspace in documents. Are you sure?",
|
||||
|
||||
@@ -21,6 +21,8 @@ export type SourceMetadata = {
|
||||
externalId?: string;
|
||||
/** Original name in the external source. */
|
||||
externalName?: string;
|
||||
/** A link to the item in the external source. */
|
||||
externalUrl?: string;
|
||||
/** Whether the item was created through a trial license. */
|
||||
trial?: boolean;
|
||||
/** The ID of the original document when this document was duplicated. */
|
||||
|
||||
@@ -27,6 +27,7 @@ export enum IntegrationService {
|
||||
Gitea = "gitea",
|
||||
Linear = "linear",
|
||||
Figma = "figma",
|
||||
Granola = "granola",
|
||||
Notion = "notion",
|
||||
Markdown = "markdown",
|
||||
Slab = "slab",
|
||||
@@ -107,16 +108,15 @@ export type IntegrationSettings<T> = T extends IntegrationType.Embed
|
||||
}
|
||||
: T extends IntegrationType.LinkedAccount
|
||||
? LinkedAccountSettings
|
||||
:
|
||||
| { url: string }
|
||||
| EmbedSettings
|
||||
| { serviceTeamId: string }
|
||||
| {
|
||||
measurementId: string;
|
||||
instanceUrl?: string;
|
||||
scriptName?: string;
|
||||
}
|
||||
| undefined;
|
||||
: | { url: string }
|
||||
| EmbedSettings
|
||||
| { serviceTeamId: string }
|
||||
| {
|
||||
measurementId: string;
|
||||
instanceUrl?: string;
|
||||
scriptName?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
/** Environment values that the server exposes to the client. */
|
||||
export type PublicEnv = {
|
||||
|
||||
Reference in new issue
Block a user