Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
157 lines (122 loc) · 3.94 KB
/
Copy pathserver.ts
File metadata and controls
157 lines (122 loc) · 3.94 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import { getBot, handlePullRequestEvent } from "@/lib/bot";
import { env } from "@/lib/env";
import { parseError } from "@/lib/error";
import { removeStaleWorkspaces } from "@/lib/workspace";
const WEBHOOK_PATHS = new Set(["/webhook", "/api/webhooks"]);
const readBody = async (request: IncomingMessage): Promise<string> => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(chunk as Buffer);
}
return Buffer.concat(chunks).toString("utf8");
};
const verifySignature = (body: string, signature: string | undefined): boolean => {
if (!signature) {
return false;
}
const expected = `sha256=${createHmac("sha256", env.GITHUB_APP_WEBHOOK_SECRET)
.update(body)
.digest("hex")}`;
const received = Buffer.from(signature);
const computed = Buffer.from(expected);
return (
received.length === computed.length && timingSafeEqual(received, computed)
);
};
const toHeaders = (request: IncomingMessage): Headers => {
const headers = new Headers();
for (const [key, value] of Object.entries(request.headers)) {
if (typeof value === "string") {
headers.set(key, value);
}
}
return headers;
};
const respond = (
response: ServerResponse,
status: number,
body: string
): void => {
response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
response.end(body);
};
const handleWebhook = async (
request: IncomingMessage,
response: ServerResponse
): Promise<void> => {
const body = await readBody(request);
if (!verifySignature(body, request.headers["x-hub-signature-256"] as string)) {
respond(response, 401, "Invalid signature");
return;
}
const event = request.headers["x-github-event"] as string | undefined;
if (event === "pull_request") {
let payload: Parameters<typeof handlePullRequestEvent>[0];
try {
payload = JSON.parse(body);
} catch {
respond(response, 400, "Invalid JSON");
return;
}
respond(response, 202, "accepted");
handlePullRequestEvent(payload).catch((error: unknown) => {
console.error(`[webhook] pull_request failed: ${parseError(error)}`);
});
return;
}
const bot = await getBot();
const handler = bot.webhooks.github;
if (!handler) {
respond(response, 404, "GitHub adapter not configured");
return;
}
const url = `http://${request.headers.host ?? "localhost"}${request.url ?? "/"}`;
const webhookRequest = new Request(url, {
body,
headers: toHeaders(request),
method: "POST",
});
const webhookResponse = await handler(webhookRequest, {
waitUntil: (task) => {
task.catch((error: unknown) => {
console.error(`[webhook] handler failed: ${parseError(error)}`);
});
},
});
respond(response, webhookResponse.status, await webhookResponse.text());
};
const server = createServer((request, response) => {
const path = (request.url ?? "/").split("?")[0];
const route = async (): Promise<void> => {
if (request.method === "GET" && (path === "/healthz" || path === "/")) {
respond(response, 200, "ok");
return;
}
if (request.method === "POST" && WEBHOOK_PATHS.has(path)) {
await handleWebhook(request, response);
return;
}
respond(response, 404, "not found");
};
route().catch((error: unknown) => {
console.error(`[server] request failed: ${parseError(error)}`);
if (!response.headersSent) {
respond(response, 500, "internal error");
}
});
});
const start = async (): Promise<void> => {
await removeStaleWorkspaces();
server.listen(env.PORT, env.HOST, () => {
console.log(
`[server] openreview listening on http://${env.HOST}:${env.PORT}`
);
});
};
start().catch((error: unknown) => {
console.error(`[server] failed to start: ${parseError(error)}`);
process.exit(1);
});