forked from QuantumLogicsLabs/PolyCode-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
356 lines (308 loc) · 10.7 KB
/
Copy pathserver.js
File metadata and controls
356 lines (308 loc) · 10.7 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const mongoose = require("mongoose");
const {
connectToMongoDB,
requireMongoConnection,
} = require("./src/config/database");
let compression;
try {
compression = require("compression");
} catch (e) {
console.warn(
"⚠️ Compression module not found. Run: npm install compression",
);
}
let rateLimit;
try {
rateLimit = require("express-rate-limit");
} catch (e) {
console.warn(
"⚠️ Rate limiting module not found. Run: npm install express-rate-limit",
);
}
// ─── OpenAPI Spec ─────────────────────────────────────────────────────────────
let swaggerJsdoc;
try {
swaggerJsdoc = require("swagger-jsdoc");
} catch (e) {
console.warn("⚠️ swagger-jsdoc not found. Run: npm install swagger-jsdoc");
}
let __swaggerSpec = null;
if (swaggerJsdoc) {
__swaggerSpec = swaggerJsdoc({
definition: {
openapi: "3.0.0",
info: {
title: "PolyCode API",
version: "1.0.0",
description: "API reference for PolyCode Backend",
},
servers: [
{
url: `http://localhost:${process.env.PORT || 5000}`,
description: "Dev server",
},
],
components: {
schemas: {
Document: {
type: "object",
properties: {
title: { type: "string" },
path: { type: "string" },
category: { type: "string" },
fileType: { type: "string" },
size: { type: "number" },
excerpt: { type: "string" },
lines: { type: "number" },
wordCount: { type: "number" },
},
},
ErrorResponse: {
type: "object",
properties: { error: { type: "string" } },
},
},
},
// paths: {} routers was define here and now they are on their own files
},
apis: [],
});
console.log("✅ API spec ready");
}
// ─── App ──────────────────────────────────────────────────────────────────────
const app = express();
app.disable("x-powered-by");
function normalizeOrigin(origin = "") {
// normalizeOrigin is a function that normalizes the origin
return origin.trim().replace(/\/$/, "");
}
const defaultAllowedOrigins = [
// defaultAllowedOrigins is an array of allowed origins
"https://code.quantumlogicslimited.com",
"https://www.code.quantumlogicslimited.com",
"https://quantumlogicslimited.com",
"https://www.quantumlogicslimited.com",
"https://digital-logics-studio.vercel.app",
"https://poly-code-frontend-iota.vercel.app",
"http://localhost:3000",
"http://127.0.0.1:3000",
];
const allowedOrigins = new Set( // Set is a collection of unique values
[
...defaultAllowedOrigins,
process.env.FRONTEND_URL,
process.env.PROD_FRONTEND_URL,
...(process.env.CORS_ORIGINS || "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean),
]
.map(normalizeOrigin)
.filter(Boolean),
);
const isAllowedOrigin = (origin) => {
if (!origin) return true;
const normalizedOrigin = normalizeOrigin(origin);
let hostname = "";
try {
hostname = new URL(normalizedOrigin).hostname;
} catch (error) {
return false;
}
if (allowedOrigins.has(normalizedOrigin) || /\.vercel\.app$/.test(hostname)) {
return true;
}
// Local dev from LAN IP (e.g. http://192.168.x.x:3000)
if (process.env.NODE_ENV !== "production") {
return /^(localhost|127\.0\.0\.1|192\.168\.|10\.|172\.(1[6-9]|2\d|3[01])\.)/.test(
hostname,
);
}
return false;
};
const CORS_METHODS = "GET,POST,PUT,DELETE,PATCH,OPTIONS";
const CORS_HEADERS = "Content-Type, Authorization, X-Requested-With";
function applyCorsHeaders(req, res) {
const origin = req.headers.origin;
if (!origin || !isAllowedOrigin(origin)) return false;
const normalizedOrigin = normalizeOrigin(origin);
res.setHeader("Access-Control-Allow-Origin", normalizedOrigin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Vary", "Origin");
return true;
}
// Handle preflight and attach CORS headers before any other middleware.
app.use((req, res, next) => {
applyCorsHeaders(req, res);
if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", CORS_METHODS);
res.setHeader("Access-Control-Allow-Headers", CORS_HEADERS);
res.setHeader("Access-Control-Max-Age", "86400");
return res.sendStatus(204);
}
return next();
});
const corsOptions = {
origin(origin, callback) {
if (!origin) return callback(null, true);
if (isAllowedOrigin(origin)) {
return callback(null, normalizeOrigin(origin));
}
console.warn(`🚫 CORS blocked origin: ${origin}`);
return callback(null, false);
},
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
optionsSuccessStatus: 204,
};
app.use((req, res, next) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "no-referrer");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
next();
});
if (compression) {
app.use(
compression({
level: 6,
threshold: 1024,
filter: (req, res) => {
if (req.headers["x-no-compression"]) return false;
return compression.filter(req, res);
},
}),
);
console.log("✅ Compression enabled");
}
app.use(cors(corsOptions));
app.options(/.*/, cors(corsOptions));
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const d = Date.now() - start;
if (d > 1000) console.warn(`🐌 Slow: ${req.method} ${req.path} - ${d}ms`);
else console.log(`⚡ ${req.method} ${req.path} - ${d}ms`);
});
next();
});
if (rateLimit) {
app.use(
"/api/",
rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: "Too many requests from this IP, please try again later.",
standardHeaders: true,
legacyHeaders: false,
}),
);
console.log("✅ Rate limiting enabled");
}
// ─── Docs routes ──────────────────────────────────────────────────────────────
// Serve logo.png from the project root
app.get("/logo.png", (req, res) => {
res.sendFile(path.join(__dirname, "logo.png"));
});
// Raw OpenAPI JSON spec
app.get("/api-docs.json", (req, res) => {
if (!__swaggerSpec)
return res.status(503).json({ error: "Spec not available" });
res.setHeader("Content-Type", "application/json");
res.send(__swaggerSpec);
});
// Custom docs HTML page
app.get("/api-docs", (req, res) => {
res.sendFile(path.join(__dirname, "api-docs.html"));
});
// ─── API Routes ───────────────────────────────────────────────────────────────
// Warm MongoDB on cold start (serverless); auth routes also await connection.
connectToMongoDB().catch((err) => {
if (/bad auth|authentication failed/i.test(err.message)) {
console.error("MongoDB initialization error:", err.message);
console.error(
" → Run: npm run db:setup (reset password in Atlas → Database Access first)",
);
return;
}
console.error("MongoDB initialization error:", err.message);
});
// Auth Routes (User & Progress) — require DB before register/login
const authRoutes = require("./src/modules/auth/auth.router");
app.use("/api/auth", requireMongoConnection, authRoutes);
const documentRoutes = require("./src/modules/documents/documents.router");
app.use("/api/documents", documentRoutes);
const playgroundRoutes = require("./src/modules/playground/playground.route");
app.use("/api/playground", playgroundRoutes);
const challengeRoutes = require("./src/routes/challenge");
app.use("/api/challenges", challengeRoutes);
const chatRoutes = require("./src/modules/chat/chat.router");
app.use("/api/chat", requireMongoConnection, chatRoutes);
// Certificate uploads are optional — a missing dependency must not take down auth/API.
try {
const certificateRoutes = require("./src/routes/Certificates.js");
app.use("/certificates", express.static(path.join(__dirname, "uploads/certificates")));
app.use("/api/certificates", certificateRoutes);
console.log("✅ Certificate routes enabled");
} catch (error) {
console.warn("⚠️ Certificate routes disabled:", error.message);
}
// Backward compatibility for older frontend builds requesting /languages directly
app.get("/languages", (req, res) => {
return res.redirect(307, "/api/documents/languages");
});
app.get("/api/health", async (req, res) => {
let mongo = "not_configured";
try {
if (!process.env.MONGODB_URI?.trim()) {
mongo = "not_configured";
} else {
await connectToMongoDB();
mongo =
mongoose.connection.readyState === 1 ? "connected" : "disconnected";
}
} catch (error) {
mongo = "error";
}
res.json({
status: "OK",
timestamp: new Date().toISOString(),
message: "Backend is running",
mongo,
});
});
// Serve bundled frontend only when API and UI run on the same host (not on Vercel backend-only).
if (process.env.NODE_ENV === "production" && !process.env.VERCEL) {
app.use(express.static(path.join(__dirname, "../PolyCode-Frontend/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../PolyCode-Frontend/build/index.html"));
});
}
app.use((err, req, res, next) => {
applyCorsHeaders(req, res);
console.error("Unhandled error:", err?.message || err);
if (res.headersSent) {
return next(err);
}
const status = err?.status || 500;
return res.status(status).json({
error: err?.message || "Internal server error",
});
});
// ─── Start ────────────────────────────────────────────────────────────────────
const PORT = process.env.PORT || 5000;
module.exports = app;
// Only bind a port when executed directly (`node server.js`), not on Vercel serverless.
if (require.main === module) {
app.listen(PORT, () => {
console.log(`🚀 Server: http://localhost:${PORT}`);
console.log(`📖 API Docs: http://localhost:${PORT}/api-docs`);
});
}