-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.js
46 lines (43 loc) · 1.42 KB
/
slack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var qs = require('qs');
var crypto = require('crypto');
var slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
if (!slackSigningSecret) {
throw new Error('Must set SLACK_SIGNING_SECRET environmental variable');
}
// verify request is from slack
// thank you https://medium.com/@rajat_sriv/verifying-requests-from-slack-using-node-js-69a8b771b704
function slackVerifyMiddleware(req, res, next) {
if (!req.body) {
console.warn('no body in request');
res.end();
return;
}
var requestBody = qs.stringify(req.body, {format: 'RFC1738'});
var timestamp = req.headers['x-slack-request-timestamp'];
var currentTime = Math.floor(new Date() / 1000);
if (Math.abs(currentTime - timestamp) > 60 * 5) {
console.warn('ending response, may be a replay attack');
res.end();
return;
}
var sigBaseString = 'v0:' + timestamp + ':' + requestBody;
var mySignature = 'v0=' +
crypto.createHmac('sha256', slackSigningSecret)
.update(sigBaseString, 'utf8')
.digest('hex');
var slackSignature = req.headers['x-slack-signature'];
if (!slackSignature) {
console.warn('received request without x-slack-signature');
res.end();
return;
}
if (crypto.timingSafeEqual(
Buffer.from(mySignature, 'utf8'),
Buffer.from(slackSignature, 'utf8'))) {
next();
} else {
console.warn('signature does not match :(');
res.end();
}
}
module.exports = slackVerifyMiddleware;