Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate TypeForm Webhook payload in Node

I set up a Typeform webhook and it's working well.

Now I'm trying to secure it, but I'm stuck in the Validate payload from Typeform section.

I adapted the outlined steps and the Ruby example (and a PHP example that Typeform Helpcenter sent me) to Node (Meteor):

const crypto = require('crypto');

function post() {
  const payload = this.bodyParams;
  const stringifiedPayload = JSON.stringify(payload);

  const secret = 'the-random-string';

  const receivedSignature = lodash.get(request, 'headers.typeform-signature', '');

  const hash = crypto
    .createHmac('sha256', secret)
    .update(stringifiedPayload, 'binary')
    .digest('base64');
  const actualSignature = `sha256=${hash}`;

  console.log('actualSignature:', actualSignature);
  console.log('receivedSignature:', receivedSignature);

  if (actualSignature !== receivedSignature) {
    return { statusCode: 200 };
  }

  // .. continue ..
});

But the actualSignature and receivedSignature never match, I get results like:

actualSignature: sha256=4xe1AF0apjIgJNf1jSBG+OFwLYZsKoyFBOzRCesXM0g=
receivedSignature: sha256=b+ZdBUL5KcMAjITxkpzIFibOL1eEtvN84JhF2+schPo=

Why could this be?

like image 530
Bart S Avatar asked Jan 21 '26 03:01

Bart S


1 Answers

You need to use the raw binary request, it is specified in the docs here

Using the HMAC SHA-256 algorithm, create a hash (using created_token as a key) of the entire received payload as binary.

Here is an example using express and the body-parser middleware

const crypto = require('crypto');
const express = require("express");
const bodyParser = require('body-parser');

const TYPEFORM_SECRET = 'your-secret';

const app = express();
const port = 3000;

app.use(bodyParser.raw({ type: 'application/json' }));

app.post(`/webhook`, (req, res) => {
  const expectedSig = req.header('Typeform-Signature');

  const hash = crypto.createHmac('sha256', TYPEFORM_SECRET)
    .update(req.body)
    .digest('base64');

  const actualSig = `sha256=${hash}`;

  if (actualSig !== expectedSig) {
    // invalid request
    res.status(403).send();
    return;
  }

  // successful

  res.status(200).send();
});

app.listen(port, () => {
  console.log(`listening on port ${port}!`);
});
like image 81
JordanW Avatar answered Jan 22 '26 18:01

JordanW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!