Skip to content

Instantly share code, notes, and snippets.

@joawan
Created September 14, 2021 20:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joawan/182afb868d694cec797e1eae5f29e7da to your computer and use it in GitHub Desktop.
Save joawan/182afb868d694cec797e1eae5f29e7da to your computer and use it in GitHub Desktop.
Method to verify slack messages
const crypto = require('crypto');
const signSecret = process.env.SLACK_SIGN_SECRET;
const validateRequest = (requestSignature, requestTime, rawBody, validFor = 300) => {
const requestValidFrom = Math.floor(Date.now() / 1000) - validFor;
if (requestTime < requestValidFrom) {
throw new Error(`Request outdated: !(${requestTime} < ${requestValidFrom})`);
}
const hmac = crypto.createHmac('sha256', signSecret);
const [version, hash] = requestSignature.split('=');
hmac.update(`${version}:${requestTime}:${rawBody}`);
const digest = hmac.digest('hex');
if (hash !== digest) {
throw new Error(`Request signature mismatch: !('${hash}' === '${digest}')`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment