forked from Eshajha19/Algo-Infinity-Verse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3606 lines (3154 loc) · 121 KB
/
Copy pathserver.js
File metadata and controls
3606 lines (3154 loc) · 121 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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from "crypto";
import fs from "fs/promises";
import http from "http";
import express from "express";
import apiRouter from "./backend/routes/api.js";
import { execFile } from "child_process";
import path from "path";
import { fileURLToPath } from "url";
import { FieldValue } from "firebase-admin/firestore";
import { initializeFirebase, getDb, COLLECTIONS } from "./firebase.js";
import { verifyCsrfToken } from "./utils/csrf-verify.js";
import multer from "multer";
import { extractResumeText } from "./backend/resume-analyzer/parser.js";
import { calculateATS } from "./backend/resume-analyzer/atsScore.js";
import { findMissingSkills } from "./backend/resume-analyzer/skills.js";
import { getSuggestions } from "./backend/resume-analyzer/suggestions.js";
import { analyzeWorkflow } from "./backend/repository-analyzer/cicdValidator.js";
import { VCSFactory } from "./backend/vcs/VCSFactory.js";
import { enqueueBulkAudit, getBatchProgress, MAX_BULK_AUDIT_URLS } from "./backend/jobs/queue.js";
import "./backend/jobs/worker.js"; // Initialize worker
import { parse as csvParse } from "csv-parse/sync";
import { v4 as uuidv4 } from "uuid";
import { generateSdlcAdvice } from "./sdlcAdvisor.js";
const JUDGE0_LANGUAGE_IDS = {
python: 71,
javascript: 63,
java: 62,
'c++': 54,
cpp: 54,
c: 50,
typescript: 74,
go: 60,
rust: 73,
ruby: 72,
swift: 83,
dart: 98,
haskell: 89,
kotlin: 78,
};
import { handleReportRequest } from "./backend/reports/reportGenerator.js";
import { getUserBenchmark } from "./backend/benchmarking/percentileService.js";
import { Server as SocketIOServer } from "socket.io";
import {
ACCESS_TOKEN_MAX_AGE_SECONDS, REFRESH_TOKEN_MAX_AGE_SECONDS, getClientIdentifier, isSignupRateLimited,
recordSignupAttempt, normalizeAuthDelay, createAccessToken,
verifyAccessToken, hashPassword, passwordMatches, validateSignup,
createRefreshToken, verifyRefreshToken, revokeTokenFamily,
activeRefreshFamilies
} from "./backend/services/auth.service.js";
import {
applyRateLimit,
loginLimiter,
signupLimiter,
forgotPasswordLimiter,
changePasswordLimiter,
deleteAccountLimiter,
resendVerificationLimiter,
resumeAnalysisLimiter,
repoAnalysisLimiter,
sdlcAdvisorLimiter,
predictionLimiter,
bulkAuditLimiter,
logErrorLimiter
} from "./backend/utils/rateLimiter.js";
import { applySM2 } from "./backend/services/memory.service.js";
import { sendVerificationEmail } from "./backend/services/email.service.js";
import {
createBattle,
joinBattle,
startBattle,
submitSolution,
getBattle,
getHistory,
} from "./pages/Dsa-Battle/Battleservice.js";
import { instrumentJS } from "./modules/code-tracer.js";
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
}).single("resume");
const uploadCsv = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024 } // 2MB limit
}).single("csv");
function validateMagicBytes(buffer, mimeType) {
if (!buffer || buffer.length < 4) return false;
const hex = buffer.slice(0, 4).toString("hex").toUpperCase();
if (mimeType === "application/pdf") {
return hex === "25504446";
}
if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
return hex === "504B0304";
}
if (mimeType === "application/msword") {
return hex === "D0CF11E0";
}
return false;
}
const userSocketMap = new Map();
const studyRooms = new Map();
const memoryUserStore = new Map();
let userCacheTimestamp = 0;
let userCacheDirty = true;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = __dirname;
const IS_VERCEL = process.env.VERCEL === "1";
const DATA_DIR = IS_VERCEL
? path.join("/tmp", "algo-infinity-verse")
: path.join(ROOT, "data");
const USERS_FILE = path.join(DATA_DIR, "users.json");
const MEMORY_FILE = path.join(DATA_DIR, "memory.json");
const TEAM_PROFILES_FILE = path.join(DATA_DIR, "team_profiles.json");
const AUDITS_FILE = path.join(DATA_DIR, "audits_history.json");
const EXECUTIONS_FILE = path.join(DATA_DIR, "executions.json");
const CLIENT_ERRORS_FILE = path.join(DATA_DIR, "client_errors.json");
const FEEDBACK_FILE = path.join(DATA_DIR, "feedback.json");
const INTERVIEW_EXPERIENCES_FILE = path.join(DATA_DIR, "interview-experiences.json");
// Caps for append-only JSON logs so they can never grow unbounded on disk.
const MAX_CLIENT_ERROR_ENTRIES = 1000;
const MAX_FEEDBACK_ENTRIES = 5000;
const MAX_INTERVIEW_EXPERIENCE_ENTRIES = 5000;
const MAX_AUDIT_HISTORY_ENTRIES = 1000;
const MAX_EXECUTIONS_ENTRIES = 5000;
const SESSION_COOKIE = "aiv_session";
const ACCESS_COOKIE = "aiv_access";
const REFRESH_COOKIE = "aiv_refresh";
const DELETION_LOG_FILE = path.join(
DATA_DIR,
"account-deletions.json"
);
// ────────────────────────────────────────────────────────────────────────────
const protectedPaths = new Set([
"/community",
"/community.html",
"/support-page",
"/support-page/",
"/support-page/index.html",
]);
const mimeTypes = {
".css": "text/css; charset=utf-8",
".html": "text/html; charset=utf-8",
".ico": "image/x-icon",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".svg": "image/svg+xml",
".webp": "image/webp",
".php": "text/html; charset=utf-8",
".pdf": "application/pdf",
".docx":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
};
async function loadEnvFile() {
const envPath = path.join(ROOT, ".env");
try {
const raw = await fs.readFile(envPath, "utf8");
raw.split(/\r?\n/).forEach((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) return;
const separatorIndex = trimmed.indexOf("=");
if (separatorIndex === -1) return;
const key = trimmed.slice(0, separatorIndex).trim();
let value = trimmed.slice(separatorIndex + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
if (key && process.env[key] === undefined) {
process.env[key] = value;
}
});
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
}
function parseCookies(cookieHeader = "") {
return cookieHeader.split(";").reduce((cookies, part) => {
const [rawName, ...rawValue] = part.trim().split("=");
if (!rawName) return cookies;
cookies[rawName] = decodeURIComponent(rawValue.join("="));
return cookies;
}, {});
}
function getRefreshToken(req) {
const cookies = parseCookies(req.headers.cookie || "");
return cookies[REFRESH_COOKIE] || null;
}
// Builds the Set-Cookie header value(s) for an authenticated response. Returns
// an array of two cookies: the short-lived access token (read by getSession)
// and the long-lived refresh token (read by getRefreshToken on /api/refresh).
// Previously this set only the access cookie, so the aiv_refresh cookie was
// never issued and silent token refresh could never succeed (#1225).
function authCookies(accessToken, refreshToken, req) {
const secure = req.headers["x-forwarded-proto"] === "https";
const cookie = (name, value, maxAge) =>
[
`${name}=${encodeURIComponent(value)}`,
"HttpOnly",
"SameSite=Lax",
"Path=/",
`Max-Age=${maxAge}`,
secure ? "Secure" : "",
]
.filter(Boolean)
.join("; ");
return [
cookie(SESSION_COOKIE, accessToken, ACCESS_TOKEN_MAX_AGE_SECONDS),
cookie(REFRESH_COOKIE, refreshToken, REFRESH_TOKEN_MAX_AGE_SECONDS),
];
}
function clearAuthCookies() {
return [
`${SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`,
`${REFRESH_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`,
];
}
let db = null;
let useFirestore = false;
async function getUserByEmail(email) {
if (!useFirestore) {
const users = await readUsers();
return users.find((u) => u.email === email) || null;
}
const snapshot = await db
.collection(COLLECTIONS.USERS)
.where("email", "==", email)
.limit(1)
.get();
if (snapshot.empty) return null;
return { ...snapshot.docs[0].data(), id: snapshot.docs[0].id };
}
async function createUser(userData) {
if (!useFirestore) {
const users = await readUsers();
users.push(userData);
await writeUsers(users);
return userData;
}
const docRef = await db.collection(COLLECTIONS.USERS).add(userData);
return { ...userData, id: docRef.id };
}
async function ensureUserStore() {
try {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(USERS_FILE);
} catch {
await fs.writeFile(USERS_FILE, "[]\n");
}
} catch (err) {
console.error("[ensureUserStore] Failed to initialize user store:", err);
}
}
async function readUsers() {
if (!userCacheDirty && memoryUserStore.size > 0) {
return Array.from(memoryUserStore.values());
}
await ensureUserStore();
try {
const stat = await fs.stat(USERS_FILE);
if (!userCacheDirty && stat.mtimeMs <= userCacheTimestamp) {
return Array.from(memoryUserStore.values());
}
const raw = await fs.readFile(USERS_FILE, "utf8");
const users = JSON.parse(raw || "[]");
memoryUserStore.clear();
users.forEach((u) => memoryUserStore.set(u.email, u));
userCacheTimestamp = stat.mtimeMs;
userCacheDirty = false;
return users;
} catch (err) {
console.error("[readUsers] Failed to read users:", err);
return Array.from(memoryUserStore.values());
}
}
async function writeUsers(users) {
await ensureUserStore();
try {
await fs.writeFile(USERS_FILE, `${JSON.stringify(users, null, 2)}\n`);
userCacheDirty = true;
} catch (err) {
console.error("[writeUsers] Failed to write users:", err);
}
}
async function ensureAuditsStore() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(AUDITS_FILE);
} catch {
await fs.writeFile(AUDITS_FILE, "[]\n");
}
}
async function readAudits() {
await ensureAuditsStore();
const raw = await fs.readFile(AUDITS_FILE, "utf8");
return JSON.parse(raw || "[]");
}
async function writeAudits(audits) {
await ensureAuditsStore();
await fs.writeFile(AUDITS_FILE, `${JSON.stringify(audits, null, 2)}\n`);
}
// ── Execution History Store ─────────────────────────────────────────────────
let executionWriteQueue = Promise.resolve();
async function ensureExecutionStore() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(EXECUTIONS_FILE);
} catch {
await fs.writeFile(EXECUTIONS_FILE, "[]\n");
}
}
async function readExecutions() {
await ensureExecutionStore();
const raw = await fs.readFile(EXECUTIONS_FILE, "utf8");
return JSON.parse(raw || "[]");
}
async function writeExecutionsAtomic(executions) {
const tmpPath = `${EXECUTIONS_FILE}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(tmpPath, `${JSON.stringify(executions, null, 2)}\n`);
await fs.rename(tmpPath, EXECUTIONS_FILE);
}
async function updateExecutionStore(mutator) {
const task = executionWriteQueue.then(async () => {
await ensureExecutionStore();
const raw = await fs.readFile(EXECUTIONS_FILE, "utf8");
const store = JSON.parse(raw || "[]");
const result = await mutator(store);
if (store.length > MAX_EXECUTIONS_ENTRIES) {
store.splice(0, store.length - MAX_EXECUTIONS_ENTRIES);
}
await writeExecutionsAtomic(store);
return result;
});
executionWriteQueue = task.catch((err) => {
console.error("[updateExecutionStore] Write task failed:", err);
});
return task;
}
// ── Memory Scanner (Spaced Repetition, SM-2) ─────────────────────────────────
// NOTE: This currently uses local JSON file storage, matching the existing
// users.json/feedback.json pattern in this codebase. In multi-instance or
// serverless (VERCEL=1 / Firestore) deployments this is not a shared source
// of truth. Migrating to Firestore (mirroring getUserByEmail/createUser's
// useFirestore branching) is tracked as a follow-up.
let memoryWriteQueue = Promise.resolve();
async function ensureMemoryStore() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(MEMORY_FILE);
} catch {
await fs.writeFile(MEMORY_FILE, "{}\n");
}
}
async function readMemoryStore() {
await ensureMemoryStore();
const raw = await fs.readFile(MEMORY_FILE, "utf8");
return JSON.parse(raw || "{}");
}
async function writeMemoryStoreAtomic(filePath, store) {
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(tmpPath, `${JSON.stringify(store, null, 2)}\n`);
await fs.rename(tmpPath, filePath);
}
// Serializes read-modify-write cycles so concurrent /api/memory/* requests
// cannot clobber each other's updates. `mutator` receives the current store
// and must return the updated store (or modify it in-place).
async function updateMemoryStore(mutator) {
const task = memoryWriteQueue.then(async () => {
await ensureMemoryStore();
const raw = await fs.readFile(MEMORY_FILE, "utf8");
const store = JSON.parse(raw || "{}");
const updated = await mutator(store);
// Write the updated store if the mutator returned a new store object.
// If the mutator mutated in-place and returned undefined or a sub-resource
// (such as a card object), we write the mutated store.
const isCard = updated && typeof updated === "object" && ("topic" in updated || "nextReviewDate" in updated || "repetitions" in updated);
const isNewStore = updated && typeof updated === "object" && !isCard;
const storeToSave = isNewStore && updated !== store ? updated : store;
await writeMemoryStoreAtomic(MEMORY_FILE, storeToSave);
return updated;
});
// Prevent one rejected task from permanently breaking the queue.
memoryWriteQueue = task.catch(() => {});
return task;
}
let teamProfilesWriteQueue = Promise.resolve();
async function ensureTeamProfilesStore() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(TEAM_PROFILES_FILE);
} catch {
await fs.writeFile(TEAM_PROFILES_FILE, "{}\n");
}
}
async function readTeamProfilesStore() {
await ensureTeamProfilesStore();
const raw = await fs.readFile(TEAM_PROFILES_FILE, "utf8");
return JSON.parse(raw || "{}");
}
async function writeTeamProfilesStoreAtomic(filePath, store) {
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(tmpPath, `${JSON.stringify(store, null, 2)}\n`);
await fs.rename(tmpPath, filePath);
}
async function updateTeamProfilesStore(mutator) {
const task = teamProfilesWriteQueue.then(async () => {
await ensureTeamProfilesStore();
const raw = await fs.readFile(TEAM_PROFILES_FILE, "utf8");
const store = JSON.parse(raw || "{}");
const updated = await mutator(store);
await writeTeamProfilesStoreAtomic(TEAM_PROFILES_FILE, store);
return updated;
});
teamProfilesWriteQueue = task.catch((err) => {
console.error("[updateTeamProfilesStore] Write task failed:", err);
});
return task;
}
// ── Serialized, size-capped JSON array append store ──────────────────────────
// Append-style endpoints (client error logs, feedback, interview experiences,
// audit history) previously did an unserialized readFile → parse → push →
// writeFile. Under concurrency those interleave and silently drop entries
// (lost writes), and they grow without bound — the anonymous /api/log-error
// route is a disk-fill DoS. This helper serializes each file's read-modify-write
// through a per-file promise chain (mirroring updateMemoryStore), writes
// atomically via a temp file + rename, and caps the array to its most recent
// `maxEntries` so the file can never grow unbounded.
const jsonArrayWriteQueues = new Map();
function appendToJsonArrayFile(filePath, entry, maxEntries = 1000) {
const previous = jsonArrayWriteQueues.get(filePath) || Promise.resolve();
const task = previous.then(async () => {
await fs.mkdir(DATA_DIR, { recursive: true });
let list = [];
try {
const raw = await fs.readFile(filePath, "utf8");
list = JSON.parse(raw || "[]");
if (!Array.isArray(list)) list = [];
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
list.push(entry);
if (list.length > maxEntries) {
list = list.slice(list.length - maxEntries);
}
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(tmpPath, `${JSON.stringify(list, null, 2)}\n`);
await fs.rename(tmpPath, filePath);
return entry;
});
// Keep the chain alive even if one write rejects, so later writes still run.
jsonArrayWriteQueues.set(filePath, task.catch(() => {}));
return task;
}
// ──────────────────────────────────────────────────────────────────────────
async function readJsonBody(req) {
if (req.body && typeof req.body === "object") return req.body;
if (req.body && typeof req.body === "string") {
try { return JSON.parse(req.body); } catch { return {}; }
}
let body = "";
for await (const chunk of req) {
body += chunk;
if (body.length > 1024 * 1024)
throw new Error("Request body is too large.");
}
return body ? JSON.parse(body) : {};
}
function sendJson(res, status, body, headers = {}) {
// Note: COOP header omitted to allow Firebase signInWithPopup to access popup.closed
// when opening cross-origin OAuth popups (Google, etc.)
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
...headers,
});
res.end(JSON.stringify(body));
}
function redirect(res, location, headers = {}) {
res.writeHead(302, { Location: location, ...headers });
res.end();
}
function getSession(req) {
const cookies = parseCookies(req.headers.cookie || "");
return verifyAccessToken(cookies[SESSION_COOKIE]);
}
// A team profile is private to its owner — the authenticated user who first
// created it — and any explicitly listed members. Profiles with no recorded
// owner are treated as unclaimed legacy data: still readable, and claimed by
// the first authenticated user who writes them. This closes the IDOR where any
// client could read/overwrite any profile just by knowing its id.
function canAccessTeamProfile(profile, userId) {
if (!profile || !profile.ownerId) return true;
if (profile.ownerId === userId) return true;
const members = Array.isArray(profile.members) ? profile.members : [];
return members.some(
(m) =>
m === userId ||
(m && typeof m === "object" && (m.id === userId || m.userId === userId)),
);
}
function normalizePathname(pathname) {
if (!pathname) return "/";
return pathname.replace(/\/+$/, "") || "/";
}
function isProtectedRoute(pathname) {
return protectedPaths.has(pathname);
}
function authorizeRequest(req, pathname) {
if (!isProtectedRoute(pathname)) {
return { authorized: true };
}
const session = getSession(req);
if (!session) {
return {
authorized: false,
redirectTo: `/login?next=${encodeURIComponent(pathname)}`,
};
}
return {
authorized: true,
session,
};
}
function validateRequest(req) {
const allowedMethods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
if (!allowedMethods.includes(req.method)) {
return {
valid: false,
status: 405,
message: "Method not allowed.",
};
}
return { valid: true };
}
// ── CSRF protection ──────────────────────────────────────────────────────────
// Previously a CSRF token was issued by /api/csrf-token but never checked, so
// every state-changing request was unprotected. A mutating request is now
// accepted only when it proves it originated from our own site, via EITHER:
// 1. a valid double-submit token — the x-csrf-token header equals
// HMAC(csrfSecret cookie), compared with crypto.timingSafeEqual
// (see verifyCsrfToken); OR
// 2. an Origin/Referer header whose host matches our own — a value a
// cross-site attacker's page cannot set on a forged request.
// A forged cross-site request carries neither and is rejected with 403.
const CSRF_SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
function isSameOriginRequest(req) {
const host = req.headers.host;
if (!host) return false;
for (const header of [req.headers.origin, req.headers.referer]) {
if (!header) continue;
try {
const requestHost = host.split(":")[0];
const urlHost = new URL(header).host.split(":")[0];
if (urlHost && requestHost && urlHost === requestHost) return true;
} catch {
// Malformed Origin/Referer header — treat as untrusted.
}
}
return false;
}
function isCsrfRequestTrusted(req) {
return verifyCsrfToken(req) || isSameOriginRequest(req);
}
async function handleApi(req, res, pathname) {
// Reject state-changing requests that cannot prove a same-site origin.
if (!CSRF_SAFE_METHODS.has(req.method) && !isCsrfRequestTrusted(req)) {
return sendJson(res, 403, { error: "CSRF validation failed." });
}
if (pathname === "/api/team-profile" && req.method === "GET") {
try {
const session = getSession(req);
if (!session) {
return sendJson(res, 401, { error: "Login required." });
}
const urlParams = new URL(req.url, `http://${req.headers.host}`).searchParams;
const teamId = urlParams.get("id");
if (!teamId) {
return sendJson(res, 400, { error: "Missing team id." });
}
let profileData = null;
if (!useFirestore) {
const store = await readTeamProfilesStore();
profileData = store[teamId] || null;
} else {
const docRef = db.collection(COLLECTIONS.TEAM_PROFILES).doc(teamId);
const snapshot = await docRef.get();
if (snapshot.exists) {
profileData = snapshot.data();
}
}
if (profileData && !canAccessTeamProfile(profileData, session.sub)) {
return sendJson(res, 403, { error: "You do not have access to this team profile." });
}
if (!profileData) {
// Return default profile with version 1
return sendJson(res, 200, {
id: teamId,
version: 1,
name: "New Team Profile",
description: "",
members: []
});
}
return sendJson(res, 200, profileData);
} catch (error) {
console.error("Fetch team profile error:", error);
return sendJson(res, 500, { error: "Failed to fetch team profile." });
}
}
if (pathname === "/api/team-profile" && req.method === "POST") {
try {
const session = getSession(req);
if (!session) {
return sendJson(res, 401, { error: "Login required." });
}
const payload = await readJsonBody(req);
const { id: teamId, version, name, description, members } = payload;
if (!teamId) {
return sendJson(res, 400, { error: "Missing team id." });
}
if (version === undefined || version === null) {
return sendJson(res, 400, { error: "Missing version for concurrency control." });
}
let updatedProfile = null;
if (!useFirestore) {
try {
updatedProfile = await updateTeamProfilesStore(store => {
const currentProfile = store[teamId] || { version: 1 };
// Ownership check: only the owner/members may modify a claimed profile.
if (!canAccessTeamProfile(currentProfile, session.sub)) {
const forbiddenError = new Error("Forbidden");
forbiddenError.status = 403;
throw forbiddenError;
}
// OCC version check
if (currentProfile.version !== version) {
const conflictError = new Error("Conflict");
conflictError.status = 409;
conflictError.currentVersion = currentProfile.version;
throw conflictError;
}
// Update data and increment version
const newProfile = {
id: teamId,
ownerId: currentProfile.ownerId || session.sub,
name: name || currentProfile.name || "New Team Profile",
description: description !== undefined ? description : (currentProfile.description || ""),
members: members || currentProfile.members || [],
version: version + 1,
updatedAt: new Date().toISOString()
};
store[teamId] = newProfile;
return newProfile;
});
} catch (error) {
if (error.status === 403) {
return sendJson(res, 403, { error: "You do not have access to this team profile." });
}
if (error.status === 409) {
return sendJson(res, 409, {
error: "Conflict detected: The profile was updated by someone else.",
currentVersion: error.currentVersion
});
}
throw error;
}
} else {
const docRef = db.collection(COLLECTIONS.TEAM_PROFILES).doc(teamId);
try {
updatedProfile = await db.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const existing = doc.exists ? doc.data() : null;
// Ownership check: only the owner/members may modify a claimed profile.
if (!canAccessTeamProfile(existing, session.sub)) {
const forbiddenError = new Error("Forbidden");
forbiddenError.status = 403;
throw forbiddenError;
}
const currentVersion = existing ? existing.version : 1;
if (currentVersion !== version) {
const conflictError = new Error("Conflict");
conflictError.status = 409;
conflictError.currentVersion = currentVersion;
throw conflictError;
}
const newProfile = {
id: teamId,
ownerId: (existing && existing.ownerId) || session.sub,
name: name || (existing ? existing.name : "New Team Profile"),
description: description !== undefined ? description : (existing ? existing.description : ""),
members: members || (existing ? existing.members : []),
version: version + 1,
updatedAt: new Date().toISOString()
};
transaction.set(docRef, newProfile);
return newProfile;
});
} catch (error) {
if (error.status === 403) {
return sendJson(res, 403, { error: "You do not have access to this team profile." });
}
if (error.status === 409) {
return sendJson(res, 409, {
error: "Conflict detected: The profile was updated by someone else.",
currentVersion: error.currentVersion
});
}
throw error;
}
}
return sendJson(res, 200, updatedProfile);
} catch (error) {
console.error("Update team profile error:", error);
return sendJson(res, 500, { error: "Failed to update team profile." });
}
}
if (
pathname === "/api/debug-env" &&
req.method === "GET" &&
process.env.ENABLE_DEBUG_ENV === "true"
) {
const keys = ["FIREBASE_API_KEY","FIREBASE_AUTH_DOMAIN","FIREBASE_PROJECT_ID","FIREBASE_STORAGE_BUCKET","FIREBASE_MESSAGING_SENDER_ID","FIREBASE_APP_ID","FIREBASE_CLIENT_EMAIL","FIREBASE_PRIVATE_KEY","SESSION_SECRET"];
const vars = {};
keys.forEach(k => {
const v = process.env[k];
vars[k] = Boolean(process.env[k]);
});
return sendJson(res, 200, vars);
}
if (pathname === "/api/firebase-config" && req.method === "GET") {
const apiKey = process.env.FIREBASE_API_KEY;
const authDomain = process.env.FIREBASE_AUTH_DOMAIN;
const projectId = process.env.FIREBASE_PROJECT_ID;
const storageBucket = process.env.FIREBASE_STORAGE_BUCKET;
const messagingSenderId = process.env.FIREBASE_MESSAGING_SENDER_ID;
const appId = process.env.FIREBASE_APP_ID;
if (!apiKey || !authDomain || !projectId || !storageBucket || !messagingSenderId || !appId) {
return sendJson(res, 503, { configured: false, error: "Firebase not configured" });
}
return sendJson(res, 200, {
configured: true,
apiKey,
authDomain,
projectId,
storageBucket,
messagingSenderId,
appId,
});
}
if (pathname === "/api/analyze-resume" && req.method === "POST") {
if (!applyRateLimit(req, res, resumeAnalysisLimiter, "Too many resume analysis requests. Please try again later.")) {
return;
}
try {
await new Promise((resolve, reject) => {
upload(req, res, (err) => {
if (err) reject(err);
else resolve();
});
});
if (!req.file) {
return sendJson(res, 400, { error: "No resume file uploaded." });
}
const allowedMimeTypes = [
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword"
];
if (!allowedMimeTypes.includes(req.file.mimetype)) {
return sendJson(res, 400, { error: "Unsupported file type. Upload PDF or DOCX." });
}
if (!validateMagicBytes(req.file.buffer, req.file.mimetype)) {
return sendJson(res, 400, { error: "File content mismatch. The uploaded file's content does not match its type." });
}
const text = await extractResumeText(req.file);
const atsScore = calculateATS(text);
const missingSkills = findMissingSkills(text);
const suggestions = getSuggestions(atsScore);
return sendJson(res, 200, {
atsScore,
missingSkills,
suggestions,
});
} catch (error) {
console.error("Resume analysis error:", error);
if (error instanceof multer.MulterError && error.code === "LIMIT_FILE_SIZE") {
return sendJson(res, 413, { error: "Resume file is too large." });
}
if (error?.message === "Unsupported file") {
return sendJson(res, 400, { error: "Unsupported file type. Upload PDF or DOCX." });
}
return sendJson(res, 500, { error: "Failed to analyze resume." });
}
}
if (pathname === "/api/analyze-repository" && req.method === "POST") {
if (!applyRateLimit(req, res, repoAnalysisLimiter, "Too many repository analysis requests. Please try again later.")) {
return;
}
try {
const payload = await readJsonBody(req);
const { repoUrl } = payload;
if (!repoUrl || !repoUrl.includes("github.com")) {
return sendJson(res, 400, { error: "Please provide a valid GitHub repository URL." });
}
const provider = VCSFactory.getProvider(repoUrl);
const workflows = await provider.getNormalizedWorkflows();
if (workflows.length === 0) {
return sendJson(res, 200, {
score: 0,
workflowsAnalyzed: 0,
details: { hasDependencies: false, hasTests: false },
recommendations: ["No GitHub Actions workflows found in .github/workflows. Add a CI/CD pipeline to automate testing."]
});
}
let bestScore = -1;
let overallDeps = false;
let overallTests = false;
for (const wf of workflows) {
const result = analyzeWorkflow(wf.commands);
if (result.score > bestScore) bestScore = result.score;
if (result.hasDependencies) overallDeps = true;
if (result.hasTests) overallTests = true;
}
const recommendations = [];
if (bestScore === 20) recommendations.push("Workflows found, but they contain no functional jobs or steps.");
if (bestScore === 50) recommendations.push("Add explicit testing commands (like 'npm test') to your workflow.");
if (bestScore === 75) recommendations.push("Ensure dependencies are installed securely before running tests.");
if (bestScore === 100) recommendations.push("Excellent! Fully functional CI/CD pipeline detected.");
return sendJson(res, 200, {
score: bestScore,
workflowsAnalyzed: workflows.length,
details: {
hasDependencies: overallDeps,
hasTests: overallTests
},
recommendations
});
} catch (err) {
console.error("Repository analysis error:", err.message);
return sendJson(res, 500, { error: "Failed to analyze repository. " + err.message });
}
}
// SDLC Advisor API
if (pathname === "/api/sdlc-advisor" && req.method === "POST") {
if (!applyRateLimit(req, res, sdlcAdvisorLimiter, "Too many SDLC advisor requests. Please try again later.")) {
return;
}
try {
const payload = await readJsonBody(req);
const { description } = payload;
if (!description) {
return sendJson(res, 400, { error: "Project description is required." });
}
const advice = await generateSdlcAdvice(description);
return sendJson(res, 200, advice);
} catch (e) {
console.error("SDLC Advisor error:", e);
return sendJson(res, 500, { error: "Failed to generate SDLC advice." });
}
}
// Bulk Audit APIs
if (pathname === "/api/audit/bulk" && req.method === "POST") {
if (!applyRateLimit(req, res, bulkAuditLimiter, "Too many bulk audit requests. Please try again later.")) {
return;
}
try {
uploadCsv(req, res, async (err) => {
if (err) return sendJson(res, 500, { error: "Upload error." });
if (!req.file) return sendJson(res, 400, { error: "No CSV file uploaded." });
try {
const records = csvParse(req.file.buffer.toString('utf-8'), { columns: false, skip_empty_lines: true });
// Extract repo URLs from the first column
const repoUrls = records.map(row => row[0]).filter(url => url && url.includes("github.com"));
if (repoUrls.length === 0) {
return sendJson(res, 400, { error: "No valid GitHub URLs found in the CSV." });
}
// Cap batch size: each URL fans out to outbound GitHub requests, so an
// unbounded CSV is a denial-of-service / cost-amplification vector.
if (repoUrls.length > MAX_BULK_AUDIT_URLS) {
return sendJson(res, 400, {
error: `Too many repositories. A maximum of ${MAX_BULK_AUDIT_URLS} is allowed per bulk audit.`,
maxAllowed: MAX_BULK_AUDIT_URLS,
received: repoUrls.length,
});
}