-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
304 lines (272 loc) · 9.02 KB
/
index.js
File metadata and controls
304 lines (272 loc) · 9.02 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
require('dotenv').config();
const express = require('express');
const http = require('http');
const cors = require('cors');
const helmet = require('helmet');
const { Server } = require('socket.io');
const path = require('path');
const db = require('./db');
const { connectRedis } = require('./redis');
const setupRedisAdapter = require('./socket/adapter');
const metrics = require('./metrics');
// Import routes
const pollRoutes = require('./routes/polls');
const authRoutes = require('./routes/auth');
// Import middleware
const { apiRateLimiter } = require('./middleware/rateLimiter');
// Initialize Express app
const app = express();
const server = http.createServer(app);
// Set up Socket.io with proper CORS
const io = new Server(server, {
cors: {
origin: process.env.NODE_ENV === 'production'
? process.env.ALLOWED_ORIGINS?.split(',') || process.env.CLIENT_URL
: ['http://localhost:3000', 'http://localhost:5173'],
methods: ['GET', 'POST'],
credentials: true
}
});
// Configure CORS middleware
app.use(cors({
origin: process.env.NODE_ENV === 'production'
? process.env.ALLOWED_ORIGINS?.split(',') || process.env.CLIENT_URL
: ['http://localhost:3000', 'http://localhost:5173'],
credentials: true
}));
// Configure Helmet with OWASP recommended security headers
app.use(
helmet({
// Content-Security-Policy
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", process.env.CLIENT_URL || ''], // Add CDN sources if needed
styleSrc: ["'self'", "'unsafe-inline'", process.env.CLIENT_URL || ''],
imgSrc: ["'self'", "data:", process.env.CLIENT_URL || ''],
connectSrc: ["'self'", process.env.API_URL || '', process.env.CLIENT_URL || ''],
fontSrc: ["'self'", "data:", process.env.CLIENT_URL || ''],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
baseUri: ["'self'"]
}
},
// X-XSS-Protection
xssFilter: true,
// X-Content-Type-Options
noSniff: true,
// X-Frame-Options
frameguard: {
action: 'deny'
},
// Strict-Transport-Security
hsts: {
maxAge: 15552000, // 180 days
includeSubDomains: true,
preload: true
},
// Referrer-Policy
referrerPolicy: {
policy: 'strict-origin-when-cross-origin'
},
// Permissions-Policy (formerly Feature-Policy)
permittedCrossDomainPolicies: {
permittedPolicies: "none"
}
})
);
// Add Permissions-Policy header separately as Helmet doesn't fully support it yet
app.use((req, res, next) => {
res.setHeader(
'Permissions-Policy',
'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'
);
next();
});
// For HTTPS environments, add additional security
if (process.env.NODE_ENV === 'production') {
// Force HTTPS
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
// Trust the X-Forwarded-Proto header only from trusted proxies
if (req.secure || req.headers['x-forwarded-proto'] === 'https') {
next();
} else {
res.redirect(`https://${req.hostname}${req.url}`);
}
} else {
next();
}
});
}
// Add security headers
app.use((req, res, next) => {
// Clear Site Data (for logout routes, if applicable)
if (req.path === '/api/auth/logout') {
res.setHeader('Clear-Site-Data', '"cache", "cookies", "storage"');
}
// Cross-Origin-Resource-Policy
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
// Cross-Origin-Opener-Policy
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
// Cross-Origin-Embedder-Policy
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
next();
});
app.use(express.json({ limit: '1mb' })); // Limit request body size
app.use(metrics.metricsMiddleware);
app.use(apiRateLimiter);
// Health check route
app.get('/health', async (req, res) => {
try {
const dbConnected = await db.testConnection();
const redisConnected = await connectRedis.testConnection(); // Assuming this method exists
res.json({
status: dbConnected && redisConnected ? 'ok' : 'degraded',
database: dbConnected ? 'connected' : 'disconnected',
redis: redisConnected ? 'connected' : 'disconnected'
});
} catch (error) {
console.error('Health check failed:', error);
res.status(500).json({
status: 'error',
message: 'Health check failed',
error: process.env.NODE_ENV === 'development' ? error.message : undefined
});
}
});
// Metrics endpoint with proper authentication
if (process.env.NODE_ENV === 'production') {
const metricsAuth = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || authHeader !== `Bearer ${process.env.METRICS_TOKEN}`) {
return res.status(401).send('Unauthorized');
}
next();
};
app.get('/metrics', metricsAuth, async (req, res) => {
try {
res.set('Content-Type', metrics.register.contentType);
res.end(await metrics.register.metrics());
} catch (error) {
console.error('Error generating metrics:', error);
res.status(500).send('Error generating metrics');
}
});
} else {
app.get('/metrics', async (req, res) => {
try {
res.set('Content-Type', metrics.register.contentType);
res.end(await metrics.register.metrics());
} catch (error) {
console.error('Error generating metrics:', error);
res.status(500).send('Error generating metrics');
}
});
}
// Routes
app.use('/api/polls', pollRoutes);
app.use('/api/auth', authRoutes);
// Add security headers for all responses
app.use((req, res, next) => {
// Cache-Control header to prevent sensitive information caching
if (req.path.startsWith('/api/')) {
res.setHeader('Cache-Control', 'no-store, max-age=0');
res.setHeader('Pragma', 'no-cache');
}
next();
});
// Serve static files in production
if (process.env.NODE_ENV === 'production') {
// Add cache headers for static assets
app.use(express.static(path.join(__dirname, '../client/dist'), {
maxAge: '1y',
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
}
}
}));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/dist/index.html'));
});
}
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Server error:', err.stack);
metrics.errorCounter.inc({ path: req.path }); // Track errors by path
// Don't expose error details in production
res.status(500).json({
message: 'Something went wrong!',
error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
// Start server function
async function startServer() {
try {
// Connect to database
await db.connect();
console.log('Database connected successfully');
// Connect to Redis
await connectRedis();
console.log('Redis connected successfully');
// Set up Redis adapter for Socket.IO
await setupRedisAdapter(io);
console.log('Redis adapter setup complete');
// Initialize socket handlers with authentication
require('./socket')(io);
// Track WebSocket connections
io.on('connection', (socket) => {
metrics.websocketConnectionsGauge.inc();
// Implement socket authentication
const token = socket.handshake.auth.token;
if (!token) {
console.warn('Socket connection attempt without authentication');
socket.disconnect(true);
return;
}
// Add listener for disconnect to properly decrement the counter
socket.on('disconnect', () => {
metrics.websocketConnectionsGauge.dec();
});
});
// Start server
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Health check available at http://localhost:${PORT}/health`);
console.log(`Metrics available at http://localhost:${PORT}/metrics`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
// Start the server
startServer();
// Handle graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM signal received. Closing HTTP server...');
server.close(() => {
console.log('HTTP server closed');
db.disconnect().then(() => {
console.log('Database connections closed');
process.exit(0);
});
});
});
// Handle uncaught exceptions and unhandled promise rejections
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
metrics.errorCounter.inc({ type: 'uncaughtException' });
// Give the server a grace period to finish existing requests
setTimeout(() => {
process.exit(1);
}, 1000);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
metrics.errorCounter.inc({ type: 'unhandledRejection' });
});
module.exports = { app, server, io };