tawn33y / whatsapp-cloud-api

A Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API.
https://www.npmjs.com/package/whatsapp-cloud-api
GNU General Public License v3.0
189 stars 51 forks source link

validate payloads as recommended by meta #60

Closed hamza-shezad closed 4 months ago

hamza-shezad commented 1 year ago

as mentioned in https://developers.facebook.com/docs/graph-api/webhooks/getting-started, event notifications should be validated with the sha256 hash provided in the X-Hub-Signature-256 this will ensure secure communication, and help rejecting bad requests

hamza-shezad commented 1 year ago

i have a solution for this:

function validateHash(req, res, next) {
  if (req.method == "GET") {
    next();
    return;
  }

  const hash = createHmac("sha256", APP_SECRET).update(JSON.stringify(req.body)).digest("hex");
  const splitHash = req.get("X-Hub-Signature-256").split("=")[1];
  if (splitHash != hash) {
    res.sendStatus(200);
    return;
  }

  next();
}

whatsappApi.startExpressServer({
  useMiddleware: (app) => {
    app.use(WEBHOOK_PATH, validateHash)
  }
})

but there is a problem with this: if there is an @ in the response, an invalid signature is produced. e.g. if i send a message with an email, the signatures do not match. this may be due to express.json middleware in https://github.com/tawn33y/whatsapp-cloud-api/blob/32270afa807b398f4d02e91a7018f0c1721f0575/src/startExpressServer.ts#L26

or some formatting applied by whatsapp? how can i verify this?

tawn33y commented 4 months ago

Closing - please read more here.