Skip to content

The open alternative to Salesforce, designed for AI.

feat(twenty-slack): release the Slack team claim when the install is revoked on the Slack side (#24097)

Abdul Rahmanbcbcf71ac424
diff --git a/packages/twenty-apps/public/slack/SETUP.md b/packages/twenty-apps/public/slack/SETUP.md
index a2487e46eef..c57cbd26232 100644
--- a/packages/twenty-apps/public/slack/SETUP.md
+++ b/packages/twenty-apps/public/slack/SETUP.md
@@ -68,9 +68,12 @@ The assistant reuses the same Slack connection — no second bot identity.
- `message.channels` — replies in public-channel threads, for un-mentioned follow-ups
- `message.groups` — same, for private channels the bot is in
- `member_joined_channel` — optional; lets the bot introduce itself when it is added to a channel
+ - `app_uninstalled` and `tokens_revoked` — the app was removed from the Slack workspace or its bot token was revoked; releases the Slack team claim so the team can be connected again
Invite the bot to any channel where it should follow threads. Slack may ask you to reinstall after changing subscriptions.
+ Event subscriptions added in app upgrades must be added here by hand on existing installs — the Slack app only reads the manifest at creation. Upgrading from any version before 0.4.1 adds `app_uninstalled` and `tokens_revoked`; without them the team claim of a Slack-side removal is never released. No new scopes are involved, so the connection itself needs no re-authorization.
+
3. **Reconnect** so the token picks up the assistant scopes.
4. **Role.** The `slack-assistant` agent binds to the app's **Slack Assistant** role automatically on install and upgrade. That role is the ceiling for everything the bot can do.
@@ -85,7 +88,7 @@ The assistant reuses the same Slack connection — no second bot identity.
- **Thread memory.** After a successful reply the bot stays active in that thread, so follow-ups need no mention. Channel threads stay active for 24 hours after the last reply (each reply renews it); DM threads never expire.
- **No silent dead-ends.** A mention or DM with no request text gets a short hint reply. The first follow-up in a thread whose 24-hour window has lapsed gets an ephemeral nudge (only that member sees it) to mention the bot again.
- **Channel welcome.** With `member_joined_channel` subscribed, the bot posts a short introduction the first time it is added to a channel, with the details (what to ask it, what it reads, and how permissions work per step 4 above) in a thread reply so the channel itself stays quiet. It fires once per channel for 30 days, and only for the bot's own join — humans joining afterwards trigger nothing. Skip the subscription if you would rather it arrived silently.
-- **One Slack workspace per Twenty workspace.** Connecting Slack claims that Slack team for the connecting Twenty workspace. On the same server, a second Twenty workspace connecting the same Slack team is rejected. Removing the connection releases the claim, so another Twenty workspace can then connect that Slack team. Uninstalling the app releases it too.
+- **One Slack workspace per Twenty workspace.** Connecting Slack claims that Slack team for the connecting Twenty workspace. On the same server, a second Twenty workspace connecting the same Slack team is rejected. Removing the connection releases the claim, so another Twenty workspace can then connect that Slack team. Uninstalling the app releases it too, and so does removing the app on the Slack side (uninstalling it from the Slack workspace or revoking its bot token) — with `app_uninstalled` and `tokens_revoked` subscribed, Slack reports the removal and the claim is released. The dead connection still shows under **Connections** until you remove it; reconnecting means removing it and adding a new connection.
## Workflow field names (for step authors)
diff --git a/packages/twenty-apps/public/slack/package.json b/packages/twenty-apps/public/slack/package.json
index bd2e50cc999..8feb897043a 100644
--- a/packages/twenty-apps/public/slack/package.json
+++ b/packages/twenty-apps/public/slack/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/slack",
- "version": "0.4.0",
+ "version": "0.4.1",
"description": "Slack assistant and workflow steps for Twenty",
"license": "MIT",
"engines": {
diff --git a/packages/twenty-apps/public/slack/slack-app-manifest.json b/packages/twenty-apps/public/slack/slack-app-manifest.json
index e4c45708a30..a1a3b1c29da 100644
--- a/packages/twenty-apps/public/slack/slack-app-manifest.json
+++ b/packages/twenty-apps/public/slack/slack-app-manifest.json
@@ -43,10 +43,12 @@
"bot_events": [
"app_home_opened",
"app_mention",
+ "app_uninstalled",
"member_joined_channel",
"message.channels",
"message.groups",
- "message.im"
+ "message.im",
+ "tokens_revoked"
]
},
"org_deploy_enabled": false,
diff --git a/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts
index 229c3eb5e83..f08f1bf997a 100644
--- a/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts
@@ -55,6 +55,9 @@ export const SLACK_TEAM_RELEASE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
export const SLACK_APP_UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'0c89ed56-7e69-40e4-b15a-919a4912ed9b';
+export const SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '144d8fcc-d44b-46a2-bb19-0d11533db9cb';
+
export const SLACK_ASSISTANT_REQUEST_OBJECT_UNIVERSAL_IDENTIFIER =
'4dfdd6c7-9042-4278-8d3e-8172a8a5e15f';
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/__tests__/slack-events-resolver.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/__tests__/slack-events-resolver.test.ts
new file mode 100644
index 00000000000..63eeefa9bb8
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/__tests__/slack-events-resolver.test.ts
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ SLACK_EVENTS_ENQUEUE_UNIVERSAL_IDENTIFIER,
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { slackEventsResolverHandler } from 'src/logic-functions/slack-events-resolver';
+import { type SlackEventsRequestBody } from 'src/logic-functions/types/slack-events-request-body.type';
+import { Response } from 'twenty-sdk/logic-function';
+
+const {
+ getSlackWebhookSecretMock,
+ verifySignatureMock,
+ resolveWorkspaceMock,
+ findClaimedWorkspaceMock,
+} = vi.hoisted(() => ({
+ getSlackWebhookSecretMock: vi.fn(),
+ verifySignatureMock: vi.fn(),
+ resolveWorkspaceMock: vi.fn(),
+ findClaimedWorkspaceMock: vi.fn(),
+}));
+
+vi.mock('src/logic-functions/utils/get-slack-webhook-secret', () => ({
+ getSlackWebhookSecret: getSlackWebhookSecretMock,
+}));
+
+vi.mock('src/logic-functions/utils/verify-slack-request-signature', () => ({
+ verifySlackRequestSignature: verifySignatureMock,
+}));
+
+vi.mock('src/logic-functions/utils/resolve-target-workspace-id', () => ({
+ resolveTargetWorkspaceId: resolveWorkspaceMock,
+}));
+
+vi.mock('src/logic-functions/utils/find-claimed-workspace-id', () => ({
+ findClaimedWorkspaceId: findClaimedWorkspaceMock,
+}));
+
+const buildRoutePayload = (body: SlackEventsRequestBody) => ({
+ body,
+ rawBody: JSON.stringify(body),
+ headers: {
+ 'x-slack-signature': 'v0=signature',
+ 'x-slack-request-timestamp': '1700000000',
+ },
+ queryStringParameters: {},
+ pathParameters: {},
+ isBase64Encoded: false,
+ requestContext: { http: { method: 'POST', path: '/' } },
+ userWorkspaceId: null,
+});
+
+describe('slackEventsResolverHandler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getSlackWebhookSecretMock.mockReturnValue({
+ success: true,
+ secret: 'secret',
+ });
+ verifySignatureMock.mockReturnValue(true);
+ });
+
+ it('should route app_uninstalled to the install-revoked function in the claiming workspace', async () => {
+ findClaimedWorkspaceMock.mockResolvedValue('workspace-1');
+
+ const body: SlackEventsRequestBody = {
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ };
+
+ const result = await slackEventsResolverHandler(buildRoutePayload(body));
+
+ expect(result).toEqual({
+ workspaceId: 'workspace-1',
+ targetLogicFunctionUniversalIdentifier:
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payload: body,
+ });
+ });
+
+ it('should route tokens_revoked to the install-revoked function', async () => {
+ findClaimedWorkspaceMock.mockResolvedValue('workspace-1');
+
+ const result = await slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'tokens_revoked', tokens: { bot: ['B123'] } },
+ }),
+ );
+
+ expect(result).toMatchObject({
+ targetLogicFunctionUniversalIdentifier:
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ });
+ });
+
+ it('should ack a removal event for an unclaimed team instead of erroring into a retry', async () => {
+ findClaimedWorkspaceMock.mockResolvedValue(null);
+
+ const result = await slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'tokens_revoked', tokens: { bot: ['B123'] } },
+ }),
+ );
+
+ expect(result).toBeInstanceOf(Response);
+ expect((result as Response).body).toEqual({
+ ok: true,
+ skipped: 'No workspace claims this Slack team',
+ });
+ });
+
+ it('should keep a removal event retryable when the claim lookup fails', async () => {
+ findClaimedWorkspaceMock.mockRejectedValue(new Error('kv unavailable'));
+
+ await expect(
+ slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ }),
+ ),
+ ).rejects.toThrow('kv unavailable');
+ });
+
+ it('should throw on a removal event with no team_id', async () => {
+ await expect(
+ slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ event: { type: 'app_uninstalled' },
+ }),
+ ),
+ ).rejects.toThrow('no team_id');
+ expect(findClaimedWorkspaceMock).not.toHaveBeenCalled();
+ });
+
+ it('should keep failing loudly when a message event targets an unclaimed team', async () => {
+ resolveWorkspaceMock.mockRejectedValue(
+ new Error('No workspace has claimed Slack team T123'),
+ );
+
+ await expect(
+ slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'message', channel_type: 'im' },
+ }),
+ ),
+ ).rejects.toThrow('No workspace has claimed Slack team T123');
+ });
+
+ it('should route other events unchanged', async () => {
+ resolveWorkspaceMock.mockResolvedValue('workspace-1');
+
+ const result = await slackEventsResolverHandler(
+ buildRoutePayload({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'message', channel_type: 'im' },
+ }),
+ );
+
+ expect(result).toMatchObject({
+ targetLogicFunctionUniversalIdentifier:
+ SLACK_EVENTS_ENQUEUE_UNIVERSAL_IDENTIFIER,
+ });
+ expect(findClaimedWorkspaceMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-install-revoked-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-install-revoked-handler.test.ts
new file mode 100644
index 00000000000..4f3b61654d9
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-install-revoked-handler.test.ts
@@ -0,0 +1,167 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { slackInstallRevokedHandler } from 'src/logic-functions/handlers/slack-install-revoked-handler';
+
+const { kvGetMock, kvDeleteMock, listConnectionsMock } = vi.hoisted(() => ({
+ kvGetMock: vi.fn(),
+ kvDeleteMock: vi.fn(),
+ listConnectionsMock: vi.fn(),
+}));
+
+vi.mock('twenty-sdk/logic-function', () => ({
+ kv: { get: kvGetMock, delete: kvDeleteMock },
+ listConnections: listConnectionsMock,
+}));
+
+const mockConnectedAccountTeams = (teamByKey: Record<string, string>) => {
+ kvGetMock.mockImplementation((key: string) => {
+ return Promise.resolve(teamByKey[key] ?? null);
+ });
+};
+
+describe('slackInstallRevokedHandler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should release the team claim and the matching connection entries on app_uninstalled', async () => {
+ listConnectionsMock.mockResolvedValue([
+ { id: 'connection-1' },
+ { id: 'connection-2' },
+ ]);
+ mockConnectedAccountTeams({
+ 'slack-connected-account-team:connection-1': 'T123',
+ 'slack-connected-account-team:connection-2': 'T999',
+ });
+ kvDeleteMock.mockResolvedValue(true);
+
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ releasedTeamId: 'T123',
+ releasedConnectedAccountIds: ['connection-1'],
+ });
+ expect(kvDeleteMock).toHaveBeenCalledWith(
+ 'slack-connected-account-team:connection-1',
+ );
+ expect(kvDeleteMock).not.toHaveBeenCalledWith(
+ 'slack-connected-account-team:connection-2',
+ );
+ expect(kvDeleteMock).toHaveBeenCalledWith('slack-team:T123', {
+ scope: 'SERVER',
+ });
+ });
+
+ it('should release the team claim even when no connection matches the team', async () => {
+ listConnectionsMock.mockResolvedValue([]);
+ mockConnectedAccountTeams({});
+ kvDeleteMock.mockResolvedValue(true);
+
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ releasedTeamId: 'T123',
+ releasedConnectedAccountIds: [],
+ });
+ expect(kvDeleteMock).toHaveBeenCalledWith('slack-team:T123', {
+ scope: 'SERVER',
+ });
+ });
+
+ it('should report no released team when the claim delete is refused', async () => {
+ listConnectionsMock.mockResolvedValue([]);
+ mockConnectedAccountTeams({});
+ kvDeleteMock.mockResolvedValue(false);
+
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ releasedTeamId: null,
+ releasedConnectedAccountIds: [],
+ });
+ });
+
+ it('should release the team claim before a failing connection lookup surfaces', async () => {
+ listConnectionsMock.mockResolvedValue([{ id: 'connection-1' }]);
+ kvGetMock.mockRejectedValue(new Error('kv unavailable'));
+ kvDeleteMock.mockResolvedValue(true);
+
+ await expect(
+ slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'app_uninstalled' },
+ }),
+ ).rejects.toThrow('kv unavailable');
+
+ expect(kvDeleteMock).toHaveBeenCalledWith('slack-team:T123', {
+ scope: 'SERVER',
+ });
+ });
+
+ it('should release the claim when a tokens_revoked event revokes the bot token', async () => {
+ listConnectionsMock.mockResolvedValue([]);
+ mockConnectedAccountTeams({});
+ kvDeleteMock.mockResolvedValue(true);
+
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'tokens_revoked', tokens: { bot: ['B123'] } },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ releasedTeamId: 'T123',
+ releasedConnectedAccountIds: [],
+ });
+ });
+
+ it('should skip a tokens_revoked event that spares the bot token', async () => {
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'tokens_revoked', tokens: { oauth: ['U123'] } },
+ });
+
+ expect(result).toEqual({ ok: true, skipped: 'No bot token was revoked' });
+ expect(listConnectionsMock).not.toHaveBeenCalled();
+ expect(kvDeleteMock).not.toHaveBeenCalled();
+ });
+
+ it('should skip a tokens_revoked event with no token list at all', async () => {
+ const result = await slackInstallRevokedHandler({
+ type: 'event_callback',
+ team_id: 'T123',
+ event: { type: 'tokens_revoked' },
+ });
+
+ expect(result).toEqual({ ok: true, skipped: 'No bot token was revoked' });
+ expect(kvDeleteMock).not.toHaveBeenCalled();
+ });
+
+ it('should throw when the event carries no team_id', async () => {
+ await expect(
+ slackInstallRevokedHandler({
+ type: 'event_callback',
+ event: { type: 'app_uninstalled' },
+ }),
+ ).rejects.toThrow('no team_id');
+ expect(kvDeleteMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-install-revoked-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-install-revoked-handler.ts
new file mode 100644
index 00000000000..a4a97dcc4ae
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-install-revoked-handler.ts
@@ -0,0 +1,23 @@
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+
+import { type SlackEventsRequestBody } from 'src/logic-functions/types/slack-events-request-body.type';
+import { releaseSlackTeamOnInstallRevoked } from 'src/logic-functions/utils/release-slack-team-on-install-revoked';
+
+export const slackInstallRevokedHandler = async (
+ body: SlackEventsRequestBody,
+) => {
+ if (
+ body.event?.type === 'tokens_revoked' &&
+ !isNonEmptyArray(body.event.tokens?.bot)
+ ) {
+ return { ok: true, skipped: 'No bot token was revoked' };
+ }
+
+ if (!isNonEmptyString(body.team_id)) {
+ throw new Error(
+ 'Slack install revocation event has no team_id; cannot release the team claim',
+ );
+ }
+
+ return releaseSlackTeamOnInstallRevoked({ teamId: body.team_id });
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/slack-events-resolver.ts b/packages/twenty-apps/public/slack/src/logic-functions/slack-events-resolver.ts
index a32b78a842e..8c251309cb9 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/slack-events-resolver.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/slack-events-resolver.ts
@@ -1,14 +1,17 @@
import { isNonEmptyString } from '@sniptt/guards';
import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
import { Response } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
import {
SLACK_CHANNEL_WELCOME_UNIVERSAL_IDENTIFIER,
SLACK_EVENTS_ENQUEUE_UNIVERSAL_IDENTIFIER,
SLACK_EVENTS_ROUTE_UNIVERSAL_IDENTIFIER,
SLACK_HOME_OPENED_UNIVERSAL_IDENTIFIER,
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { type SlackEventsRequestBody } from 'src/logic-functions/types/slack-events-request-body.type';
+import { findClaimedWorkspaceId } from 'src/logic-functions/utils/find-claimed-workspace-id';
import { getSlackWebhookSecret } from 'src/logic-functions/utils/get-slack-webhook-secret';
import { resolveTargetWorkspaceId } from 'src/logic-functions/utils/resolve-target-workspace-id';
import { verifySlackRequestSignature } from 'src/logic-functions/utils/verify-slack-request-signature';
@@ -57,10 +60,38 @@ export const slackEventsResolverHandler = async (
return new Response({ challenge: body.challenge });
}
+ const targetLogicFunctionUniversalIdentifier =
+ resolveTargetLogicFunctionUniversalIdentifier(body);
+
+ if (
+ targetLogicFunctionUniversalIdentifier ===
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER
+ ) {
+ if (!isNonEmptyString(body.team_id)) {
+ throw new Error(
+ 'Slack event has no team_id; cannot resolve the target workspace',
+ );
+ }
+
+ const claimedWorkspaceId = await findClaimedWorkspaceId(body.team_id);
+
+ if (!isDefined(claimedWorkspaceId)) {
+ return new Response({
+ ok: true,
+ skipped: 'No workspace claims this Slack team',
+ });
+ }
+
+ return {
+ workspaceId: claimedWorkspaceId,
+ targetLogicFunctionUniversalIdentifier,
+ payload: body,
+ };
+ }
+
return {
workspaceId: await resolveTargetWorkspaceId(body),
- targetLogicFunctionUniversalIdentifier:
- resolveTargetLogicFunctionUniversalIdentifier(body),
+ targetLogicFunctionUniversalIdentifier,
payload: body,
};
};
@@ -73,6 +104,9 @@ const resolveTargetLogicFunctionUniversalIdentifier = (
return SLACK_CHANNEL_WELCOME_UNIVERSAL_IDENTIFIER;
case 'app_home_opened':
return SLACK_HOME_OPENED_UNIVERSAL_IDENTIFIER;
+ case 'app_uninstalled':
+ case 'tokens_revoked':
+ return SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER;
default:
return SLACK_EVENTS_ENQUEUE_UNIVERSAL_IDENTIFIER;
}
@@ -82,7 +116,7 @@ export default defineLogicFunction({
universalIdentifier: SLACK_EVENTS_ROUTE_UNIVERSAL_IDENTIFIER,
name: 'slack-events-resolver',
description:
- 'Receives Slack Events API callbacks, verifies the request signature in the owner workspace, answers the url_verification handshake, and resolves the target workspace plus the function that handles the event (assistant enqueue, the channel welcome on member_joined_channel, or the suggested prompts on app_home_opened).',
+ 'Receives Slack Events API callbacks, verifies the request signature in the owner workspace, answers the url_verification handshake, and resolves the target workspace plus the function that handles the event (assistant enqueue, the channel welcome on member_joined_channel, the suggested prompts on app_home_opened, or the team release on app_uninstalled and tokens_revoked).',
timeoutSeconds: 15,
handler: slackEventsResolverHandler,
serverRouteTriggerSettings: {
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/slack-install-revoked.ts b/packages/twenty-apps/public/slack/src/logic-functions/slack-install-revoked.ts
new file mode 100644
index 00000000000..d7873778730
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/slack-install-revoked.ts
@@ -0,0 +1,14 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { slackInstallRevokedHandler } from 'src/logic-functions/handlers/slack-install-revoked-handler';
+
+export default defineLogicFunction({
+ universalIdentifier:
+ SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'slack-install-revoked',
+ description:
+ 'Runs in the resolved workspace when Slack reports the app was uninstalled from its workspace (app_uninstalled) or its bot token was revoked (tokens_revoked). Releases the server-scoped slack-team claim and the per-connection team entries so the Slack team can be connected again. Covers Slack-side removals, which skip the onDisconnect hook entirely, and also fires on Twenty-side disconnects because the server revokes the token at Slack before dispatching that hook; both paths release the same keys idempotently.',
+ timeoutSeconds: 30,
+ handler: slackInstallRevokedHandler,
+});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-events-request-body.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-events-request-body.type.ts
index 647b6c7b0ca..1f457502dd7 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-events-request-body.type.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-events-request-body.type.ts
@@ -3,6 +3,11 @@ type SlackEventAuthorization = {
is_bot?: boolean;
};
+type SlackRevokedTokens = {
+ oauth?: string[];
+ bot?: string[];
+};
+
type SlackInboundEvent = {
type?: string;
subtype?: string;
@@ -14,6 +19,7 @@ type SlackInboundEvent = {
thread_ts?: string;
channel?: string;
tab?: string;
+ tokens?: SlackRevokedTokens;
};
export type SlackEventsRequestBody = {
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/find-claimed-workspace-id.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/find-claimed-workspace-id.ts
new file mode 100644
index 00000000000..b75985ae632
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/find-claimed-workspace-id.ts
@@ -0,0 +1,14 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { kv } from 'twenty-sdk/logic-function';
+
+import { getSlackTeamKvKey } from 'src/logic-functions/utils/get-slack-team-kv-key';
+
+export const findClaimedWorkspaceId = async (
+ teamId: string,
+): Promise<string | null> => {
+ const claimedWorkspaceId = await kv.get<string>(getSlackTeamKvKey(teamId), {
+ scope: 'SERVER',
+ });
+
+ return isNonEmptyString(claimedWorkspaceId) ? claimedWorkspaceId : null;
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/release-slack-team-on-install-revoked.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/release-slack-team-on-install-revoked.ts
new file mode 100644
index 00000000000..1508aad1dc6
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/release-slack-team-on-install-revoked.ts
@@ -0,0 +1,48 @@
+import { kv, listConnections } from 'twenty-sdk/logic-function';
+
+import { getSlackConnectedAccountTeam } from 'src/logic-functions/utils/get-slack-connected-account-team';
+import { getSlackConnectedAccountTeamKvKey } from 'src/logic-functions/utils/get-slack-connected-account-team-kv-key';
+import { getSlackTeamKvKey } from 'src/logic-functions/utils/get-slack-team-kv-key';
+
+type ReleaseSlackTeamOnInstallRevokedArgs = {
+ teamId: string;
+};
+
+type ReleaseSlackTeamOnInstallRevokedResult = {
+ ok: true;
+ releasedTeamId: string | null;
+ releasedConnectedAccountIds: string[];
+};
+
+export const releaseSlackTeamOnInstallRevoked = async ({
+ teamId,
+}: ReleaseSlackTeamOnInstallRevokedArgs): Promise<ReleaseSlackTeamOnInstallRevokedResult> => {
+ const hasReleasedTeam = await kv.delete(getSlackTeamKvKey(teamId), {
+ scope: 'SERVER',
+ });
+
+ const connections = await listConnections({ providerName: 'slack' });
+
+ const connectedAccountTeams = await Promise.all(
+ connections.map(async (connection) => ({
+ connectedAccountId: connection.id,
+ teamId: await getSlackConnectedAccountTeam(connection.id),
+ })),
+ );
+
+ const releasedConnectedAccountIds = connectedAccountTeams
+ .filter((connectedAccountTeam) => connectedAccountTeam.teamId === teamId)
+ .map((connectedAccountTeam) => connectedAccountTeam.connectedAccountId);
+
+ await Promise.all(
+ releasedConnectedAccountIds.map((connectedAccountId) =>
+ kv.delete(getSlackConnectedAccountTeamKvKey(connectedAccountId)),
+ ),
+ );
+
+ return {
+ ok: true,
+ releasedTeamId: hasReleasedTeam ? teamId : null,
+ releasedConnectedAccountIds,
+ };
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-target-workspace-id.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-target-workspace-id.ts
index e94e7cf6073..b31cbe110ae 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-target-workspace-id.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-target-workspace-id.ts
@@ -1,8 +1,8 @@
import { isNonEmptyString } from '@sniptt/guards';
-import { kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
import { type SlackEventsRequestBody } from 'src/logic-functions/types/slack-events-request-body.type';
-import { getSlackTeamKvKey } from 'src/logic-functions/utils/get-slack-team-kv-key';
+import { findClaimedWorkspaceId } from 'src/logic-functions/utils/find-claimed-workspace-id';
export const resolveTargetWorkspaceId = async (
body: SlackEventsRequestBody,
@@ -15,11 +15,9 @@ export const resolveTargetWorkspaceId = async (
);
}
- const claimedWorkspaceId = await kv.get<string>(getSlackTeamKvKey(teamId), {
- scope: 'SERVER',
- });
+ const claimedWorkspaceId = await findClaimedWorkspaceId(teamId);
- if (!isNonEmptyString(claimedWorkspaceId)) {
+ if (!isDefined(claimedWorkspaceId)) {
throw new Error(
`No workspace has claimed Slack team ${teamId}. Connect the Slack app in the target workspace first.`,
);