-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
283 lines (247 loc) · 11.4 KB
/
server.js
File metadata and controls
283 lines (247 loc) · 11.4 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
const express = require("express");
const dotenv = require("dotenv");
const helmet = require("helmet");
const cors = require("cors");
const path = require("path");
const os = require("os");
// ── Load env vars FIRST ──────────────────────────────────────────────────────
dotenv.config();
/* ─────────────────────────────────────────
Required ENV validation
───────────────────────────────────────── */
const REQUIRED_ENV = [
"MONGO_URI",
"JWT_SECRET",
"ADMIN_SECRET",
"ADMIN_USER",
"ADMIN_PASS",
"ENC_KEY",
"GEMINI_API_KEY", // ← added: AI routes need this at boot time
];
const missingEnv = REQUIRED_ENV.filter((k) => !process.env[k]);
if (missingEnv.length) {
console.error("❌ Missing required env variables:", missingEnv.join(", "));
process.exit(1);
}
if (process.env.ENC_KEY.length !== 32) {
console.error("❌ ENC_KEY must be exactly 32 characters.");
process.exit(1);
}
/* ─────────────────────────────────────────
Imports (after env is validated)
───────────────────────────────────────── */
const connectDB = require("./config/db");
const errorHandler = require("./middleware/errorHandler");
const {
globalLimiter,
loginLimiter,
signupLimiter,
joinLimiter,
} = require("./middleware/rateLimiter");
const authRoutes = require("./routes/auth.routes");
const snippetRoutes = require("./routes/snippet.routes");
const workspaceRoutes = require("./routes/workspace.routes");
const githubRoutes = require("./routes/github.routes");
const userRoutes = require("./routes/user.routes");
const collectionRoutes = require("./routes/collection.routes");
const activityRoutes = require("./routes/activity.routes");
const adminRoutes = require("./routes/admin.routes");
const aiRoutes = require("./routes/ai.routes");
/* ─────────────────────────────────────────
App init
───────────────────────────────────────── */
const app = express();
const PORT = Number(process.env.PORT) || 5000;
app.disable("x-powered-by");
app.set("trust proxy", 1);
/* ─────────────────────────────────────────
Security — helmet
CSP loosened just enough for health/ping
endpoints to work from a browser tab
───────────────────────────────────────── */
app.use(
helmet({
crossOriginResourcePolicy: { policy: "cross-origin" },
contentSecurityPolicy: false, // disable CSP for pure API server
})
);
/* ─────────────────────────────────────────
Body parsers
2 mb for AI routes (code can be large)
───────────────────────────────────────── */
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true, limit: "2mb" }));
/* ─────────────────────────────────────────
CORS
───────────────────────────────────────── */
const ALLOWED_ORIGINS = [
"http://localhost:5173",
"http://localhost:3000",
...(process.env.CLIENT_URL
? process.env.CLIENT_URL.split(",").map((u) => u.trim())
: []),
].filter(Boolean);
const corsOptions = {
origin(origin, callback) {
// Allow server-to-server / curl / Postman (no origin header)
if (!origin) return callback(null, true);
if (ALLOWED_ORIGINS.includes(origin)) return callback(null, true);
return callback(
Object.assign(new Error(`CORS: origin "${origin}" is not allowed`), { status: 403 })
);
},
methods : ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "x-admin-key"],
credentials : true,
optionsSuccessStatus: 204,
};
// Preflight must come BEFORE globalLimiter so OPTIONS never hits the rate limiter
app.options("*", cors(corsOptions));
app.use(cors(corsOptions));
/* ─────────────────────────────────────────
Global rate limiter (after CORS / preflight)
───────────────────────────────────────── */
app.use(globalLimiter);
/* ─────────────────────────────────────────
Route-specific limiters (before routes)
───────────────────────────────────────── */
app.use("/api/auth/login", loginLimiter);
app.use("/api/auth/signup", signupLimiter);
app.use("/api/workspaces/join", joinLimiter);
/* ─────────────────────────────────────────
Health / diagnostic endpoints
───────────────────────────────────────── */
app.get("/ping", (_req, res) => res.send("pong"));
app.get("/health", (_req, res) => {
res.status(200).json({
status : "ok",
uptime : Math.floor(process.uptime()),
env : process.env.NODE_ENV || "development",
time : new Date().toISOString(),
node : process.version,
platform : `${os.type()} ${os.release()}`,
memoryMB : Math.round(process.memoryUsage().rss / 1024 / 1024),
});
});
app.get("/cors-test", (_req, res) => {
res.json({ message: "✅ CORS is working correctly" });
});
// ── Route map (dev only) ─────────────────────────────────────────────────────
// Hit GET /routes in development to see every registered route
if (process.env.NODE_ENV !== "production") {
app.get("/routes", (_req, res) => {
const routes = [];
app._router.stack.forEach((layer) => {
if (layer.route) {
routes.push({
path : layer.route.path,
methods: Object.keys(layer.route.methods).join(", ").toUpperCase(),
});
} else if (layer.name === "router" && layer.handle.stack) {
layer.handle.stack.forEach((sub) => {
if (sub.route) {
routes.push({
path : layer.regexp.source + sub.route.path,
methods: Object.keys(sub.route.methods).join(", ").toUpperCase(),
});
}
});
}
});
res.json({ count: routes.length, routes });
});
}
/* ─────────────────────────────────────────
API Routes
Order matters: more specific paths first
───────────────────────────────────────── */
app.use("/api/auth", authRoutes);
app.use("/api/snippets", snippetRoutes);
app.use("/api/workspaces", workspaceRoutes);
app.use("/api/user", githubRoutes);
app.use("/api/users", userRoutes);
app.use("/api/collections", collectionRoutes);
app.use("/api/activity", activityRoutes);
app.use("/api/admin", adminRoutes);
app.use("/api/ai", aiRoutes); // ✅ /api/ai/snippets/:id/review etc.
/* ─────────────────────────────────────────
404 — must be AFTER all routes
───────────────────────────────────────── */
app.use((req, res) => {
res.status(404).json({
error : "Route not found",
method: req.method,
path : req.path,
});
});
/* ─────────────────────────────────────────
Global error handler — must be LAST
(4-argument signature is required by Express)
───────────────────────────────────────── */
app.use(errorHandler);
/* ─────────────────────────────────────────
Server bootstrap
───────────────────────────────────────── */
let server;
async function startServer() {
try {
await connectDB();
server = app.listen(PORT, () => {
const divider = "─".repeat(42);
console.log(divider);
console.log(`🚀 Server : http://localhost:${PORT}`);
console.log(`🌍 Environment : ${process.env.NODE_ENV || "development"}`);
console.log(
`🔗 Origins : ${
ALLOWED_ORIGINS.length ? ALLOWED_ORIGINS.join(", ") : "none configured"
}`
);
console.log(`🤖 AI routes : /api/ai/snippets/:id/{review|explain|suggest-tags|fix|convert}`);
if (process.env.NODE_ENV !== "production") {
console.log(`🗺️ Route map : http://localhost:${PORT}/routes`);
}
console.log(divider);
});
// Increase keep-alive for Render / Railway deployments
server.keepAliveTimeout = 65_000;
server.headersTimeout = 70_000;
} catch (error) {
console.error("❌ Failed to start server:", error.message);
process.exit(1);
}
}
/* ─────────────────────────────────────────
Graceful shutdown
───────────────────────────────────────── */
function shutdown(signal) {
console.log(`\n⚠️ ${signal} received — shutting down gracefully…`);
if (!server) return process.exit(0);
// Stop accepting new connections
server.close((err) => {
if (err) {
console.error("❌ Error closing server:", err.message);
return process.exit(1);
}
console.log("✅ Server closed cleanly");
process.exit(0);
});
// Force-kill after 10 s if something hangs
setTimeout(() => {
console.error("❌ Force shutdown after 10 s timeout");
process.exit(1);
}, 10_000).unref();
}
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("unhandledRejection", (reason) => {
console.error("❌ Unhandled Promise Rejection:", reason);
});
process.on("uncaughtException", (error) => {
console.error("❌ Uncaught Exception:", error);
process.exit(1);
});
/* ─────────────────────────────────────────
Boot
───────────────────────────────────────── */
startServer();
module.exports = app;