-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
38 lines (31 loc) · 978 Bytes
/
middleware.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
require('dotenv').config()
const crypto = require('crypto')
const secret = process.env.SECRET_TOKEN
const onlyPushPingEvent = (req, res, next) => {
if (['ping', 'push'].includes(req.get('X-Github-Event'))) {
return next()
}
return res.status(400).json({
message: 'Only accept push event'
})
}
const verifyPostData = (req, res, next) => {
if (!req.body) {
return res.status(400).json({
message: 'Request body empty'
})
}
const sig = Buffer.from(req.get('X-Hub-Signature-256') || '', 'utf8')
const hmac = crypto.createHmac('sha256', secret)
const digest = Buffer.from('sha256=' + hmac.update(JSON.stringify(req.body)).digest('hex'), 'utf8')
if (sig.length !== digest.length || !crypto.timingSafeEqual(digest, sig)) {
return res.status(400).json({
message: `Request body digest (${digest}) did not match X-Hub-Signature-256 (${sig})`
})
}
return next()
}
module.exports = {
onlyPushPingEvent,
verifyPostData
}