-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
594 lines (501 loc) · 15.9 KB
/
server.js
File metadata and controls
594 lines (501 loc) · 15.9 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { createServer } from "node:http";
import { readFile, writeFile, mkdir, access } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";
import {
createHash,
createHmac,
randomBytes,
scryptSync,
timingSafeEqual,
} from "node:crypto";
import { reviewSubmission } from "./gemini.js";
import {
fetchGitHubPullRequest,
mergeGitHubIntoInput,
postGitHubComment,
} from "./github.js";
dotenv.config({ quiet: true });
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, "public");
const dataDir = path.join(__dirname, "data");
const storePath = path.join(dataDir, "store.json");
const port = Number(process.env.PORT || 3000);
const sessionSecret = process.env.SESSION_SECRET || "local-dev-session-secret";
const auth0Domain = process.env.AUTH0_DOMAIN || "";
const auth0ClientId = process.env.AUTH0_CLIENT_ID || "";
const auth0ClientSecret = process.env.AUTH0_CLIENT_SECRET || "";
const auth0CallbackUrl =
process.env.AUTH0_CALLBACK_URL || `http://localhost:${port}/auth/auth0/callback`;
const auth0BaseUrl = auth0Domain ? `https://${auth0Domain}` : "";
const mimeTypes = {
".css": "text/css; charset=utf-8",
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
};
const sessions = new Map();
const auth0States = new Map();
async function ensureStore() {
await mkdir(dataDir, { recursive: true });
try {
await access(storePath);
} catch {
await writeFile(
storePath,
JSON.stringify({ users: [], reviews: [] }, null, 2),
"utf8",
);
}
}
async function readStore() {
await ensureStore();
const raw = await readFile(storePath, "utf8");
return JSON.parse(raw);
}
async function writeStore(store) {
await writeFile(storePath, JSON.stringify(store, null, 2), "utf8");
}
function sendJson(response, statusCode, data) {
response.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
});
response.end(JSON.stringify(data));
}
function sendRedirect(response, location) {
response.writeHead(302, { Location: location });
response.end();
}
function parseCookies(request) {
const cookieHeader = request.headers.cookie || "";
const cookies = {};
for (const part of cookieHeader.split(";")) {
const [key, ...rest] = part.trim().split("=");
if (!key) {
continue;
}
cookies[key] = decodeURIComponent(rest.join("="));
}
return cookies;
}
function signValue(value) {
return createHmac("sha256", sessionSecret).update(value).digest("hex");
}
function setSessionCookie(response, sessionId) {
const signed = `${sessionId}.${signValue(sessionId)}`;
response.setHeader(
"Set-Cookie",
`pr_review_session=${encodeURIComponent(signed)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=604800`,
);
}
function clearSessionCookie(response) {
response.setHeader(
"Set-Cookie",
"pr_review_session=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0",
);
}
function getVerifiedSessionId(request) {
const cookies = parseCookies(request);
const raw = cookies.pr_review_session;
if (!raw) {
return null;
}
const [sessionId, signature] = raw.split(".");
if (!sessionId || !signature) {
return null;
}
const expected = signValue(sessionId);
const actualBuffer = Buffer.from(signature);
const expectedBuffer = Buffer.from(expected);
if (
actualBuffer.length !== expectedBuffer.length ||
!timingSafeEqual(actualBuffer, expectedBuffer)
) {
return null;
}
return sessionId;
}
async function getAuthenticatedUser(request) {
const sessionId = getVerifiedSessionId(request);
if (!sessionId) {
return null;
}
const session = sessions.get(sessionId);
if (!session) {
return null;
}
const store = await readStore();
const user = store.users.find((entry) => entry.id === session.userId);
if (!user) {
sessions.delete(sessionId);
return null;
}
return sanitizeUser(user);
}
function sanitizeUser(user) {
return {
id: user.id,
name: user.name,
email: user.email,
authProvider: user.authProvider,
avatarUrl: user.avatarUrl || "",
initials: getInitials(user.name || user.email),
};
}
function getInitials(value) {
return value
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toUpperCase() || "")
.join("") || "U";
}
function hashPassword(password) {
const salt = randomBytes(16).toString("hex");
const hash = scryptSync(password, salt, 64).toString("hex");
return `${salt}:${hash}`;
}
function verifyPassword(password, stored) {
const [salt, existingHash] = stored.split(":");
const computed = scryptSync(password, salt, 64).toString("hex");
return timingSafeEqual(Buffer.from(existingHash), Buffer.from(computed));
}
function createId(prefix) {
return `${prefix}_${randomBytes(8).toString("hex")}`;
}
function createSession(response, userId) {
const sessionId = createId("sess");
sessions.set(sessionId, {
userId,
createdAt: new Date().toISOString(),
});
setSessionCookie(response, sessionId);
}
async function readRequestBody(request) {
const chunks = [];
for await (const chunk of request) {
chunks.push(chunk);
}
return Buffer.concat(chunks).toString("utf8");
}
function extractReviewMeta(review, input) {
const ratingMatch = review.match(/## Rating\s+(.+)/i);
const summaryMatch = review.match(/## Summary\s+([\s\S]*?)(?:##|$)/i);
return {
rating: ratingMatch ? ratingMatch[1].trim() : "No rating",
summary: summaryMatch
? summaryMatch[1].trim().replace(/\s+/g, " ").slice(0, 180)
: "Saved review",
label:
input.prUrl ||
input.issueUrl ||
input.prText.split("\n").find(Boolean) ||
"PR review",
};
}
async function handleSignup(request, response) {
try {
const body = JSON.parse((await readRequestBody(request)) || "{}");
const name = (body.name || "").trim();
const email = (body.email || "").trim().toLowerCase();
const password = body.password || "";
if (!name || !email || !password) {
sendJson(response, 400, { error: "Name, email, and password are required." });
return;
}
const store = await readStore();
const existing = store.users.find((user) => user.email === email);
if (existing) {
sendJson(response, 400, { error: "An account with this email already exists." });
return;
}
const user = {
id: createId("user"),
name,
email,
passwordHash: hashPassword(password),
authProvider: "email",
avatarUrl: "",
createdAt: new Date().toISOString(),
};
store.users.push(user);
await writeStore(store);
createSession(response, user.id);
sendJson(response, 201, { user: sanitizeUser(user), reviews: [] });
} catch (error) {
sendJson(response, 400, { error: error.message || "Unable to create account." });
}
}
async function handleLogin(request, response) {
try {
const body = JSON.parse((await readRequestBody(request)) || "{}");
const email = (body.email || "").trim().toLowerCase();
const password = body.password || "";
const store = await readStore();
const user = store.users.find((entry) => entry.email === email);
if (!user || user.authProvider !== "email" || !verifyPassword(password, user.passwordHash)) {
sendJson(response, 401, { error: "Invalid email or password." });
return;
}
createSession(response, user.id);
const reviews = store.reviews
.filter((review) => review.userId === user.id)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
sendJson(response, 200, { user: sanitizeUser(user), reviews });
} catch (error) {
sendJson(response, 400, { error: error.message || "Unable to log in." });
}
}
function handleLogout(response) {
clearSessionCookie(response);
sendJson(response, 200, { success: true });
}
async function handleMe(request, response) {
const user = await getAuthenticatedUser(request);
if (!user) {
sendJson(response, 200, {
user: null,
reviews: [],
googleAuthEnabled: Boolean(auth0Domain && auth0ClientId && auth0ClientSecret),
githubIntegrationEnabled: Boolean(process.env.GITHUB_TOKEN),
});
return;
}
const store = await readStore();
const reviews = store.reviews
.filter((review) => review.userId === user.id)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
sendJson(response, 200, {
user,
reviews,
googleAuthEnabled: Boolean(auth0Domain && auth0ClientId && auth0ClientSecret),
githubIntegrationEnabled: Boolean(process.env.GITHUB_TOKEN),
});
}
async function handleGitHubFetch(request, response) {
const user = await getAuthenticatedUser(request);
if (!user) {
sendJson(response, 401, { error: "Please log in to fetch pull requests." });
return;
}
try {
const body = JSON.parse((await readRequestBody(request)) || "{}");
const githubPr = await fetchGitHubPullRequest(body.prUrl || "");
sendJson(response, 200, { githubPr });
} catch (error) {
sendJson(response, 400, { error: error.message || "Unable to fetch this PR." });
}
}
async function handleReview(request, response) {
const user = await getAuthenticatedUser(request);
if (!user) {
sendJson(response, 401, { error: "Please log in to create and save reviews." });
return;
}
try {
const body = JSON.parse((await readRequestBody(request)) || "{}");
const input = {
issueUrl: body.issueUrl || "",
issueText: body.issueText || "",
prUrl: body.prUrl || "",
prText: body.prText || "",
previousCode: body.previousCode || "",
currentCode: body.currentCode || "",
companyName: body.companyName || "",
companyGuidelines: body.companyGuidelines || "",
};
let githubPr = null;
if (body.fetchFromGitHub && input.prUrl) {
githubPr = await fetchGitHubPullRequest(input.prUrl);
}
const reviewInput = githubPr ? mergeGitHubIntoInput(input, githubPr) : input;
const review = await reviewSubmission(reviewInput);
let githubComment = null;
if (body.postComment && input.prUrl) {
githubComment = await postGitHubComment(
input.prUrl,
`## Automated PR Review\n\n${review}`,
);
}
const meta = extractReviewMeta(review, input);
const store = await readStore();
const record = {
id: createId("review"),
userId: user.id,
createdAt: new Date().toISOString(),
input,
review,
meta,
githubPr: githubPr
? {
title: githubPr.title,
author: githubPr.author,
changedFiles: githubPr.changedFiles,
additions: githubPr.additions,
deletions: githubPr.deletions,
headBranch: githubPr.headBranch,
baseBranch: githubPr.baseBranch,
htmlUrl: githubPr.htmlUrl,
}
: null,
githubCommentUrl: githubComment?.html_url || "",
};
store.reviews.push(record);
await writeStore(store);
sendJson(response, 200, {
review,
reviewRecord: record,
githubPr: record.githubPr,
githubCommentUrl: record.githubCommentUrl,
});
} catch (error) {
sendJson(response, 400, { error: error.message || "Unable to review this submission." });
}
}
async function handleAuth0GoogleStart(response) {
if (!auth0Domain || !auth0ClientId || !auth0ClientSecret) {
sendRedirect(response, "/?auth=google_not_configured");
return;
}
const state = randomBytes(12).toString("hex");
auth0States.set(state, Date.now());
const params = new URLSearchParams({
client_id: auth0ClientId,
redirect_uri: auth0CallbackUrl,
response_type: "code",
scope: "openid email profile",
connection: "google-oauth2",
prompt: "login",
state,
});
sendRedirect(response, `${auth0BaseUrl}/authorize?${params.toString()}`);
}
async function handleAuth0Callback(request, response, url) {
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
if (!code || !state || !auth0States.has(state)) {
sendRedirect(response, "/?auth=google_failed");
return;
}
auth0States.delete(state);
try {
const tokenResponse = await fetch(`${auth0BaseUrl}/oauth/token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code,
client_id: auth0ClientId,
client_secret: auth0ClientSecret,
redirect_uri: auth0CallbackUrl,
grant_type: "authorization_code",
}),
});
const tokenData = await tokenResponse.json();
if (!tokenResponse.ok || !tokenData.access_token) {
throw new Error("Auth0 token exchange failed.");
}
const userResponse = await fetch(`${auth0BaseUrl}/userinfo`, {
headers: {
Authorization: `Bearer ${tokenData.access_token}`,
},
});
const auth0User = await userResponse.json();
if (!userResponse.ok || !auth0User.email) {
throw new Error("Auth0 user profile fetch failed.");
}
const store = await readStore();
let user = store.users.find(
(entry) => entry.auth0Sub === auth0User.sub || entry.email === auth0User.email,
);
if (!user) {
user = {
id: createId("user"),
name: auth0User.name || auth0User.email,
email: auth0User.email,
authProvider: "google",
avatarUrl: auth0User.picture || "",
auth0Sub: auth0User.sub,
createdAt: new Date().toISOString(),
};
store.users.push(user);
} else {
user.name = auth0User.name || user.name;
user.avatarUrl = auth0User.picture || user.avatarUrl || "";
user.auth0Sub = auth0User.sub || user.auth0Sub;
user.authProvider = "google";
}
await writeStore(store);
createSession(response, user.id);
sendRedirect(response, "/");
} catch {
sendRedirect(response, "/?auth=google_failed");
}
}
async function handleStaticFile(pathname, response) {
const requestPath = pathname === "/" ? "/index.html" : pathname;
const filePath = path.join(publicDir, requestPath);
try {
const file = await readFile(filePath);
const extension = path.extname(filePath);
response.writeHead(200, {
"Content-Type": mimeTypes[extension] || "text/plain; charset=utf-8",
});
response.end(file);
} catch {
response.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8",
});
response.end("Not found");
}
}
const server = createServer(async (request, response) => {
const url = new URL(request.url || "/", `http://${request.headers.host}`);
const { pathname } = url;
if (request.method === "GET" && pathname === "/api/me") {
await handleMe(request, response);
return;
}
if (request.method === "POST" && pathname === "/api/signup") {
await handleSignup(request, response);
return;
}
if (request.method === "POST" && pathname === "/api/login") {
await handleLogin(request, response);
return;
}
if (request.method === "POST" && pathname === "/api/logout") {
handleLogout(response);
return;
}
if (request.method === "POST" && pathname === "/api/review") {
await handleReview(request, response);
return;
}
if (request.method === "POST" && pathname === "/api/github/fetch-pr") {
await handleGitHubFetch(request, response);
return;
}
if (request.method === "GET" && pathname === "/auth/google/start") {
await handleAuth0GoogleStart(response);
return;
}
if (request.method === "GET" && pathname === "/auth/auth0/callback") {
await handleAuth0Callback(request, response, url);
return;
}
if (request.method === "GET") {
await handleStaticFile(pathname, response);
return;
}
response.writeHead(405, {
"Content-Type": "text/plain; charset=utf-8",
});
response.end("Method not allowed");
});
server.listen(port, () => {
console.log(`PR Review Agent UI running at http://localhost:${port}`);
});