Skip to content

Instantly share code, notes, and snippets.

@jonchurch
Last active June 16, 2017 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchurch/1510e24f3093bd9027a0f906db18c90b to your computer and use it in GitHub Desktop.
Save jonchurch/1510e24f3093bd9027a0f906db18c90b to your computer and use it in GitHub Desktop.
Express Middleware for Botkit -- Verify xhub signature of requests sent to webhook
var crypto = require('crypto');
var bodyParser = require('body-parser');
var debug = require('debug')('botkit:verify_xhub_fb');
module.exports = function(webserver, controller) {
if (controller.config.validate_requests === true) {
// Load verify middleware just for post route on our receive webhook, and catch any errors it might throw to prevent the request from being parsed further.
webserver.post('/facebook/receive', bodyParser.json({verify: verifyRequest}));
webserver.use(abortOnValidationError);
}
// Verifies the SHA1 signature of the raw request payload before bodyParser parses it
// Will abort parsing if signature is invalid, and pass a generic error to response
function verifyRequest(req, res, buf, encoding) {
var expected = req.headers['x-hub-signature'];
var calculated = getSignature(buf);
if (expected !== calculated) {
throw new Error('Invalid signature on incoming request');
} else {
// debug('** X-Hub Verification successful!')
}
}
function getSignature(buf) {
var hmac = crypto.createHmac('sha1', controller.config.app_secret);
hmac.update(buf, 'utf-8');
return 'sha1=' + hmac.digest('hex');
}
function abortOnValidationError(err, req, res, next) {
if (err) {
controller.log('** Invalid X-HUB signature on incoming request!');
debug('** X-HUB Validation Error:', err);
res.status(400).send({
error: 'Invalid signature.'
});
} else {
next();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment