-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
282 lines (248 loc) · 8.61 KB
/
server.js
File metadata and controls
282 lines (248 loc) · 8.61 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
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://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;
}
return (
allowedOrigins.has(normalizedOrigin) || /\.vercel\.app$/.test(hostname)
);
};
const corsOptions = { // corsOptions is an object that contains the options for the cors middleware
origin(origin, callback) {
// Server-to-server tools (curl, health checks) omit Origin.
if (!origin) return callback(null, true);
if (isAllowedOrigin(origin)) {
return callback(null, normalizeOrigin(origin));
}
console.warn(`🚫 CORS blocked origin: ${origin}`);
return callback(new Error(`CORS: Origin ${origin} is not allowed`));
},
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) => {
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);
// 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"));
});
}
// ─── Start ────────────────────────────────────────────────────────────────────
const PORT = process.env.PORT || 5000;
// Vercel runs Express as a serverless function — export the app, do not call listen().
if (process.env.VERCEL) {
module.exports = app;
} else {
app.listen(PORT, () => {
console.log(`🚀 Server: http://localhost:${PORT}`);
console.log(`📖 API Docs: http://localhost:${PORT}/api-docs`);
});
}