-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (90 loc) · 2.98 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const debug = require('debug')('vhs-hookhub-github-nomos')
debug('Loading vhs-hookhub-github-nomos')
debug(__dirname)
const express = require('express')
const router = express.Router()
const config = require('./config.json')
const { xHubSignatureMiddleware } = require('x-hub-signature-middleware')
const smb = require('slack-message-builder')
// Perform sanity check
router.use(function (req, res, next) {
if (
req.header('X-Hub-Signature') == null ||
req.header('X-Hub-Signature').length < 40 ||
req.header('X-GitHub-Event') == undefined ||
req.header('X-GitHub-Event') == '' ||
req.rawBody == undefined
) {
res.status(412).send({
result: 'ERROR',
message: 'Missing or invalid request arguments'
})
} else {
next()
}
})
// Check X-Hub-Signature
router.use(
xHubSignatureMiddleware({
algorithm: 'sha1',
secret: config.github.secret,
require: true,
getRawBody: (req) => req.rawBody
})
)
/* Default handler. */
router.use('/', async function (req, res, next) {
debug('Handling default request')
let post_body = generateMessage(req.header('X-GitHub-Event'), req.body)
debug('post_body:', post_body)
const post_options = {
method: 'POST',
body: JSON.stringify(post_body)
}
try {
const data = await (await fetch(config.slack.url, post_options)).json()
res.send({
result: 'OK',
message: data
})
} catch (err) {
res.status(500).send({
result: 'ERROR',
message: err
})
}
})
module.exports = router
const generateMessage = function (event_type, payload) {
let slack_message = smb()
.username(config.slack.options.username)
.iconEmoji(config.slack.options.icon_emoji)
.channel(config.slack.options.channel)
if (event_type === 'push') {
payload.commits.forEach(function (commit) {
slack_message = slack_message
.text("The following commit(s) got pushed to '" + payload.repository.name + "':\r\r")
.attachment()
.fallback('Required plain-text summary of the attachment.')
.color('#0000cc')
.authorName(payload.sender.login)
.authorLink(payload.sender.html_url)
.authorIcon(payload.sender.avatar_url)
.title('Commit: ' + commit.id)
.titleLink(commit.url)
.text(commit.message)
.footer('Via: vhs-hookhub-github-nomos')
.ts(Math.round(Date.parse(commit.timestamp) / 1000))
.end()
})
} else {
slack_message = slack_message.text(
"We received a new '" +
event_type +
"' notification for '" +
payload.repository.name +
"', but we didn't know what to do with this event!"
)
}
return slack_message.json()
}