-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
143 lines (118 loc) · 3.5 KB
/
index.js
File metadata and controls
143 lines (118 loc) · 3.5 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
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
import express from "express";
import crypto from "crypto";
import { runDecisionEngine } from "./engine/decisionEngine.js";
import { enforcePR } from "./engine/enforce.js";
import { saveDecision, readDecisions } from "./engine/decisionStore.js";
const app = express();
app.use(express.json());
const SECRET = process.env.GITHUB_SECRET;
// 🔥 Deduplication store with TTL (memory-safe)
const processedEvents = new Map();
const EVENT_TTL = 10 * 60 * 1000; // 10 minutes
// --- Verify GitHub Webhook Signature ---
function verifySignature(req) {
const signature = req.headers["x-hub-signature-256"];
if (!signature || !SECRET) return true;
const hmac = crypto.createHmac("sha256", SECRET);
const digest =
"sha256=" + hmac.update(JSON.stringify(req.body)).digest("hex");
try {
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(digest)
);
} catch {
return false;
}
}
// --- Webhook Handler ---
app.post("/webhook", async (req, res) => {
try {
// ✅ Signature verification
if (!verifySignature(req)) {
console.log("Invalid signature");
return res.sendStatus(401);
}
const deliveryId = req.headers["x-github-delivery"];
const event = req.headers["x-github-event"];
const now = Date.now();
// 🔥 Cleanup old events
for (const [id, timestamp] of processedEvents.entries()) {
if (now - timestamp > EVENT_TTL) {
processedEvents.delete(id);
}
}
// 🔥 Deduplication check
if (processedEvents.has(deliveryId)) {
console.log("Duplicate event ignored:", deliveryId);
return res.sendStatus(200);
}
processedEvents.set(deliveryId, now);
const normalized = {
event,
repo: req.body.repository?.full_name || null,
action: req.body.action || null,
pr: req.body.pull_request?.number || null,
timestamp: new Date().toISOString(),
};
console.log(
`EVENT: ${event} | ${normalized.repo} | PR #${normalized.pr}`
);
// --- Decision Engine ---
let decisions = runDecisionEngine(event, req.body);
// 🔥 Ensure push always produces decision
if (event === "push") {
decisions = [
{
contract: "MAIN_BRANCH_CHECK",
decision: "approve",
reason: "Push event validation"
}
];
console.log("DECISION: approve (push)");
}
// --- v0.3: Save Decision ---
const record = {
id: deliveryId,
event,
repo: normalized.repo,
pr: normalized.pr,
sha: req.body.pull_request?.head?.sha || req.body.after,
decisions,
timestamp: new Date().toISOString()
};
console.log("SAVING DECISION:", record.id);
saveDecision(record);
// --- Enforcement ---
if (decisions && decisions.length > 0) {
await enforcePR(decisions, req.body);
}
res.sendStatus(200);
} catch (err) {
console.error("Webhook error:", err);
res.sendStatus(500);
}
});
// --- Health Check ---
app.get("/", (_, res) => {
res.send("Manthan Webhook Running");
});
// --- Query Decisions (v0.3.1) ---
app.get("/decisions", (req, res) => {
try {
const { repo, pr, sha } = req.query;
const results = readDecisions({ repo, pr, sha });
res.json({
count: results.length,
results
});
} catch (err) {
console.error("Query error:", err);
res.sendStatus(500);
}
});
// --- Server Start ---
const PORT = process.env.PORT || 8080;
app.listen(PORT, "0.0.0.0", () => {
console.log(`🚀 Manthan running on port ${PORT}`);
});