Last active
August 8, 2017 02:20
-
-
Save adis-io/becda706373ad3d60da7 to your computer and use it in GitHub Desktop.
Github's webhook handling with nodejs + restify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var restify = require('restify'), | |
crypto = require('crypto'); | |
var secret = "my-app-secret"; | |
function payload(req, res, next) { | |
getRawBody(req, { | |
length: req.headers['content-length'], | |
limit: '2mb', | |
encoding: 'utf-8' | |
}, function (err, string) { | |
if (err) | |
return next(err); | |
console.log('body parsed'); | |
var github_signature = req.headers['x-hub-signature']; | |
if (!string) { | |
console.log('no body'); | |
res.send('no body'); | |
next(); | |
} | |
var my = my_signature(string); | |
if (github_signature == my) { | |
// do other job, for example pull data from your repo with shelljs | |
} | |
console.log('Signatures didn\'t match'); | |
next(); | |
}); | |
} | |
function my_signature(payload_body) { | |
return "sha1=" + crypto.createHmac('sha1', secret).update(JSON.stringify(payload_body)).digest('hex'); | |
} | |
var server = restify.createServer(); | |
server.post('/payload', payload); | |
server.on('uncaughtException', function (req, res, route, err) { | |
console.log('uncaughtException', err.stack); | |
}); | |
server.listen(4567, '127.0.0.1', function() { | |
console.log('%s listening at %s', server.name, server.url); | |
}); |
You should put your secret in an environmental variable, and you should use a secure compare not the ==
operator.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.github.com/webhooks/securing/ - here example for sinatra