Files
outline/plugins/granola/server/api/granola.test.ts
T
Tom Moor ba2d9888cc 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
2026-12-05 14:59:12 -05:00

318 lines
9.9 KiB
TypeScript

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: [] },
});
});
});