Skip to content

The open alternative to Salesforce, designed for AI.

Granola 4/8: Connect Granola webhooks and live synchronization (#25573)

nitinb1701251d4ac
diff --git a/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts
new file mode 100644
index 00000000000..da9f8880424
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts
@@ -0,0 +1 @@
+export const GRANOLA_NOTE_ID_PATTERN = /^not_[a-zA-Z0-9]{14}$/;
diff --git a/packages/twenty-apps/public/granola/src/constants/granola-webhook-registration-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-webhook-registration-route-path.ts
new file mode 100644
index 00000000000..680fa113d47
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/constants/granola-webhook-registration-route-path.ts
@@ -0,0 +1,2 @@
+export const GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH =
+ '/granola/webhook-registration';
diff --git a/packages/twenty-apps/public/granola/src/constants/granola-webhook-removal-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-webhook-removal-route-path.ts
new file mode 100644
index 00000000000..f356ca4446e
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/constants/granola-webhook-removal-route-path.ts
@@ -0,0 +1 @@
+export const GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH = '/granola/webhook-removal';
diff --git a/packages/twenty-apps/public/granola/src/constants/granola.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola.constant.ts
new file mode 100644
index 00000000000..e610e4bbb3e
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/constants/granola.constant.ts
@@ -0,0 +1,2 @@
+export const GRANOLA_WEBHOOK_REGISTRATION_KEY = 'granola-webhook-registration';
+export const GRANOLA_PENDING_REGISTRATION_KEY = 'granola-pending-registration';
diff --git a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
index 7bd62878b84..1f4d2bc3f66 100644
--- a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
@@ -13,6 +13,8 @@ export const GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER =
'91dd18b2-ddfd-4516-bda6-db0e3a2d3e33';
export const GRANOLA_WEBHOOK_UNIVERSAL_IDENTIFIER =
'1c7fb7ac-89b4-4d01-a4bf-d331b694a0ac';
+export const GRANOLA_REMOVE_WEBHOOK_UNIVERSAL_IDENTIFIER =
+ '4b297591-6fff-42d0-8ebf-d6f614de6555';
export const GRANOLA_UNINSTALL_UNIVERSAL_IDENTIFIER =
'c97f76e2-78b9-4221-9053-c353ea6522b0';
export const GRANOLA_BACKFILL_UNIVERSAL_IDENTIFIER =
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
index 0649fe95eb8..4c6455bbc71 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
@@ -2,9 +2,11 @@ import styled from '@emotion/styled';
import { isNonEmptyString } from '@sniptt/guards';
import { useId, useState } from 'react';
import { t } from 'twenty-sdk/front-component';
+import { isDefined } from 'twenty-sdk/utils';
import { Status } from 'twenty-ui/data-display';
-import { IconKey } from 'twenty-ui/icon';
-import { Button, LightButton } from 'twenty-ui/input';
+import { Loader } from 'twenty-ui/feedback';
+import { IconKey, IconTrash } from 'twenty-ui/icon';
+import { Button, IconButton, LightButton } from 'twenty-ui/input';
import { Section } from 'twenty-ui/layout';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { H2Title } from 'twenty-ui/typography';
@@ -12,9 +14,11 @@ import { H2Title } from 'twenty-ui/typography';
import { LabelledSettingsField } from 'src/front-components/components/LabelledSettingsField';
import { SettingsOptionCardContent } from 'src/front-components/components/SettingsOptionCardContent';
import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
+import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';
import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';
import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';
import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
+import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';
const StyledKeyForm = styled.form`
display: flex;
@@ -22,45 +26,78 @@ const StyledKeyForm = styled.form`
gap: ${() => themeCssVariables.spacing[3]};
`;
-const StyledButtonRow = styled.div`
+const StyledActions = styled.div`
display: flex;
gap: ${() => themeCssVariables.spacing[2]};
+ justify-content: flex-start;
`;
+const StyledConnectButtonContainer = styled.div`
+ button {
+ gap: ${() => themeCssVariables.spacing[2]};
+ min-width: ${() => themeCssVariables.spacing[32]};
+ padding-inline: ${() => themeCssVariables.spacing[4]};
+ }
+`;
+
+const StyledConnectionHint = styled.div`
+ color: ${() => themeCssVariables.font.color.secondary};
+ font-family: ${() => themeCssVariables.font.family};
+ font-size: ${() => themeCssVariables.font.size.sm};
+`;
+
+// Button's isLoading animation clips the title; keep the loader in its icon slot.
+const ConnectionLoader = () => <Loader />;
+
type GranolaConnectionSectionProps = {
status: GranolaConnectionStatus;
isConnecting: boolean;
+ isRemoving: boolean;
connectError: string | undefined;
+ removeError: string | undefined;
onConnect: (apiKey: string) => Promise<boolean>;
+ onRemove: () => Promise<void>;
onRetry: () => void;
};
-const getConnectionDescription = (status: GranolaConnectionStatus) =>
- status.isConnected
- ? t('Connected to Granola.')
- : (status.error ?? t('Granola rejected the saved key.'));
-
export const GranolaConnectionSection = ({
status,
isConnecting,
+ isRemoving,
connectError,
+ removeError,
onConnect,
+ onRemove,
onRetry,
}: GranolaConnectionSectionProps) => {
const inputId = useId();
const [apiKeyDraft, setApiKeyDraft] = useState('');
- const [isReplacingKey, setIsReplacingKey] = useState(false);
const trimmedApiKeyDraft = apiKeyDraft.trim();
- const isKeyRejected =
- status.isApiKeySet && !status.isConnected && status.isGranolaReachable;
- const isKeyFormVisible =
- !status.isApiKeySet || isKeyRejected || isReplacingKey;
- const isCancelVisible = status.isConnected && isReplacingKey;
+ const isConnected =
+ !isConnecting &&
+ isGranolaConnectionReady(status) &&
+ !isDefined(connectError);
+ const connectionError = isConnecting
+ ? undefined
+ : (connectError ??
+ (status.isApiKeySet && !isConnected
+ ? t('Could not connect to Granola. Try again.')
+ : undefined));
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
+ if (isConnecting || isRemoving) {
+ return;
+ }
+
+ if (status.isApiKeySet) {
+ onRetry();
+
+ return;
+ }
+
if (!isNonEmptyString(trimmedApiKeyDraft)) {
return;
}
@@ -69,7 +106,6 @@ export const GranolaConnectionSection = ({
if (isSaved) {
setApiKeyDraft('');
- setIsReplacingKey(false);
}
};
@@ -82,72 +118,78 @@ export const GranolaConnectionSection = ({
)}
/>
<StyledSettingsSectionStack>
- {status.isApiKeySet && (
+ {isConnected && (
<StyledSettingsCard>
<SettingsOptionCardContent
Icon={IconKey}
title={t('API key')}
- description={getConnectionDescription(status)}
- >
- {status.isConnected && (
- <Status color="green" text={t('Connected')} />
- )}
- {isKeyRejected && <Status color="red" text={t('Rejected')} />}
- {!status.isGranolaReachable && (
- <>
- <Status color="orange" text={t('Unreachable')} />
- <LightButton title={t('Retry')} onClick={onRetry} />
- </>
- )}
- {status.isConnected && !isReplacingKey && (
- <LightButton
- title={t('Replace')}
- onClick={() => setIsReplacingKey(true)}
- />
+ description={t(
+ 'New and updated notes appear in Call Recordings automatically.',
)}
+ >
+ <Status color="green" text={t('Connected')} />
+ <IconButton
+ Icon={IconTrash}
+ variant="tertiary"
+ accent="danger"
+ ariaLabel={
+ isRemoving ? t('Removing API key') : t('Remove API key')
+ }
+ disabled={isRemoving}
+ onClick={() => onRemove()}
+ />
</SettingsOptionCardContent>
</StyledSettingsCard>
)}
- {isKeyFormVisible && (
+ {isDefined(removeError) && (
+ <StyledSettingsError>{removeError}</StyledSettingsError>
+ )}
+ {!isConnected && (
<StyledKeyForm onSubmit={handleSubmit}>
<LabelledSettingsField
- label={status.isApiKeySet ? t('New API key') : t('API key')}
+ label={t('API key')}
inputId={inputId}
- errorMessage={connectError}
- hint={t(
- 'Workspace keys sync notes shared with the whole workspace. Personal keys also sync your own notes.',
- )}
+ errorMessage={connectionError}
>
<StyledSettingsTextInput
id={inputId}
type="password"
autoComplete="off"
- placeholder="grn_…"
+ placeholder={status.isApiKeySet ? '••••••••' : 'grn_…'}
value={apiKeyDraft}
- disabled={isConnecting}
+ disabled={isConnecting || isRemoving || status.isApiKeySet}
onChange={(event) => setApiKeyDraft(event.target.value)}
/>
</LabelledSettingsField>
- <StyledButtonRow>
- <Button
- type="submit"
- title={t('Connect')}
- accent="blue"
- isLoading={isConnecting}
- disabled={isConnecting || !isNonEmptyString(trimmedApiKeyDraft)}
- />
- {isCancelVisible && (
- <Button
+ <StyledActions>
+ {status.isApiKeySet && isDefined(connectionError) && (
+ <LightButton
title={t('Cancel')}
- variant="secondary"
- disabled={isConnecting}
- onClick={() => {
- setIsReplacingKey(false);
- setApiKeyDraft('');
- }}
+ disabled={isRemoving}
+ onClick={() => onRemove()}
/>
)}
- </StyledButtonRow>
+ <StyledConnectButtonContainer>
+ <Button
+ type="submit"
+ title={isConnecting ? t('Connecting') : t('Connect')}
+ accent="blue"
+ justify="center"
+ Icon={isConnecting ? ConnectionLoader : undefined}
+ disabled={
+ isConnecting ||
+ isRemoving ||
+ (!status.isApiKeySet &&
+ !isNonEmptyString(trimmedApiKeyDraft))
+ }
+ />
+ </StyledConnectButtonContainer>
+ </StyledActions>
+ {isConnecting && (
+ <StyledConnectionHint role="status">
+ {t('Configuring your connection. This may take a few seconds.')}
+ </StyledConnectionHint>
+ )}
</StyledKeyForm>
)}
</StyledSettingsSectionStack>
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
index 9a1f3bb395a..0f303ef9329 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
@@ -7,6 +7,7 @@ import {
useColorScheme,
useFrontComponentId,
} from 'twenty-sdk/front-component';
+import { isDefined } from 'twenty-sdk/utils';
import { THEME_DARK, THEME_LIGHT } from 'twenty-ui/theme';
import {
ThemeContext,
@@ -18,7 +19,9 @@ import { GranolaConnectionSection } from 'src/front-components/components/Granol
import { OnMountEffect } from 'src/front-components/components/OnMountEffect';
import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
import { fetchGranolaConnectionStatusOrThrow } from 'src/front-components/utils/fetch-granola-connection-status-or-throw.util';
-import { saveGranolaApiKeyOrThrow } from 'src/front-components/utils/save-granola-api-key-or-throw.util';
+import { registerGranolaWebhookOrThrow } from 'src/front-components/utils/register-granola-webhook-or-throw.util';
+import { removeGranolaWebhookOrThrow } from 'src/front-components/utils/remove-granola-webhook-or-throw.util';
+import { setGranolaApiKeyOrThrow } from 'src/front-components/utils/set-granola-api-key-or-throw.util';
const StyledContainer = styled.div`
box-sizing: border-box;
@@ -26,6 +29,10 @@ const StyledContainer = styled.div`
flex-direction: column;
gap: ${() => themeCssVariables.spacing[8]};
width: 100%;
+
+ button svg {
+ pointer-events: none;
+ }
`;
const StyledNotice = styled.div`
@@ -40,30 +47,73 @@ type GranolaSettingsState =
| { step: 'unavailable' }
| { step: 'ready'; status: GranolaConnectionStatus };
+const shouldSetUpLiveSync = (status: GranolaConnectionStatus) =>
+ status.isConnected &&
+ status.canManage &&
+ status.needsRegistration &&
+ !isDefined(status.registration);
+
export const GranolaSettings = () => {
const colorScheme = useColorScheme();
const frontComponentId = useFrontComponentId();
const [state, setState] = useState<GranolaSettingsState>({ step: 'loading' });
const [isConnecting, setIsConnecting] = useState(false);
const [connectError, setConnectError] = useState<string | undefined>();
+ const [isRemoving, setIsRemoving] = useState(false);
+ const [removeError, setRemoveError] = useState<string | undefined>();
+ const [isRegistering, setIsRegistering] = useState(false);
+ const [registrationError, setRegistrationError] = useState<
+ string | undefined
+ >();
- const loadConnectionStatus = async () => {
+ const refreshConnectionStatus = async () => {
try {
- setState({
- step: 'ready',
- status: await fetchGranolaConnectionStatusOrThrow(),
- });
+ const status = await fetchGranolaConnectionStatusOrThrow();
+
+ setState({ step: 'ready', status });
+
+ return status;
} catch {
- setState({ step: 'unavailable' });
+ setRegistrationError(t('Could not connect to Granola. Try again.'));
+ setState((current) =>
+ current.step === 'ready' ? current : { step: 'unavailable' },
+ );
+
+ return undefined;
}
};
+ const registerLiveSync = async () => {
+ setIsRegistering(true);
+ setRegistrationError(undefined);
+
+ try {
+ await registerGranolaWebhookOrThrow();
+ } catch {
+ setRegistrationError(t('Could not connect to Granola. Try again.'));
+ }
+
+ await refreshConnectionStatus();
+ setIsRegistering(false);
+ };
+
+ const loadConnectionStatus = async () => {
+ setIsRegistering(true);
+ setRegistrationError(undefined);
+ const status = await refreshConnectionStatus();
+
+ if (isDefined(status) && shouldSetUpLiveSync(status)) {
+ await registerLiveSync();
+ }
+ setIsRegistering(false);
+ };
+
const handleConnect = async (apiKey: string): Promise<boolean> => {
setIsConnecting(true);
setConnectError(undefined);
try {
- await saveGranolaApiKeyOrThrow({ frontComponentId, apiKey });
+ await setGranolaApiKeyOrThrow({ frontComponentId, apiKey });
} catch {
setConnectError(t('Could not save the API key. Try again.'));
setIsConnecting(false);
@@ -77,6 +127,25 @@ export const GranolaSettings = () => {
return true;
};
+ // Deleting the endpoint needs the key that created it, so the webhook goes
+ // before the variable is cleared.
+ const handleRemove = async () => {
+ setIsRemoving(true);
+ setRemoveError(undefined);
+
+ try {
+ await removeGranolaWebhookOrThrow();
+ await setGranolaApiKeyOrThrow({ frontComponentId, apiKey: '' });
+ setConnectError(undefined);
+ setRegistrationError(undefined);
+ } catch {
+ setRemoveError(t('Could not remove the API key. Try again.'));
+ }
+
+ await refreshConnectionStatus();
+ setIsRemoving(false);
+ };
+
// twenty-ui components read icon sizes off ThemeContext, and the context
// default resolves them to var() strings an SVG size attribute cannot use.
return (
@@ -103,10 +172,17 @@ export const GranolaSettings = () => {
{state.step === 'ready' && (
<GranolaConnectionSection
status={state.status}
- isConnecting={isConnecting}
- connectError={connectError}
+ isConnecting={isConnecting || isRegistering}
+ isRemoving={isRemoving}
+ connectError={connectError ?? registrationError}
+ removeError={removeError}
onConnect={handleConnect}
- onRetry={loadConnectionStatus}
+ onRemove={handleRemove}
+ onRetry={
+ state.status.isConnected && state.status.canManage
+ ? registerLiveSync
+ : loadConnectionStatus
+ }
/>
)}
</StyledContainer>
diff --git a/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx b/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx
index 73d1fa5957d..f47062f065f 100644
--- a/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx
@@ -5,6 +5,6 @@ import { GranolaSettings } from 'src/front-components/components/GranolaSettings
export default defineSettingsFrontComponent({
universalIdentifier: GRANOLA_SETTINGS_UNIVERSAL_IDENTIFIER,
name: 'granola-settings',
- description: 'Granola connection settings.',
+ description: 'Granola account connection settings.',
component: GranolaSettings,
});
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
index 0c7ed682afb..b647a9408df 100644
--- a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
@@ -1,10 +1,20 @@
import { z } from 'zod';
+import { GRANOLA_WEBHOOK_SCOPE_SCHEMA } from 'src/logic-functions/types/granola-api.type';
+
export const GRANOLA_CONNECTION_STATUS_SCHEMA = z.object({
isConnected: z.boolean(),
isApiKeySet: z.boolean(),
isGranolaReachable: z.boolean().default(true),
+ canManage: z.boolean().default(false),
+ needsRegistration: z.boolean().default(false),
error: z.string().optional(),
+ registration: z
+ .object({
+ scopes: z.array(GRANOLA_WEBHOOK_SCOPE_SCHEMA),
+ isActive: z.boolean(),
+ })
+ .optional(),
});
export type GranolaConnectionStatus = z.infer<
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/is-granola-connection-ready.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/is-granola-connection-ready.test.ts
new file mode 100644
index 00000000000..f0267d63c79
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/is-granola-connection-ready.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { GRANOLA_CONNECTION_STATUS_SCHEMA } from 'src/front-components/types/granola-connection-status.type';
+import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';
+
+describe('isGranolaConnectionReady', () => {
+ it('requires an accepted key and an active registration', () => {
+ expect(
+ isGranolaConnectionReady(
+ GRANOLA_CONNECTION_STATUS_SCHEMA.parse({
+ isConnected: true,
+ isApiKeySet: true,
+ registration: { scopes: ['workspace'], isActive: true },
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it.each([
+ { registration: undefined },
+ { registration: { scopes: ['workspace'], isActive: false } },
+ { needsRegistration: true },
+ { isConnected: false },
+ { isGranolaReachable: false },
+ { error: 'Connection failed' },
+ ])(
+ 'does not show connected for an incomplete or failed connection: %j',
+ (overrides) => {
+ expect(
+ isGranolaConnectionReady(
+ GRANOLA_CONNECTION_STATUS_SCHEMA.parse({
+ isConnected: true,
+ isApiKeySet: true,
+ registration: { scopes: ['workspace'], isActive: true },
+ ...overrides,
+ }),
+ ),
+ ).toBe(false);
+ },
+ );
+});
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/is-granola-connection-ready.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/is-granola-connection-ready.util.ts
new file mode 100644
index 00000000000..260828287c0
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/is-granola-connection-ready.util.ts
@@ -0,0 +1,19 @@
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
+
+export const isGranolaConnectionReady = (
+ status: Pick<
+ GranolaConnectionStatus,
+ | 'isConnected'
+ | 'isGranolaReachable'
+ | 'needsRegistration'
+ | 'registration'
+ | 'error'
+ >,
+): boolean =>
+ status.isConnected &&
+ status.isGranolaReachable &&
+ !status.needsRegistration &&
+ !isDefined(status.error) &&
+ (status.registration?.isActive ?? false);
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.ts
new file mode 100644
index 00000000000..5105040d773
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.ts
@@ -0,0 +1,19 @@
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { z } from 'zod';
+
+const ACTION_RESULT_SCHEMA = z.discriminatedUnion('success', [
+ z.object({ success: z.literal(true) }),
+ z.object({ success: z.literal(false), error: z.string() }),
+]);
+
+export const postGranolaWebhookActionOrThrow = async (
+ routePath: string,
+): Promise<void> => {
+ const result = ACTION_RESULT_SCHEMA.parse(
+ await new RestApiClient().post(`/s${routePath}`, {}),
+ );
+
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.ts
new file mode 100644
index 00000000000..a3aa7f05468
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.ts
@@ -0,0 +1,5 @@
+import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-webhook-registration-route-path';
+import { postGranolaWebhookActionOrThrow } from 'src/front-components/utils/post-granola-webhook-action-or-throw.util';
+
+export const registerGranolaWebhookOrThrow = (): Promise<void> =>
+ postGranolaWebhookActionOrThrow(GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH);
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.ts
new file mode 100644
index 00000000000..eec0018bb2a
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.ts
@@ -0,0 +1,5 @@
+import { GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH } from 'src/constants/granola-webhook-removal-route-path';
+import { postGranolaWebhookActionOrThrow } from 'src/front-components/utils/post-granola-webhook-action-or-throw.util';
+
+export const removeGranolaWebhookOrThrow = (): Promise<void> =>
+ postGranolaWebhookActionOrThrow(GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH);
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
similarity index 94%
rename from packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.ts
rename to packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
index b4aa369ce92..15269723a6e 100644
--- a/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
@@ -3,7 +3,7 @@ import { MetadataApiClient } from 'twenty-client-sdk/metadata';
import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
-export const saveGranolaApiKeyOrThrow = async ({
+export const setGranolaApiKeyOrThrow = async ({
frontComponentId,
apiKey,
}: {
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
index 936cefdddb7..8138261da4a 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
@@ -1,20 +1,23 @@
import { isNonEmptyString } from '@sniptt/guards';
import { defineLogicFunction } from 'twenty-sdk/define';
import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
import { GRANOLA_CONNECTION_STATUS_ROUTE_PATH } from 'src/constants/granola-connection-status-route-path';
import { GRANOLA_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';
export const granolaConnectionStatusHandler = async () => {
if (!isNonEmptyString(process.env[GRANOLA_API_KEY_ENV_VAR_NAME]?.trim())) {
return { isConnected: false, isApiKeySet: false };
}
+ const client = createGranolaClientOrThrow();
try {
- await createGranolaClientOrThrow().listFolders({ page_size: 1 });
- return { isConnected: true, isApiKeySet: true };
+ await client.listFolders({ page_size: 1 });
} catch (error) {
if (error instanceof GranolaApiError) {
return { isConnected: false, isApiKeySet: true, error: error.message };
@@ -29,12 +32,46 @@ export const granolaConnectionStatusHandler = async () => {
}
throw error;
}
+ const canManage = await currentUserCanManageGranolaOrThrow();
+ try {
+ const { webhook_endpoints: endpoints } =
+ await client.listWebhookEndpoints();
+ const registration = await findGranolaRegistrationForCurrentKey();
+ const endpoint = endpoints.find(
+ (candidate) => candidate.id === registration?.webhookEndpointId,
+ );
+ if (!isDefined(endpoint)) {
+ return {
+ isConnected: true,
+ isApiKeySet: true,
+ canManage,
+ needsRegistration: true,
+ };
+ }
+ return {
+ isConnected: true,
+ isApiKeySet: true,
+ canManage,
+ registration: { scopes: endpoint.scopes, isActive: endpoint.enabled },
+ };
+ } catch (error) {
+ if (error instanceof GranolaApiError) {
+ return {
+ isConnected: true,
+ isApiKeySet: true,
+ canManage,
+ needsRegistration: true,
+ error: error.message,
+ };
+ }
+ throw error;
+ }
};
export default defineLogicFunction({
universalIdentifier: GRANOLA_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER,
name: 'granola-connection-status',
- description: 'Checks the saved Granola API key.',
+ description: 'Checks the saved Granola API key and the live webhook status.',
timeoutSeconds: 60,
handler: granolaConnectionStatusHandler,
httpRouteTriggerSettings: {
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts
new file mode 100644
index 00000000000..71f5899107e
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts
@@ -0,0 +1,38 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-webhook-registration-route-path';
+import { GRANOLA_REGISTER_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
+import { ensureGranolaWebhookRegistrationOrThrow } from 'src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util';
+
+export const granolaRegisterWebhookHandler = async () => {
+ if (!(await currentUserCanManageGranolaOrThrow())) {
+ return {
+ success: false,
+ error: 'Application management permission is required.',
+ };
+ }
+ try {
+ await ensureGranolaWebhookRegistrationOrThrow();
+ return { success: true };
+ } catch (error) {
+ if (error instanceof GranolaApiError) {
+ return { success: false, error: error.message };
+ }
+ throw error;
+ }
+};
+
+export default defineLogicFunction({
+ universalIdentifier: GRANOLA_REGISTER_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ name: 'granola-register-webhook',
+ description: 'Registers the Granola webhook for the saved key.',
+ timeoutSeconds: 60,
+ handler: granolaRegisterWebhookHandler,
+ httpRouteTriggerSettings: {
+ path: GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH,
+ httpMethod: 'POST',
+ isAuthRequired: true,
+ },
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-remove-webhook.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-remove-webhook.ts
new file mode 100644
index 00000000000..ac1ea124da2
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-remove-webhook.ts
@@ -0,0 +1,35 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH } from 'src/constants/granola-webhook-removal-route-path';
+import { GRANOLA_REMOVE_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
+import { removeGranolaWebhookRegistration } from 'src/logic-functions/utils/remove-granola-webhook-registration.util';
+
+export const granolaRemoveWebhookHandler = async () => {
+ if (!(await currentUserCanManageGranolaOrThrow())) {
+ return {
+ success: false,
+ error: 'Application management permission is required.',
+ };
+ }
+
+ const { deletedWebhookCount } = await removeGranolaWebhookRegistration({
+ client: createGranolaClientOrThrow(),
+ });
+
+ return { success: true, deletedWebhookCount };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: GRANOLA_REMOVE_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ name: 'granola-remove-webhook',
+ description: 'Removes the registered Granola webhook for the saved key.',
+ timeoutSeconds: 60,
+ handler: granolaRemoveWebhookHandler,
+ httpRouteTriggerSettings: {
+ path: GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH,
+ httpMethod: 'POST',
+ isAuthRequired: true,
+ },
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts
new file mode 100644
index 00000000000..f6b58475200
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts
@@ -0,0 +1,34 @@
+import { defineUninstallLogicFunction } from 'twenty-sdk/define';
+
+import { GRANOLA_UNINSTALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { cleanupPendingGranolaRegistrationOrThrow } from 'src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util';
+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { removeGranolaWebhookRegistration } from 'src/logic-functions/utils/remove-granola-webhook-registration.util';
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const granolaUninstallHandler = async () => {
+ const client = createGranolaClientOrThrow();
+ try {
+ const { webhook_endpoints: endpoints } =
+ await client.listWebhookEndpoints();
+ await cleanupPendingGranolaRegistrationOrThrow({
+ client,
+ endpoints,
+ apiUrl: process.env.TWENTY_API_URL,
+ });
+ } catch (error) {
+ console.error(
+ `[granola] Could not clean up the pending registration during uninstall; check Granola webhook settings. ${toErrorMessage(error)}`,
+ );
+ }
+
+ return removeGranolaWebhookRegistration({ client });
+};
+
+export default defineUninstallLogicFunction({
+ universalIdentifier: GRANOLA_UNINSTALL_UNIVERSAL_IDENTIFIER,
+ name: 'granola-uninstall',
+ description: 'Removes the registered Granola webhook on uninstall.',
+ timeoutSeconds: 30,
+ handler: granolaUninstallHandler,
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook-resolver.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook-resolver.ts
new file mode 100644
index 00000000000..252e401c81f
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook-resolver.ts
@@ -0,0 +1,58 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
+import {
+ kv,
+ Response,
+ type ServerRouteResolverResult,
+} from 'twenty-sdk/logic-function';
+
+import {
+ GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ GRANOLA_WEBHOOK_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { getGranolaRegistrationClaimKey } from 'src/logic-functions/utils/get-granola-registration-claim-key.util';
+
+export const granolaWebhookResolverHandler = async (
+ routePayload: RoutePayload<unknown>,
+): Promise<ServerRouteResolverResult> => {
+ const receivedAt = Date.now();
+ const registrationId = routePayload.queryStringParameters?.registrationId;
+ if (!isNonEmptyString(registrationId)) {
+ return new Response(
+ { error: 'Missing Granola registration identifier' },
+ { status: 400 },
+ );
+ }
+ const workspaceId = await kv.get<string>(
+ getGranolaRegistrationClaimKey(registrationId),
+ { scope: 'SERVER' },
+ );
+ if (!isNonEmptyString(workspaceId)) {
+ return new Response(
+ { error: 'Unknown Granola registration' },
+ { status: 404 },
+ );
+ }
+ return {
+ workspaceId,
+ targetLogicFunctionUniversalIdentifier:
+ GRANOLA_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ payload: { routePayload, receivedAt },
+ };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ name: 'granola-webhook-resolver',
+ description: 'Routes signed Granola deliveries to the registered workspace.',
+ timeoutSeconds: 15,
+ handler: granolaWebhookResolverHandler,
+ serverRouteTriggerSettings: {
+ httpMethods: ['POST'],
+ forwardedRequestHeaders: [
+ 'webhook-id',
+ 'webhook-timestamp',
+ 'webhook-signature',
+ ],
+ },
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts
new file mode 100644
index 00000000000..79a753b3202
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts
@@ -0,0 +1,112 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
+import { kv, RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import {
+ GRANOLA_PENDING_REGISTRATION_KEY,
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+} from 'src/constants/granola.constant';
+import { GRANOLA_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { GRANOLA_WEBHOOK_PAYLOAD_SCHEMA } from 'src/logic-functions/types/granola-api.type';
+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';
+import { GranolaTranscriptLimitError } from 'src/logic-functions/types/granola-transcript-limit-error';
+import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';
+import { buildRetryableGranolaError } from 'src/logic-functions/utils/build-retryable-granola-error.util';
+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { getGranolaApiKeyFingerprint } from 'src/logic-functions/utils/get-granola-api-key-fingerprint.util';
+import { parseJsonOrUndefined } from 'src/logic-functions/utils/parse-json-or-undefined.util';
+import { syncGranolaNoteToCallRecordingOrThrow } from 'src/logic-functions/utils/sync-granola-note-to-call-recording-or-throw.util';
+import { verifyStandardWebhookSignature } from 'src/logic-functions/utils/verify-standard-webhook-signature.util';
+
+export const granolaWebhookHandler = async ({
+ routePayload,
+ receivedAt,
+}: {
+ routePayload: RoutePayload<unknown>;
+ receivedAt: number;
+}) => {
+ const registrationId = routePayload.queryStringParameters?.registrationId;
+ const registration = await kv.get<GranolaWebhookRegistration>(
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+ );
+ if (registration?.registrationId !== registrationId) {
+ const pendingId = await kv.get<string>(GRANOLA_PENDING_REGISTRATION_KEY);
+ if (pendingId === registrationId) {
+ throw new RetryableLogicFunctionError(
+ 'Granola webhook registration is still being saved.',
+ );
+ }
+ }
+ const apiKey = process.env[GRANOLA_API_KEY_ENV_VAR_NAME];
+ if (
+ !isDefined(registration) ||
+ registration.registrationId !== registrationId ||
+ !isNonEmptyString(apiKey) ||
+ getGranolaApiKeyFingerprint(apiKey) !== registration.apiKeyFingerprint
+ ) {
+ return {
+ success: false,
+ error: 'Unknown Granola registration',
+ };
+ }
+ const rawBody = routePayload.rawBody;
+ const webhookId = routePayload.headers['webhook-id'];
+ const timestamp = routePayload.headers['webhook-timestamp'];
+ const signature = routePayload.headers['webhook-signature'];
+ if (
+ !isNonEmptyString(rawBody) ||
+ !isNonEmptyString(webhookId) ||
+ !isNonEmptyString(timestamp) ||
+ !isNonEmptyString(signature) ||
+ !verifyStandardWebhookSignature({
+ signingSecret: registration.signingSecret,
+ webhookId,
+ timestamp,
+ signature,
+ rawBody,
+ receivedAt,
+ })
+ ) {
+ return { success: false, error: 'Invalid Granola webhook signature' };
+ }
+ const parsed = GRANOLA_WEBHOOK_PAYLOAD_SCHEMA.safeParse(
+ parseJsonOrUndefined(rawBody),
+ );
+ if (!parsed.success || parsed.data.event_id !== webhookId) {
+ return { success: false, error: 'Invalid Granola webhook event' };
+ }
+ const result = await syncGranolaNoteToCallRecordingOrThrow({
+ coreApiClient: new CoreApiClient({ runAs: 'application' }),
+ client: createGranolaClientOrThrow(),
+ noteId: parsed.data.note_id,
+ }).catch((error: unknown) => {
+ if (
+ error instanceof GranolaApiError ||
+ error instanceof GranolaInvalidResponseError ||
+ error instanceof GranolaTranscriptLimitError
+ ) {
+ return { skipped: true, reason: error.message };
+ }
+ if (error instanceof RetryableLogicFunctionError) {
+ throw error;
+ }
+ throw buildRetryableGranolaError({
+ operation: 'Note synchronization',
+ error,
+ });
+ });
+ return { success: true, ...result };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: GRANOLA_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ name: 'granola-webhook',
+ description:
+ 'Verifies signed Granola events and synchronizes notes into Call Recordings.',
+ timeoutSeconds: 900,
+ handler: granolaWebhookHandler,
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts
index a7a1a87f344..e8f9ec1cebb 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts
@@ -1,5 +1,7 @@
import { z } from 'zod';
+import { GRANOLA_NOTE_ID_PATTERN } from 'src/constants/granola-api.constant';
+
const GRANOLA_DATE_TIME_SCHEMA = z.string().datetime({ offset: true });
const GRANOLA_USER_SCHEMA = z.object({
name: z.string().nullable(),
@@ -64,6 +66,12 @@ export const GRANOLA_WEBHOOK_EVENT_SCHEMA = z.enum([
'note.generated',
]);
+export const GRANOLA_WEBHOOK_PAYLOAD_SCHEMA = z.object({
+ event_id: z.string().min(1),
+ event_type: GRANOLA_WEBHOOK_EVENT_SCHEMA,
+ note_id: z.string().regex(GRANOLA_NOTE_ID_PATTERN),
+});
+
export const GRANOLA_WEBHOOK_ENDPOINT_SCHEMA = z.object({
id: z.string(),
object: z.literal('webhook_endpoint'),
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-invalid-response-error.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-invalid-response-error.ts
new file mode 100644
index 00000000000..78930a39622
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-invalid-response-error.ts
@@ -0,0 +1,6 @@
+export class GranolaInvalidResponseError extends Error {
+ constructor() {
+ super('Granola returned an unexpected response.');
+ this.name = 'GranolaInvalidResponseError';
+ }
+}
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts
new file mode 100644
index 00000000000..61586b83453
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts
@@ -0,0 +1,10 @@
+import { type GranolaWebhookScope } from 'src/logic-functions/types/granola-api.type';
+
+export type GranolaWebhookRegistration = {
+ registrationId: string;
+ webhookEndpointId: string;
+ signingSecret: string;
+ apiKeyFingerprint: string;
+ scopes: GranolaWebhookScope[];
+ folderIds: string[];
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts
index 76fd901cfae..3112bf2721b 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts
@@ -3,6 +3,7 @@ import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';
import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';
import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
const API_KEY = 'grn_test_secret';
@@ -107,9 +108,11 @@ describe('createGranolaClientOrThrow', () => {
.fn<typeof fetch>()
.mockResolvedValue(Response.json({ folders: API_KEY })),
);
- await expect(
- createGranolaClientOrThrow({ apiKey: API_KEY }).listFolders(),
- ).rejects.toThrow('Granola returned an unexpected response.');
+ const promise = createGranolaClientOrThrow({
+ apiKey: API_KEY,
+ }).listFolders();
+ await expect(promise).rejects.toBeInstanceOf(GranolaInvalidResponseError);
+ await expect(promise).rejects.not.toThrow(API_KEY);
});
it('rejects blank keys before making a request', () => {
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-webhook-endpoint-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-webhook-endpoint-or-throw.test.ts
new file mode 100644
index 00000000000..958ad141fe4
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-webhook-endpoint-or-throw.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+
+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { createGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/create-granola-webhook-endpoint-or-throw.util';
+
+const SCOPE_MISMATCH_BODY = {
+ code: 'VALIDATION_ERROR',
+ message: 'Invalid scopes',
+ details: [
+ {
+ field: 'scopes',
+ issue:
+ 'The workspace scope requires authenticating with a workspace API key',
+ },
+ ],
+};
+
+const REQUEST_BODY_SCHEMA = z.object({ scopes: z.array(z.string()) });
+
+const buildEndpointResponse = (scopes: string[]) =>
+ Response.json({
+ id: 'whe_2mKr8fQxLp7Ta3',
+ object: 'webhook_endpoint',
+ url: 'https://example.com/hook',
+ url_redacted: false,
+ events: ['note.generated', 'note.access_granted', 'note.edited'],
+ folder_ids: [],
+ scopes,
+ created_by: null,
+ enabled: true,
+ created_at: '2026-09-05T10:00:00Z',
+ signing_secret: 'whsec_c2VjcmV0',
+ });
+
+const stubGranolaAcceptingScopes = (acceptedScopes: string) => {
+ const mockedFetch = vi
+ .fn<typeof fetch>()
+ .mockImplementation(async (_url, request) => {
+ const { scopes } = REQUEST_BODY_SCHEMA.parse(
+ JSON.parse(String(request?.body)),
+ );
+
+ return scopes.join(',') === acceptedScopes
+ ? buildEndpointResponse(scopes)
+ : Response.json(SCOPE_MISMATCH_BODY, { status: 400 });
+ });
+ vi.stubGlobal('fetch', mockedFetch);
+
+ return mockedFetch;
+};
+
+const requestedScopes = (mockedFetch: ReturnType<typeof vi.fn<typeof fetch>>) =>
+ mockedFetch.mock.calls.map(
+ ([, request]) =>
+ REQUEST_BODY_SCHEMA.parse(JSON.parse(String(request?.body))).scopes,
+ );
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('createGranolaWebhookEndpointOrThrow', () => {
+ it('registers a workspace key with workspace scope on the first attempt', async () => {
+ const mockedFetch = stubGranolaAcceptingScopes('workspace');
+
+ const endpoint = await createGranolaWebhookEndpointOrThrow({
+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),
+ url: 'https://example.com/hook',
+ preferredScopes: undefined,
+ folderIds: [],
+ });
+
+ expect(endpoint.scopes).toEqual(['workspace']);
+ expect(requestedScopes(mockedFetch)).toEqual([['workspace']]);
+ });
+
+ it('falls back to personal scopes when Granola rejects workspace scope for a personal key', async () => {
+ const mockedFetch = stubGranolaAcceptingScopes('personal,public');
+
+ const endpoint = await createGranolaWebhookEndpointOrThrow({
+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),
+ url: 'https://example.com/hook',
+ preferredScopes: undefined,
+ folderIds: ['fol_2mKr8fQxLp7Ta3'],
+ });
+
+ expect(endpoint.scopes).toEqual(['personal', 'public']);
+ expect(requestedScopes(mockedFetch)).toEqual([
+ ['workspace'],
+ ['personal', 'public'],
+ ]);
+ expect(String(mockedFetch.mock.calls[1][1]?.body)).toContain(
+ 'fol_2mKr8fQxLp7Ta3',
+ );
+ });
+
+ it('tries the previously registered scopes first', async () => {
+ const mockedFetch = stubGranolaAcceptingScopes('personal,public');
+
+ await createGranolaWebhookEndpointOrThrow({
+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),
+ url: 'https://example.com/hook',
+ preferredScopes: ['personal', 'public'],
+ folderIds: [],
+ });
+
+ expect(requestedScopes(mockedFetch)).toEqual([['personal', 'public']]);
+ });
+
+ it('rethrows errors that are not a scope mismatch', async () => {
+ const mockedFetch = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response(null, { status: 403 }));
+ vi.stubGlobal('fetch', mockedFetch);
+
+ const promise = createGranolaWebhookEndpointOrThrow({
+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),
+ url: 'https://example.com/hook',
+ preferredScopes: undefined,
+ folderIds: [],
+ });
+
+ await expect(promise).rejects.toBeInstanceOf(GranolaApiError);
+ await expect(promise).rejects.toMatchObject({ status: 403 });
+ expect(mockedFetch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts
new file mode 100644
index 00000000000..3c4c44b1b69
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { getGranolaWebhookDestinationUrlOrThrow } from 'src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util';
+
+describe('getGranolaWebhookDestinationUrlOrThrow', () => {
+ it('builds the server route under the API URL with the registration id', () => {
+ expect(
+ getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl: 'https://crm.example.com/',
+ registrationId: 'reg-1',
+ }),
+ ).toBe(
+ 'https://crm.example.com/webhooks/server/91dd18b2-ddfd-4516-bda6-db0e3a2d3e33?registrationId=reg-1',
+ );
+ });
+
+ it('drops an existing query string and hash from the API URL', () => {
+ expect(
+ getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl: 'https://crm.example.com/base?token=1#top',
+ registrationId: 'reg-1',
+ }),
+ ).toBe(
+ 'https://crm.example.com/base/webhooks/server/91dd18b2-ddfd-4516-bda6-db0e3a2d3e33?registrationId=reg-1',
+ );
+ });
+
+ it('rejects a non-HTTPS API URL', () => {
+ expect(() =>
+ getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl: 'http://localhost:3000',
+ registrationId: 'reg-1',
+ }),
+ ).toThrow('HTTPS');
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/verify-standard-webhook-signature.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/verify-standard-webhook-signature.test.ts
new file mode 100644
index 00000000000..b39e4081cbc
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/verify-standard-webhook-signature.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import { verifyStandardWebhookSignature } from 'src/logic-functions/utils/verify-standard-webhook-signature.util';
+
+const SIGNED_DELIVERY = {
+ signingSecret: 'whsec_MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=',
+ webhookId: 'evt_123',
+ timestamp: '1788566400',
+ signature: 'v1,I69TZ8seQwYgHkoZm8BOY6Y4t1ndllzqrjq8ARHdk8I=',
+ rawBody: '{"note_id":"not_12345678901234"}',
+ receivedAt: 1788566400000,
+};
+
+describe('verifyStandardWebhookSignature', () => {
+ it('verifies an independently computed HMAC vector', () => {
+ expect(verifyStandardWebhookSignature(SIGNED_DELIVERY)).toBe(true);
+ });
+
+ it('accepts one matching signature among rotated signatures', () => {
+ expect(
+ verifyStandardWebhookSignature({
+ ...SIGNED_DELIVERY,
+ signature: `v1,aW52YWxpZA== ${SIGNED_DELIVERY.signature}`,
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ { rawBody: '{"note_id":"not_00000000000000"}' },
+ { webhookId: 'evt_other' },
+ { signingSecret: 'whsec_d3Jvbmc=' },
+ { signature: 'v2,I69TZ8seQwYgHkoZm8BOY6Y4t1ndllzqrjq8ARHdk8I=' },
+ { timestamp: '1788566400.0' },
+ { receivedAt: 1788566701000 },
+ { receivedAt: 1788566099000 },
+ { receivedAt: Number.NaN },
+ ])('rejects tampering or invalid freshness: %j', (overrides) => {
+ expect(
+ verifyStandardWebhookSignature({ ...SIGNED_DELIVERY, ...overrides }),
+ ).toBe(false);
+ });
+
+ it('measures freshness at server receipt, independent of worker execution time', () => {
+ expect(
+ verifyStandardWebhookSignature({
+ ...SIGNED_DELIVERY,
+ receivedAt: 1788566699000,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/build-retryable-granola-error.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/build-retryable-granola-error.util.ts
new file mode 100644
index 00000000000..34d9b23cd12
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/build-retryable-granola-error.util.ts
@@ -0,0 +1,14 @@
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const buildRetryableGranolaError = ({
+ operation,
+ error,
+}: {
+ operation: string;
+ error: unknown;
+}): RetryableLogicFunctionError =>
+ new RetryableLogicFunctionError(
+ `[granola] ${operation} failed: ${toErrorMessage(error)}`,
+ );
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util.ts
new file mode 100644
index 00000000000..25f8880dde8
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util.ts
@@ -0,0 +1,50 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { GRANOLA_PENDING_REGISTRATION_KEY } from 'src/constants/granola.constant';
+import { type GranolaWebhookEndpoint } from 'src/logic-functions/types/granola-api.type';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { deleteStaleGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util';
+import { getGranolaRegistrationClaimKey } from 'src/logic-functions/utils/get-granola-registration-claim-key.util';
+import { getGranolaWebhookDestinationUrlOrThrow } from 'src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util';
+
+export const cleanupPendingGranolaRegistrationOrThrow = async ({
+ client,
+ endpoints,
+ apiUrl,
+}: {
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'deleteWebhookEndpoint'
+ >;
+ endpoints: Pick<GranolaWebhookEndpoint, 'id' | 'url'>[];
+ apiUrl: string | undefined;
+}): Promise<void> => {
+ const pendingId = await kv.get<string>(GRANOLA_PENDING_REGISTRATION_KEY);
+
+ if (!isNonEmptyString(pendingId)) {
+ return;
+ }
+
+ if (isDefined(apiUrl)) {
+ const pendingUrl = getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl,
+ registrationId: pendingId,
+ });
+
+ for (const orphan of endpoints.filter(
+ (candidate) => candidate.url === pendingUrl,
+ )) {
+ await deleteStaleGranolaWebhookEndpointOrThrow({
+ client,
+ webhookEndpointId: orphan.id,
+ });
+ }
+ }
+
+ await kv.delete(getGranolaRegistrationClaimKey(pendingId), {
+ scope: 'SERVER',
+ });
+ await kv.delete(GRANOLA_PENDING_REGISTRATION_KEY);
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts
index aa123e93ec2..ec2979cee20 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts
@@ -4,6 +4,7 @@ import { isDefined } from 'twenty-sdk/utils';
import { z } from 'zod';
import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';
import {
GRANOLA_FOLDER_SCHEMA,
GRANOLA_NOTE_SCHEMA,
@@ -92,7 +93,7 @@ export const createGranolaClientOrThrow = ({
const result = schema.safeParse(payload);
if (!result.success) {
- throw new Error('Granola returned an unexpected response.');
+ throw new GranolaInvalidResponseError();
}
return result.data;
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-webhook-endpoint-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-webhook-endpoint-or-throw.util.ts
new file mode 100644
index 00000000000..9b6d3f82c8f
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-webhook-endpoint-or-throw.util.ts
@@ -0,0 +1,61 @@
+import { isNonEmptyArray } from '@sniptt/guards';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type GranolaWebhookScope } from 'src/logic-functions/types/granola-api.type';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { isGranolaScopeValidationError } from 'src/logic-functions/utils/is-granola-scope-validation-error.util';
+
+const GRANOLA_WORKSPACE_KEY_SCOPES: GranolaWebhookScope[] = ['workspace'];
+const GRANOLA_PERSONAL_KEY_SCOPES: GranolaWebhookScope[] = [
+ 'personal',
+ 'public',
+];
+
+// Granola answers a scope that does not match the key type with a 400 on `scopes`.
+export const createGranolaWebhookEndpointOrThrow = async ({
+ client,
+ url,
+ preferredScopes,
+ folderIds,
+}: {
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'createWebhookEndpoint'
+ >;
+ url: string;
+ preferredScopes: GranolaWebhookScope[] | undefined;
+ folderIds: string[];
+}) => {
+ const scopeCandidates = [
+ preferredScopes,
+ GRANOLA_WORKSPACE_KEY_SCOPES,
+ GRANOLA_PERSONAL_KEY_SCOPES,
+ ]
+ .filter(isDefined)
+ .filter(
+ (scopes, index, candidates) =>
+ candidates.findIndex(
+ (candidate) => candidate.join(',') === scopes.join(','),
+ ) === index,
+ );
+
+ for (const [index, scopes] of scopeCandidates.entries()) {
+ try {
+ return await client.createWebhookEndpoint({
+ url,
+ scopes,
+ events: ['note.generated', 'note.access_granted', 'note.edited'],
+ ...(isNonEmptyArray(folderIds) ? { folder_ids: folderIds } : {}),
+ });
+ } catch (error) {
+ if (
+ index === scopeCandidates.length - 1 ||
+ !isGranolaScopeValidationError(error)
+ ) {
+ throw error;
+ }
+ }
+ }
+
+ throw new Error('Granola webhook endpoint could not be created.');
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/current-user-can-manage-granola-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/current-user-can-manage-granola-or-throw.util.ts
new file mode 100644
index 00000000000..9a5754ac528
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/current-user-can-manage-granola-or-throw.util.ts
@@ -0,0 +1,12 @@
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+export const currentUserCanManageGranolaOrThrow =
+ async (): Promise<boolean> => {
+ const { currentUser } = await new MetadataApiClient().query({
+ currentUser: { currentUserWorkspace: { permissionFlags: true } },
+ });
+
+ return (currentUser.currentUserWorkspace?.permissionFlags ?? []).includes(
+ 'APPLICATIONS',
+ );
+ };
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util.ts
new file mode 100644
index 00000000000..0ab4950370c
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util.ts
@@ -0,0 +1,21 @@
+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+
+export const deleteStaleGranolaWebhookEndpointOrThrow = async ({
+ client,
+ webhookEndpointId,
+}: {
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'deleteWebhookEndpoint'
+ >;
+ webhookEndpointId: string;
+}): Promise<void> => {
+ try {
+ await client.deleteWebhookEndpoint({ webhookEndpointId });
+ } catch (error) {
+ if (!(error instanceof GranolaApiError && error.status === 404)) {
+ throw error;
+ }
+ }
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts
new file mode 100644
index 00000000000..e68a6eb0f00
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts
@@ -0,0 +1,113 @@
+import { randomUUID } from 'node:crypto';
+import { isNonEmptyString } from '@sniptt/guards';
+import { kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import {
+ GRANOLA_PENDING_REGISTRATION_KEY,
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+} from 'src/constants/granola.constant';
+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
+import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';
+import { cleanupPendingGranolaRegistrationOrThrow } from 'src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util';
+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { createGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/create-granola-webhook-endpoint-or-throw.util';
+import { deleteStaleGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util';
+import { getGranolaApiKeyFingerprint } from 'src/logic-functions/utils/get-granola-api-key-fingerprint.util';
+import { getGranolaRegistrationClaimKey } from 'src/logic-functions/utils/get-granola-registration-claim-key.util';
+import { getGranolaWebhookDestinationUrlOrThrow } from 'src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util';
+import { repairGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/repair-granola-webhook-endpoint-or-throw.util';
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const ensureGranolaWebhookRegistrationOrThrow =
+ async (): Promise<GranolaWebhookRegistration> => {
+ const apiKey = process.env[GRANOLA_API_KEY_ENV_VAR_NAME]?.trim();
+ const apiUrl = process.env.TWENTY_API_URL;
+ if (!isNonEmptyString(apiKey) || !isNonEmptyString(apiUrl)) {
+ throw new Error('Granola API key and Twenty server URL are required.');
+ }
+ const client = createGranolaClientOrThrow({ apiKey });
+ const apiKeyFingerprint = getGranolaApiKeyFingerprint(apiKey);
+ const existing = await kv.get<GranolaWebhookRegistration>(
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+ );
+ const { webhook_endpoints: endpoints } =
+ await client.listWebhookEndpoints();
+ await cleanupPendingGranolaRegistrationOrThrow({
+ client,
+ endpoints,
+ apiUrl,
+ });
+ const endpoint = endpoints.find(
+ (candidate) => candidate.id === existing?.webhookEndpointId,
+ );
+ const isExistingKeyCurrent =
+ isDefined(existing) && existing.apiKeyFingerprint === apiKeyFingerprint;
+ if (isExistingKeyCurrent && isDefined(endpoint)) {
+ const repairedEndpoint = await repairGranolaWebhookEndpointOrThrow({
+ client,
+ endpoint,
+ expectedUrl: getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl,
+ registrationId: existing.registrationId,
+ }),
+ });
+ const registration = {
+ ...existing,
+ scopes: repairedEndpoint.scopes,
+ folderIds: repairedEndpoint.folder_ids,
+ };
+ await kv.set(GRANOLA_WEBHOOK_REGISTRATION_KEY, registration);
+ return registration;
+ }
+ // Settings removes the key before a new one is added, so a foreign endpoint
+ // only appears after an out-of-band variable edit and cannot be deleted here.
+ if (!isExistingKeyCurrent && isDefined(endpoint)) {
+ console.error(
+ `[granola] Endpoint ${endpoint.id} belongs to a replaced API key; remove it in Granola settings.`,
+ );
+ }
+ const registrationId = randomUUID();
+ const url = getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl,
+ registrationId,
+ });
+ await kv.set(GRANOLA_PENDING_REGISTRATION_KEY, registrationId);
+ await kv.set(getGranolaRegistrationClaimKey(registrationId), null, {
+ scope: 'SERVER',
+ });
+ const createdEndpoint = await createGranolaWebhookEndpointOrThrow({
+ client,
+ url,
+ preferredScopes: isExistingKeyCurrent ? existing.scopes : undefined,
+ folderIds: existing?.folderIds ?? [],
+ });
+ const registration: GranolaWebhookRegistration = {
+ registrationId,
+ webhookEndpointId: createdEndpoint.id,
+ signingSecret: createdEndpoint.signing_secret,
+ apiKeyFingerprint,
+ scopes: createdEndpoint.scopes,
+ folderIds: createdEndpoint.folder_ids,
+ };
+ try {
+ await kv.set(GRANOLA_WEBHOOK_REGISTRATION_KEY, registration);
+ } catch (error) {
+ try {
+ await deleteStaleGranolaWebhookEndpointOrThrow({
+ client,
+ webhookEndpointId: createdEndpoint.id,
+ });
+ await kv.delete(getGranolaRegistrationClaimKey(registrationId), {
+ scope: 'SERVER',
+ });
+ } catch (rollbackError) {
+ console.error(
+ `[granola] Could not roll back endpoint ${createdEndpoint.id} after a failed registration save: ${toErrorMessage(rollbackError)}`,
+ );
+ }
+ throw error;
+ }
+ await kv.delete(GRANOLA_PENDING_REGISTRATION_KEY);
+ return registration;
+ };
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/find-granola-registration-for-current-key.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/find-granola-registration-for-current-key.util.ts
new file mode 100644
index 00000000000..7c0a15745ea
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/find-granola-registration-for-current-key.util.ts
@@ -0,0 +1,27 @@
+import { kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { GRANOLA_WEBHOOK_REGISTRATION_KEY } from 'src/constants/granola.constant';
+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
+import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';
+import { getGranolaApiKeyFingerprint } from 'src/logic-functions/utils/get-granola-api-key-fingerprint.util';
+
+export const findGranolaRegistrationForCurrentKey = async (): Promise<
+ GranolaWebhookRegistration | undefined
+> => {
+ const registration = await kv.get<GranolaWebhookRegistration>(
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+ );
+
+ if (
+ !isDefined(registration) ||
+ registration.apiKeyFingerprint !==
+ getGranolaApiKeyFingerprint(
+ process.env[GRANOLA_API_KEY_ENV_VAR_NAME] ?? '',
+ )
+ ) {
+ return undefined;
+ }
+
+ return registration;
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-api-key-fingerprint.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-api-key-fingerprint.util.ts
new file mode 100644
index 00000000000..9b802e8354d
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-api-key-fingerprint.util.ts
@@ -0,0 +1,4 @@
+import { createHash } from 'node:crypto';
+
+export const getGranolaApiKeyFingerprint = (apiKey: string): string =>
+ createHash('sha256').update(apiKey.trim()).digest('hex');
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-registration-claim-key.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-registration-claim-key.util.ts
new file mode 100644
index 00000000000..b09a575b8f7
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-registration-claim-key.util.ts
@@ -0,0 +1,3 @@
+export const getGranolaRegistrationClaimKey = (
+ registrationId: string,
+): string => `granola-registration:${registrationId}`;
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts
new file mode 100644
index 00000000000..01400a6949d
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts
@@ -0,0 +1,19 @@
+import { GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+
+export const getGranolaWebhookDestinationUrlOrThrow = ({
+ apiUrl,
+ registrationId,
+}: {
+ apiUrl: string;
+ registrationId: string;
+}): string => {
+ const destinationUrl = new URL(apiUrl);
+ if (destinationUrl.protocol !== 'https:') {
+ throw new Error('Granola requires a public HTTPS Twenty server URL.');
+ }
+ destinationUrl.pathname = `${destinationUrl.pathname.replace(/\/+$/, '')}/webhooks/server/${GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;
+ destinationUrl.search = '';
+ destinationUrl.hash = '';
+ destinationUrl.searchParams.set('registrationId', registrationId);
+ return destinationUrl.toString();
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-scope-validation-error.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-scope-validation-error.util.ts
new file mode 100644
index 00000000000..6d16916b128
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-scope-validation-error.util.ts
@@ -0,0 +1,6 @@
+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
+
+export const isGranolaScopeValidationError = (error: unknown): boolean =>
+ error instanceof GranolaApiError &&
+ error.status === 400 &&
+ error.details.some((detail) => detail.field === 'scopes');
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/parse-json-or-undefined.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/parse-json-or-undefined.util.ts
new file mode 100644
index 00000000000..566f9c40b8c
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/parse-json-or-undefined.util.ts
@@ -0,0 +1,7 @@
+export const parseJsonOrUndefined = (rawBody: string): unknown => {
+ try {
+ return JSON.parse(rawBody);
+ } catch {
+ return undefined;
+ }
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts
new file mode 100644
index 00000000000..3e29884a7ee
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts
@@ -0,0 +1,47 @@
+import { kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { GRANOLA_WEBHOOK_REGISTRATION_KEY } from 'src/constants/granola.constant';
+import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { deleteStaleGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util';
+import { getGranolaRegistrationClaimKey } from 'src/logic-functions/utils/get-granola-registration-claim-key.util';
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const removeGranolaWebhookRegistration = async ({
+ client,
+}: {
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'deleteWebhookEndpoint'
+ >;
+}): Promise<{ deletedWebhookCount: number }> => {
+ const registration = await kv.get<GranolaWebhookRegistration>(
+ GRANOLA_WEBHOOK_REGISTRATION_KEY,
+ );
+
+ if (!isDefined(registration)) {
+ return { deletedWebhookCount: 0 };
+ }
+
+ let deletedWebhookCount = 0;
+
+ try {
+ await deleteStaleGranolaWebhookEndpointOrThrow({
+ client,
+ webhookEndpointId: registration.webhookEndpointId,
+ });
+ deletedWebhookCount = 1;
+ } catch (error) {
+ console.error(
+ `[granola] Could not remove endpoint ${registration.webhookEndpointId}; remove it in Granola settings. ${toErrorMessage(error)}`,
+ );
+ }
+
+ await kv.delete(getGranolaRegistrationClaimKey(registration.registrationId), {
+ scope: 'SERVER',
+ });
+ await kv.delete(GRANOLA_WEBHOOK_REGISTRATION_KEY);
+
+ return { deletedWebhookCount };
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/repair-granola-webhook-endpoint-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/repair-granola-webhook-endpoint-or-throw.util.ts
new file mode 100644
index 00000000000..70ac1a1d3ff
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/repair-granola-webhook-endpoint-or-throw.util.ts
@@ -0,0 +1,27 @@
+import { type GranolaWebhookEndpoint } from 'src/logic-functions/types/granola-api.type';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+
+export const repairGranolaWebhookEndpointOrThrow = async ({
+ client,
+ endpoint,
+ expectedUrl,
+}: {
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'updateWebhookEndpoint'
+ >;
+ endpoint: GranolaWebhookEndpoint;
+ expectedUrl: string;
+}): Promise<GranolaWebhookEndpoint> => {
+ const isUrlStale = !endpoint.url_redacted && endpoint.url !== expectedUrl;
+
+ if (endpoint.enabled && !isUrlStale) {
+ return endpoint;
+ }
+
+ return client.updateWebhookEndpoint({
+ webhookEndpointId: endpoint.id,
+ enabled: true,
+ ...(isUrlStale ? { url: expectedUrl } : {}),
+ });
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/sync-granola-note-to-call-recording-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/sync-granola-note-to-call-recording-or-throw.util.ts
new file mode 100644
index 00000000000..e797d9933a8
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/sync-granola-note-to-call-recording-or-throw.util.ts
@@ -0,0 +1,60 @@
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { computeCallRecordingIdForGranolaNote } from 'src/logic-functions/utils/compute-call-recording-id-for-granola-note.util';
+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
+import { fetchGranolaNoteWithTranscriptOrThrow } from 'src/logic-functions/utils/fetch-granola-note-with-transcript-or-throw.util';
+import { findMatchingCalendarEventOrThrow } from 'src/logic-functions/utils/find-matching-calendar-event-or-throw.util';
+import { formatGranolaSummary } from 'src/logic-functions/utils/format-granola-summary.util';
+import { getGranolaNoteTimeRange } from 'src/logic-functions/utils/get-granola-note-time-range.util';
+import { getGranolaNoteTitle } from 'src/logic-functions/utils/get-granola-note-title.util';
+import { mapGranolaTranscriptToEntries } from 'src/logic-functions/utils/map-granola-transcript-to-entries.util';
+import { upsertCallRecordingOrThrow } from 'src/logic-functions/utils/upsert-call-recording-or-throw.util';
+
+export const syncGranolaNoteToCallRecordingOrThrow = async ({
+ coreApiClient,
+ client,
+ noteId,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ client: Pick<
+ ReturnType<typeof createGranolaClientOrThrow>,
+ 'getNote' | 'listTranscriptPage'
+ >;
+ noteId: string;
+}) => {
+ const note = await fetchGranolaNoteWithTranscriptOrThrow({ client, noteId });
+ const callRecordingId = computeCallRecordingIdForGranolaNote(note.id);
+ const { startedAt, endedAt } = getGranolaNoteTimeRange(note);
+ const transcript = mapGranolaTranscriptToEntries({
+ transcript: note.transcript,
+ owner: note.owner,
+ startedAt,
+ });
+ const summary = formatGranolaSummary(note);
+ const title = getGranolaNoteTitle(note);
+ const calendarEventId = await findMatchingCalendarEventOrThrow({
+ coreApiClient,
+ note,
+ });
+ const hasContent = isNonEmptyArray(transcript) || isNonEmptyString(summary);
+ const result = await upsertCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ fields: {
+ ...(isNonEmptyString(title) ? { title } : {}),
+ status: hasContent ? 'COMPLETED' : 'PROCESSING',
+ recordingRequestStatus: 'REQUESTED',
+ externalRecordingId: note.id,
+ startedAt,
+ endedAt,
+ ...(isNonEmptyArray(transcript) ? { transcript } : {}),
+ ...(isNonEmptyString(summary)
+ ? { summary: { markdown: summary, blocknote: null } }
+ : {}),
+ ...(isDefined(calendarEventId) ? { calendarEventId } : {}),
+ },
+ });
+ return { ...result, calendarEventId };
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/to-error-message.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/to-error-message.util.ts
new file mode 100644
index 00000000000..d9fa1691ab6
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/to-error-message.util.ts
@@ -0,0 +1,2 @@
+export const toErrorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/verify-standard-webhook-signature.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/verify-standard-webhook-signature.util.ts
new file mode 100644
index 00000000000..de946cfc354
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/verify-standard-webhook-signature.util.ts
@@ -0,0 +1,46 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+const WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
+
+export const verifyStandardWebhookSignature = ({
+ signingSecret,
+ webhookId,
+ timestamp,
+ signature,
+ rawBody,
+ receivedAt,
+}: {
+ signingSecret: string;
+ webhookId: string;
+ timestamp: string;
+ signature: string;
+ rawBody: string;
+ receivedAt: number;
+}): boolean => {
+ if (
+ !/^\d+$/.test(timestamp) ||
+ !Number.isFinite(receivedAt) ||
+ Math.abs(receivedAt / 1000 - Number(timestamp)) >
+ WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS ||
+ !signingSecret.startsWith('whsec_')
+ ) {
+ return false;
+ }
+ const secret = Buffer.from(signingSecret.slice(6), 'base64');
+ if (secret.length === 0) {
+ return false;
+ }
+ const expectedSignature = createHmac('sha256', secret)
+ .update(`${webhookId}.${timestamp}.${rawBody}`)
+ .digest();
+ return signature.split(/\s+/).some((candidate) => {
+ if (!candidate.startsWith('v1,')) {
+ return false;
+ }
+ const candidateSignature = Buffer.from(candidate.slice(3), 'base64');
+ return (
+ candidateSignature.length === expectedSignature.length &&
+ timingSafeEqual(candidateSignature, expectedSignature)
+ );
+ });
+};