-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
333 lines (279 loc) · 10.3 KB
/
Copy pathserver.js
File metadata and controls
333 lines (279 loc) · 10.3 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
const express = require('express');
const helmet = require('helmet');
const logger = require('./utils/logger');
const authRoutes = require('./routes/auth.routes');
const vpsRoutes = require('./routes/vps.routes');
const persistenceService = require('./services/persistence.service');
const proxmoxService = require('./services/proxmox.service');
// Load environment variables
require('dotenv').config();
// Initialize Express application
const app = express();
// ============================================================================
// SECURITY MIDDLEWARE (Requirement 13.1, 13.4, 13.5)
// ============================================================================
// Helmet security headers
app.use(helmet({
hsts: {
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
},
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Allow inline scripts for single-page app
imgSrc: ["'self'", 'data:', 'https:']
}
},
noSniff: true,
xssFilter: true,
referrerPolicy: { policy: 'strict-origin-when-cross-origin' }
}));
// ============================================================================
// STATIC FILES
// ============================================================================
// Serve static files from public directory
app.use(express.static('public'));
// ============================================================================
// CORS CONFIGURATION (Requirement 13.4)
// ============================================================================
app.use((req, res, next) => {
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim())
: ['http://localhost:3000', 'http://127.0.0.1:3000'];
const origin = req.headers.origin;
if (origin && allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
// Handle preflight requests
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
// ============================================================================
// BODY PARSING MIDDLEWARE
// ============================================================================
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// ============================================================================
// REQUEST LOGGING
// ============================================================================
app.use((req, res, next) => {
logger.info('Incoming request', {
method: req.method,
path: req.path,
ip: req.ip
});
next();
});
// ============================================================================
// HEALTH CHECK ENDPOINT (Requirement 5.1, 7.1)
// ============================================================================
app.get('/api/health', async (req, res) => {
const startTime = Date.now();
const health = {
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
checks: {}
};
try {
// Check Proxmox connectivity
try {
await proxmoxService.listVMs();
health.checks.proxmox = { status: 'ok', message: 'Proxmox connectivity verified' };
} catch (error) {
health.checks.proxmox = { status: 'error', message: 'Proxmox connectivity failed' };
health.status = 'degraded';
}
// Check JSON file read/write capability
try {
await persistenceService.readVPSData();
health.checks.persistence = { status: 'ok', message: 'Persistence layer accessible' };
} catch (error) {
health.checks.persistence = { status: 'error', message: 'Persistence layer failed' };
health.status = 'degraded';
}
// Check iptables accessibility
try {
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
await execFileAsync('iptables', ['-L', '-n', '-t', 'nat'], { timeout: 5000 });
health.checks.iptables = { status: 'ok', message: 'iptables accessible' };
} catch (error) {
health.checks.iptables = { status: 'error', message: 'iptables not accessible' };
health.status = 'degraded';
}
health.responseTime = Date.now() - startTime;
const statusCode = health.status === 'healthy' ? 200 : 503;
return res.status(statusCode).json({
success: health.status === 'healthy',
data: health
});
} catch (error) {
logger.error('Health check failed', { error: error.message });
return res.status(503).json({
success: false,
error: 'Health check failed',
data: {
status: 'unhealthy',
timestamp: new Date().toISOString()
}
});
}
});
// ============================================================================
// ROUTE MOUNTING (Requirement 13.1, 13.2, 13.3)
// ============================================================================
app.use('/api/auth', authRoutes);
app.use('/api/vps', vpsRoutes);
// ============================================================================
// 404 HANDLER
// ============================================================================
app.use((req, res) => {
res.status(404).json({
success: false,
error: 'Endpoint not found'
});
});
// ============================================================================
// GLOBAL ERROR HANDLING MIDDLEWARE (Requirement 15.2, 15.3, 15.4, 15.5)
// ============================================================================
app.use((err, req, res, next) => {
// Log full error details internally (Requirement 15.2)
logger.error('Unhandled error', {
error: err.message,
stack: err.stack,
path: req.path,
method: req.method,
ip: req.ip
});
// Determine appropriate status code (Requirement 15.3)
let statusCode = err.statusCode || 500;
// Sanitize error message (Requirement 15.4, 15.5)
let errorMessage = 'Internal server error';
if (statusCode === 400) {
errorMessage = err.message || 'Bad request';
} else if (statusCode === 401) {
errorMessage = 'Authentication required';
} else if (statusCode === 403) {
errorMessage = 'Access forbidden';
} else if (statusCode === 404) {
errorMessage = 'Resource not found';
} else if (statusCode === 429) {
errorMessage = 'Too many requests';
} else {
// Never expose internal error details in production (Requirement 15.4, 15.5)
errorMessage = 'An error occurred while processing your request';
}
// Return sanitized error response (Requirement 15.2, 15.3)
return res.status(statusCode).json({
success: false,
error: errorMessage
});
});
// ============================================================================
// STARTUP RECONCILIATION (Requirement 8.5, 8.6, 8.7)
// ============================================================================
async function performStartupReconciliation() {
try {
logger.info('Starting reconciliation with Proxmox');
await persistenceService.reconcileWithProxmox(proxmoxService);
logger.info('Reconciliation completed successfully');
} catch (error) {
// Continue startup even if reconciliation fails (Requirement 8.7)
logger.error('Reconciliation failed, but continuing startup', {
error: error.message,
stack: error.stack
});
}
}
// ============================================================================
// GRACEFUL SHUTDOWN HANDLING (Requirement 10.1, 10.2, 10.3)
// ============================================================================
let isShuttingDown = false;
let server;
function gracefulShutdown(signal) {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
logger.info(`Received ${signal}, starting graceful shutdown`);
// Stop accepting new connections
server.close(() => {
logger.info('Server closed, all connections terminated');
process.exit(0);
});
// Force shutdown after 30 seconds
setTimeout(() => {
logger.error('Forced shutdown after timeout');
process.exit(1);
}, 30000);
}
// Handle shutdown signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
logger.error('Uncaught exception', {
error: error.message,
stack: error.stack
});
gracefulShutdown('uncaughtException');
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled promise rejection', {
reason: reason,
promise: promise
});
});
// ============================================================================
// SERVER STARTUP (Requirement 13.1, 13.2, 13.3)
// ============================================================================
async function startServer() {
try {
// Perform startup reconciliation
await performStartupReconciliation();
// Get configuration from environment (Requirement 13.2, 13.3)
const PORT = process.env.PORT || 3000;
const BIND_ADDRESS = process.env.BIND_ADDRESS || '127.0.0.1';
// Start server (Requirement 13.1)
server = app.listen(PORT, BIND_ADDRESS, () => {
logger.info('VPS Control Panel started', {
port: PORT,
bindAddress: BIND_ADDRESS,
nodeVersion: process.version,
environment: process.env.NODE_ENV || 'production',
note: 'Single-process mode - PM2 cluster mode not supported'
});
});
// Handle server errors
server.on('error', (error) => {
if (error.code === 'EADDRINUSE') {
logger.error(`Port ${PORT} is already in use`);
} else if (error.code === 'EACCES') {
logger.error(`Permission denied to bind to ${BIND_ADDRESS}:${PORT}`);
} else {
logger.error('Server error', { error: error.message });
}
process.exit(1);
});
} catch (error) {
logger.error('Failed to start server', {
error: error.message,
stack: error.stack
});
process.exit(1);
}
}
// Start the server
startServer();
module.exports = app;