Created
February 21, 2020 18:00
-
-
Save PopeFelix/a62b7046477f6926558b732cb2bb58de to your computer and use it in GitHub Desktop.
Github webhook listener using Node.js and Express.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const app = express() | |
const port = 80 | |
const bodyParser = require('body-parser') | |
const crypto = require('crypto') | |
const secret = process.env.WEBHOOK_SECRET | |
app.use( | |
bodyParser.urlencoded({ | |
extended: true | |
}) | |
) | |
app.use(bodyParser.json()) | |
app.all('/', (req, res) => { | |
const { method, url } = req | |
console.log('Request URL: ' + url) | |
console.log('Request method: ' + method) | |
console.log('Request headers: ' + JSON.stringify(req.headers, null, 2)) | |
console.log('Request body: ' + JSON.stringify(req.body, null, 2)) | |
if (verifySignature(JSON.stringify(req.body), req.headers['x-hub-signature'])) { | |
console.log('Request verified') | |
res.send('OK') | |
} else { | |
console.log('Request failed verification') | |
res.status(403).send('The request could not be verified') | |
} | |
}) | |
app.listen(port, () => console.log(`Listening on port ${port}`)) | |
const verifySignature = (body, headerSignature) => { | |
const hmac = crypto.createHmac('sha1', secret) | |
hmac.update(body) | |
const digest = hmac.digest('hex') | |
const bodySignature = `sha1=${digest}` | |
return crypto.timingSafeEqual(Buffer.from(bodySignature), Buffer.from(headerSignature)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment