-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
Β·397 lines (338 loc) Β· 10.6 KB
/
Copy pathserver.js
File metadata and controls
executable file
Β·397 lines (338 loc) Β· 10.6 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/usr/bin/env node
import process from "node:process";
/**
* Turning Wheel - Secure Full-Stack Backend
* Complete E2E encryption, JWT authentication, and mystical API
*/
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import slowDown from 'express-slow-down';
import morgan from 'morgan';
import dotenv from 'dotenv';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// Security imports
import ExpressBrute from 'express-brute';
import MongoStore from 'express-brute/lib/stores/memory.js';
import mongoSanitize from 'express-mongo-sanitize';
import xss from 'xss';
import hpp from 'hpp';
// Custom modules
import logger from './utils/logger.js';
import { validateEnv } from './utils/validation.js';
import { initializeDatabase as _initializeDatabase } from './config/database.js';
import { initializeRedis as _initializeRedis } from './config/redis.js';
import { setupWebSocket } from './config/websocket.js';
// Route imports
import authRoutes from './routes/auth.js';
import wheelRoutes from './routes/wheel.js';
import userRoutes from './routes/user.js';
import analyticsRoutes from './routes/analytics.js';
import healthRoutes from './routes/health.js';
import encryptionRoutes from './routes/encryption.js';
// Middleware imports
import { authMiddleware } from './middleware/auth.js';
import { errorHandler } from './middleware/errorHandler.js';
import { securityMiddleware } from './middleware/security.js';
import { validationMiddleware } from './middleware/validation.js';
// Load environment variables
dotenv.config();
// Validate environment
validateEnv();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 8080;
const NODE_ENV = process.env.NODE_ENV || 'development';
// Trust proxy for rate limiting and security
app.set('trust proxy', 1);
// === SECURITY MIDDLEWARE STACK ===
// Helmet for security headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'"],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
workerSrc: ["'none'"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}
}));
// CORS configuration
const corsOptions = {
origin: process.env.FRONTEND_URL || 'http://localhost:3000',
credentials: true,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-Encryption-Key'],
exposedHeaders: ['X-Total-Count', 'X-Rate-Limit-*']
};
app.use(cors(corsOptions));
// Compression for better performance
app.use(compression({
level: 6,
threshold: 1024,
filter: (req, res) => {
if (req.headers['x-no-compression']) {
return false;
}
return compression.filter(req, res);
}
}));
// Request logging
app.use(morgan(NODE_ENV === 'production' ? 'combined' : 'dev', {
stream: {
write: (message) => logger.info(message.trim())
}
}));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: NODE_ENV === 'production' ? 100 : 1000,
message: {
error: 'Too many requests from this IP, please try again later.',
retryAfter: '15 minutes'
},
standardHeaders: true,
legacyHeaders: false,
handler: (req, res) => {
logger.warn(`Rate limit exceeded for IP: ${req.ip}`);
res.status(429).json({
error: 'Rate limit exceeded',
message: 'Too many requests, please slow down'
});
}
});
app.use('/api/', limiter);
// Slow down middleware for additional protection
const speedLimiter = slowDown({
windowMs: 15 * 60 * 1000, // 15 minutes
delayAfter: 50, // allow 50 requests per 15 minutes at full speed
delayMs: 500, // add 500ms delay per request after delayAfter
maxDelayMs: 20000, // max delay of 20 seconds
});
app.use('/api/', speedLimiter);
// Brute force protection
const bruteStore = new MongoStore();
const bruteforce = new ExpressBrute(bruteStore, {
freeRetries: 5,
minWait: 5 * 60 * 1000, // 5 minutes
maxWait: 60 * 60 * 1000, // 1 hour
lifetime: 24 * 60 * 60, // 1 day (seconds)
});
// Body parsing with size limits
app.use(express.json({
limit: '10mb',
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
app.use(express.urlencoded({
extended: true,
limit: '10mb'
}));
// Security sanitization
app.use(mongoSanitize({
replaceWith: '_'
}));
app.use(hpp());
// XSS protection middleware
app.use((req, res, next) => {
if (req.body) {
Object.keys(req.body).forEach(key => {
if (typeof req.body[key] === 'string') {
req.body[key] = xss(req.body[key]);
}
});
}
next();
});
// Custom security middleware
app.use(securityMiddleware);
// Request ID and correlation
app.use((req, res, next) => {
req.id = crypto.randomUUID();
req.timestamp = new Date().toISOString();
res.setHeader('X-Request-ID', req.id);
next();
});
// === STATIC FILE SERVING ===
app.use('/static', express.static(join(__dirname, '../public'), {
maxAge: '1d',
etag: true,
lastModified: true
}));
// === API ROUTES ===
// Health check (no auth required)
app.use('/api/health', healthRoutes);
// Authentication routes
app.use('/api/auth', bruteforce.prevent, authRoutes);
// Encryption/Decryption utility routes
app.use('/api/crypto', authMiddleware, encryptionRoutes);
// Protected routes (require authentication)
app.use('/api/wheel', authMiddleware, wheelRoutes);
app.use('/api/user', authMiddleware, userRoutes);
app.use('/api/analytics', authMiddleware, analyticsRoutes);
// === MYSTICAL ENDPOINTS ===
// Get all wheel stages
app.get('/api/wheel/stages', authMiddleware, async (req, res) => {
try {
const stages = await getWheelStages();
res.json({
success: true,
data: stages,
timestamp: new Date().toISOString()
});
} catch (error) {
logger.error('Failed to fetch wheel stages:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch wheel stages'
});
}
});
// Record user journey progress
app.post('/api/wheel/progress', authMiddleware, validationMiddleware, async (req, res) => {
try {
const { stageId, timeSpent, insights, encrypted } = req.body;
const userId = req.user.id;
const progress = await recordProgress({
userId,
stageId,
timeSpent,
insights: encrypted ? insights : await encryptInsights(insights),
timestamp: new Date()
});
res.json({
success: true,
data: progress,
message: 'Progress recorded successfully'
});
} catch (error) {
logger.error('Failed to record progress:', error);
res.status(500).json({
success: false,
error: 'Failed to record progress'
});
}
});
// === WEBSOCKET INITIALIZATION ===
const server = app.listen(PORT, () => {
logger.info(`π Turning Wheel Backend Server running on port ${PORT}`);
logger.info(`π Environment: ${NODE_ENV}`);
logger.info(`π Security: E2E encryption enabled`);
logger.info(`π Mystical API: Ready for spiritual journeys`);
});
// Setup WebSocket for real-time features
setupWebSocket(server);
// === ERROR HANDLING ===
// 404 handler
app.use('*', (req, res) => {
logger.warn(`404 - Route not found: ${req.method} ${req.originalUrl}`);
res.status(404).json({
success: false,
error: 'Route not found',
message: `The path ${req.originalUrl} does not exist on this server`
});
});
// Global error handler (must be last)
app.use(errorHandler);
// === GRACEFUL SHUTDOWN ===
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
/**
* Initiates a graceful shutdown of the server upon receiving a signal.
*
* The function logs the received signal and attempts to close the HTTP server.
* It then proceeds to close database and Redis connections, logging each step.
* If the shutdown process takes longer than 30 seconds, it forcefully exits the process.
* In case of any errors during the shutdown, it logs the error and exits with a failure status.
*
* @param {string} signal - The signal that triggered the shutdown process.
*/
function gracefulShutdown(signal) {
logger.info(`Received ${signal}. Starting graceful shutdown...`);
server.close(async () => {
logger.info('HTTP server closed.');
try {
// Close database connections
await closeDatabase();
logger.info('Database connections closed.');
// Close Redis connection
await closeRedis();
logger.info('Redis connection closed.');
logger.info('Graceful shutdown completed.');
process.exit(0);
} catch (error) {
logger.error('Error during shutdown:', error);
process.exit(1);
}
});
// Force close after 30 seconds
setTimeout(() => {
logger.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 30000);
}
// === HELPER FUNCTIONS ===
/**
* Retrieves the stages of the wheel, typically from a database.
*/
function getWheelStages() {
// This would typically come from database
return [
{
id: 1,
title: "Creative Remembering",
symbol: "π±",
essence: "The seeds of the past are unearthed, not as static relics, but as living fragments ready to be reimagined.",
meaning: "Our histories are fertile soil β the fragments we carry forward become the foundation for new growth.",
action: "Hold a small stone or seed and name aloud one memory you wish to carry forward.",
chant: "In the deep hum of time, I awaken what was β\\nCreative Remembering, the seeds unbroken."
},
// ... other stages would be loaded from database
];
}
/**
* Records the progress data for a user.
*/
function recordProgress(progressData) {
// This would save to database
logger.info(`Recording progress for user ${progressData.userId}, stage ${progressData.stageId}`);
return progressData;
}
/** Encrypts insights using AES-GCM encryption. */
function encryptInsights(insights) {
// This would use AES-GCM encryption
return insights; // Placeholder
}
/**
* Closes database connections.
*/
async function closeDatabase() {
// Close database connections
}
/**
* Closes Redis connections.
*/
async function closeRedis() {
// Close Redis connections
}
// Export for testing
export default app;