|
| 1 | +import { ENV, logger, prisma } from '@jetstream/api-config'; |
| 2 | +import type { Request, Response } from '@jetstream/api-types'; |
| 3 | +import { getErrorMessageAndStackObj } from '@jetstream/shared/utils'; |
| 4 | +import crypto from 'crypto'; |
| 5 | +import { LRUCache } from 'lru-cache'; |
| 6 | +import { z } from 'zod'; |
| 7 | + |
| 8 | +// Cache for tracking used webhook tokens to prevent replay attacks |
| 9 | +// Tokens expire after 15 minutes, same as our timestamp validation window |
| 10 | +const WEBHOOK_TOKEN_CACHE = new LRUCache<string, boolean>({ |
| 11 | + max: 10000, // Store up to 10k recent tokens |
| 12 | + ttl: 1000 * 60 * 15, // 15 minutes |
| 13 | +}); |
| 14 | + |
| 15 | +// Maximum age for webhook timestamps (in seconds) |
| 16 | +const MAX_TIMESTAMP_AGE_SECONDS = 60 * 15; // 15 minutes |
| 17 | + |
| 18 | +// Mailgun webhook payload schema based on their documentation |
| 19 | +const MailgunWebhookSignatureSchema = z.object({ |
| 20 | + timestamp: z.string(), |
| 21 | + token: z.string(), |
| 22 | + signature: z.string(), |
| 23 | +}); |
| 24 | + |
| 25 | +const MailgunDeliveryStatusSchema = z |
| 26 | + .object({ |
| 27 | + code: z.number().optional(), |
| 28 | + message: z.string().optional(), |
| 29 | + description: z.string().optional(), |
| 30 | + 'enhanced-code': z.string().optional(), |
| 31 | + 'attempt-no': z.number().optional(), |
| 32 | + 'mx-host': z.string().optional(), |
| 33 | + 'session-seconds': z.number().optional(), |
| 34 | + tls: z.boolean().optional(), |
| 35 | + 'certificate-verified': z.boolean().optional(), |
| 36 | + }) |
| 37 | + .optional(); |
| 38 | + |
| 39 | +const MailgunEnvelopeSchema = z |
| 40 | + .object({ |
| 41 | + sender: z.string().optional(), |
| 42 | + 'sending-ip': z.string().optional(), |
| 43 | + transport: z.string().optional(), |
| 44 | + targets: z.string().optional(), |
| 45 | + }) |
| 46 | + .optional(); |
| 47 | + |
| 48 | +const MailgunMessageHeadersSchema = z |
| 49 | + .object({ |
| 50 | + to: z.string().optional(), |
| 51 | + from: z.string().optional(), |
| 52 | + subject: z.string().optional(), |
| 53 | + 'message-id': z.string().optional(), |
| 54 | + }) |
| 55 | + .optional(); |
| 56 | + |
| 57 | +const MailgunMessageSchema = z |
| 58 | + .object({ |
| 59 | + headers: MailgunMessageHeadersSchema, |
| 60 | + size: z.number().optional(), |
| 61 | + attachments: z.array(z.any()).optional(), |
| 62 | + }) |
| 63 | + .optional(); |
| 64 | + |
| 65 | +const MailgunFlagsSchema = z |
| 66 | + .object({ |
| 67 | + 'is-test-mode': z.boolean().optional(), |
| 68 | + 'is-routed': z.boolean().optional(), |
| 69 | + 'is-authenticated': z.boolean().optional(), |
| 70 | + 'is-system-test': z.boolean().optional(), |
| 71 | + }) |
| 72 | + .optional(); |
| 73 | + |
| 74 | +const MailgunEventDataSchema = z.object({ |
| 75 | + id: z.string().optional(), |
| 76 | + event: z.string(), |
| 77 | + timestamp: z.number(), |
| 78 | + 'log-level': z.string().optional(), |
| 79 | + recipient: z.string(), |
| 80 | + 'recipient-domain': z.string().optional(), |
| 81 | + 'recipient-provider': z.string().optional(), |
| 82 | + 'delivery-status': MailgunDeliveryStatusSchema, |
| 83 | + envelope: MailgunEnvelopeSchema, |
| 84 | + message: MailgunMessageSchema, |
| 85 | + flags: MailgunFlagsSchema, |
| 86 | + tags: z.array(z.string()).optional(), |
| 87 | + 'user-variables': z.record(z.string(), z.any()).optional(), |
| 88 | +}); |
| 89 | + |
| 90 | +const MailgunWebhookPayloadSchema = z.object({ |
| 91 | + signature: MailgunWebhookSignatureSchema, |
| 92 | + 'event-data': MailgunEventDataSchema, |
| 93 | +}); |
| 94 | + |
| 95 | +export const routeDefinition = { |
| 96 | + webhook: { |
| 97 | + controllerFn: () => mailgunWebhookHandler, |
| 98 | + }, |
| 99 | +}; |
| 100 | + |
| 101 | +const mailgunWebhookHandler = async (req: Request, res: Response) => { |
| 102 | + try { |
| 103 | + // Parse and validate the webhook payload |
| 104 | + const rawBody = req.body as Buffer; |
| 105 | + const parseResult = MailgunWebhookPayloadSchema.safeParse(JSON.parse(rawBody.toString())); |
| 106 | + |
| 107 | + if (!parseResult.success) { |
| 108 | + logger.warn({ error: parseResult.error }, 'Invalid Mailgun webhook payload'); |
| 109 | + return res.status(400).send('Invalid payload'); |
| 110 | + } |
| 111 | + |
| 112 | + const { signature, 'event-data': eventData } = parseResult.data; |
| 113 | + |
| 114 | + // Verify webhook signature if signing key is configured |
| 115 | + if (ENV.MAILGUN_WEBHOOK_SIGNING_KEY) { |
| 116 | + // Check timestamp freshness to prevent replay attacks |
| 117 | + const timestampAge = Math.abs(Date.now() / 1000 - parseInt(signature.timestamp)); |
| 118 | + if (timestampAge > MAX_TIMESTAMP_AGE_SECONDS) { |
| 119 | + logger.warn( |
| 120 | + { timestamp: signature.timestamp, age: timestampAge }, |
| 121 | + 'Mailgun webhook timestamp too old or too far in the future', |
| 122 | + ); |
| 123 | + return res.status(403).send('Invalid timestamp'); |
| 124 | + } |
| 125 | + |
| 126 | + // Check if this token has already been used (replay attack prevention) |
| 127 | + if (WEBHOOK_TOKEN_CACHE.has(signature.token)) { |
| 128 | + logger.warn({ token: signature.token }, 'Mailgun webhook token already used (replay attack)'); |
| 129 | + return res.status(403).send('Token already used'); |
| 130 | + } |
| 131 | + |
| 132 | + // Verify the signature |
| 133 | + const isValid = verifyWebhookSignature({ |
| 134 | + timestamp: signature.timestamp, |
| 135 | + token: signature.token, |
| 136 | + signature: signature.signature, |
| 137 | + signingKey: ENV.MAILGUN_WEBHOOK_SIGNING_KEY, |
| 138 | + }); |
| 139 | + |
| 140 | + if (!isValid) { |
| 141 | + logger.warn({ timestamp: signature.timestamp }, 'Invalid Mailgun webhook signature'); |
| 142 | + return res.status(403).send('Invalid signature'); |
| 143 | + } |
| 144 | + |
| 145 | + // Cache the token to prevent replay attacks |
| 146 | + WEBHOOK_TOKEN_CACHE.set(signature.token, true); |
| 147 | + } else { |
| 148 | + logger.warn('Mailgun webhook signing key not configured - skipping signature verification'); |
| 149 | + return res.status(500).send('Webhook signing key not configured'); |
| 150 | + } |
| 151 | + |
| 152 | + // Extract recipient domain from recipient email |
| 153 | + const recipientDomain = eventData['recipient-domain'] || eventData.recipient.split('@')[1] || 'unknown'; |
| 154 | + |
| 155 | + // Store the webhook event in the database |
| 156 | + await prisma.mailgunWebhookEvent.create({ |
| 157 | + data: { |
| 158 | + // Event metadata |
| 159 | + eventId: eventData.id, |
| 160 | + event: eventData.event, |
| 161 | + timestamp: new Date(eventData.timestamp * 1000), |
| 162 | + logLevel: eventData['log-level'], |
| 163 | + |
| 164 | + // Recipient information |
| 165 | + recipient: eventData.recipient, |
| 166 | + recipientDomain, |
| 167 | + recipientProvider: eventData['recipient-provider'], |
| 168 | + |
| 169 | + // Message information |
| 170 | + subject: eventData.message?.headers?.subject, |
| 171 | + messageId: eventData.message?.headers?.['message-id'], |
| 172 | + fromAddress: eventData.message?.headers?.from, |
| 173 | + toAddress: eventData.message?.headers?.to, |
| 174 | + messageSize: eventData.message?.size, |
| 175 | + |
| 176 | + // Delivery status |
| 177 | + deliveryCode: eventData['delivery-status']?.code, |
| 178 | + deliveryMessage: eventData['delivery-status']?.message, |
| 179 | + deliveryDescription: eventData['delivery-status']?.description, |
| 180 | + deliveryEnhancedCode: eventData['delivery-status']?.['enhanced-code'], |
| 181 | + deliveryAttemptNo: eventData['delivery-status']?.['attempt-no'], |
| 182 | + deliveryMxHost: eventData['delivery-status']?.['mx-host'], |
| 183 | + deliverySessionSeconds: eventData['delivery-status']?.['session-seconds'], |
| 184 | + deliveryTls: eventData['delivery-status']?.tls, |
| 185 | + deliveryCertVerified: eventData['delivery-status']?.['certificate-verified'], |
| 186 | + |
| 187 | + // Envelope information |
| 188 | + envelopeSender: eventData.envelope?.sender, |
| 189 | + envelopeSendingIp: eventData.envelope?.['sending-ip'], |
| 190 | + envelopeTransport: eventData.envelope?.transport, |
| 191 | + |
| 192 | + // Metadata |
| 193 | + tags: eventData.tags || [], |
| 194 | + userVariables: eventData['user-variables'], |
| 195 | + flags: eventData.flags, |
| 196 | + }, |
| 197 | + }); |
| 198 | + |
| 199 | + res.status(200).end(); |
| 200 | + } catch (err) { |
| 201 | + logger.error(getErrorMessageAndStackObj(err), 'Error processing Mailgun webhook'); |
| 202 | + return res.status(500).send(`Error processing Mailgun webhook`); |
| 203 | + } |
| 204 | +}; |
| 205 | + |
| 206 | +function verifyWebhookSignature({ |
| 207 | + timestamp, |
| 208 | + token, |
| 209 | + signature, |
| 210 | + signingKey, |
| 211 | +}: { |
| 212 | + timestamp: string; |
| 213 | + token: string; |
| 214 | + signature: string; |
| 215 | + signingKey: string; |
| 216 | +}): boolean { |
| 217 | + const encodedToken = crypto.createHmac('sha256', signingKey).update(timestamp.concat(token)).digest('hex'); |
| 218 | + return encodedToken === signature; |
| 219 | +} |
0 commit comments