Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 63 additions & 2 deletions backend/src/api/email/email.handlers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import crypto from "crypto";
import { Request, Response } from "express-serve-static-core";
import { load } from "cheerio";
import { Decimal } from "decimal.js";
Expand All @@ -8,22 +9,82 @@ import {
updateOrderPaymentStatus,
} from "./email.services";

function verifyMailgunSignature(
timestamp: number,
token: string,
signature: string,
): boolean {
const signingKey = process.env.MAILGUN_WEBHOOK_SIGNING_KEY;
if (!signingKey) {
console.error("MAILGUN_WEBHOOK_SIGNING_KEY is not set");
return false;
}
const hmac = crypto.createHmac("sha256", signingKey);
hmac.update(timestamp + token);
const digest = hmac.digest("hex");
return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature));
}

function verifyDkim(messageHeaders: string): boolean {
try {
const headers: [string, string][] = JSON.parse(messageHeaders);

// Check that Mailgun's DKIM verification passed
const dkimResult = headers.find(
([name]) => name.toLowerCase() === "x-mailgun-dkim-check-result",
);
if (!dkimResult || dkimResult[1].toLowerCase() !== "pass") {
console.error("DKIM check did not pass:", dkimResult?.[1]);
return false;
}

// Verify the DKIM signature domain is venmo.com
const dkimSig = headers.find(
([name]) => name.toLowerCase() === "dkim-signature",
);
if (!dkimSig) {
console.error("No DKIM-Signature header found");
return false;
}
const domainMatch = dkimSig[1].match(/\bd=([^;\s]+)/);
if (!domainMatch || domainMatch[1].toLowerCase() !== "venmo.com") {
console.error("DKIM signature domain is not venmo.com:", domainMatch?.[1]);
return false;
}

return true;
} catch (err) {
console.error("Failed to parse message-headers for DKIM check:", err);
return false;
}
}

export const parseEmailHandler = async (
req: Request<{}, any, MailgunInboundEmailBody, {}>,
res: Response
res: Response,
) => {
try {
const {
from,
subject,
"body-html": bodyHtml,
"body-plain": bodyPlain,
"message-headers": messageHeaders,
timestamp,
token,
signature,
} = req.body;

// TODO: Verify Mailgun signature
if (!verifyMailgunSignature(timestamp, token, signature)) {
res.status(401).json({ message: "invalid signature" });
return;
}

// Verify the email was actually signed by Venmo (DKIM)
if (!verifyDkim(messageHeaders)) {
res.status(401).json({ message: "DKIM verification failed" });
return;
}

// Confirm sender is Venmo
if (from !== "Venmo <venmo@venmo.com>") {
Expand Down
2 changes: 1 addition & 1 deletion backend/src/api/email/email.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const MailgunInboundEmailBody = z.object({
timestamp: z.coerce.number(),
token: z.string(),
signature: z.string(),
"message-headers": z.string().optional(),
"message-headers": z.string(),
"content-id-map": z.string().optional(),
});

Expand Down