-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
283 lines (219 loc) · 8.51 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
var Http = require('http');
var Https = require('https');
var Url = require('url');
var Querystring = require('querystring');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');
var Crypto = require('crypto');
function reply(statusCode, res) {
var message = { message: Http.STATUS_CODES[statusCode].toLowerCase() };
message.result = statusCode >= 400 ? 'error' : 'ok';
message = JSON.stringify(message);
var headers = {
'Content-Type': 'application/json',
'Content-Length': message.length
};
res.writeHead(statusCode, headers);
res.end(message);
}
function parse(data) {
var result;
try {
result = JSON.parse(data);
} catch (e) {
result = false;
}
return result;
}
function serverHandler(req, res) {
var self = this;
var url = Url.parse(req.url, true);
var buffer = [];
var bufferLength = 0;
var failed = false;
var isForm = false;
var remoteAddress;
if (this.trustProxy !== false) {
remoteAddress = req.headers['x-forwarded-for'];
}
remoteAddress = remoteAddress || req.ip || req.socket.remoteAddress || req.socket.socket.remoteAddress;
req.on('data', function (chunk) {
if (failed) {
return;
}
buffer.push(chunk);
bufferLength += chunk.length;
});
req.on('end', function (chunk) {
if (failed) {
return;
}
var data;
if (chunk) {
buffer.push(chunk);
bufferLength += chunk.length;
}
self.logger.log(Util.format('received %d bytes from %s', bufferLength, remoteAddress));
var event = req.headers['x-github-event'] || req.headers['x-gogs-event'] || req.headers['x-event-key'] || (req.headers['x-gitlab-event'] ? req.headers['x-gitlab-event'].split(' ')[0].toLowerCase() : 'unknown');
if (event === 'ping') {
self.emit(event, null, null, data);
return reply(200, res);
}
if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
isForm = true;
data = Buffer.concat(buffer, bufferLength).toString();
} else {
//this is already a string when sent as JSON
data = Buffer.concat(buffer, bufferLength);
}
self.getSecret(req, function (err, secret) {
if (err) {
self.logger.error(Util.format('error getting secret for %s, returning 403', res.url));
self.logger.error(err.stack);
return reply(403, res);
}
if (secret) {
var signature = req.headers['x-hub-signature'];
if (!signature) {
self.logger.error('secret configured, but missing signature, returning 403');
return reply(403, res);
}
signature = signature.replace(/^sha1=/, '');
var digest = Crypto.createHmac('sha1', secret).update(data).digest('hex');
if (signature !== digest) {
self.logger.error('got invalid signature, returning 403');
return reply(403, res);
}
}
if (isForm) {
data = Querystring.parse(data).payload;
}
data = parse(data);
// invalid json
if (!data) {
self.logger.error(Util.format('received invalid data from %s, returning 400', remoteAddress));
return reply(400, res);
}
data.request = req;
// handle GitLab system hook
if (event !== 'system'){
// invalid json
if (!data.repository || !data.repository.name) {
self.logger.error(Util.format('received incomplete data from %s, returning 400', remoteAddress));
return reply(400, res);
}
var repo = data.repository.name;
var ref = data.ref;
// and now we emit a bunch of data
if (ref) {
self.logger.log(Util.format('got %s event on %s:%s from %s', event, repo, ref, remoteAddress));
}
else {
self.logger.log(Util.format('got %s event on %s from %s', event, repo, remoteAddress));
}
self.emit('*', event, repo, ref, data);
self.emit(repo, event, ref, data);
self.emit(repo + ':' + ref, event, data);
self.emit(event, repo, ref, data);
self.emit(event + ':' + repo, ref, data);
self.emit(event + ':' + repo + ':' + ref, data);
} else {
var type = data.event_name;
// invalid json
if (!type) {
self.logger.error(Util.format('received incomplete data from %s, returning 400', remoteAddress));
return reply(400, res);
}
self.logger.log(Util.format('got %s event of type %s from %s', event, type, remoteAddress));
// and now we emit a bunch of data
self.emit('*', event, type, data);
self.emit(type, event, data);
}
reply(200, res);
});
});
self.logger.log(Util.format(req.method, req.url, remoteAddress));
// 404 if the path is wrong
if (!self.checkUrl(url)) {
self.logger.error(Util.format('got invalid path from %s, returning 404', remoteAddress));
failed = true;
return reply(404, res);
}
// 204 if healthchecks are enabled and it's a GET
// note that we flag the request as failed only to
// stop processing any further incoming request data
if (req.method === 'GET' && this.enableHealthcheck) {
failed = true;
return reply(this.healthcheckCode, res);
}
// 405 if the method is wrong
if (req.method !== 'POST') {
self.logger.error(Util.format('got invalid method from %s, returning 405', remoteAddress));
failed = true;
return reply(405, res);
}
// 400 if it's not a github, gitlab, or bitbucket event
if (!req.headers.hasOwnProperty('x-github-event') && !req.headers.hasOwnProperty('x-gitlab-event') && !req.headers.hasOwnProperty('x-gogs-event') && !req.headers.hasOwnProperty('x-event-key')) {
self.logger.error(Util.format('missing x-github-event, x-gitlab-event, x-gogs-event, or x-event-key header from %s, returning 400', remoteAddress));
failed = true;
return reply(400, res);
}
}
var GithubHook = function (options) {
if (!(this instanceof GithubHook)) {
return new GithubHook(options);
}
options = options || {};
this.port = options.port || 3420;
this.host = options.host || '0.0.0.0';
this.secret = options.secret || false;
this.logger = options.logger || console;
this.path = options.path || '/github/callback';
this.wildcard = options.wildcard || false;
this.trustProxy = options.trustProxy || false;
this.enableHealthcheck = options.enableHealthcheck || false;
this.healthcheckCode = options.healthcheckCode || 204;
if (options.https) {
this.server = Https.createServer(options.https, serverHandler.bind(this));
}
else {
this.server = Http.createServer(serverHandler.bind(this));
}
EventEmitter.call(this);
};
Util.inherits(GithubHook, EventEmitter);
GithubHook.prototype.listen = function (callback) {
var self = this;
self.server.listen(self.port, self.host, function () {
self.logger.log(Util.format('listening for hook events on %s:%d', self.host, self.port));
if (typeof callback === 'function') {
callback();
}
});
};
GithubHook.prototype.checkUrl = function (url) {
if (url.pathname === this.path) {
return true;
}
if (this.wildcard && (url.pathname.indexOf(this.path + '/') === 0)) {
return true;
}
return false;
};
GithubHook.prototype.stop = function (callback) {
var self = this;
self.server.close(function () {
self.logger.log('stopped listening for github events');
self.server = Http.createServer(serverHandler.bind(this));
if (typeof callback === 'function') {
callback();
}
});
};
GithubHook.prototype.getSecret = function (req, next) {
if (typeof this.secret === 'function') {
return this.secret(req, next);
}
return next(null, this.secret);
};
module.exports = GithubHook;