Skip to content

Instantly share code, notes, and snippets.

@OllieJones
Created October 5, 2017 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OllieJones/655ab469769f1e09b26cfbbe2cb8b3c2 to your computer and use it in GitHub Desktop.
Save OllieJones/655ab469769f1e09b26cfbbe2cb8b3c2 to your computer and use it in GitHub Desktop.
Github webhooks use a shared secret for validation. The webhook itself contains a header X-Hub-Signature containing a hash of the webhook body. This function checks that hash against the body.
'use strict';
const crypto = require( 'crypto' );
function validateGithub( secret, signature, rawBody ) {
if( (!signature) || signature.length === 0 ) return false;
if( (!rawBody) || rawBody.length === 0 ) return false;
try {
const splits = signature.split( '=' );
if( splits.length > 1 ) {
/* signature looks like sha1=12345678cafecafefedcba9876543210 */
const hash = splits[0];
const sig = splits.slice( 1 ).join( '' );
const hmac = crypto.createHmac( hash, secret );
var computed = new Buffer( hmac.update( rawBody, 'utf8' ).digest( 'hex' ) );
var header = new Buffer( sig );
return crypto.timingSafeEqual( computed, header );
}
else {
return false;
}
}
catch( exception ) {
return false;
}
}
module.exports = validateGithub;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment