Skip to content

Commit ab14cc9

Browse files
feat(slack): native Sim app trigger mode behind the preview-gated slack_v2 block
Restore the native Sim Slack app mode for the slack_oauth trigger using a single-credential-picker design. The trigger is only reachable through the preview-gated slack_v2 block, so the mode inherits that gate — no separate env flag. - Re-add SIM_SUBSCRIBED_EVENTS / SLACK_SIM_EVENT_OPTIONS derived exports. - Merge the trigger credential picker (credentialKind: 'any') so it lists Sim OAuth accounts and reusable custom bots together, mirroring the slack_v2 block. - Event dropdown narrows to the Sim app's subscribed events when an OAuth account is selected, all events for a custom bot (resolved client-side from the warmed credential list). - Deploy branch discriminates by the RESOLVED credential, not a UI field: a bot credential routes by credential id (custom app); otherwise validate the event against SIM_SUBSCRIBED_EVENTS, resolve the credential owner's token, derive routingKey from Slack team_id (auth.test), and route on the shared Sim app. - The ingest endpoint and team_id fan-out routing already existed on staging. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018asmKsWQ5Vi7T7wD9uHofz
1 parent efe1de3 commit ab14cc9

4 files changed

Lines changed: 313 additions & 48 deletions

File tree

apps/sim/lib/webhooks/deploy.test.ts

Lines changed: 139 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/**
22
* @vitest-environment node
33
*/
4-
import { credential } from '@sim/db/schema'
5-
import { resetDbChainMock } from '@sim/testing'
4+
import { account, credential } from '@sim/db/schema'
5+
import { queueTableRows, resetDbChainMock } from '@sim/testing'
66
import { eq } from 'drizzle-orm'
7-
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
7+
import { afterAll, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
88
import type { SubBlockConfig } from '@/blocks/types'
99
import type { BlockState } from '@/stores/workflows/workflow/types'
1010

@@ -25,7 +25,33 @@ vi.mock('@/lib/webhooks/pending-verification', () => ({
2525
PendingWebhookVerificationTracker: vi.fn(),
2626
}))
2727

28-
import { buildProviderConfig, resolveTriggerCredentialId } from '@/lib/webhooks/deploy'
28+
const {
29+
mockGetSlackBotCredential,
30+
mockResolveOAuthAccountId,
31+
mockRefreshAccessTokenIfNeeded,
32+
mockFetchSlackTeamId,
33+
} = vi.hoisted(() => ({
34+
mockGetSlackBotCredential: vi.fn(),
35+
mockResolveOAuthAccountId: vi.fn(),
36+
mockRefreshAccessTokenIfNeeded: vi.fn(),
37+
mockFetchSlackTeamId: vi.fn(),
38+
}))
39+
vi.mock('@/app/api/auth/oauth/utils', () => ({
40+
getSlackBotCredential: mockGetSlackBotCredential,
41+
resolveOAuthAccountId: mockResolveOAuthAccountId,
42+
refreshAccessTokenIfNeeded: mockRefreshAccessTokenIfNeeded,
43+
}))
44+
vi.mock('@/lib/webhooks/providers/slack', () => ({
45+
fetchSlackTeamId: mockFetchSlackTeamId,
46+
}))
47+
48+
import {
49+
buildProviderConfig,
50+
resolveTriggerCredentialId,
51+
resolveWebhookConfigForBlock,
52+
} from '@/lib/webhooks/deploy'
53+
import { getBlock } from '@/blocks'
54+
import { getTrigger } from '@/triggers'
2955

3056
afterAll(resetDbChainMock)
3157

@@ -191,3 +217,112 @@ describe('resolveTriggerCredentialId', () => {
191217
expect(eq).toHaveBeenCalledWith(credential.accountId, 'credential-1')
192218
})
193219
})
220+
221+
describe('resolveWebhookConfigForBlock — slack_oauth routing', () => {
222+
const slackTriggerDef = {
223+
provider: 'slack_app',
224+
name: 'Slack',
225+
subBlocks: [
226+
{ id: 'eventType', mode: 'trigger', required: true },
227+
{
228+
id: 'customBotCredential',
229+
mode: 'trigger',
230+
canonicalParamId: 'botCredential',
231+
serviceId: 'slack',
232+
required: true,
233+
},
234+
{
235+
id: 'manualBotCredential',
236+
mode: 'trigger-advanced',
237+
canonicalParamId: 'botCredential',
238+
required: true,
239+
},
240+
],
241+
}
242+
243+
function resolveSlack(
244+
values: Record<string, unknown>,
245+
workflow: Record<string, unknown> = { workspaceId: 'ws-1' }
246+
) {
247+
;(getBlock as unknown as Mock).mockReturnValue({ category: 'triggers' })
248+
;(getTrigger as unknown as Mock).mockReturnValue(slackTriggerDef)
249+
return resolveWebhookConfigForBlock({
250+
block: makeBlock('slack_oauth', values),
251+
workflow,
252+
userId: 'deployer-1',
253+
requestId: 'req-1',
254+
})
255+
}
256+
257+
it('routes a custom bot credential by credential id on the slack provider', async () => {
258+
mockGetSlackBotCredential.mockResolvedValue({ workspaceId: 'ws-1', botUserId: 'BUSER' })
259+
260+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_bot_1' })
261+
262+
expect(result?.success).toBe(true)
263+
if (!result?.success) throw new Error('expected success')
264+
expect(result.config.provider).toBe('slack')
265+
expect(result.config.routingKey).toBe('cred_bot_1')
266+
expect(result.config.triggerPath).toBeNull()
267+
expect(result.config.providerConfig.bot_user_id).toBe('BUSER')
268+
})
269+
270+
it('rejects a custom bot credential from another workspace', async () => {
271+
mockGetSlackBotCredential.mockResolvedValue({ workspaceId: 'other-ws', botUserId: 'BUSER' })
272+
273+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_bot_1' })
274+
275+
expect(result?.success).toBe(false)
276+
if (result?.success) throw new Error('expected failure')
277+
expect(result?.error?.status).toBe(400)
278+
expect(result?.error?.message).toContain('not available in this workspace')
279+
})
280+
281+
it('rejects a non-simSubscribed event on the native Sim app (OAuth account)', async () => {
282+
mockGetSlackBotCredential.mockResolvedValue(null)
283+
284+
const result = await resolveSlack({
285+
eventType: 'file_shared',
286+
customBotCredential: 'cred_oauth_1',
287+
})
288+
289+
expect(result?.success).toBe(false)
290+
if (result?.success) throw new Error('expected failure')
291+
expect(result?.error?.status).toBe(400)
292+
expect(result?.error?.message).toContain('not available on the Sim Slack app')
293+
expect(mockRefreshAccessTokenIfNeeded).not.toHaveBeenCalled()
294+
})
295+
296+
it('routes an OAuth account by team_id on the slack_app provider', async () => {
297+
mockGetSlackBotCredential.mockResolvedValue(null)
298+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: 'acct-1' })
299+
queueTableRows(account, [{ userId: 'owner-1' }])
300+
mockRefreshAccessTokenIfNeeded.mockResolvedValue('xoxb-token')
301+
mockFetchSlackTeamId.mockResolvedValue({ teamId: 'T123', userId: 'UBOT' })
302+
303+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_oauth_1' })
304+
305+
expect(result?.success).toBe(true)
306+
if (!result?.success) throw new Error('expected success')
307+
expect(result.config.provider).toBe('slack_app')
308+
expect(result.config.routingKey).toBe('T123')
309+
expect(result.config.triggerPath).toBeNull()
310+
expect(result.config.providerConfig.bot_user_id).toBe('UBOT')
311+
// Owner's token, not the deploying actor's.
312+
expect(mockRefreshAccessTokenIfNeeded).toHaveBeenCalledWith('cred_oauth_1', 'owner-1', 'req-1')
313+
})
314+
315+
it('fails when the connected Slack account token cannot be resolved', async () => {
316+
mockGetSlackBotCredential.mockResolvedValue(null)
317+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: '' })
318+
mockRefreshAccessTokenIfNeeded.mockResolvedValue(null)
319+
320+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_oauth_1' })
321+
322+
expect(result?.success).toBe(false)
323+
if (result?.success) throw new Error('expected failure')
324+
expect(result?.error?.status).toBe(400)
325+
expect(result?.error?.message).toContain('Could not access the connected Slack account')
326+
expect(mockFetchSlackTeamId).not.toHaveBeenCalled()
327+
})
328+
})

apps/sim/lib/webhooks/deploy.ts

Lines changed: 100 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { db } from '@sim/db'
2-
import { credential, webhook, workflowDeploymentVersion } from '@sim/db/schema'
2+
import { account, credential, webhook, workflowDeploymentVersion } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { getErrorMessage } from '@sim/utils/errors'
55
import { generateShortId } from '@sim/utils/id'
@@ -15,6 +15,7 @@ import {
1515
projectDesiredWebhookProviderConfig,
1616
} from '@/lib/webhooks/provider-subscriptions'
1717
import { getProviderHandler } from '@/lib/webhooks/providers'
18+
import { fetchSlackTeamId } from '@/lib/webhooks/providers/slack'
1819
import {
1920
prepareStableWebhookRegistrations,
2021
type StableDesiredWebhookRegistration,
@@ -26,12 +27,17 @@ import {
2627
isCanonicalPair,
2728
resolveActiveCanonicalValue,
2829
} from '@/lib/workflows/subblocks/visibility'
29-
import { getSlackBotCredential } from '@/app/api/auth/oauth/utils'
30+
import {
31+
getSlackBotCredential,
32+
refreshAccessTokenIfNeeded,
33+
resolveOAuthAccountId,
34+
} from '@/app/api/auth/oauth/utils'
3035
import { getBlock } from '@/blocks'
3136
import type { SubBlockConfig } from '@/blocks/types'
3237
import type { BlockState } from '@/stores/workflows/workflow/types'
3338
import { getTrigger, isTriggerValid } from '@/triggers'
3439
import { SYSTEM_SUBBLOCK_IDS } from '@/triggers/constants'
40+
import { SIM_SUBSCRIBED_EVENTS } from '@/triggers/slack/shared'
3541

3642
const logger = createLogger('DeployWebhookSync')
3743

@@ -355,7 +361,12 @@ export async function resolveTriggerCredentialId(
355361
return resolvedCredential?.id ?? null
356362
}
357363

358-
async function resolveWebhookConfigForBlock(input: {
364+
/**
365+
* Resolves a trigger block to its persisted webhook config, including the
366+
* Slack-specific routing branch. Exported for unit testing that branch; not part
367+
* of the public deploy API.
368+
*/
369+
export async function resolveWebhookConfigForBlock(input: {
359370
block: BlockState
360371
workflow: Record<string, unknown>
361372
userId: string
@@ -425,43 +436,100 @@ async function resolveWebhookConfigForBlock(input: {
425436
let effectivePath: string | null = triggerPath
426437
let routingKey: string | null = null
427438
if (triggerId === 'slack_oauth') {
428-
// Custom-bot only: events route by the bot credential to one shared ingest
429-
// URL verified with the bot's own signing secret. The native Sim-app path
430-
// (team_id routing via the official app) is intentionally not supported yet.
431-
const botCredentialId =
439+
// One credential picker feeds two backends. The credential's resolved kind —
440+
// not a UI field — picks the branch: a Slack bot credential routes by the
441+
// credential id (custom bring-your-own app); an OAuth account routes by Slack
442+
// team_id on the native shared Sim app.
443+
const slackCredentialId =
432444
typeof providerConfig.botCredential === 'string' ? providerConfig.botCredential : undefined
433-
if (!botCredentialId) {
445+
if (!slackCredentialId) {
434446
return {
435447
success: false,
436-
error: { message: 'Select a Slack bot credential for the trigger.', status: 400 },
448+
error: { message: 'Select a Slack account or bot for the trigger.', status: 400 },
437449
}
438450
}
439-
const botCredential = await getSlackBotCredential(botCredentialId)
440-
if (!botCredential) {
441-
return {
442-
success: false,
443-
error: {
444-
message: 'The selected Slack bot credential is missing or invalid. Reconnect it.',
445-
status: 400,
446-
},
451+
const botCredential = await getSlackBotCredential(slackCredentialId)
452+
if (botCredential) {
453+
// Custom bring-your-own bot: events route by the bot credential to one
454+
// shared ingest URL verified with the bot's own signing secret.
455+
const workflowWorkspace =
456+
typeof input.workflow.workspaceId === 'string' ? input.workflow.workspaceId : undefined
457+
if (!workflowWorkspace || botCredential.workspaceId !== workflowWorkspace) {
458+
return {
459+
success: false,
460+
error: {
461+
message: 'The selected Slack bot credential is not available in this workspace.',
462+
status: 400,
463+
},
464+
}
447465
}
448-
}
449-
const workflowWorkspace =
450-
typeof input.workflow.workspaceId === 'string' ? input.workflow.workspaceId : undefined
451-
if (!workflowWorkspace || botCredential.workspaceId !== workflowWorkspace) {
452-
return {
453-
success: false,
454-
error: {
455-
message: 'The selected Slack bot credential is not available in this workspace.',
456-
status: 400,
457-
},
466+
effectiveProvider = 'slack'
467+
effectivePath = null
468+
routingKey = slackCredentialId
469+
providerConfig.credentialId = slackCredentialId
470+
if (botCredential.botUserId) providerConfig.bot_user_id = botCredential.botUserId
471+
} else {
472+
// Native Sim app: an OAuth-connected account. The app only subscribes to a
473+
// fixed event set, so reject anything outside it before deriving routing.
474+
const eventType =
475+
typeof providerConfig.eventType === 'string' ? providerConfig.eventType : null
476+
if (!eventType || !SIM_SUBSCRIBED_EVENTS.includes(eventType)) {
477+
return {
478+
success: false,
479+
error: {
480+
message:
481+
'This event is not available on the Sim Slack app. Use a custom bot or choose a supported event.',
482+
status: 400,
483+
},
484+
}
485+
}
486+
// Resolve the credential OWNER's token (not the deploying actor's) — in a
487+
// shared workspace a teammate can deploy a trigger wired to someone else's
488+
// Slack account.
489+
let tokenOwnerUserId = input.userId
490+
const resolvedAccount = await resolveOAuthAccountId(slackCredentialId)
491+
if (resolvedAccount?.accountId) {
492+
const [owner] = await db
493+
.select({ userId: account.userId })
494+
.from(account)
495+
.where(eq(account.id, resolvedAccount.accountId))
496+
.limit(1)
497+
if (owner?.userId) tokenOwnerUserId = owner.userId
498+
}
499+
const botToken = await refreshAccessTokenIfNeeded(
500+
slackCredentialId,
501+
tokenOwnerUserId,
502+
input.requestId
503+
)
504+
if (!botToken) {
505+
return {
506+
success: false,
507+
error: {
508+
message: 'Could not access the connected Slack account. Reconnect it and try again.',
509+
status: 400,
510+
},
511+
}
512+
}
513+
try {
514+
const { teamId, userId: botUserId } = await fetchSlackTeamId(botToken)
515+
routingKey = teamId
516+
if (botUserId) providerConfig.bot_user_id = botUserId
517+
} catch (error: unknown) {
518+
logger.error(
519+
`[${input.requestId}] Slack team_id resolution failed for ${input.block.id}`,
520+
error
521+
)
522+
return {
523+
success: false,
524+
error: {
525+
message: 'Could not verify the connected Slack workspace. Reconnect it and try again.',
526+
status: 400,
527+
},
528+
}
458529
}
530+
effectiveProvider = 'slack_app'
531+
effectivePath = null
459532
}
460-
effectiveProvider = 'slack'
461-
effectivePath = null
462-
routingKey = botCredentialId
463-
providerConfig.credentialId = botCredentialId
464-
if (botCredential.botUserId) providerConfig.bot_user_id = botCredential.botUserId
465533
}
466534

467535
return {

0 commit comments

Comments
 (0)