-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (61 loc) · 2.02 KB
/
server.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict'
require('dotenv').load({ silent: true })
const http = require('http')
const bl = require('bl')
const glob = require('glob')
const crypto = require('crypto')
const debug = require('debug')('server')
const url = process.env.WEBHOOK_URL || '/'
const port = process.env.PORT || 3000
const scripts = process.env.SCRIPTS || './scripts/**/*.js'
const secret = process.env.GITHUB_WEBHOOK_SECRET
const sign = (blob) => 'sha1=' + crypto.createHmac('sha1', secret).update(blob).digest('hex')
http.ServerResponse.prototype.status = function (code, message) {
this.statusCode = code
this.statusMessage = message
return this
}
const app = http.createServer((req, res) => {
var action;
res.on('finish', () => {
console.log(`${req.method} ${req.url}#${action} => ${res.statusCode} ${res.statusMessage}`)
})
if (req.method !== 'POST' && req.url !== url) {
return res.status(404).end()
}
const event = req.headers['x-github-event']
const signature = req.headers['x-hub-signature']
if (!event) return res.status(400, 'Missing x-github-event Header').end()
if (!signature) return res.status(400, 'Missing x-hub-signature Header').end()
req.pipe(bl(function (err, data) {
if (err) return res.status(400, 'Error reading input').end()
if (secret && signature !== sign(data)) {
return res.status(400, 'Signature mismatch').end()
}
data = tryParseJSON(data)
if (!data) return res.status(400, 'Invalid JSON').end()
const repo = data.repository.name
const org = data.repository.owner.login || data.organization.login
action = data.action = data.action ? event + '.' + data.action : event
debug(data)
app.emit(data.action, data, org, repo)
res.end()
}))
})
.listen(port, () => {
console.log('orgbot listening on port', port)
})
// load the scripts
glob.sync(scripts).forEach((file) => {
console.log('Loading:', file)
require(file)(app)
})
function tryParseJSON (data) {
data = String(data)
try {
return JSON.parse(data)
} catch (e) {
debug(data)
debug(e)
}
}