The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Delete Fathom webhooks on disconnect (#25520)
nitin9c175e5d822a
diff --git a/packages/twenty-apps/public/fathom/package.json b/packages/twenty-apps/public/fathom/package.jsonindex 508ae397e72..6a29fcee533 100644--- a/packages/twenty-apps/public/fathom/package.json+++ b/packages/twenty-apps/public/fathom/package.json@@ -5,6 +5,7 @@"engines": {"node": "^24.5.0","npm": "please-use-yarn",+ "twenty": ">=2.38.0","yarn": ">=4.0.2"},"keywords": [],@@ -27,8 +28,8 @@"@types/node": "^24.7.2","@typescript/native-preview": "^7.0.0-dev.20260116.1","oxlint": "^0.16.0",- "twenty-client-sdk": "2.35.0",- "twenty-sdk": "2.35.0",+ "twenty-client-sdk": "2.38.0",+ "twenty-sdk": "2.38.0","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1","vitest": "^4.0.0"diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-disconnect.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-disconnect.test.tsnew file mode 100644index 00000000000..22fb8606dca--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-disconnect.test.ts@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';++const sdkMocks = vi.hoisted(() => ({+ deleteWebhook: vi.fn(),+ getConnection: vi.fn(),+ kvDelete: vi.fn(),+ kvGet: vi.fn(),+ kvSet: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ kv: { get: sdkMocks.kvGet, set: sdkMocks.kvSet, delete: sdkMocks.kvDelete },+ getConnection: sdkMocks.getConnection,+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ deleteWebhook = sdkMocks.deleteWebhook;+ },+}));++const { fathomDisconnectHandler } = await import(+ 'src/logic-functions/fathom-disconnect'+);++const payload = {+ connectionProviderId: 'provider-1',+ connectionProviderName: 'fathom',+ connectedAccountId: 'connection-1',+};++const registration = {+ webhookId: 'webhook-1',+ secret: 'secret',+ isActive: true,+ isInitialBackfillEnqueued: true,+};++describe('fathomDisconnectHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ sdkMocks.kvGet.mockResolvedValue(registration);+ sdkMocks.getConnection.mockResolvedValue({+ id: 'connection-1',+ accessToken: 'token-1',+ });+ });++ it('deletes the Fathom webhook, the registration and the server claim', async () => {+ expect(await fathomDisconnectHandler(payload)).toEqual({ success: true });+ expect(sdkMocks.deleteWebhook).toHaveBeenCalledWith({ id: 'webhook-1' });+ expect(sdkMocks.kvDelete.mock.calls).toEqual([+ ['fathom-webhook:connection-1'],+ ['fathom-connection:connection-1', { scope: 'SERVER' }],+ ]);+ });++ it('releases the server claim when no webhook was ever registered', async () => {+ sdkMocks.kvGet.mockResolvedValue(null);++ expect(await fathomDisconnectHandler(payload)).toEqual({ success: true });+ expect(sdkMocks.getConnection).not.toHaveBeenCalled();+ expect(sdkMocks.deleteWebhook).not.toHaveBeenCalled();+ expect(sdkMocks.kvDelete.mock.calls).toEqual([+ ['fathom-connection:connection-1', { scope: 'SERVER' }],+ ]);+ });++ it('completes the cleanup when Fathom already dropped the webhook', async () => {+ sdkMocks.deleteWebhook.mockRejectedValue(buildFathomNotFoundError());++ expect(await fathomDisconnectHandler(payload)).toEqual({ success: true });+ expect(sdkMocks.kvDelete).toHaveBeenCalledTimes(2);+ expect(console.error).not.toHaveBeenCalled();+ });++ it('keeps the inactive registration and logs the leaked webhook when Fathom fails', async () => {+ sdkMocks.deleteWebhook.mockRejectedValue(new Error('Fathom unavailable'));++ await expect(fathomDisconnectHandler(payload)).rejects.toThrow(+ 'Fathom unavailable',+ );+ expect(sdkMocks.kvSet).toHaveBeenCalledWith('fathom-webhook:connection-1', {+ ...registration,+ isActive: false,+ });+ expect(sdkMocks.kvDelete).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('leaked webhook webhook-1'),+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.tsindex e844282f2f2..6e0aea0a48b 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.ts@@ -1,11 +1,15 @@import { defineLogicFunction } from 'twenty-sdk/define';-import { kv } from 'twenty-sdk/logic-function';+import { getConnection, kv } from 'twenty-sdk/logic-function';import { isDefined } from 'src/utils/is-defined';import { FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { type FathomConnectionHookPayload } from 'src/logic-functions/types/fathom-connection-hook-payload.type';import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { deleteStaleFathomWebhook } from 'src/logic-functions/utils/delete-stale-fathom-webhook.util';+import { getFathomConnectionClaimKey } from 'src/logic-functions/utils/get-fathom-connection-claim-key.util';import { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';export const fathomDisconnectHandler = async (payload: FathomConnectionHookPayload,@@ -15,14 +19,39 @@ export const fathomDisconnectHandler = async ();const registration = await kv.get<FathomWebhookRegistration>(registrationKey);- if (isDefined(registration)) {- // Twenty runs onDisconnect after deleting the token, so the secret is kept only- // to acknowledge Fathom deliveries still in flight.- // TODO: delete the webhook, this registration and the server-scoped connection- // claim here, and drop isActive, once the engine carries #25215.- await kv.set(registrationKey, { ...registration, isActive: false });+ if (!isDefined(registration)) {+ await kv.delete(getFathomConnectionClaimKey(payload.connectedAccountId), {+ scope: 'SERVER',+ });++ return { success: true };}+ await kv.set(registrationKey, { ...registration, isActive: false });++ const connection = await getConnection(payload.connectedAccountId);++ try {+ await deleteStaleFathomWebhook({+ fathomClient: createFathomClient(connection.accessToken),+ webhookId: registration.webhookId,+ });+ } catch (error) {+ // Twenty deletes the connected account right after this hook, so the+ // registration left behind is keyed on an id that never comes back and this+ // log line is the only record of the webhook still live in Fathom.+ console.error(+ `[fathom] leaked webhook ${registration.webhookId} for connected account ${payload.connectedAccountId}: ${toErrorMessage(error)}`,+ );++ throw error;+ }++ await kv.delete(registrationKey);+ await kv.delete(getFathomConnectionClaimKey(payload.connectedAccountId), {+ scope: 'SERVER',+ });+return { success: true };};@@ -30,7 +59,7 @@ export default defineLogicFunction({universalIdentifier: FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER,name: 'fathom-disconnect',description:- 'Disables webhook ingestion after a user removes their Fathom connection.',- timeoutSeconds: 10,+ 'Deletes the registered Fathom webhook after a user removes their connection.',+ timeoutSeconds: 30,handler: fathomDisconnectHandler,});diff --git a/packages/twenty-apps/public/fathom/yarn.lock b/packages/twenty-apps/public/fathom/yarn.lockindex dfa64f1a66f..f44b58080aa 100644--- a/packages/twenty-apps/public/fathom/yarn.lock+++ b/packages/twenty-apps/public/fathom/yarn.lock@@ -933,8 +933,8 @@ __metadata:"@typescript/native-preview": "npm:^7.0.0-dev.20260116.1"fathom-typescript: "npm:0.0.43"oxlint: "npm:^0.16.0"- twenty-client-sdk: "npm:2.35.0"- twenty-sdk: "npm:2.35.0"+ twenty-client-sdk: "npm:2.38.0"+ twenty-sdk: "npm:2.38.0"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"vitest: "npm:^4.0.0"@@ -2809,22 +2809,22 @@ __metadata:languageName: nodelinkType: hard-"twenty-client-sdk@npm:2.35.0":- version: 2.35.0- resolution: "twenty-client-sdk@npm:2.35.0"+"twenty-client-sdk@npm:2.38.0":+ version: 2.38.0+ resolution: "twenty-client-sdk@npm:2.38.0"dependencies:"@genql/runtime": "npm:^2.10.0"esbuild: "npm:^0.28.1"graphql: "npm:^16.8.1"lodash: "npm:^4.17.21"prettier: "npm:^3.8.3"- checksum: 10c0/2ce66e4647c6c6f4b4897896858f8abab3dd8aa6112b8c5c6387082ce484b6a2fb9b90060526601b13329c207ae530d25a6ba80197868a8653156505e0736f5d+ checksum: 10c0/2ab1c0371a5b48187211477740d833c8454e624d45b4ea1b964864077745d85e6921f5e8452eacb1eceab44e698507a4854686e225e467dd4f5fc481553b047blanguageName: nodelinkType: hard-"twenty-sdk@npm:2.35.0":- version: 2.35.0- resolution: "twenty-sdk@npm:2.35.0"+"twenty-sdk@npm:2.38.0":+ version: 2.38.0+ resolution: "twenty-sdk@npm:2.38.0"dependencies:"@sniptt/guards": "npm:^0.2.0"axios: "npm:^1.16.0"@@ -2843,12 +2843,12 @@ __metadata:semver: "npm:7.6.3"sharp: "npm:^0.35.3"tinyglobby: "npm:^0.2.15"- twenty-client-sdk: "npm:2.35.0"+ twenty-client-sdk: "npm:2.38.0"typescript: "npm:^5.9.3"uuid: "npm:^13.0.2"bin:twenty: dist/cli.cjs- checksum: 10c0/4cb27d3b449b2fbe692516cc29b2689232e4f40de1181132ea3d9743a1fc1c9284204ddf50632fc737d06748ff9c6903630124c02382b4f61eec120beaa9f9d5+ checksum: 10c0/9946e0018f6233bbd8bd3ab0ca9dcc96276b25126b9c14328b90b15b8f2948d550ebb9395354ec87066bd8ab74372d242d94c4e5629b4cd16421bf21beb8a62elanguageName: nodelinkType: hard