|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { NextResponse } from 'next/server' |
| 3 | +import type { |
| 4 | + AuthContext, |
| 5 | + EventMatchContext, |
| 6 | + WebhookProviderHandler, |
| 7 | +} from '@/lib/webhooks/providers/types' |
| 8 | +import { verifyTokenAuth } from '@/lib/webhooks/providers/utils' |
| 9 | + |
| 10 | +const logger = createLogger('WebhookProvider:ServiceNow') |
| 11 | + |
| 12 | +function asRecord(body: unknown): Record<string, unknown> { |
| 13 | + return body && typeof body === 'object' && !Array.isArray(body) |
| 14 | + ? (body as Record<string, unknown>) |
| 15 | + : {} |
| 16 | +} |
| 17 | + |
| 18 | +export const servicenowHandler: WebhookProviderHandler = { |
| 19 | + verifyAuth({ request, requestId, providerConfig }: AuthContext): NextResponse | null { |
| 20 | + const secret = providerConfig.webhookSecret as string | undefined |
| 21 | + if (!secret?.trim()) { |
| 22 | + logger.warn(`[${requestId}] ServiceNow webhook missing webhookSecret — rejecting`) |
| 23 | + return new NextResponse('Unauthorized - Webhook secret not configured', { status: 401 }) |
| 24 | + } |
| 25 | + |
| 26 | + if ( |
| 27 | + !verifyTokenAuth(request, secret.trim(), 'x-sim-webhook-secret') && |
| 28 | + !verifyTokenAuth(request, secret.trim()) |
| 29 | + ) { |
| 30 | + logger.warn(`[${requestId}] ServiceNow webhook secret verification failed`) |
| 31 | + return new NextResponse('Unauthorized - Invalid webhook secret', { status: 401 }) |
| 32 | + } |
| 33 | + |
| 34 | + return null |
| 35 | + }, |
| 36 | + |
| 37 | + async matchEvent({ webhook, workflow, body, requestId, providerConfig }: EventMatchContext) { |
| 38 | + const triggerId = providerConfig.triggerId as string | undefined |
| 39 | + if (!triggerId) { |
| 40 | + return true |
| 41 | + } |
| 42 | + |
| 43 | + const { isServiceNowEventMatch } = await import('@/triggers/servicenow/utils') |
| 44 | + const configuredTableName = providerConfig.tableName as string | undefined |
| 45 | + const obj = asRecord(body) |
| 46 | + |
| 47 | + if (!isServiceNowEventMatch(triggerId, obj, configuredTableName)) { |
| 48 | + logger.debug( |
| 49 | + `[${requestId}] ServiceNow event mismatch for trigger ${triggerId}. Skipping execution.`, |
| 50 | + { webhookId: webhook.id, workflowId: workflow.id, triggerId } |
| 51 | + ) |
| 52 | + return false |
| 53 | + } |
| 54 | + |
| 55 | + return true |
| 56 | + }, |
| 57 | +} |
0 commit comments