|
| 1 | +const http = require('http'); |
| 2 | +const https = require('https'); |
| 3 | +const url = require('url'); |
| 4 | +const cp = require('child_process'); |
| 5 | + |
| 6 | +function reply (res, code) { |
| 7 | + res.writeHead(code); |
| 8 | + res.end(http.STATUS_CODES[code]); |
| 9 | +} |
| 10 | + |
| 11 | +function validate (u, state, cb) { |
| 12 | + console.log('validating webhook...'); |
| 13 | + const cbUrl = url.parse(u); |
| 14 | + |
| 15 | + const req = https.request({ |
| 16 | + method: 'POST', |
| 17 | + hostname: cbUrl.hostname, |
| 18 | + path: cbUrl.path |
| 19 | + }, (res) => { |
| 20 | + cb(null, res.statusCode); |
| 21 | + }); |
| 22 | + |
| 23 | + req.on('error', cb); |
| 24 | + |
| 25 | + req.write(JSON.stringify({ state: state })); |
| 26 | + req.end(); |
| 27 | +} |
| 28 | + |
| 29 | +http.createServer(function (req, res) { |
| 30 | + if (req.method === 'POST') { |
| 31 | + const parsedUrl = url.parse(req.url, true); |
| 32 | + |
| 33 | + if (parsedUrl.pathname === '/hook' && parsedUrl.query.token === process.env.DHH_TOKEN) { |
| 34 | + var body = ''; |
| 35 | + |
| 36 | + req.on('data', (chunk) => { |
| 37 | + body += chunk; |
| 38 | + }); |
| 39 | + |
| 40 | + req.on('end', () => { |
| 41 | + try { |
| 42 | + const payload = JSON.parse(body); |
| 43 | + if (payload.repository.repo_name === process.env.DHH_REPO && payload.push_data.tag === process.env.DHH_TAG) { |
| 44 | + console.log('executing command...'); |
| 45 | + cp.exec(process.env.DHH_CMD, { |
| 46 | + cwd: process.env.DHH_CWD |
| 47 | + }, function (err, stdout, stderr) { |
| 48 | + var state = 'success'; |
| 49 | + var code = 200; |
| 50 | + |
| 51 | + if (err) { |
| 52 | + console.error(err); |
| 53 | + state = 'failure'; |
| 54 | + code = 500; |
| 55 | + } else { |
| 56 | + console.log(stdout); |
| 57 | + console.log(stderr); |
| 58 | + } |
| 59 | + |
| 60 | + validate(payload.callback_url, state, (err, statusCode) => { |
| 61 | + if (err) { |
| 62 | + console.error(err); |
| 63 | + } |
| 64 | + console.log(`webhook callback response: ${statusCode}`); |
| 65 | + reply(res, code); |
| 66 | + }); |
| 67 | + }); |
| 68 | + } else { |
| 69 | + throw new Error('Mismatched repo or tag in payload'); |
| 70 | + } |
| 71 | + } catch (e) { |
| 72 | + console.error(e); |
| 73 | + reply(res, 400); |
| 74 | + } |
| 75 | + }); |
| 76 | + } else { |
| 77 | + console.log(`Ignoring ${req.method} ${req.url}`); |
| 78 | + reply(res, 404); |
| 79 | + } |
| 80 | + } else { |
| 81 | + console.log(`Ignoring ${req.method} ${req.url}`); |
| 82 | + reply(res, 404); |
| 83 | + } |
| 84 | +}).listen(process.env.DHH_PORT, () => { |
| 85 | + console.log('Server listening...'); |
| 86 | +}); |
0 commit comments