Skip to content

Instantly share code, notes, and snippets.

@mutoe
Created April 4, 2024 09:47
Show Gist options
  • Save mutoe/0149e1706fd92e839a9b934eb37ee870 to your computer and use it in GitHub Desktop.
Save mutoe/0149e1706fd92e839a9b934eb37ee870 to your computer and use it in GitHub Desktop.
Github Webhooks
const http = require('http')
const crypto = require('crypto')
const execFile = require('child_process').execFile
const port = 10010
const secret = 'your_secret'
const bashFile = './onpush.sh'
const sign = data => `sha1=${crypto.createHmac('sha1', secret).update(data).digest('hex')}`
const app = http.createServer((req, res) => {
let body = ''
req.on('data', chunk => void (body += chunk))
req.on('end', () => {
const sha1 = sign(body)
body = JSON.parse(body)
console.log('Received request', {repo: body.repository.full_name,ref: body.ref})
if (secret && req.headers['x-hub-signature'] !== sha1) {
console.warn('Request failed: invalid secret')
res.writeHead(403)
res.end(JSON.stringify({ message: 'invalid secret' }))
return
}
stdout = execFile(bashFile, (err, stdout, stderr) => {
if (err) {
res.writeHead(500)
res.end(JSON.stringify({ error: err }))
return
}
if (stderr) console.error(stderr)
console.log(stdout)
res.writeHead(200)
res.end()
console.log('Update succeed!')
})
})
})
app.listen(port, () => {
console.log(`Webhook is listening on port ${port}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment