-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook-server.cjs
More file actions
80 lines (68 loc) · 2.65 KB
/
webhook-server.cjs
File metadata and controls
80 lines (68 loc) · 2.65 KB
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
const http = require('http');
const { exec } = require('child_process');
const crypto = require('crypto');
require('dotenv').config();
const PORT = process.env.WEBHOOK_PORT || 9903;
const SECRET = process.env.WEBHOOK_SECRET || '';
const TARGET_BRANCH = 'refs/heads/main';
let deploying = false;
function verifySignature(payload, signature) {
if (!SECRET) return true;
const hmac = crypto.createHmac('sha256', SECRET);
const digest = 'sha256=' + hmac.update(payload).digest('hex');
return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature));
}
http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const signature = req.headers['x-hub-signature-256'];
if (SECRET && (!signature || !verifySignature(body, signature))) {
console.warn('Invalid webhook signature');
res.writeHead(401);
res.end('Unauthorized\n');
return;
}
const payload = JSON.parse(body);
const branch = payload.ref;
if (branch !== TARGET_BRANCH) {
console.log(`Push to ${branch} ignored.`);
res.writeHead(200);
res.end('Ignored.\n');
return;
}
if (deploying) {
console.log('Deploy already in progress, skipping.');
res.writeHead(200);
res.end('Deploy already in progress.\n');
return;
}
deploying = true;
console.log(`Push detected to ${branch}. Running deployment script...`);
exec('/storage/www/storno/docs/deploy.sh', (err, stdout, stderr) => {
deploying = false;
if (err) {
console.error('Deploy failed:', stderr);
} else {
console.log('Deploy complete:', stdout);
}
});
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Deploy started.\n');
} catch (e) {
console.error('Failed to parse payload:', e);
res.writeHead(400);
res.end('Invalid payload\n');
}
});
} else {
res.writeHead(405);
res.end('Method Not Allowed\n');
}
}).listen(PORT, () => {
console.log(`Webhook listener running on port ${PORT}`);
});