-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
283 lines (240 loc) · 9.94 KB
/
Copy pathserver.js
File metadata and controls
283 lines (240 loc) · 9.94 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
require('dotenv').config();
// Log rejections instead of risking abrupt process exit (e.g. legacy DB paths).
process.on('unhandledRejection', (reason) => {
const msg = reason && reason.stack ? reason.stack : String(reason);
console.error('[unhandledRejection]', msg);
});
const express = require('express');
const helmet = require('helmet');
const session = require('express-session');
const csrf = require('@dr.pogodin/csurf');
const cookieParser = require('cookie-parser');
const fs = require('fs');
const passport = require('passport');
const http = require('http');
const https = require('https');
const socketIo = require('socket.io');
const {serverLogger, logAccessedPath, logger} = require("./public/services/loggingService");
const startupCheck = require("./public/services/startupCheck");
const routeManager = require("./public/managers/routesManager");
const accountManagerRouter = require("./public/managers/accountManager");
const aiAgentManagerRouter = require("./public/managers/aiAgentManager");
const projectManagerRouter = require("./public/managers/projectManager");
const notifManager = require("./public/managers/notificationManager");
const statusManager = require("./public/managers/statusManager");
const PORT = process.env.PORT || 9090;
const app = express();
let server = null
async function createServer() {
try {
if (process.env.USE_NGINX_SSL === 'true') {
serverLogger.info("Starting HTTP Server with nginx https SSL");
server = http.createServer(app)
} else if (process.env.ENABLE_HTTPS === 'true') {
serverLogger.info("Starting local HTTPS Server");
if (!process.env.SSL_KEY_PATH || !process.env.SSL_CERT_PATH) {
throw new Error("SSL Key or Certificate paths not found");
}
const httpsOptions = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH),
};
server = https.createServer(httpsOptions, app);
} else {
serverLogger.warn("Starting HTTP Server, TRAFFIC IS NOT ENCRYPTED!!!");
serverLogger.warn("DO NOT USE THIS IN PRODUCTION!!");
server = http.createServer(app);
}
} catch (error) {
serverLogger.error("UNABLE TO START SERVER:", error);
serverLogger.warn("Please check if the server key and certificate files exist and are correctly configured.");
process.exit(1);
}
}
createServer()
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Store user socket connections (userID -> socketID)
const userSockets = new Map();
// Socket.io connection handling
io.on('connection', (socket) => {
console.log(`\n[Socket.io] Client connected: ${socket.id}`);
serverLogger.info(`Socket connected: ${socket.id}`);
// Register user socket
socket.on('register', (userID) => {
if (userID) {
userSockets.set(userID, socket.id);
console.log(`[Socket.io] User registered: ${userID} → socket ${socket.id}`);
console.log(`[Socket.io] Total connected users: ${userSockets.size}`);
console.log(`[Socket.io] Active users: [${Array.from(userSockets.keys()).join(', ')}]\n`);
serverLogger.info(`User ${userID} registered with socket ${socket.id}`);
} else {
console.log(`[Socket.io] ✗ Registration failed - no userID provided`);
}
});
socket.on('disconnect', () => {
// Remove user from map
for (const [userID, socketID] of userSockets.entries()) {
if (socketID === socket.id) {
userSockets.delete(userID);
console.log(`\n[Socket.io] User disconnected: ${userID}`);
console.log(`[Socket.io] Total connected users: ${userSockets.size}\n`);
serverLogger.info(`User ${userID} disconnected`);
break;
}
}
});
});
// Make io and userSockets globally available
global.io = io;
global.userSockets = userSockets;
async function serverSetUp() {
// Security headers
app.disable('x-powered-by');
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'",
"cdn.tailwindcss.com",
"unpkg.com",
"cdnjs.cloudflare.com",
"code.jquery.com",
"cdn.jsdelivr.net"],
styleSrc: ["'self'", "'unsafe-inline'",
"cdn.tailwindcss.com",
"cdnjs.cloudflare.com",
"fonts.googleapis.com",
"cdn.jsdelivr.net"],
fontSrc: ["'self'", "fonts.gstatic.com", "anima-uploads.s3.amazonaws.com", "cdn.jsdelivr.net", "data:"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "wss:", "ws:"],
frameSrc: ["'none'"],
frameAncestors: ["'none'"],
formAction: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
mediaSrc: ["'self'", "blob:"]
},
},
crossOriginEmbedderPolicy: false,
}));
app.use((req, res, next) => {
logAccessedPath(req)
next();
});
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(session({
secret: process.env.SESSION_SECRET || 'secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 7 * 24 * 60 * 60 * 1000,
sameSite: 'strict'
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.set('trust proxy', 1);
// CSRF protection setup (moved here from checkServerEnvironment)
if (process.env.ENABLE_USER_CHECKING === 'true') {
const csrfProtection = csrf({
cookie: {
httpOnly: true,
secure: false,
sameSite: 'lax'
}
});
app.use(csrfProtection);
serverLogger.warn(`The server is started in production mode with user checking enabled.`)
} else {
// Mock CSRF token for development
app.use((req, res, next) => {
req.csrfToken = () => 'disabled';
next();
});
}
app.set('view engine', 'ejs');
app.set('views', __dirname + '/public/views');
app.use(express.static('public'));
app.use("/api", accountManagerRouter);
app.use("/api", projectManagerRouter);
app.use("/api", notifManager);
app.use("/api", aiAgentManagerRouter);
app.use("/api", statusManager);
app.use("/", routeManager);
app.use((req, res) => {
if (req.originalUrl.startsWith("/api/")) {
return res.status(404).json({
success: false,
message: "API endpoint not found"
});
}
res.status(404).render("Error", {
statusCode: 404,
errorMessage: "The page you are looking for does not exist."
});
});
}
async function checkServerEnvironment() {
if (process.env.ENABLE_USER_CHECKING !== 'true') {
const red = '\x1b[31m';
const yellow = '\x1b[33m';
const reset = '\x1b[0m';
const bold = '\x1b[1m';
console.warn(`\n${red}${bold}${"=".repeat(70)}`);
console.warn(`WARNING: SECURITY FEATURES DISABLED`);
console.warn(`${"=".repeat(70)}${reset}`);
console.warn(`${yellow}User authentication and CSRF protection are NOT enforced!`);
console.warn(`This should ONLY be used in development/testing.`);
console.warn(`DO NOT run this configuration in production!${reset}`);
console.warn(`${red}${bold}To enforce User and CSRF checking, set the value of ENABLE_USER_CHECKING environment variable to 'true'${reset}`);
console.warn(`${red}${bold}${"=".repeat(70)}${reset}\n`);
console.warn(`${yellow}Waiting 15 seconds before starting server...${reset}`);
serverLogger.warn(`SERVER STARTED IN DEVELOPMENT MODE - SECURITY FEATURES DISABLED!`);
serverLogger.warn(`User authentication and CSRF protection are NOT enforced.`);
const start = Date.now();
while (Date.now() - start < 15000) {
}
console.warn(`${yellow}Proceeding with server startup...${reset}\n`);
serverLogger.info(`Server startup resumed.`);
}
// Add cache control for static files in development
if (process.env.NODE_ENV !== 'production') {
app.use((req, res, next) => {
// Disable caching for JS, CSS, and other static files in development
if (req.url.match(/\.(js|css|json)$/)) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
next();
});
}
}
async function startServer() {
try {
serverLogger.info('Server is starting...');
await checkServerEnvironment()
await startupCheck(); // ensure DB + MinIO are ready
await serverSetUp()
server.listen(PORT, () => {
const protocol = process.env.ENABLE_HTTPS === 'true' ? 'https' : 'http';
serverLogger.info(`Server running on ${protocol}://localhost:${PORT}`);
serverLogger.info('Server is now online');
});
} catch (err) {
serverLogger.error(`Server Startup Failed:`, err);
console.error("Startup failed:", err);
process.exit(1);
}
}
startServer();