-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvalidateRequest.js
50 lines (40 loc) · 1.31 KB
/
validateRequest.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
47
48
49
50
const crypto = require('crypto');
const qs = require('qs');
const isValidTimestamp = (req) => {
const currentTimestamp = (new Date()).getTime();
const requestTimestamp = req.headers['x-slack-request-timestamp'];
return Math.abs(currentTimestamp / 1000 - requestTimestamp) <= 60 * 5;
}
const isValidSignature = (req, signingSecret) => {
const slackSignature = req.headers['x-slack-signature'];
const requestBody = qs.stringify(req.body, { format:'RFC1738' });
const timestamp = req.headers['x-slack-request-timestamp'];
const sigBasestring = `v0:${timestamp}:${requestBody}`;
const mySignature = 'v0=' +
crypto.createHmac('sha256', signingSecret)
.update(sigBasestring, 'utf8')
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(mySignature, 'hex'),
Buffer.from(slackSignature, 'hex')
);
}
const validateRequest = (req, signingSecret) => {
if (!isValidTimestamp(req)) {
return {
isValid: false,
reason: 'Replay attack detected',
}
}
if (!isValidSignature(req, signingSecret)) {
return {
isValid: false,
reason: 'Signature mismatch',
}
}
return {
isValid: true,
reason: '',
}
};
module.exports = validateRequest;