-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
97 lines (83 loc) · 2.64 KB
/
app.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
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const fs = require("fs");
const app = express();
const exec = require("child_process").exec;
const crypto = require("crypto");
const execCallback = (err, stdout, stderr, next) => {
if (stdout) console.log(stdout);
if (stderr) console.error(stderr);
if (err) console.error(err);
if (next && typeof next === "function") next();
};
const createSignature = (body) => {
const hmac = crypto.createHmac(
"sha1",
process.env.PICD_GITHUB_WEBHOOK_SECRET
);
const signature = hmac.update(JSON.stringify(body)).digest("hex");
return `sha1=${signature}`;
};
const compareSignature = (remoteSignature, localSignature) => {
const remote = Buffer.from(remoteSignature);
const local = Buffer.from(localSignature);
return crypto.timingSafeEqual(remote, local);
};
const verifySignature = (req, res, next) => {
const { headers, body } = req;
const remoteSignature = headers["x-hub-signature"];
if (
remoteSignature &&
!compareSignature(remoteSignature, createSignature(body))
) {
return res.status(401).send("Signature mismatch! Get fucked loser!");
}
next();
};
const handlePush = (req, res) => {
console.log(
`${req.body.sender.login} updated ${req.body.repository.full_name}`
);
const projectPath = path.join(process.env.PICD_BASEPATH, req.body.repository.name);
fs.access(projectPath, fs.constants.F_OK, (err) => {
if (err) {
console.error(err);
res.sendStatus(500);
return res.end();
}
// reset local changes if any
exec(`git -C ${projectPath} reset --hard`, (err, stdout, stderr) =>
execCallback(err, stdout, stderr, () => {
// ditch local files if any
exec(`git -C ${projectPath} clean -df`, (err, stdout, stderr) =>
execCallback(err, stdout, stderr, () => {
// pull latest
exec(`git -C ${projectPath} pull`, (err, stdout, stderr) =>
execCallback(err, stdout, stderr, () => {
// restart process
exec(`pm2 restart ${req.body.repository.name}`, execCallback);
})
);
})
);
})
);
res.sendStatus(200);
res.end();
});
};
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.sendStatus(500);
res.end();
});
app.get("/github-push-webhook", (req, res) => {
res.sendStatus(200);
res.end();
});
app.post("/github-push-webhook", verifySignature, handlePush);
app.listen(process.env.PICD_PORT, () => {
console.log(`[Pi-CD] listening on ${process.env.PICD_PORT}`);
});