Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Last active December 29, 2022 12:36
Show Gist options
  • Save mikaelvesavuori/223bf0b4339f9a32cac45cc55cc6e062 to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/223bf0b4339f9a32cac45cc55cc6e062 to your computer and use it in GitHub Desktop.
Verify GitHub webhook secret using Node and TypeScript
import { createHmac, timingSafeEqual } from 'crypto';
const TOKEN = 'SOME_SECRET_VALUE';
/**
* @description Verify GitHub secret from signature.
*
* There are a ton of these examples out there but some are really messy and this one tidies them up a bit.
*
* @param {string} headerValue - Pass in `headers['X-Hub-Signature-256']`. Looks something like 'sha256=3fead968c...'
* @param {any} body - Your request body
*/
export function verifySignature(headerValue: string, body: any) {
const signature = Buffer.from(headerValue, 'utf8');
const hmac = createHmac('sha256', TOKEN).update(JSON.stringify(body)).digest('hex');
const digest = Buffer.from('sha256=' + hmac, 'utf8');
if (signature.length !== digest.length || !timingSafeEqual(digest, signature)) return false;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment