|
| 1 | +import crypto from "node:crypto"; |
| 2 | +import { assertNever } from "@argos/util/assertNever"; |
| 3 | +import { invariant } from "@argos/util/invariant"; |
| 4 | +import express, { RequestHandler, Router } from "express"; |
| 5 | +import { z } from "zod"; |
| 6 | + |
| 7 | +import config from "@/config/index.js"; |
| 8 | +import { NotificationMessage } from "@/database/models"; |
| 9 | + |
| 10 | +import { asyncHandler } from "../util"; |
| 11 | + |
| 12 | +const router = Router(); |
| 13 | + |
| 14 | +const verifyWebhookSignature: RequestHandler = (req, res, next) => { |
| 15 | + const secret = config.get("resend.webhookSecret"); |
| 16 | + |
| 17 | + if (!secret) { |
| 18 | + res.status(400).send('Missing "resend.webhookSecret"'); |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + const svixId = req.headers["svix-id"]; |
| 23 | + const svixTimestamp = req.headers["svix-timestamp"]; |
| 24 | + const svixSignatureHeader = req.headers["svix-signature"]; |
| 25 | + |
| 26 | + if ( |
| 27 | + typeof svixId !== "string" || |
| 28 | + typeof svixTimestamp !== "string" || |
| 29 | + typeof svixSignatureHeader !== "string" |
| 30 | + ) { |
| 31 | + res.status(400).send("Missing headers"); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + const svixSignatures = svixSignatureHeader.split(" ").map((s) => { |
| 36 | + const [, value] = s.split(","); |
| 37 | + if (!value) { |
| 38 | + return null; |
| 39 | + } |
| 40 | + return value; |
| 41 | + }); |
| 42 | + |
| 43 | + if (svixSignatures.some((s) => s === null)) { |
| 44 | + res.status(400).send("Invalid signature header"); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + const secretParts = secret.split("_"); |
| 49 | + invariant(secretParts[1], 'Secret must be in the format "whsec_<base64>"'); |
| 50 | + const secretBytes = Buffer.from(secretParts[1], "base64"); |
| 51 | + const message = `${svixId}.${svixTimestamp}.${req.body}`; |
| 52 | + |
| 53 | + const expectedSignature = crypto |
| 54 | + .createHmac("sha256", secretBytes) |
| 55 | + .update(message) |
| 56 | + .digest("base64"); |
| 57 | + |
| 58 | + if (!svixSignatures.includes(expectedSignature)) { |
| 59 | + res.status(401).send("Invalid signature"); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + next(); |
| 64 | +}; |
| 65 | + |
| 66 | +const EventSchema = z.object({ |
| 67 | + type: z.enum(["email.delivered", "email.clicked"]), |
| 68 | + data: z.object({ |
| 69 | + email_id: z.string(), |
| 70 | + }), |
| 71 | +}); |
| 72 | + |
| 73 | +router.post( |
| 74 | + "/resend/event-handler", |
| 75 | + express.text({ type: "*/*" }), |
| 76 | + verifyWebhookSignature, |
| 77 | + asyncHandler(async (req, res) => { |
| 78 | + const body = JSON.parse(req.body); |
| 79 | + const parsed = EventSchema.safeParse(body); |
| 80 | + if (!parsed.success) { |
| 81 | + res.status(400).send("Invalid payload"); |
| 82 | + return; |
| 83 | + } |
| 84 | + const event = parsed.data; |
| 85 | + |
| 86 | + const message = await NotificationMessage.query() |
| 87 | + .where("channel", "email") |
| 88 | + .where("externalId", event.data.email_id) |
| 89 | + .first(); |
| 90 | + |
| 91 | + if (!message) { |
| 92 | + res.status(200).send("Message not found"); |
| 93 | + return; |
| 94 | + } |
| 95 | + |
| 96 | + switch (event.type) { |
| 97 | + case "email.delivered": { |
| 98 | + if (!message.deliveredAt) { |
| 99 | + await message |
| 100 | + .$query() |
| 101 | + .patch({ deliveredAt: new Date().toISOString() }); |
| 102 | + } |
| 103 | + break; |
| 104 | + } |
| 105 | + case "email.clicked": { |
| 106 | + if (!message.linkClickedAt) { |
| 107 | + await message |
| 108 | + .$query() |
| 109 | + .patch({ linkClickedAt: new Date().toISOString() }); |
| 110 | + } |
| 111 | + break; |
| 112 | + } |
| 113 | + default: |
| 114 | + assertNever(event.type); |
| 115 | + } |
| 116 | + |
| 117 | + res.status(200).send("Message updated"); |
| 118 | + }), |
| 119 | +); |
| 120 | + |
| 121 | +export const apiMiddleware: Router = router; |
0 commit comments