Created
October 5, 2017 12:49
-
-
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.
This file contains hidden or 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
'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