-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
382 lines (302 loc) · 11.1 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
const EventEmitter = require('events');
const express = require('express');
const fs = require('fs').promises;
const Queue = require('./Queue');
const crypto = require('crypto');
const { processWebhookPayload } = require('./utils');
const child_process = require('child_process');
/**
* @class
* @classdesc The Pipeliner class creates objects that listens to GitHub webhooks and emit events
*
* @fires Pipeliner#push
* @fires Pipeliner#pull_request
* @fires Pipeliner#merge
* @fires Pipeliner#release
* @fires Pipeliner#new_branch
* @fires Pipeliner#new_tag
* @fires Pipeliner#unauthorized_webhook
*/
class Pipeliner extends EventEmitter {
_isSignatureValid(signature, body) {
const json = JSON.stringify(body);
const expectedSignature = crypto.createHmac('sha256', this._hmacSecret).update(json).digest('hex');
return expectedSignature == signature;
}
async _doesPathExists(path) {
try {
await fs.stat(path);
return true;
} catch {
return false;
}
}
_runCommand(cmd, args=[]) {
return new Promise(resolve => {
let output = '';
let stderr = '';
let stdout = '';
const spawned = child_process.spawn(cmd, args);
spawned.stdout.setEncoding("utf-8");
spawned.stderr.setEncoding("utf-8");
spawned.stderr.on("data", (data) => {
stderr += data;
output += data;
});
spawned.stdout.on('data', (data) => {
stdout += data;
output += data;
});
let err = null;
let hasErred = false;
spawned.on("error", (error) => {
err = error;
hasErred = true
});
spawned.on('close', () => {
resolve({
hasErred,
err,
output,
stdout,
stderr,
});
});
})
}
_processWebhook = async (payload) => {
const result = processWebhookPayload(payload);
const {
event,
organization,
repository,
} = result;
// emit events
if (event) {
/**
*
* Emmitted when a new tag is created on a repository
*
* @event Pipeliner#new_tag
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.tag Name of the tag created
* @property {string} data.branch The branch on which the tag was created
*/
/**
*
* Emmitted when a new branch is created on a repository
*
* @event Pipeliner#new_branch
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.branch Name of branch that was created
*/
/**
*
* Emmitted when a new release is created on a repository
*
* @event Pipeliner#release
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.branch Name of branch the realease was created from
* @property {string} data.tag Name of tag the release was created from
*/
/**
*
* Emmitted when changes are pushed to a repository
*
* @event Pipeliner#push
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.branch Name of the branch the changes were pushed to
*/
/**
*
* Emmitted when a pull request is made
*
* @event Pipeliner#pull_request
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.branch Name of branch requesting to be merged
* @property {string} data.base_branch Name of branch the changes are supposed to be merged to
*/
/**
*
* Emmitted when two branches are merged
*
* @event Pipeliner#merge
* @type {object}
* @property {string} organization GitHub organization name
* @property {string} repository GitHub repository name
* @property {object} originalPayload Original data send by GitHub
* @property {object} data
* @property {string} data.branch Name of branch that was requested to be merged
* @property {string} data.base_branch Base branch
*/
this.emit(event, result);
}
/**
* This events has all the headers and body from GitHub. You can extend the capabilities using this package by listening to this event
*
* @event Pipeliner#webhook
* @type {object}
* @property {object} headers - Headers sent by GitHub
* @property {object} body - The body of the request send by GitHub
*/
this.emit('webhook', payload);
// run scripts if available
const repoPath = `${this._scriptsPath}/${organization}/${repository}`;
const nodeScriptPath = `${repoPath}/${event}.js`;
const bashScriptPath = `${repoPath}/${event}.sh`;
const bashScriptExists = await this._doesPathExists(bashScriptPath);
const nodeScriptExists = await this._doesPathExists(nodeScriptPath);
if (bashScriptExists) {
const response = await this._runCommand('bash', [ bashScriptPath ]);
const { hasErred, err, output, stdout, stderr } = response;
try {
await this.notify(hasErred, err, output, stdout, stderr);
} catch {};
}
if (nodeScriptExists) {
const response = await this._runCommand('node', [ nodeScriptPath ]);
const { hasErred, err, output, stdout, stderr } = response;
try {
await this.notify(hasErred, err, output, stdout, stderr);
} catch {};
}
}
_endpointHandler = async (req, res) => {
// send response immediately
res.sendStatus(200);
// validate signature
const { body, headers } = req;
let signature = headers['x-hub-signature-256'];
let valid;
if (!signature) {
valid = false;
} else {
if (signature.indexOf('sha256=') === 0) {
signature = signature.substring("sha256=".length);
}
valid = this._isSignatureValid(signature, body);
}
if (!valid) {
/**
*
* This event is emitted an unauthroized client tries to send a webhook event
*
* @event Pipeliner#unauthorized_webhook
* @type {object} Headers from the request
*/
this.emit('unauthorized_webhook', headers);
return;
}
// add to queue
this._queue.add(() => this._processWebhook({ headers, body }));
}
/**
*
* To be overidden. It will be called when a script is finished with the output from the script
*
* @param {boolean} hasErred indicates whether the command was run successfully
* @param {Error} err The error that occured. null if hasErred is false
* @param {string} output both stdout and stderr logs
* @param {string} stdout stdout log
* @param {string} stderr stderr log
*/
async notify(hasErred, err, output, stdout, stderr) {
}
/**
* This method initialize the pipeliner to start listening for webhook events
* @returns {Promise}
*/
async init() {
if (!this._expressApp) {
// create an express app and listen on the provided port
this._expressApp = express();
this._expressApp.use(express.json());
this._expressApp.use(express.urlencoded({ extended: true }));
await (() => {
return new Promise(resolve => {
this._httpServer = this._expressApp.listen(this._port, resolve);
});
})();
this._usingExternalExpressApp = false;
} else {
this._usingExternalExpressApp = true;
}
// attach enndpoint handler to the route
this._expressApp.post(this._endpointPath, this._endpointHandler);
this._initialized = true;
}
/**
* This method stops the Pipeliner instance from listening to webhook events
* @returns {Promise}
*/
stop() {
if (!this._initialized)
return;
if (this._usingExternalExpressApp)
throw new Error('The server express app was not created inside Pipeliner');
return new Promise(resolve => {
this._httpServer.close(() => {
this._expressApp = null;
this._httpServer = null;
this._initialized = false;
resolve();
})
});
}
/**
*
* @param {object} options
* @param {object} options.expressApp an express application (created by require('express)())
* @param {object} options.port The port to make the express application listen to. Only used when options.expressApp was not passed
* @param {object} options.endpointPath The path the webhook events will be posted by GitHub
* @param {object} options.scriptsPath The path where scripts that response to events are stored
* @param {object} options.hmacSecret The secret used to verify if GitHub really sent the webhook events, not some ill-intended party
*/
constructor(options) {
const {
expressApp,
port=process.env.PORT,
endpointPath='/github-webhook',
scriptsPath=process.env.PWD,
hmacSecret,
} = options;
super();
// validate
if (!port && !expressApp) {
throw new Error('Provide either "port" or "expressApp"');
}
if (!hmacSecret) {
throw new Error('"hmacSecret" is required');
}
if (typeof hmacSecret !== 'string') {
throw new Error('"hmacSecret" value should be a string');
}
this._port = port;
this._expressApp = expressApp;
this._endpointPath = endpointPath;
this._scriptsPath = scriptsPath;
this._hmacSecret = hmacSecret;
this._queue = new Queue();
}
}
module.exports = Pipeliner;