learnshopify.dev/Workspace
code reading

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();
}
1. Why compute the digest over the raw body Buffer instead of `JSON.stringify(req.body)` after parsing?
2. Without this middleware, what can anyone who finds the endpoint URL do?
3. Why `crypto.timingSafeEqual` instead of comparing the two digests with `===`?
4. What breaks if you delete the length check above the `timingSafeEqual` call?
5. Where should `SHOPIFY_CLIENT_SECRET` live?
0 / 1 task solved