Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | /** * Resend Webhook Handler * * Receives webhook events from Resend to track email delivery status. * * Events handled: * - email.sent - Email was sent successfully * - email.delivered - Email was delivered to recipient * - email.delivery_delayed - Delivery was delayed * - email.complained - Recipient marked as spam * - email.bounced - Email bounced * - email.opened - Email was opened (if tracking enabled) * - email.clicked - Link in email was clicked (if tracking enabled) * * @see https://resend.com/docs/dashboard/webhooks/introduction */ import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { logger } from '@/lib/logging'; import crypto from 'crypto'; // Prevent static generation export const dynamic = 'force-dynamic'; // Webhook event types from Resend type ResendEventType = | 'email.sent' | 'email.delivered' | 'email.delivery_delayed' | 'email.complained' | 'email.bounced' | 'email.opened' | 'email.clicked'; // Map Resend events to our EmailStatus enum const eventToStatus: Record<ResendEventType, string> = { 'email.sent': 'SENT', 'email.delivered': 'DELIVERED', 'email.delivery_delayed': 'QUEUED', // Keep as queued, still pending 'email.complained': 'BOUNCED', // Treat spam complaints as bounces 'email.bounced': 'BOUNCED', 'email.opened': 'OPENED', 'email.clicked': 'CLICKED' }; // Resend webhook payload structure interface ResendWebhookPayload { type: ResendEventType; created_at: string; data: { email_id: string; from: string; to: string[]; subject: string; created_at: string; // Additional fields for specific events bounce?: { message: string; type: string; }; click?: { ipAddress: string; link: string; timestamp: string; userAgent: string; }; open?: { ipAddress: string; timestamp: string; userAgent: string; }; }; } /** * Verify Resend webhook signature * * @param payload - Raw request body * @param signature - Signature from Resend-Signature header * @param secret - Webhook signing secret * @returns Boolean indicating if signature is valid */ function verifyWebhookSignature( payload: string, signature: string, secret: string ): boolean { if (!signature || !secret) { return false; } try { // Resend sends signature in format: t=timestamp,v1=signature const parts = signature.split(','); const timestamp = parts.find(p => p.startsWith('t='))?.slice(2); const signatureValue = parts.find(p => p.startsWith('v1='))?.slice(3); if (!timestamp || !signatureValue) { return false; } // Verify timestamp is within 5 minutes to prevent replay attacks const timestampMs = parseInt(timestamp) * 1000; const now = Date.now(); if (Math.abs(now - timestampMs) > 5 * 60 * 1000) { logger.warn('Webhook signature timestamp too old', { category: 'EMAIL' }); return false; } // Compute expected signature const signedPayload = `${timestamp}.${payload}`; const expectedSignature = crypto .createHmac('sha256', secret) .update(signedPayload) .digest('hex'); // Use timing-safe comparison return crypto.timingSafeEqual( Buffer.from(signatureValue), Buffer.from(expectedSignature) ); } catch (error) { logger.error('Webhook signature verification error', error instanceof Error ? error : new Error(String(error)), { category: 'EMAIL' }); return false; } } /** * POST /api/email/webhook * * Handle incoming Resend webhook events */ export async function POST(request: NextRequest): Promise<NextResponse> { const webhookSecret = process.env.RESEND_WEBHOOK_SECRET; // In development, allow without signature verification if (process.env.NODE_ENV === 'production' && webhookSecret) { const signature = request.headers.get('resend-signature') || ''; const rawBody = await request.text(); if (!verifyWebhookSignature(rawBody, signature, webhookSecret)) { logger.warn('Invalid webhook signature', { category: 'EMAIL' }); return NextResponse.json( { error: 'Invalid signature' }, { status: 401 } ); } // Parse verified body try { const payload: ResendWebhookPayload = JSON.parse(rawBody); return await processWebhookEvent(payload); } catch { return NextResponse.json( { error: 'Invalid JSON' }, { status: 400 } ); } } // Development mode or no secret configured try { const payload: ResendWebhookPayload = await request.json(); return await processWebhookEvent(payload); } catch { return NextResponse.json( { error: 'Invalid JSON' }, { status: 400 } ); } } /** * Process a webhook event and update email log */ async function processWebhookEvent( payload: ResendWebhookPayload ): Promise<NextResponse> { const { type, data } = payload; logger.info(`Received webhook event: ${type}`, { category: 'EMAIL', emailId: data.email_id, to: data.to }); // Get the new status const newStatus = eventToStatus[type]; if (!newStatus) { logger.warn(`Unknown webhook event type: ${type}`, { category: 'EMAIL' }); return NextResponse.json({ received: true }); } try { // Find email log by message ID const emailLog = await prisma.emailLog.findFirst({ where: { messageId: data.email_id } }); if (!emailLog) { // Try finding by recipient email and subject (fallback) const recentLog = await prisma.emailLog.findFirst({ where: { to: data.to[0], subject: data.subject, createdAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) // Last 24 hours } }, orderBy: { createdAt: 'desc' } }); if (recentLog) { await updateEmailLog(recentLog.id, type, newStatus, data); } else { logger.warn(`Email log not found for message: ${data.email_id}`, { category: 'EMAIL' }); } } else { await updateEmailLog(emailLog.id, type, newStatus, data); } return NextResponse.json({ received: true }); } catch (error) { logger.error('Failed to process webhook event', error instanceof Error ? error : new Error(String(error)), { category: 'EMAIL' }); return NextResponse.json( { error: 'Failed to process event' }, { status: 500 } ); } } /** * Update email log with event data */ async function updateEmailLog( id: number, eventType: ResendEventType, status: string, data: ResendWebhookPayload['data'] ): Promise<void> { const updateData: Record<string, Date | string | null> = { status, messageId: data.email_id }; // Set timestamps based on event type switch (eventType) { case 'email.sent': updateData.sentAt = new Date(); break; case 'email.opened': updateData.openedAt = new Date(); break; case 'email.clicked': updateData.clickedAt = new Date(); break; case 'email.bounced': case 'email.complained': updateData.error = data.bounce?.message || 'Email bounced'; break; } await prisma.emailLog.update({ where: { id }, data: updateData }); logger.info(`Updated email log ${id} to status ${status}`, { category: 'EMAIL' }); } |