Sarah's verification middleware, mounted before the orders handler. Work out why each line is there.
import crypto from "node:crypto";
const SECRET = process.env.SHOPIFY_CLIENT_SECRET;
// Mounted with express.raw(), so req.body is the untouched Buffer.
export function verifyShopifyWebhook(req, res, next) {
const provided = req.headers["x-shopify-hmac-sha256"];
if (!provided) {
return res.status(401).send("Missing signature");
}
const computed = crypto
.createHmac("sha256", SECRET)
.update(req.body)
.digest("base64");
const providedBuf = Buffer.from(provided, "utf8");
const computedBuf = Buffer.from(computed, "utf8");
// timingSafeEqual throws on buffers of different lengths,
// so reject cleanly before comparing.
if (providedBuf.length !== computedBuf.length) {
return res.status(401).send("Invalid signature");
}
if (!crypto.timingSafeEqual(providedBuf, computedBuf)) {
return res.status(401).send("Invalid signature");
}
next();
}