-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
86 lines (71 loc) · 2.48 KB
/
index.ts
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
import express, { type Request, type Response } from "express";
import crypto from "crypto";
import {
checkoutRepoPR,
commitAndPushChanges,
deleteRepo,
getTargetRepo,
runPrettier,
} from "./internals";
const app = express();
const port = 8080;
const GH_WH_SEC = process.env.GITHUB_WEBHOOK_SECRET ?? "";
if (!GH_WH_SEC) {
console.error("GITHUB_WEBHOOK_SECRET is not set");
process.exit(1);
}
app.use(express.json());
function verifySignature(req: Request, secret: string) {
const signature = (req.headers["x-hub-signature-256"] as string) || "";
const hmac = crypto.createHmac("sha256", secret);
const digest = `sha256=${hmac
.update(JSON.stringify(req.body))
.digest("hex")}`;
return crypto.timingSafeEqual(
new Uint8Array(Buffer.from(signature)),
new Uint8Array(Buffer.from(digest))
);
}
app.get("/", (req: Request, res: Response) => {
res.send("Hello from autogit! 🤖");
});
app.post("/gh", (req: Request, res: Response) => {
if (!verifySignature(req, GH_WH_SEC)) {
return res.status(401).send("Invalid signature");
}
const event = req.headers["x-github-event"];
const payload = req.body;
console.info(`Received event: ${event}`);
// console.info(JSON.stringify(payload, null, 2));
if (event === "pull_request") {
const action = payload.action;
const prNumber = payload.number;
const repo = payload.repository.full_name;
const user = payload.pull_request.user.login;
const skipUsers = ["autogit"];
if (skipUsers.includes(user)) {
console.info(`🛑 PR #${prNumber} is from ${user}, skipping...`);
return res.status(200).send("Webhook received");
}
const targetRepo = getTargetRepo(user);
const ref = payload.pull_request.head.ref;
const tempDir = crypto.randomUUID();
console.info(
`ℹ️ PR #${prNumber} action: ${action}, target ${targetRepo}, using temp directory: ${tempDir}`
);
try {
deleteRepo(tempDir);
checkoutRepoPR(targetRepo, ref, tempDir);
runPrettier(tempDir);
commitAndPushChanges(tempDir, user);
} catch (error) {
console.error("❌ Failed to process PR:", error);
} finally {
deleteRepo(tempDir);
}
}
res.status(200).send("Webhook received");
});
app.listen(port, () => {
console.info(`Server is running on http://localhost:${port}`);
});