Files
outline/plugins/granola/server/api/granola.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

269 lines
7.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;