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

301 lines
8.4 KiB
TypeScript

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();
}
}