|
| 1 | +import crypto from 'crypto' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { NextResponse } from 'next/server' |
| 4 | +import { safeCompare } from '@/lib/core/security/encryption' |
| 5 | +import type { |
| 6 | + AuthContext, |
| 7 | + EventMatchContext, |
| 8 | + FormatInputContext, |
| 9 | + FormatInputResult, |
| 10 | + WebhookProviderHandler, |
| 11 | +} from '@/lib/webhooks/providers/types' |
| 12 | + |
| 13 | +const logger = createLogger('WebhookProvider:Intercom') |
| 14 | + |
| 15 | +/** |
| 16 | + * Validate Intercom webhook signature using HMAC-SHA1. |
| 17 | + * Intercom signs payloads with the app's Client Secret and sends the |
| 18 | + * signature in the X-Hub-Signature header as "sha1=<hex>". |
| 19 | + */ |
| 20 | +function validateIntercomSignature(secret: string, signature: string, body: string): boolean { |
| 21 | + try { |
| 22 | + if (!secret || !signature || !body) { |
| 23 | + logger.warn('Intercom signature validation missing required fields', { |
| 24 | + hasSecret: !!secret, |
| 25 | + hasSignature: !!signature, |
| 26 | + hasBody: !!body, |
| 27 | + }) |
| 28 | + return false |
| 29 | + } |
| 30 | + |
| 31 | + if (!signature.startsWith('sha1=')) { |
| 32 | + logger.warn('Intercom signature has invalid format', { |
| 33 | + signature: `${signature.substring(0, 10)}...`, |
| 34 | + }) |
| 35 | + return false |
| 36 | + } |
| 37 | + |
| 38 | + const providedSignature = signature.substring(5) |
| 39 | + const computedHash = crypto.createHmac('sha1', secret).update(body, 'utf8').digest('hex') |
| 40 | + |
| 41 | + return safeCompare(computedHash, providedSignature) |
| 42 | + } catch (error) { |
| 43 | + logger.error('Error validating Intercom signature:', error) |
| 44 | + return false |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export const intercomHandler: WebhookProviderHandler = { |
| 49 | + verifyAuth({ request, rawBody, requestId, providerConfig }: AuthContext) { |
| 50 | + const secret = providerConfig.webhookSecret as string | undefined |
| 51 | + if (!secret) { |
| 52 | + return null |
| 53 | + } |
| 54 | + |
| 55 | + const signature = request.headers.get('X-Hub-Signature') |
| 56 | + if (!signature) { |
| 57 | + logger.warn(`[${requestId}] Intercom webhook missing X-Hub-Signature header`) |
| 58 | + return new NextResponse('Unauthorized - Missing Intercom signature', { status: 401 }) |
| 59 | + } |
| 60 | + |
| 61 | + if (!validateIntercomSignature(secret, signature, rawBody)) { |
| 62 | + logger.warn(`[${requestId}] Intercom signature verification failed`, { |
| 63 | + signatureLength: signature.length, |
| 64 | + secretLength: secret.length, |
| 65 | + }) |
| 66 | + return new NextResponse('Unauthorized - Invalid Intercom signature', { status: 401 }) |
| 67 | + } |
| 68 | + |
| 69 | + return null |
| 70 | + }, |
| 71 | + |
| 72 | + handleReachabilityTest(body: unknown, requestId: string) { |
| 73 | + const obj = body as Record<string, unknown> | null |
| 74 | + if (obj?.topic === 'ping') { |
| 75 | + logger.info( |
| 76 | + `[${requestId}] Intercom ping event detected - returning 200 without triggering workflow` |
| 77 | + ) |
| 78 | + return NextResponse.json({ |
| 79 | + status: 'ok', |
| 80 | + message: 'Webhook endpoint verified', |
| 81 | + }) |
| 82 | + } |
| 83 | + return null |
| 84 | + }, |
| 85 | + |
| 86 | + async formatInput({ body }: FormatInputContext): Promise<FormatInputResult> { |
| 87 | + return { input: body } |
| 88 | + }, |
| 89 | + |
| 90 | + async matchEvent({ webhook, body, requestId, providerConfig }: EventMatchContext) { |
| 91 | + const triggerId = providerConfig.triggerId as string | undefined |
| 92 | + const obj = body as Record<string, unknown> |
| 93 | + const topic = obj?.topic as string | undefined |
| 94 | + |
| 95 | + if (triggerId && triggerId !== 'intercom_webhook') { |
| 96 | + const { isIntercomEventMatch } = await import('@/triggers/intercom/utils') |
| 97 | + if (!isIntercomEventMatch(triggerId, topic || '')) { |
| 98 | + logger.debug( |
| 99 | + `[${requestId}] Intercom event mismatch for trigger ${triggerId}. Topic: ${topic}. Skipping execution.`, |
| 100 | + { |
| 101 | + webhookId: webhook.id, |
| 102 | + triggerId, |
| 103 | + receivedTopic: topic, |
| 104 | + } |
| 105 | + ) |
| 106 | + return false |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return true |
| 111 | + }, |
| 112 | + |
| 113 | + extractIdempotencyId(body: unknown) { |
| 114 | + const obj = body as Record<string, unknown> |
| 115 | + if (obj?.id && obj?.type === 'notification_event') { |
| 116 | + return String(obj.id) |
| 117 | + } |
| 118 | + return null |
| 119 | + }, |
| 120 | +} |
0 commit comments