From 03670fb350e817c00866a87d51e7ede4ebb7acf5 Mon Sep 17 00:00:00 2001 From: Julian Duque Date: Sat, 14 Feb 2015 10:48:33 -0500 Subject: [PATCH] improve and secure deploy process This will avoid DDoS on /update route adding proper github webhooks validation, better deploy solutions were suggested in #40 but this will suffice from now --- config.template.json | 9 ++++++--- package.json | 3 ++- server.js | 38 +++++++++++++++++++++++++++----------- 3 files changed, 35 insertions(+), 15 deletions(-) diff --git a/config.template.json b/config.template.json index 311dd8c5..1417e1db 100644 --- a/config.template.json +++ b/config.template.json @@ -1,5 +1,8 @@ { - "meetup": { - "apiKey": "xxxxxxxxx" - } + "meetup": { + "apiKey": "xxxxxxxxx" + }, + "github": { + "secret": "xxxxxxxxxx" + } } diff --git a/package.json b/package.json index 9c6624e3..54ea9b8b 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,8 @@ "dependencies": { "async": "^0.9.0", "express": "^4.7.2", - "harp": "^0.14.0", + "github-webhook-middleware": "0.0.2", + "harp": "^0.15.2", "moment": "^2.5.1", "morgan": "^1.2.2", "request": "^2.39.0" diff --git a/server.js b/server.js index 311a9cac..41eec817 100644 --- a/server.js +++ b/server.js @@ -1,11 +1,18 @@ +'use strict'; + var express = require('express'), - harp = require('harp'), - path = require('path'), - fs = require('fs'), + webhook = require('github-webhook-middleware'), exec = require('child_process').exec, + config = require('./config'), events = require('./events'), router = require('./router'), - app = express(); + app = express(), + port = process.env.PORT || 8080; + +// Setup Github Webhooks +var validateWebhook = webhook({ + secret: config.github.secret +}); // Static Server app.use(express.static(__dirname + '/public')); @@ -16,23 +23,32 @@ app.use(router); // Fetch Events app.get('/events.json', function (req, res) { events(function (err, data) { - if (err) { + if (err) return res.status(500).send(err.message); - } res.send(data); }); }); // Update site -app.post('/update', function (req, res) { +app.post('/update', validateWebhook, function (req, res) { + if (req.headers['x-github-event'] !== 'push') + return res.status(200).json({ status: 'nothing to do' }); + exec('git pull && grunt build', function (err, stdout, stderr) { - if (err) return; + if (err) return res.status(500).send(err.message); + // Log git and grunt output console.log(stdout); - throw new Error('Restart action required'); + console.error(stderr); + + res.status(200).json({ status: 'ok' }); + + // Restart node process after update + process.exit(0); }); }); -app.listen(8080); -console.log("MedellinJS started"); +app.listen(port, function () { + console.log('MedellinJS listening on http://localhost:%s', port); +});