-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathserver.js
More file actions
246 lines (211 loc) · 6.86 KB
/
Copy pathserver.js
File metadata and controls
246 lines (211 loc) · 6.86 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
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const path = require("path");
const fs = require("fs");
const crypto = require("crypto");
const fetchUserInfo = require("./scripts/fetch-user-info");
const { rateLimit } = require("express-rate-limit");
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
// Trust Render.com proxy so req.ip returns real client IP
app.set("trust proxy", 1);
// 1. Per-request nonce generator (used by CSP and HTML nonce injection)
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString("base64url");
next();
});
// 2. Security headers via Helmet
// Sets: Content-Security-Policy, X-Frame-Options, X-Content-Type-Options,
// Referrer-Policy, Strict-Transport-Security, and more.
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
// Allow fetch/XHR to external APIs used by the frontend
connectSrc: [
"'self'",
"https://raw.githubusercontent.com",
"https://leetcode-api-dun.vercel.app",
"https://lc-backend-lyq2.onrender.com",
"https://cdn.jsdelivr.net",
],
// Inline scripts need a per-request nonce; external scripts from 'self'
// are allowed automatically.
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
// Allow inline styles (style attributes) + Google Fonts and FontAwesome stylesheet
styleSrc: [
"'self'",
"'unsafe-inline'",
"https://fonts.googleapis.com",
"https://cdnjs.cloudflare.com",
],
// Google Fonts and FontAwesome fonts
fontSrc: [
"'self'",
"https://fonts.gstatic.com",
"https://cdnjs.cloudflare.com",
],
// Images: self + data: URIs (used by matrix canvas)
imgSrc: ["'self'", "data:"],
// No plugins
objectSrc: ["'none'"],
// No framing (clickjacking protection)
frameAncestors: ["'none'"],
// Upgrade HTTP to HTTPS when possible
upgradeInsecureRequests: [],
},
},
crossOriginEmbedderPolicy: false, // keep false so Google Fonts load
}),
);
// 3. Static assets (JS, CSS, images) — served normally
// HTML files are excluded — they go through nonce injection via routes.
const staticMiddleware = express.static(path.join(__dirname, "frontend"), {
index: false,
});
app.use((req, res, next) => {
if (req.path.endsWith(".html")) return next();
staticMiddleware(req, res, next);
});
// 4. HTML page routes — inject per-request nonce into __NONCE__ placeholders
function serveHtml(res, filePath) {
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
return res.status(500).send("Error loading page");
}
const html = data.replace(/__NONCE__/g, res.locals.nonce);
res.type("html").send(html);
});
}
/* HOME ROUTES */
app.get("/", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "index.html"));
});
app.get("/leaderboard", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "leaderboard.html"));
});
app.get("/about", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "about.html"));
});
app.get("/registration", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "registration.html"));
});
app.get("/privacy", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "privacy.html"));
});
app.get("/terms", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "terms.html"));
});
// Redirect direct .html file access so nonce injection still applies
app.get(/\.html$/, (req, res) => {
const cleanPath = req.path.replace(/\.html$/, "");
res.redirect(301, cleanPath || "/");
});
// 5. Utility endpoints
app.get("/uptime", (req, res) => {
res.json({ status: "Website is running ✅" });
});
app.get("/user/:username", (req, res) => {
serveHtml(res, path.join(__dirname, "frontend", "user.html"));
});
// ---- Rate limiter for API endpoint ----
const apiLimiter = rateLimit({
windowMs: 60 * 1000, // 1-minute window
limit: parseInt(process.env.API_RATE_LIMIT, 10) || 30,
standardHeaders: "draft-8",
legacyHeaders: false,
message: { error: "Rate limit exceeded", retryAfter: 60 },
handler: (req, res, next, options) => {
res.status(options.statusCode);
res.set("Retry-After", Math.ceil(options.windowMs / 1000));
res.json(options.message);
},
});
// ---- Cache configuration ----
const userCache = new Map();
const CACHE_TTL_MS = 2 * 60 * 1000; // 2 minutes
// Helper to prune cache to bound memory usage
function pruneUserCache() {
if (userCache.size > 1000) {
const now = Date.now();
for (const [key, value] of userCache.entries()) {
if (now - value.timestamp > CACHE_TTL_MS) {
userCache.delete(key);
}
}
}
}
app.use("/api/user/:username", apiLimiter);
app.get("/api/user/:username", async (req, res) => {
const username = req.params.username;
const usernameRegex = /^[a-zA-Z0-9_-]+$/;
if (!usernameRegex.test(username)) {
return res.status(400).json({ error: "Invalid username format" });
}
const cached = userCache.get(username);
const now = Date.now();
if (cached) {
if (now - cached.timestamp < CACHE_TTL_MS && cached.data) {
return res.json(cached.data);
}
if (cached.promise) {
try {
const data = await cached.promise;
return res.json(data);
} catch (err) {
if (cached.data) {
console.warn(
`[Cache Fallback] Serving stale data after pending fetch failed...`,
);
return res.json(cached.data);
}
}
}
}
let fetchPromise;
try {
fetchPromise = fetchUserInfo(username);
userCache.set(username, {
...cached,
timestamp: cached ? cached.timestamp : 0,
promise: fetchPromise,
});
const data = await fetchPromise;
pruneUserCache();
userCache.set(username, {
timestamp: Date.now(),
data,
promise: null,
});
res.json(data);
} catch (err) {
userCache.set(username, {
...cached,
promise: null,
});
if (cached && cached.data) {
console.warn(
`[Cache Fallback] Failed to fetch fresh data for user: ${username}. Serving stale cached data. Error: ${err.message}`,
);
return res.json(cached.data);
}
console.error(
`[Cache Error] Failed to fetch data for user: ${username} (No cached fallback available). Error: ${err.message}`,
);
res.status(502).json({
error: "Failed to fetch user details from external LeetCode API wrapper",
details: err.message,
});
}
});
// 404 handler
app.use((req, res) => {
res.status(404);
serveHtml(res, path.join(__dirname, "frontend", "404.html"));
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});