chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,136 @@
/**
* @vitest-environment node
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockParseWebhookBody,
mockFindWebhooksByRoutingKey,
mockDispatchResolvedWebhookTarget,
mockGetSlackBotCredential,
mockHandleChallenge,
mockVerifySignature,
} = vi.hoisted(() => ({
mockParseWebhookBody: vi.fn(),
mockFindWebhooksByRoutingKey: vi.fn(),
mockDispatchResolvedWebhookTarget: vi.fn(),
mockGetSlackBotCredential: vi.fn(),
mockHandleChallenge: vi.fn(),
mockVerifySignature: vi.fn(),
}))
vi.mock('@/lib/core/admission/gate', () => ({
tryAdmit: () => ({ release: vi.fn() }),
admissionRejectedResponse: () => new Response(null, { status: 503 }),
}))
vi.mock('@/app/api/auth/oauth/utils', () => ({
getSlackBotCredential: mockGetSlackBotCredential,
}))
vi.mock('@/lib/webhooks/processor', () => ({
parseWebhookBody: mockParseWebhookBody,
findWebhooksByRoutingKey: mockFindWebhooksByRoutingKey,
dispatchResolvedWebhookTarget: mockDispatchResolvedWebhookTarget,
}))
vi.mock('@/lib/webhooks/providers/slack', () => ({
handleSlackChallenge: mockHandleChallenge,
verifySlackRequestSignature: mockVerifySignature,
resolveSlackEventKey: () => null,
}))
import { POST } from '@/app/api/webhooks/slack/custom/[credentialId]/route'
const CREDENTIAL_ID = 'cred-123'
function makeRequest() {
return new Request('https://sim.test/api/webhooks/slack/custom/cred-123', {
method: 'POST',
headers: { 'x-slack-request-timestamp': '1700000000' },
}) as unknown as import('next/server').NextRequest
}
const context = { params: Promise.resolve({ credentialId: CREDENTIAL_ID }) }
const messageBody = {
team_id: 'T1',
api_app_id: 'A1',
event: { type: 'message', channel_type: 'channel', channel: 'C1', ts: '1.1' },
}
function webhook(id: string) {
return { webhook: { id, blockId: `blk-${id}`, providerConfig: {} }, workflow: { id: `wf-${id}` } }
}
describe('Slack custom-bot webhook route', () => {
beforeEach(() => {
vi.clearAllMocks()
mockHandleChallenge.mockReturnValue(null)
mockVerifySignature.mockReturnValue(null)
mockParseWebhookBody.mockResolvedValue({
body: messageBody,
rawBody: JSON.stringify(messageBody),
})
mockGetSlackBotCredential.mockResolvedValue({
signingSecret: 'sec',
botToken: 'xoxb-x',
teamId: 'T1',
})
mockFindWebhooksByRoutingKey.mockResolvedValue([webhook('wh1')])
mockDispatchResolvedWebhookTarget.mockResolvedValue({
outcome: 'queued',
response: new Response(null, { status: 200 }),
reason: 'queued',
})
})
it('echoes the url_verification challenge without loading the credential', async () => {
mockHandleChallenge.mockReturnValue(new Response('ok', { status: 200 }))
await POST(makeRequest(), context)
expect(mockGetSlackBotCredential).not.toHaveBeenCalled()
expect(mockVerifySignature).not.toHaveBeenCalled()
})
it('404s an unknown credential', async () => {
mockGetSlackBotCredential.mockResolvedValue(null)
const res = await POST(makeRequest(), context)
expect(res.status).toBe(404)
expect(mockDispatchResolvedWebhookTarget).not.toHaveBeenCalled()
})
it('verifies with the credential signing secret and rejects a bad signature', async () => {
mockVerifySignature.mockReturnValue(new Response(null, { status: 401 }))
const res = await POST(makeRequest(), context)
expect(mockVerifySignature).toHaveBeenCalledWith(
'sec',
expect.anything(),
expect.any(String),
expect.any(String)
)
expect(res.status).toBe(401)
expect(mockDispatchResolvedWebhookTarget).not.toHaveBeenCalled()
})
it('fans out by credential id (provider slack) and dispatches each webhook', async () => {
const res = await POST(makeRequest(), context)
expect(mockFindWebhooksByRoutingKey).toHaveBeenCalledWith(
CREDENTIAL_ID,
expect.any(String),
'slack'
)
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(1)
expect(res.status).toBe(200)
})
it('still returns 200 when the dispatcher filters the event', async () => {
mockDispatchResolvedWebhookTarget.mockResolvedValue({
outcome: 'ignored',
response: new Response(null, { status: 200 }),
reason: 'filtered',
})
const res = await POST(makeRequest(), context)
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(1)
expect(res.status).toBe(200)
})
})
@@ -0,0 +1,88 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { admissionRejectedResponse, tryAdmit } from '@/lib/core/admission/gate'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { findWebhooksByRoutingKey, parseWebhookBody } from '@/lib/webhooks/processor'
import { handleSlackChallenge, verifySlackRequestSignature } from '@/lib/webhooks/providers/slack'
import { dispatchSlackWebhooks } from '@/lib/webhooks/slack-dispatch'
import { getSlackBotCredential } from '@/app/api/auth/oauth/utils'
const logger = createLogger('SlackCustomBotWebhookAPI')
export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'
export const maxDuration = 60
/**
* Ingest endpoint for a reusable custom Slack bot. The bot's single Event
* Subscriptions Request URL embeds its credential id, so every trigger that
* references the same bot credential shares one URL — routed here by
* `routingKey = credentialId` (mirrors the native `/api/webhooks/slack`
* `team_id` fan-out). Requests are HMAC-verified with the credential's OWN
* signing secret (not the shared env secret).
*/
export const POST = withRouteHandler(
async (request: NextRequest, context: { params: Promise<{ credentialId: string }> }) => {
const ticket = tryAdmit()
if (!ticket) {
return admissionRejectedResponse()
}
try {
return await handleSlackCustomBotWebhook(request, context)
} finally {
ticket.release()
}
}
)
async function handleSlackCustomBotWebhook(
request: NextRequest,
context: { params: Promise<{ credentialId: string }> }
): Promise<NextResponse> {
const receivedAt = Date.now()
const requestId = generateRequestId()
const { credentialId } = await context.params
const parseResult = await parseWebhookBody(request, requestId)
if (parseResult instanceof NextResponse) {
return parseResult
}
const { body, rawBody } = parseResult
// Echo Slack's url_verification challenge unconditionally — this is how Slack
// verifies the Request URL when the app is created from the manifest, before
// the bot is installed / the credential is finalized.
const challenge = handleSlackChallenge(body)
if (challenge) {
return challenge
}
const botCredential = await getSlackBotCredential(credentialId)
if (!botCredential) {
logger.warn(`[${requestId}] Unknown Slack bot credential ${credentialId}`)
return new NextResponse(null, { status: 404 })
}
const authError = verifySlackRequestSignature(
botCredential.signingSecret,
request,
rawBody,
requestId
)
if (authError) {
return authError
}
const webhooks = await findWebhooksByRoutingKey(credentialId, requestId, 'slack')
if (webhooks.length === 0) {
logger.info(
`[${requestId}] No active trigger for bot credential ${credentialId}; nothing to run`
)
return new NextResponse(null, { status: 200 })
}
await dispatchSlackWebhooks(webhooks, { body, request, requestId, receivedAt })
return new NextResponse(null, { status: 200 })
}
@@ -0,0 +1,126 @@
/**
* @vitest-environment node
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { mockParseWebhookBody, mockFindWebhooksByRoutingKey, mockDispatchResolvedWebhookTarget } =
vi.hoisted(() => ({
mockParseWebhookBody: vi.fn(),
mockFindWebhooksByRoutingKey: vi.fn(),
mockDispatchResolvedWebhookTarget: vi.fn(),
}))
vi.mock('@/lib/core/admission/gate', () => ({
tryAdmit: () => ({ release: vi.fn() }),
admissionRejectedResponse: () => new Response(null, { status: 503 }),
}))
vi.mock('@/lib/core/config/env', () => ({
env: { SLACK_SIGNING_SECRET: 'test-secret' },
}))
vi.mock('@/lib/webhooks/processor', () => ({
parseWebhookBody: mockParseWebhookBody,
findWebhooksByRoutingKey: mockFindWebhooksByRoutingKey,
dispatchResolvedWebhookTarget: mockDispatchResolvedWebhookTarget,
}))
vi.mock('@/lib/webhooks/providers/slack', () => ({
handleSlackChallenge: () => null,
verifySlackRequestSignature: () => null,
resolveSlackEventKey: () => null,
}))
import { POST } from '@/app/api/webhooks/slack/route'
function makeRequest() {
return new Request('https://sim.test/api/webhooks/slack', {
method: 'POST',
headers: { 'x-slack-request-timestamp': '1700000000' },
}) as unknown as import('next/server').NextRequest
}
function webhook(id: string) {
return { webhook: { id, blockId: `blk-${id}`, providerConfig: {} }, workflow: { id: `wf-${id}` } }
}
async function run(body: Record<string, unknown>) {
mockParseWebhookBody.mockResolvedValue({ body, rawBody: JSON.stringify(body) })
await POST(makeRequest())
}
const messageBody = {
team_id: 'T1',
api_app_id: 'A1',
event: { type: 'message', channel_type: 'channel', channel: 'C1', ts: '1.1' },
}
describe('Slack app webhook route', () => {
beforeEach(() => {
vi.clearAllMocks()
mockFindWebhooksByRoutingKey.mockResolvedValue([webhook('wh1')])
mockDispatchResolvedWebhookTarget.mockResolvedValue({
outcome: 'queued',
response: new Response(null, { status: 200 }),
reason: 'queued',
})
})
it('dispatches each webhook resolved for the event team', async () => {
await run(messageBody)
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(1)
})
it('continues cleanly when the dispatcher filters the event', async () => {
mockDispatchResolvedWebhookTarget.mockResolvedValue({
outcome: 'ignored',
response: new Response(null, { status: 200 }),
reason: 'filtered',
})
await run(messageBody)
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(1)
})
it('routes via Slack Connect authorizations and dedups overlapping webhooks', async () => {
// Two candidate teams (outer + authorization) that resolve to overlapping webhooks.
mockFindWebhooksByRoutingKey.mockImplementation(async (teamId: string) =>
teamId === 'T1' ? [webhook('wh1')] : [webhook('wh1'), webhook('wh2')]
)
await run({
...messageBody,
authorizations: [{ team_id: 'T2' }],
})
expect(mockFindWebhooksByRoutingKey).toHaveBeenCalledTimes(2)
// wh1 (in both) is dispatched once, wh2 once — dedup by webhook id.
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(2)
})
it('returns 200 with no team_id', async () => {
await run({ event: { type: 'message' } })
expect(mockFindWebhooksByRoutingKey).not.toHaveBeenCalled()
expect(mockDispatchResolvedWebhookTarget).not.toHaveBeenCalled()
})
it('routes an interaction payload by payload.team.id', async () => {
await run({
type: 'block_actions',
api_app_id: 'A1',
team: { id: 'T1' },
user: { id: 'U1' },
actions: [{ action_id: 'approve_btn' }],
})
expect(mockFindWebhooksByRoutingKey).toHaveBeenCalledWith('T1', expect.anything())
expect(mockDispatchResolvedWebhookTarget).toHaveBeenCalledTimes(1)
})
it('fails closed on an interaction missing payload.team.id (never routes on user.team_id)', async () => {
await run({
type: 'block_actions',
api_app_id: 'A1',
user: { id: 'U1', team_id: 'T_OTHER' },
actions: [{ action_id: 'approve_btn' }],
})
expect(mockFindWebhooksByRoutingKey).not.toHaveBeenCalled()
expect(mockDispatchResolvedWebhookTarget).not.toHaveBeenCalled()
})
})
+112
View File
@@ -0,0 +1,112 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { admissionRejectedResponse, tryAdmit } from '@/lib/core/admission/gate'
import { env } from '@/lib/core/config/env'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { findWebhooksByRoutingKey, parseWebhookBody } from '@/lib/webhooks/processor'
import { handleSlackChallenge, verifySlackRequestSignature } from '@/lib/webhooks/providers/slack'
import { dispatchSlackWebhooks } from '@/lib/webhooks/slack-dispatch'
const logger = createLogger('SlackAppWebhookAPI')
export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'
export const maxDuration = 60
/**
* Single ingest endpoint for the official Sim Slack app. Every workspace's
* events arrive here and are routed to listening workflows by Slack `team_id`
* (and Slack Connect `authorizations[].team_id`) after HMAC verification with
* the shared app signing secret. This is the request URL configured in the
* app's Event Subscriptions.
*/
export const POST = withRouteHandler(async (request: NextRequest) => {
const ticket = tryAdmit()
if (!ticket) {
return admissionRejectedResponse()
}
try {
return await handleSlackAppWebhook(request)
} finally {
ticket.release()
}
})
async function handleSlackAppWebhook(request: NextRequest): Promise<NextResponse> {
const receivedAt = Date.now()
const requestId = generateRequestId()
const parseResult = await parseWebhookBody(request, requestId)
if (parseResult instanceof NextResponse) {
return parseResult
}
const { body, rawBody } = parseResult
// Slack's endpoint verification handshake — echo the challenge back.
const challenge = handleSlackChallenge(body)
if (challenge) {
return challenge
}
const signingSecret = env.SLACK_SIGNING_SECRET
if (!signingSecret) {
logger.error(`[${requestId}] SLACK_SIGNING_SECRET is not configured`)
return new NextResponse('Slack app not configured', { status: 500 })
}
const authError = verifySlackRequestSignature(signingSecret, request, rawBody, requestId)
if (authError) {
return authError
}
const payload = body as Record<string, unknown>
// Route by the installed workspace(s). For Slack Connect the outer `team_id`
// may be the sender's workspace, so every authorized installation is a
// routing candidate. Team ids are Slack-attested (post-signature), never user
// input.
const teamIds = new Set<string>()
if (typeof payload.team_id === 'string' && payload.team_id.length > 0) {
teamIds.add(payload.team_id)
}
const authorizations = Array.isArray(payload.authorizations) ? payload.authorizations : []
for (const authorization of authorizations) {
const teamId = (authorization as Record<string, unknown>)?.team_id
if (typeof teamId === 'string' && teamId.length > 0) {
teamIds.add(teamId)
}
}
// Interactivity payloads (block_actions / view_submission) carry no top-level
// `team_id` / `authorizations`; the install/context workspace is at
// `payload.team.id`. Route on that ONLY — never `payload.user.team_id`, which
// in Slack Connect can be a different (external) tenant. Slack-attested,
// post-signature, so not user-forgeable.
if (teamIds.size === 0) {
const interactionTeamId = (payload.team as Record<string, unknown> | undefined)?.id
if (typeof interactionTeamId === 'string' && interactionTeamId.length > 0) {
teamIds.add(interactionTeamId)
}
}
if (teamIds.size === 0) {
logger.warn(`[${requestId}] Slack event missing team_id`)
return new NextResponse(null, { status: 200 })
}
const webhooksById = new Map<string, { webhook: any; workflow: any }>()
for (const teamId of teamIds) {
const found = await findWebhooksByRoutingKey(teamId, requestId)
for (const entry of found) {
webhooksById.set(entry.webhook.id, entry)
}
}
const webhooks = [...webhooksById.values()]
if (webhooks.length === 0) {
return new NextResponse(null, { status: 200 })
}
await dispatchSlackWebhooks(webhooks, { body, request, requestId, receivedAt })
return new NextResponse(null, { status: 200 })
}