diff --git a/api/server/routes/slack-workspaces.js b/api/server/routes/slack-workspaces.js index a6eec179cf..7ec71d583e 100644 --- a/api/server/routes/slack-workspaces.js +++ b/api/server/routes/slack-workspaces.js @@ -32,4 +32,5 @@ router.post( handlers.connect, ); router.delete('/workspaces/:workspaceId', requireJwtAuth, requireSameOrigin, handlers.disconnect); +router.post('/workspaces/:workspaceId/remove', requireJwtAuth, requireSameOrigin, handlers.remove); module.exports = router; diff --git a/client/src/components/Channels/Workspaces.spec.tsx b/client/src/components/Channels/Workspaces.spec.tsx index 7b7d157c8e..fa4c4f6530 100644 --- a/client/src/components/Channels/Workspaces.spec.tsx +++ b/client/src/components/Channels/Workspaces.spec.tsx @@ -16,6 +16,7 @@ jest.mock('librechat-data-provider', () => { getSlackApps: jest.fn(), connectSlackWorkspace: jest.fn(), disconnectSlackWorkspace: jest.fn(), + removeSlackWorkspace: jest.fn(), cancelSlackWorkspaceInstall: jest.fn(), }, }; @@ -77,6 +78,9 @@ beforeEach(() => { expiresInSeconds: 600, }); cancel = jest.spyOn(dataService, 'cancelSlackWorkspaceInstall').mockResolvedValue(undefined); + jest.spyOn(dataService, 'removeSlackWorkspace').mockImplementation(async () => { + response = { ...response, workspaces: [] }; + }); popup.closed = false; popup.location.href = ''; popup.close.mockClear(); @@ -127,10 +131,13 @@ test('disconnect requires confirmation and refreshes the org workspace state', a const user = userEvent.setup(); page(); await screen.findByText('Engineering'); + expect( + screen.queryByRole('button', { name: 'com_ui_slack_workspaces_remove' }), + ).not.toBeInTheDocument(); const appReads = jest.mocked(dataService.getSlackApps).mock.calls.length; await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' })); expect(disconnect).not.toHaveBeenCalled(); - const confirmation = screen.getByRole('group', { name: 'com_ui_slack_workspaces_confirm' }); + const confirmation = screen.getByRole('dialog', { name: 'com_ui_slack_workspaces_disconnect' }); await user.click( within(confirmation).getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' }), ); @@ -142,7 +149,47 @@ test('disconnect requires confirmation and refreshes the org workspace state', a expect( screen.queryByRole('button', { name: 'com_ui_slack_workspaces_reconnect' }), ).not.toBeInTheDocument(); - expect(screen.queryByRole('group')).not.toBeInTheDocument(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); +}); + +test('only admins can confirm removal of a disconnected workspace', async () => { + const user = userEvent.setup(); + response.workspaces = [{ ...workspace, status: 'disconnected' }]; + const { client } = page(); + await user.click(await screen.findByRole('button', { name: 'com_ui_slack_workspaces_remove' })); + expect(dataService.removeSlackWorkspace).not.toHaveBeenCalled(); + expect( + screen.getByRole('dialog', { name: 'com_ui_slack_workspaces_remove' }), + ).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'com_ui_slack_workspaces_remove' })).toHaveLength(1); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(screen.getByRole('button', { name: 'com_ui_slack_workspaces_remove' })).toHaveFocus(); + await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_remove' })); + await user.click( + within(screen.getByRole('dialog')).getByRole('button', { + name: 'com_ui_slack_workspaces_remove', + }), + ); + await waitFor(() => + expect(dataService.removeSlackWorkspace).toHaveBeenCalledWith('workspace-1', 'revision-1'), + ); + await waitFor(() => expect(screen.queryByText('Engineering')).not.toBeInTheDocument()); + await waitFor(() => + expect(screen.getByRole('heading', { name: 'com_ui_slack_workspaces_title' })).toHaveFocus(), + ); + response = { + ...response, + canManage: false, + workspaces: [{ ...workspace, status: 'disconnected' }], + }; + await act(async () => { + await client.invalidateQueries([QueryKeys.slackWorkspaces]); + }); + await screen.findByText('Engineering'); + expect( + screen.queryByRole('button', { name: 'com_ui_slack_workspaces_remove' }), + ).not.toBeInTheDocument(); }); test('keeps the confirmed revision when workspace metadata changes before disconnect', async () => { @@ -157,15 +204,15 @@ test('keeps the confirmed revision when workspace metadata changes before discon }); disconnect.mockRejectedValueOnce(new Error('Workspace changed')); await user.click( - within(screen.getByRole('group')).getByRole('button', { + within(screen.getByRole('dialog')).getByRole('button', { name: 'com_ui_slack_workspaces_disconnect', }), ); await waitFor(() => expect(disconnect).toHaveBeenLastCalledWith('workspace-1', 'revision-1')); - await waitFor(() => expect(screen.queryByRole('group')).not.toBeInTheDocument()); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' })); await user.click( - within(screen.getByRole('group')).getByRole('button', { + within(screen.getByRole('dialog')).getByRole('button', { name: 'com_ui_slack_workspaces_disconnect', }), ); diff --git a/client/src/components/Channels/Workspaces.tsx b/client/src/components/Channels/Workspaces.tsx index f51084b139..eb4a76ea23 100644 --- a/client/src/components/Channels/Workspaces.tsx +++ b/client/src/components/Channels/Workspaces.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react'; -import { Button, Spinner } from '@librechat/client'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { MutationKeys, QueryKeys, dataService } from 'librechat-data-provider'; +import { Button, Chip, OGDialog, OGDialogTemplate, Spinner } from '@librechat/client'; import type { SlackWorkspace } from 'librechat-data-provider'; import { watchOAuthSettlements } from '~/data-provider/PullRequest/signIn'; import { useSlackWorkspaces } from './useSlackWorkspaces'; @@ -30,6 +30,9 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { const [pending, setPending] = useState(false); const [failed, setFailed] = useState(false); const [confirm, setConfirm] = useState(null); + const actionRef = useRef(null); + const headingRef = useRef(null); + const settingsRef = useRef(null); const flow = useRef(null); const deadline = useRef>(); const mounted = useRef(true); @@ -48,13 +51,18 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { mutationFn: (input: { workspaceId?: string; appId?: string }) => dataService.connectSlackWorkspace(input.workspaceId, input.appId), }); - const disconnect = useMutation({ - mutationKey: [MutationKeys.slackWorkspaces, principalKey, 'disconnect'], + const retire = useMutation({ + mutationKey: [MutationKeys.slackWorkspaces, principalKey, 'retire'], mutationFn: (workspace: SlackWorkspace) => - dataService.disconnectSlackWorkspace(workspace.workspaceId, workspace.revision), + workspace.status === 'disconnected' + ? dataService.removeSlackWorkspace(workspace.workspaceId, workspace.revision) + : dataService.disconnectSlackWorkspace(workspace.workspaceId, workspace.revision), onSettled: async () => { - setConfirm(null); - await refresh(); + try { + await refresh(); + } finally { + setConfirm(null); + } }, }); const cancel = useMutation({ @@ -142,21 +150,30 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { const first = status.data?.pages[0]; const workspaces = status.data?.pages.flatMap((page) => page.workspaces) ?? []; + const activeTone = first?.configured ? 'success' : 'warning'; if (first && !first.configured && workspaces.length === 0) return null; - const busy = pending || connect.isLoading || disconnect.isLoading || cancel.isLoading; + const confirmLabel = + confirm?.status === 'disconnected' + ? 'com_ui_slack_workspaces_remove_confirm' + : 'com_ui_slack_workspaces_confirm'; + const confirmAction = + confirm?.status === 'disconnected' + ? 'com_ui_slack_workspaces_remove' + : 'com_ui_slack_workspaces_disconnect'; + const busy = pending || connect.isLoading || retire.isLoading || cancel.isLoading; return (
-

+

{localize('com_ui_slack_workspaces_title')}

{localize('com_ui_slack_workspaces_description')}

{status.isLoading && } - {(status.isError || failed || disconnect.isError || cancel.isError) && ( + {(status.isError || failed || retire.isError || cancel.isError) && (

{localize( channelErrorLabel( - connect.error ?? disconnect.error ?? cancel.error ?? status.error, + connect.error ?? retire.error ?? cancel.error ?? status.error, 'com_ui_slack_workspaces_error', ), )} @@ -166,7 +183,7 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { onClick={() => { setFailed(false); connect.reset(); - disconnect.reset(); + retire.reset(); cancel.reset(); void status.refetch(); }} @@ -203,8 +220,15 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { key={workspace.workspaceId} className="border-border-light space-y-2 rounded-lg border p-3" > -

{workspace.teamName}

-

{localize(workspaceStatusLabel(workspace, first?.configured))}

+
+

{workspace.teamName}

+ + {localize(workspaceStatusLabel(workspace, first?.configured))} + +
{first?.canManage && (
{first.configured && workspace.status === 'active' && ( @@ -216,32 +240,21 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { {localize('com_ui_slack_workspaces_reconnect')} )} - {workspace.status === 'active' && ( - - )} -
- )} - {confirm?.workspaceId === workspace.workspaceId && ( -
-

{localize('com_ui_slack_workspaces_confirm')}

-
- - -
+
)}
@@ -255,6 +268,41 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) { {localize('com_ui_slack_workspaces_more')} )} + { + if (!open && !retire.isLoading) setConfirm(null); + }} + > + {localize(confirmLabel)}

} + cancelDisabled={retire.isLoading} + onCloseAutoFocus={(event) => { + event.preventDefault(); + if (actionRef.current?.isConnected) actionRef.current.focus(); + else if (headingRef.current?.isConnected) headingRef.current.focus(); + else settingsRef.current?.focus(); + }} + selection={ + + } + /> +
); } diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index e9504a17b2..3517152847 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -10,6 +10,8 @@ "com_ui_slack_workspaces_empty": "No Slack workspaces are connected.", "com_ui_slack_workspaces_admin": "An organization administrator with agent management permission can connect and disconnect workspaces.", "com_ui_slack_workspaces_waiting": "Finish connecting in the Slack window. Your workspace list will update when you return.", + "com_ui_slack_workspaces_remove": "Remove workspace", + "com_ui_slack_workspaces_remove_confirm": "Remove this disconnected workspace from your organization’s list? Connecting again requires a fresh installation. This does not uninstall the app from Slack.", "com_ui_slack_workspaces_confirm": "Disconnect this workspace for your organization? New Slack requests will stop. The Slack app will remain installed, and completed actions cannot be undone.", "com_ui_slack_workspaces_more": "Show more workspaces", "com_ui_slack_workspaces_error": "Could not update Slack workspaces. Check the workspace list and try again. Allow pop-ups when connecting a workspace.", @@ -3962,7 +3964,7 @@ "com_ui_slack_apps_signing_secret": "Signing secret", "com_ui_slack_apps_update": "Replace credentials", "com_ui_slack_apps_remove": "Remove app", - "com_ui_slack_apps_confirm_remove": "Remove this app’s saved credentials? Disconnect its workspaces first. This does not delete the app from Slack.", + "com_ui_slack_apps_confirm_remove": "Remove this app’s saved credentials and disconnected workspaces from the list? Disconnect its active workspaces first. This does not delete the app from Slack.", "com_ui_slack_apps_error": "Could not save or remove the Slack app. Refresh and try again. Disconnect active workspaces before removing an app.", "com_ui_slack_apps_saved": "Slack app saved. Finish its settings in Slack, then install a workspace.", "com_ui_slack_apps_callbacks": "Configure these URLs in your Slack app", diff --git a/e2e/specs/mock/scenarios/slack-workspaces.spec.ts b/e2e/specs/mock/scenarios/slack-workspaces.spec.ts index c89179c6fe..4c85ec0f16 100644 --- a/e2e/specs/mock/scenarios/slack-workspaces.spec.ts +++ b/e2e/specs/mock/scenarios/slack-workspaces.spec.ts @@ -60,6 +60,13 @@ for (const theme of ['light', 'dark']) { }); return; } + if (url.pathname.endsWith('/workspace-browser/remove')) { + expect(route.request().method()).toBe('POST'); + expect(route.request().postDataJSON()).toEqual({ revision: 'installed' }); + workspaces = []; + await route.fulfill({ status: 204 }); + return; + } if (url.pathname.endsWith('/connect')) { expect(route.request().postDataJSON()).toMatchObject({ appId: 'A123' }); attempt++; @@ -147,8 +154,8 @@ for (const theme of ['light', 'dark']) { .getByRole('button', { name: 'Disconnect workspace', exact: true }) .click(); expect(disconnected).toBe(0); - await workspacesPanel - .getByRole('group') + await page + .getByRole('dialog', { name: 'Disconnect workspace', exact: true }) .getByRole('button', { name: 'Disconnect workspace', exact: true, @@ -156,6 +163,32 @@ for (const theme of ['light', 'dark']) { .click(); await expect(workspacesPanel.getByText('Disconnected', { exact: true })).toBeVisible(); expect(disconnected).toBe(1); + await workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }).click(); + const removal = page.getByRole('dialog', { name: 'Remove workspace', exact: true }); + await expect(removal.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(removal).not.toBeVisible(); + await expect( + workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }), + ).toBeFocused(); + await workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }).click(); + await expect(removal).toContainText('This does not uninstall the app from Slack.'); + await expect( + removal.getByRole('button', { name: 'Remove workspace', exact: true }), + ).toHaveCount(1); + if (process.env.E2E_SLACK_WORKSPACES_VISUAL_PREFIX) { + await removal.scrollIntoViewIfNeeded(); + await page.screenshot({ + animations: 'disabled', + path: `${process.env.E2E_SLACK_WORKSPACES_VISUAL_PREFIX}-remove-${theme}.png`, + }); + } + await removal.getByRole('button', { name: 'Remove workspace', exact: true }).click(); + await expect(workspacesPanel.getByText('Example engineering')).toHaveCount(0); + await expect(workspacesPanel.getByText('No Slack workspaces are connected.')).toBeVisible(); + await expect( + workspacesPanel.getByRole('heading', { name: 'Organization Slack workspaces', exact: true }), + ).toBeFocused(); await page.keyboard.press('Escape'); await expect(page.locator('#prompt-textarea')).toBeVisible(); }); diff --git a/packages/api/src/channels/workspaceHttp.ts b/packages/api/src/channels/workspaceHttp.ts index 451a1d401f..dc86800644 100644 --- a/packages/api/src/channels/workspaceHttp.ts +++ b/packages/api/src/channels/workspaceHttp.ts @@ -43,6 +43,7 @@ export interface SlackWorkspaceHandlers { get: RequestHandler; connect: RequestHandler; disconnect: RequestHandler; + remove: RequestHandler; cancel: RequestHandler; callback: RequestHandler; } @@ -89,6 +90,19 @@ export function createSlackWorkspaceHandlers(deps: { } }; + const workspaceAction = (action: 'disconnect' | 'remove') => + browser(async (req, res, principal) => { + const id = identifier.safeParse(req.params.workspaceId); + const body = z.object({ revision: identifier }).strict().safeParse(req.body); + if (!id.success || !body.success) { + res.status(400).json({ ok: false, error: { code: 'workspace_changed' } }); + return; + } + const result = await deps.service[action](principal, id.data, body.data.revision); + if (!result.ok) res.status(result.error.code === 'forbidden' ? 403 : 409).json(result); + else res.sendStatus(204); + }); + return { apps: browser(async (req, res, principal) => { const page = pageQuery.safeParse(req.query); @@ -187,17 +201,8 @@ export function createSlackWorkspaceHandlers(deps: { ); res.json(result.value); }), - disconnect: browser(async (req, res, principal) => { - const id = identifier.safeParse(req.params.workspaceId); - const body = z.object({ revision: identifier }).strict().safeParse(req.body); - if (!id.success || !body.success) { - res.status(400).json({ ok: false, error: { code: 'workspace_changed' } }); - return; - } - const result = await deps.service.disconnect(principal, id.data, body.data.revision); - if (!result.ok) res.status(result.error.code === 'forbidden' ? 403 : 409).json(result); - else res.sendStatus(204); - }), + disconnect: workspaceAction('disconnect'), + remove: workspaceAction('remove'), cancel: browser(async (req, res, principal) => { if (!/^[a-f0-9]{64}$/.test(req.params.flowId)) { res.status(400).json({ ok: false, error: { code: 'invalid_install' } }); diff --git a/packages/api/src/channels/workspaces.spec.ts b/packages/api/src/channels/workspaces.spec.ts index 40d2224fa9..801d9ab5df 100644 --- a/packages/api/src/channels/workspaces.spec.ts +++ b/packages/api/src/channels/workspaces.spec.ts @@ -292,6 +292,7 @@ describe('Slack workspace installation', () => { server.post('/workspaces/apps/:appId/remove', handlers.removeApp); server.get('/workspaces/:workspaceId', handlers.get); server.delete('/workspaces/:workspaceId', handlers.disconnect); + server.post('/workspaces/:workspaceId/remove', handlers.remove); server.post('/workspaces/connect', setOAuthSession, handlers.connect); server.delete('/workspaces/attempts/:flowId', handlers.cancel); server.get('/api/channels/workspaces/oauth/callback', handlers.callback); @@ -376,6 +377,31 @@ describe('Slack workspace installation', () => { ); }); + it('requires current tenant-admin authority and a disconnected revision to remove a workspace', async () => { + const { flow } = await start(); + const installed = await scoped(() => service.finish(flow, 'code')); + if (!installed.ok) throw new Error(installed.error.code); + const { workspaceId, revision } = installed.value; + const remove = (body: object, tenant = 'org-a') => + http() + .post(`/workspaces/${workspaceId}/remove`) + .set('x-test-user', 'yes') + .set('x-test-tenant', tenant) + .set('x-test-user-tenant', tenant) + .send(body); + await remove({}).expect(400); + await remove({ revision }).expect(409); + await scoped(() => storage.disconnect(workspaceId, revision)); + const retired = await scoped(() => storage.read(workspaceId)); + await remove({ revision: retired!.revision }, 'org-b').expect(409); + canManage.mockResolvedValue(false); + await remove({ revision: retired!.revision }).expect(403); + canManage.mockResolvedValue(true); + await remove({ revision }).expect(409); + await remove({ revision: retired!.revision }).expect(204); + expect((await scoped(() => storage.list())).workspaces).toEqual([]); + }); + it('returns one saved workspace as credential-free tenant metadata', async () => { const { flow } = await start(); const installed = await scoped(() => service.finish(flow, 'test-code')); diff --git a/packages/api/src/channels/workspaces.ts b/packages/api/src/channels/workspaces.ts index 57dfbd55da..c4007d3db2 100644 --- a/packages/api/src/channels/workspaces.ts +++ b/packages/api/src/channels/workspaces.ts @@ -305,6 +305,16 @@ export function createSlackWorkspaceService(deps: { return installed.ok ? { ok: true, value: installed.workspace } : failure(installed.code); }, + async remove( + principal: SlackWorkspacePrincipal, + workspaceId: string, + expectedRevision: string, + ): Promise> { + if (!inScope(principal) || !(await deps.canManage(principal))) return failure('forbidden'); + return (await deps.storage.remove(workspaceId, expectedRevision)) + ? { ok: true, value: true } + : failure('workspace_changed'); + }, async disconnect( principal: SlackWorkspacePrincipal, workspaceId: string, diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts index 6eedaa2eca..fbd956f572 100644 --- a/packages/data-provider/src/data-service.ts +++ b/packages/data-provider/src/data-service.ts @@ -230,6 +230,10 @@ export function disconnectSlackWorkspace(workspaceId: string, revision: string): return request.deleteWithOptions(endpoints.slackWorkspaces(workspaceId), { data: { revision } }); } +export function removeSlackWorkspace(workspaceId: string, revision: string): Promise { + return request.post(`${endpoints.slackWorkspaces(workspaceId)}/remove`, { revision }); +} + export function cancelSlackWorkspaceInstall(flowId: string): Promise { return request.delete(`${endpoints.slackWorkspaces()}/attempts/${encodeURIComponent(flowId)}`); } diff --git a/packages/data-schemas/src/methods/slackWorkspace.spec.ts b/packages/data-schemas/src/methods/slackWorkspace.spec.ts index 9e840d080e..f7d8634542 100644 --- a/packages/data-schemas/src/methods/slackWorkspace.spec.ts +++ b/packages/data-schemas/src/methods/slackWorkspace.spec.ts @@ -148,9 +148,44 @@ describe('organization-owned Slack workspaces', () => { expect(await store.removeApp('A123', disconnected!.revision)).toBe('removed'); expect(await store.app('A123')).toBeNull(); expect((await store.apps()).apps).toEqual([]); + expect((await store.list()).workspaces).toEqual([]); + expect(await store.read(installed.workspace.workspaceId)).toMatchObject({ + status: 'disconnected', + removedAt: expect.any(Date), + }); }); }); + it('removes only a current disconnected workspace and preserves installation fences', async () => { + await scoped('org-a', () => start('original')); + const installed = await scoped('org-a', () => finish('original')); + if (!installed.ok) throw new Error('Test install failed'); + const { workspaceId, revision } = installed.workspace; + expect(await scoped('org-a', () => store.remove(workspaceId, revision))).toBe(false); + await scoped('org-a', () => start('delayed-before-disconnect')); + await scoped('org-a', () => store.disconnect(workspaceId, revision)); + const retired = await scoped('org-a', () => store.read(workspaceId)); + expect(retired?.encryptedBotToken).toBeUndefined(); + expect(await scoped('org-b', () => store.remove(workspaceId, retired!.revision))).toBe(false); + expect(await scoped('org-a', () => store.remove(workspaceId, revision))).toBe(false); + expect(await scoped('org-a', () => store.remove(workspaceId, retired!.revision))).toBe(true); + expect((await scoped('org-a', () => store.list())).workspaces).toEqual([]); + expect(await scoped('org-a', () => store.read(workspaceId))).toMatchObject({ + status: 'disconnected', + removedAt: expect.any(Date), + }); + expect(await scoped('org-a', () => finish('delayed-before-disconnect'))).toEqual({ + ok: false, + code: 'stale_install', + }); + await scoped('org-a', () => start('fresh-install')); + const fresh = await scoped('org-a', () => finish('fresh-install')); + if (!fresh.ok) throw new Error('Fresh install failed'); + expect(fresh.workspace.workspaceId).not.toBe(workspaceId); + expect((await scoped('org-a', () => store.list())).workspaces).toEqual([fresh.workspace]); + expect(await scoped('org-a', () => store.remove(workspaceId, retired!.revision))).toBe(false); + }); + it('allows only one concurrent update of the same organization app revision', async () => { await scoped('org-a', async () => { const current = await store.configureApp(appCredentials, userId); diff --git a/packages/data-schemas/src/methods/slackWorkspace.ts b/packages/data-schemas/src/methods/slackWorkspace.ts index 02046d5ff2..bdfe0a0f9f 100644 --- a/packages/data-schemas/src/methods/slackWorkspace.ts +++ b/packages/data-schemas/src/methods/slackWorkspace.ts @@ -72,6 +72,8 @@ export interface SlackWorkspaceStorage { read(workspaceId: string): Promise; metadata(workspaceId: string): Promise; disconnect(workspaceId: string, expectedRevision?: string): Promise; + /** Hide a retired installation while retaining its callback and ownership fences. */ + remove(workspaceId: string, expectedRevision: string): Promise; /** Trusted routing metadata, read only after authenticating the Slack request. */ route(appId: string, teamId: string): Promise; } @@ -198,7 +200,13 @@ export function createSlackWorkspaceStorage( }, { session }, ); - return changed.matchedCount ? 'removed' : 'conflict'; + if (!changed.matchedCount) return 'conflict'; + await workspaces.updateMany( + { appId, tenantId: tenantId ?? null, status: 'disconnected' }, + { $set: { removedAt: new Date(), revision: nanoid() } }, + { session }, + ); + return 'removed'; }); }, async startInstall(input) { @@ -329,7 +337,11 @@ export function createSlackWorkspaceStorage( if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new TypeError('Invalid Slack workspace page size'); const records = await workspaces - .find({ tenantId: tenantId ?? null, ...(cursor ? { workspaceId: { $gt: cursor } } : {}) }) + .find({ + tenantId: tenantId ?? null, + removedAt: { $exists: false }, + ...(cursor ? { workspaceId: { $gt: cursor } } : {}), + }) .sort({ workspaceId: 1 }) .limit(limit + 1) .read('primary') @@ -387,6 +399,19 @@ export function createSlackWorkspaceStorage( return true; }); }, + async remove(workspaceId, expectedRevision) { + const removed = await workspaces.updateOne( + { + workspaceId, + tenantId: tenant() ?? null, + revision: expectedRevision, + status: 'disconnected', + removedAt: { $exists: false }, + }, + { $set: { removedAt: new Date(), revision: nanoid() } }, + ); + return removed.matchedCount === 1; + }, async route(appId, teamId) { return runAsSystem(async () => { const record = await workspaces diff --git a/packages/data-schemas/src/models/slackWorkspace.ts b/packages/data-schemas/src/models/slackWorkspace.ts index 3d08902c9b..eeae4cc3cc 100644 --- a/packages/data-schemas/src/models/slackWorkspace.ts +++ b/packages/data-schemas/src/models/slackWorkspace.ts @@ -7,6 +7,7 @@ import { applyTenantIsolation } from './plugins/tenantIsolation'; export interface SlackWorkspaceRecord extends SlackWorkspace { encryptedBotToken?: string; installOrder: number; + removedAt?: Date; authorityWrites?: number; } @@ -54,6 +55,7 @@ export function createSlackWorkspaceModel( encryptedBotToken: { type: String, select: false }, installOrder: { type: Number, required: true }, authorityWrites: { type: Number, default: 0 }, + removedAt: Date, }, { timestamps: true }, );