The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(slack): report a rejected bot token to the platform connection (#25763)
Abdul Rahmanf37f45d9ab47
diff --git a/packages/twenty-apps/public/slack/package.json b/packages/twenty-apps/public/slack/package.jsonindex 898d7c08bd3..c48337a5968 100644--- a/packages/twenty-apps/public/slack/package.json+++ b/packages/twenty-apps/public/slack/package.json@@ -1,10 +1,10 @@{"name": "@twentyhq/slack",- "version": "1.1.0",+ "version": "1.2.0","description": "Slack assistant and workflow steps for Twenty","license": "MIT","engines": {- "twenty": ">=2.37.0",+ "twenty": ">=2.40.0","node": "^24.5.0","npm": "please-use-yarn","yarn": ">=4.0.2"@@ -41,8 +41,8 @@"oxlint": "^0.16.0","react": "^18.2.0","react-dom": "^18.2.0",- "twenty-client-sdk": "^2.37.0",- "twenty-sdk": "^2.37.0",+ "twenty-client-sdk": "^2.40.0",+ "twenty-sdk": "^2.40.0","twenty-ui": "^1.0.0-alpha.1","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1",diff --git a/packages/twenty-apps/public/slack/src/__tests__/slack-agent-tools.integration-test.ts b/packages/twenty-apps/public/slack/src/__tests__/slack-agent-tools.integration-test.tsindex 506cdf5108b..b373badaf01 100644--- a/packages/twenty-apps/public/slack/src/__tests__/slack-agent-tools.integration-test.ts+++ b/packages/twenty-apps/public/slack/src/__tests__/slack-agent-tools.integration-test.ts@@ -343,6 +343,7 @@ describe('Slack agent tools', () => {accessToken: 'xoxb-revoked-token',scopes: [],authFailedAt: null,+ authFailedReason: null,},]);diff --git a/packages/twenty-apps/public/slack/src/__tests__/utils/build-slack-app-connection.util.ts b/packages/twenty-apps/public/slack/src/__tests__/utils/build-slack-app-connection.util.tsindex e5e910a238b..3582a4e4aef 100644--- a/packages/twenty-apps/public/slack/src/__tests__/utils/build-slack-app-connection.util.ts+++ b/packages/twenty-apps/public/slack/src/__tests__/utils/build-slack-app-connection.util.ts@@ -16,5 +16,6 @@ export const buildSlackAppConnection = (accessToken,scopes: ['chat:write', 'channels:read'],authFailedAt: null,+ authFailedReason: null,...overrides,});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.tsindex 54800f4bb31..7cf60928e1e 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts@@ -28,6 +28,7 @@ describe('slackConnectionStatusHandler', () => {vi.mocked(getSlackClient).mockResolvedValue({success: true,client: {} as WebClient,+ connectionId: 'connected-account-1',});vi.mocked(resolveSlackConnectionHealth).mockResolvedValue({connectionHealth: 'ok',diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.tsindex e9d034d7624..81c44bcf506 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts@@ -24,7 +24,10 @@ export const slackConnectionStatusHandler =}const [connectionHealthReport, rosterMatchRunOutcome] = await Promise.all([- resolveSlackConnectionHealth(slackClientResult.client),+ resolveSlackConnectionHealth({+ slackClient: slackClientResult.client,+ connectionId: slackClientResult.connectionId,+ }),readSlackRosterMatchRunOutcome(),]);diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/get-slack-connection.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/get-slack-connection.test.tsindex 26ad3434168..595f54082a5 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/get-slack-connection.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/get-slack-connection.test.ts@@ -17,7 +17,7 @@ describe('getSlackConnection', () => {it('should query connections for the slack provider', async () => {listConnectionsMock.mockResolvedValue([- { visibility: 'workspace', accessToken: 'workspace-token' },+ { id: 'conn-ws', visibility: 'workspace', accessToken: 'workspace-token' },]);await getSlackConnection();@@ -27,24 +27,32 @@ describe('getSlackConnection', () => {it('should prefer a workspace-visibility connection over a personal one', async () => {listConnectionsMock.mockResolvedValue([- { visibility: 'personal', accessToken: 'personal-token' },- { visibility: 'workspace', accessToken: 'workspace-token' },+ { id: 'conn-personal', visibility: 'personal', accessToken: 'personal-token' },+ { id: 'conn-ws', visibility: 'workspace', accessToken: 'workspace-token' },]);const result = await getSlackConnection();- expect(result).toEqual({ success: true, accessToken: 'workspace-token' });+ expect(result).toEqual({+ success: true,+ accessToken: 'workspace-token',+ connectionId: 'conn-ws',+ });});it('should fall back to the first connection when none are workspace-visible', async () => {listConnectionsMock.mockResolvedValue([- { visibility: 'personal', accessToken: 'first-token' },- { visibility: 'personal', accessToken: 'second-token' },+ { id: 'conn-first', visibility: 'personal', accessToken: 'first-token' },+ { id: 'conn-second', visibility: 'personal', accessToken: 'second-token' },]);const result = await getSlackConnection();- expect(result).toEqual({ success: true, accessToken: 'first-token' });+ expect(result).toEqual({+ success: true,+ accessToken: 'first-token',+ connectionId: 'conn-first',+ });});it('should fail when there is no Slack connection', async () => {diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.tsindex 8f6f3a5dcfa..a05a8ecc83b 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts@@ -5,6 +5,14 @@ import { fetchCurrentWorkspaceId } from 'src/logic-functions/utils/fetch-currentimport { findClaimedWorkspaceId } from 'src/logic-functions/utils/find-claimed-workspace-id';import { resolveSlackConnectionHealth } from 'src/logic-functions/utils/resolve-slack-connection-health';+const { reportConnectionAuthFailureMock } = vi.hoisted(() => ({+ reportConnectionAuthFailureMock: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', () => ({+ reportConnectionAuthFailure: reportConnectionAuthFailureMock,+}));+vi.mock('src/logic-functions/utils/find-claimed-workspace-id', () => ({findClaimedWorkspaceId: vi.fn(),}));@@ -17,19 +25,27 @@ const authTest = vi.fn();const slackClient = { auth: { test: authTest } } as unknown as WebClient;+const CONNECTION_ID = 'connected-account-1';++const resolveHealth = () =>+ resolveSlackConnectionHealth({ slackClient, connectionId: CONNECTION_ID });+describe('resolveSlackConnectionHealth', () => {beforeEach(() => {vi.clearAllMocks();authTest.mockResolvedValue({ ok: true, team_id: 'T1' });+ reportConnectionAuthFailureMock.mockResolvedValue(undefined);vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-1');vi.mocked(fetchCurrentWorkspaceId).mockResolvedValue('workspace-1');});it('should report a healthy connection claimed by this workspace', async () => {- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: 'ok',installedSlackTeamId: 'T1',});++ expect(reportConnectionAuthFailureMock).not.toHaveBeenCalled();});it('should report a rejected token', async () => {@@ -39,25 +55,89 @@ describe('resolveSlackConnectionHealth', () => {}),);- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({+ connectionHealth: 'token_rejected',+ installedSlackTeamId: undefined,+ });+ });++ it('should flag the platform connection when the token is rejected', async () => {+ authTest.mockRejectedValue(+ Object.assign(new Error('An API error occurred: token_revoked'), {+ data: { ok: false, error: 'token_revoked' },+ }),+ );++ await resolveHealth();++ expect(reportConnectionAuthFailureMock).toHaveBeenCalledTimes(1);+ expect(reportConnectionAuthFailureMock).toHaveBeenCalledWith({+ connectionId: CONNECTION_ID,+ reason: expect.stringContaining('token_revoked'),+ });+ });++ it('should still report a rejected token when the platform report fails', async () => {+ authTest.mockRejectedValue(+ Object.assign(new Error('An API error occurred: invalid_auth'), {+ data: { ok: false, error: 'invalid_auth' },+ }),+ );+ reportConnectionAuthFailureMock.mockRejectedValue(+ new Error('platform unavailable'),+ );++ await expect(resolveHealth()).resolves.toEqual({connectionHealth: 'token_rejected',installedSlackTeamId: undefined,});++ expect(reportConnectionAuthFailureMock).toHaveBeenCalledTimes(1);+ });++ it('should not let a stalled platform report hold up the health result', async () => {+ vi.useFakeTimers();++ try {+ authTest.mockRejectedValue(+ Object.assign(new Error('An API error occurred: invalid_auth'), {+ data: { ok: false, error: 'invalid_auth' },+ }),+ );+ reportConnectionAuthFailureMock.mockReturnValue(+ new Promise(() => undefined),+ );++ const healthPromise = resolveHealth();++ await vi.advanceTimersByTimeAsync(5_000);++ await expect(healthPromise).resolves.toEqual({+ connectionHealth: 'token_rejected',+ installedSlackTeamId: undefined,+ });++ expect(reportConnectionAuthFailureMock).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }});it('should not raise an alarm on a transient auth.test failure', async () => {authTest.mockRejectedValue(new Error('socket hang up'));- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: undefined,installedSlackTeamId: undefined,});++ expect(reportConnectionAuthFailureMock).not.toHaveBeenCalled();});it('should claim no health when auth.test returns no team id', async () => {authTest.mockResolvedValue({ ok: true });- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: undefined,installedSlackTeamId: undefined,});@@ -66,7 +146,7 @@ describe('resolveSlackConnectionHealth', () => {it('should report an unclaimed team', async () => {vi.mocked(findClaimedWorkspaceId).mockResolvedValue(null);- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: 'team_unclaimed',installedSlackTeamId: 'T1',});@@ -75,7 +155,7 @@ describe('resolveSlackConnectionHealth', () => {it('should report a team claimed by another workspace', async () => {vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-2');- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: 'team_claimed_by_another_workspace',installedSlackTeamId: 'T1',});@@ -86,7 +166,7 @@ describe('resolveSlackConnectionHealth', () => {new Error('kv unavailable'),);- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: undefined,installedSlackTeamId: 'T1',});@@ -96,7 +176,7 @@ describe('resolveSlackConnectionHealth', () => {vi.mocked(fetchCurrentWorkspaceId).mockResolvedValue(undefined);vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-2');- await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({+ await expect(resolveHealth()).resolves.toEqual({connectionHealth: undefined,installedSlackTeamId: 'T1',});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-client.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-client.tsindex d8d5cdbfe42..bb3601bf939 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-client.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-client.ts@@ -7,7 +7,8 @@ import { getSlackConnection } from 'src/logic-functions/utils/get-slack-connectiexport const getSlackClient = async (options?: WebClientOptions,): Promise<- { success: true; client: WebClient } | { success: false; error: string }+ | { success: true; client: WebClient; connectionId: string }+ | { success: false; error: string }> => {const connectionResult = await getSlackConnection();@@ -24,5 +25,6 @@ export const getSlackClient = async (rejectRateLimitedCalls: true,...options,}),+ connectionId: connectionResult.connectionId,};};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-connection.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-connection.tsindex b9eddd97fab..a1b8ed6c776 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-connection.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-connection.ts@@ -1,7 +1,8 @@import { listConnections } from 'twenty-sdk/logic-function';export const getSlackConnection = async (): Promise<- { success: true; accessToken: string } | { success: false; error: string }+ | { success: true; accessToken: string; connectionId: string }+ | { success: false; error: string }> => {try {const connections = await listConnections({ providerName: 'slack' });@@ -17,7 +18,11 @@ export const getSlackConnection = async (): Promise<};}- return { success: true, accessToken: connection.accessToken };+ return {+ success: true,+ accessToken: connection.accessToken,+ connectionId: connection.id,+ };} catch (error) {const message =error instanceof Errordiff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.tsindex 5f3a639e5c0..1807aa3edca 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts@@ -1,5 +1,6 @@import { type WebClient } from '@slack/web-api';import { isNonEmptyString } from '@sniptt/guards';+import { reportConnectionAuthFailure } from 'twenty-sdk/logic-function';import { isDefined } from 'twenty-sdk/utils';import { SLACK_AUTH_ERROR_CODES } from 'src/logic-functions/constants/slack-auth-error-codes';@@ -19,7 +20,11 @@ export type SlackConnectionHealthReport = {type SlackAuthProbe =| { isAuthenticated: true; installedTeamId: string | undefined }- | { isAuthenticated: false; isTokenRejected: boolean };+ | {+ isAuthenticated: false;+ isTokenRejected: boolean;+ slackErrorCode: string | undefined;+ };type SlackTeamClaimLookup =| { isReadable: true; claimedWorkspaceId: string | null }@@ -43,10 +48,38 @@ const probeSlackAuth = async (isTokenRejected:isNonEmptyString(slackErrorCode) &&SLACK_AUTH_ERROR_CODES.includes(slackErrorCode),+ slackErrorCode,};}};+const REPORT_SLACK_TOKEN_REJECTED_TIMEOUT_MS = 5_000;++const reportSlackTokenRejected = async ({+ connectionId,+ slackErrorCode,+}: {+ connectionId: string;+ slackErrorCode: string | undefined;+}): Promise<void> => {+ let timeoutId: ReturnType<typeof setTimeout> | undefined;++ const reportPromise = reportConnectionAuthFailure({+ connectionId,+ reason: `Slack rejected the stored bot token (${slackErrorCode ?? 'auth error'}). Reconnect to restore the integration.`,+ }).catch(() => undefined);++ const timeoutPromise = new Promise<void>((resolve) => {+ timeoutId = setTimeout(resolve, REPORT_SLACK_TOKEN_REJECTED_TIMEOUT_MS);+ });++ try {+ await Promise.race([reportPromise, timeoutPromise]);+ } finally {+ clearTimeout(timeoutId);+ }+};+const readSlackTeamClaim = (installedTeamId: string,): Promise<SlackTeamClaimLookup> =>@@ -58,18 +91,29 @@ const readSlackTeamClaim = (// An undefined health means unverified, not healthy: a transient Slack or// claim-store failure must never tell an admin to reconnect a working// integration.-export const resolveSlackConnectionHealth = async (- slackClient: WebClient,-): Promise<SlackConnectionHealthReport> => {+export const resolveSlackConnectionHealth = async ({+ slackClient,+ connectionId,+}: {+ slackClient: WebClient;+ connectionId: string;+}): Promise<SlackConnectionHealthReport> => {const authProbe = await probeSlackAuth(slackClient);if (!authProbe.isAuthenticated) {- return {- connectionHealth: authProbe.isTokenRejected- ? SLACK_CONNECTION_HEALTH.TOKEN_REJECTED- : undefined,- installedSlackTeamId: undefined,- };+ if (authProbe.isTokenRejected) {+ await reportSlackTokenRejected({+ connectionId,+ slackErrorCode: authProbe.slackErrorCode,+ });++ return {+ connectionHealth: SLACK_CONNECTION_HEALTH.TOKEN_REJECTED,+ installedSlackTeamId: undefined,+ };+ }++ return { connectionHealth: undefined, installedSlackTeamId: undefined };}const installedSlackTeamId = authProbe.installedTeamId;diff --git a/packages/twenty-apps/public/slack/yarn.lock b/packages/twenty-apps/public/slack/yarn.lockindex 84c74337a01..4fad342bfc4 100644--- a/packages/twenty-apps/public/slack/yarn.lock+++ b/packages/twenty-apps/public/slack/yarn.lock@@ -1475,8 +1475,8 @@ __metadata:oxlint: "npm:^0.16.0"react: "npm:^18.2.0"react-dom: "npm:^18.2.0"- twenty-client-sdk: "npm:^2.37.0"- twenty-sdk: "npm:^2.37.0"+ twenty-client-sdk: "npm:^2.40.0"+ twenty-sdk: "npm:^2.40.0"twenty-ui: "npm:^1.0.0-alpha.1"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"@@ -4073,22 +4073,22 @@ __metadata:languageName: nodelinkType: hard-"twenty-client-sdk@npm:2.37.0, twenty-client-sdk@npm:^2.37.0":- version: 2.37.0- resolution: "twenty-client-sdk@npm:2.37.0"+"twenty-client-sdk@npm:2.40.0, twenty-client-sdk@npm:^2.40.0":+ version: 2.40.0+ resolution: "twenty-client-sdk@npm:2.40.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/0250a95b803a468f7bd9261b7a55a862b9b6daf840adf21ab7a4067906761e710703f79f7571f6400716afc4e612eda7da2bb1948c23a5adff07d59cc30ba10e+ checksum: 10c0/60d046ffe7aa289607933e9442fed05f9f8e97b64d6acbe3bbcfe065184cd6c76e86fcc6530d609d6f54d600b5302b2ac709ffddd16737d2e83f3d56b67256c0languageName: nodelinkType: hard-"twenty-sdk@npm:^2.37.0":- version: 2.37.0- resolution: "twenty-sdk@npm:2.37.0"+"twenty-sdk@npm:^2.40.0":+ version: 2.40.0+ resolution: "twenty-sdk@npm:2.40.0"dependencies:"@sniptt/guards": "npm:^0.2.0"axios: "npm:^1.16.0"@@ -4107,12 +4107,12 @@ __metadata:semver: "npm:7.6.3"sharp: "npm:^0.35.3"tinyglobby: "npm:^0.2.15"- twenty-client-sdk: "npm:2.37.0"+ twenty-client-sdk: "npm:2.40.0"typescript: "npm:^5.9.3"uuid: "npm:^13.0.2"bin:twenty: dist/cli.cjs- checksum: 10c0/ddbc01430cfbcc878d2b23851b5f5ae7a76fb453d5a578e876ab7e999093a62aa8c025d22b1095d20fad363f8e6cf885a7c002ad64498fdbb9dfc695a1fc1f9c+ checksum: 10c0/74fab301ba98f17ad16396eb48a55af43ea8d4583e8e863c4248774962dce5a272fcb24ae78c8214f2997c9146b3815e1542c202d52ed89d035550eaa8151d96languageName: nodelinkType: hard