-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathserver.js
More file actions
295 lines (255 loc) Β· 9.58 KB
/
server.js
File metadata and controls
295 lines (255 loc) Β· 9.58 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
require('dotenv').config({ override: true });
const express = require('express');
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const { exec } = require('child_process');
const logger = require('./utils/logger');
const requestLoggingMiddleware = require('./middleware/requestLogger');
const { sessionMonitorMiddleware } = require('./middleware/sessionMonitor');
const { structuredErrorHandler } = require('./middleware/structuredErrorHandler');
const responseContractMiddleware = require('./middleware/responseContract');
const { localeMiddleware } = require('./utils/messages');
const {
errorLogger,
responseTimeLogger,
uncaughtExceptionHandler,
unhandledRejectionHandler
} = require('./middleware/errorLogger');
const requestIdMiddleware = require("./middleware/requestId");
const helmet = require('helmet');
const cors = require('cors');
const swaggerUi = require('swagger-ui-express');
const yaml = require('yamljs');
const rateLimit = require('express-rate-limit');
const uploadRoutes = require('./routes/uploadRoutes');
const systemRoutes = require('./routes/systemRoutes');
const { metricsMiddleware, metricsEndpoint } = require('./Monitor_&_Logging/metrics');
const { runAlertCheckJob } = require('./services/securityAlertService');
const FRONTEND_ORIGIN = 'http://localhost:3000';
console.log('π§ Environment Variables Check:');
console.log(' SUPABASE_URL:', process.env.SUPABASE_URL ? 'β Set' : 'β Missing');
console.log(' SUPABASE_ANON_KEY:', process.env.SUPABASE_ANON_KEY ? 'β Set' : 'β Missing');
console.log(' HTTPS_PORT:', process.env.HTTPS_PORT || '443 (default)');
console.log(' HTTP_PORT:', process.env.HTTP_PORT || process.env.PORT || '80 (default)');
console.log('');
const app = express();
const HTTPS_PORT = Number(process.env.HTTPS_PORT) || 443;
const HTTP_PORT = Number(process.env.HTTP_PORT || process.env.PORT) || 80;
const tlsKeyPath = process.env.TLS_KEY_PATH || path.join(__dirname, 'certs', 'local-key.pem');
const tlsCertPath = process.env.TLS_CERT_PATH || path.join(__dirname, 'certs', 'local-cert.pem');
let db = require('./dbConnection');
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const tempDir = path.join(uploadsDir, 'temp');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
function cleanupOldFiles() {
const now = Date.now();
const ONE_DAY = 24 * 60 * 60 * 1000;
try {
for (const file of fs.readdirSync(tempDir)) {
const filePath = path.join(tempDir, file);
const stats = fs.statSync(filePath);
if (now - stats.mtimeMs > ONE_DAY) {
fs.unlinkSync(filePath);
}
}
} catch (err) {
console.error('Error during file cleanup:', err);
}
}
cleanupOldFiles();
setInterval(cleanupOldFiles, 3 * 60 * 60 * 1000);
let alertIntervalId = null;
// --- Trusted early middlewares ---
app.use(requestIdMiddleware);
app.use(requestLoggingMiddleware);
app.use(sessionMonitorMiddleware);
app.use(localeMiddleware);
app.use(responseContractMiddleware);
app.use(cors({
origin: (origin, callback) => {
if (!origin) return callback(null, true);
if (
origin.startsWith('http://localhost') ||
origin.startsWith('http://127.0.0.1') ||
origin.startsWith('chrome-extension://eggdlmopfankeonchoflhfoglaakobma') ||
origin.startsWith('https://apifox.cn-hangzhou.log.aliyuncs.com')
) {
callback(null, true);
} else {
callback(new Error(`CORS blocked: ${origin}`));
}
},
credentials: true,
}));
app.options('*', cors({ origin: FRONTEND_ORIGIN, credentials: true }));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
app.set('trust proxy', 1);
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", 'https://cdn.jsdelivr.net'],
styleSrc: ["'self'", "'unsafe-inline'", 'https://cdn.jsdelivr.net'],
objectSrc: ["'none'"],
},
},
crossOriginEmbedderPolicy: true,
hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 1000,
standardHeaders: true,
legacyHeaders: false,
message: { status: 429, error: 'Too many requests, please try again later.' },
});
app.use(limiter);
try {
const swaggerDocument = yaml.load('./index.yaml');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
console.log('π Swagger loaded successfully');
} catch (e) {
console.warn('β οΈ Swagger YAML failed to parse β /api-docs disabled:', String(e.message).split('\n')[0]);
}
app.use(responseTimeLogger);
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(metricsMiddleware);
app.get('/api/metrics', metricsEndpoint);
app.get('/api/ai/stats', (req, res) => {
const aiMonitor = require('./services/aiServiceMonitor');
res.json({ success: true, data: aiMonitor.getStats() });
});
app.get('/api/health', (_req, res) => {
res.json({ status: 'ok', tls: '1.3 enforced' });
});
app.get('/api', (_req, res) => {
res.json({
status: 'ok',
message: 'NutriHelp API is running',
uptime: process.uptime(),
metrics: '/api/metrics',
docs: '/api-docs',
});
});
app.get('/', (_req, res) => res.redirect('/api'));
app.use('/api/system', systemRoutes);
const routesRegistrar = require('./routes');
routesRegistrar(app);
app.use('/api', uploadRoutes);
app.use('/uploads', express.static('uploads'));
app.use('/api/sms', require('./routes/sms'));
app.use('/security', require('./routes/securityEvents'));
app.use(errorLogger);
app.use(structuredErrorHandler);
app.use((err, req, res, next) => {
const status = err.status || 500;
const message = process.env.NODE_ENV === 'production' ? 'Internal Server Error' : err.message;
res.status(status).json({
success: false,
error: message,
requestId: req.requestId,
timestamp: new Date().toISOString(),
});
});
process.on('uncaughtException', uncaughtExceptionHandler);
process.on('unhandledRejection', unhandledRejectionHandler);
function gracefulShutdown(signal) {
console.log(`\n[server] ${signal} received β shutting down gracefully`);
if (alertIntervalId) {
clearInterval(alertIntervalId);
alertIntervalId = null;
console.log('[server] CT-004 Alert checking job stopped');
}
httpsServer.close(() => process.exit(0));
setTimeout(() => process.exit(1), 10000).unref();
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
function createHttpsServer() {
try {
const tlsOptions = {
key: fs.readFileSync(tlsKeyPath),
cert: fs.readFileSync(tlsCertPath),
minVersion: 'TLSv1.3',
maxVersion: 'TLSv1.3',
};
return https.createServer(tlsOptions, app);
} catch (error) {
if (process.env.NODE_ENV === 'production') {
console.error('Failed to start HTTPS server with TLS 1.3 enforcement.');
process.exit(1);
}
console.warn('β οΈ TLS certs not found β falling back to HTTP for local development.');
return null;
}
}
function createRedirectServer() {
return http.createServer((req, res) => {
const host = (req.headers.host || 'localhost').replace(/:\d+$/, `:${HTTPS_PORT}`);
const redirectUrl = `https://${host}${req.url || '/'}`;
res.writeHead(301, { Location: redirectUrl });
res.end();
});
}
const httpsServer = createHttpsServer();
const useHttpFallback = httpsServer === null;
const activePort = useHttpFallback ? HTTP_PORT : HTTPS_PORT;
const activeServer = useHttpFallback ? http.createServer(app) : httpsServer;
if (!useHttpFallback) {
const redirectServer = createRedirectServer();
redirectServer.on('error', (err) => {
if (err.code === 'EACCES' || err.code === 'EADDRINUSE') {
console.warn(`β οΈ HTTP redirect server could not start on port ${HTTP_PORT} (${err.code}).`);
return;
}
throw err;
});
redirectServer.listen(HTTP_PORT);
}
activeServer.listen(activePort, async () => {
console.log('\nπ NutriHelp API launched successfully!');
console.log('='.repeat(50));
const proto = useHttpFallback ? 'http' : 'https';
if (useHttpFallback) {
console.log(`π HTTP server running on port ${activePort} (dev mode β no TLS)`);
console.log(`π Swagger UI: http://localhost:${activePort}/api-docs`);
} else {
console.log(`π HTTPS server running on port ${activePort} (TLS 1.3 only)`);
console.log(`π HTTP redirect server running on port ${HTTP_PORT}`);
console.log(`π Swagger UI: https://localhost:${activePort}/api-docs`);
}
console.log('='.repeat(50));
console.log('π‘ Press Ctrl+C to stop the server \n');
// CT-004: Start alert job only after the server is fully bound and ready.
// The interval callback is wrapped so a single failing run never stops
// future runs (runAlertCheckJob already has an internal try/catch).
try {
await runAlertCheckJob();
alertIntervalId = setInterval(async () => {
try {
await runAlertCheckJob();
} catch (err) {
console.error('[server] Alert check job failed unexpectedly:', err.message);
}
}, 5 * 60 * 1000);
console.log('[server] CT-004 Alert checking job initialized (5-minute interval)');
} catch (err) {
console.warn('[server] Failed to run initial alert check:', err.message);
}
if (process.platform === 'win32') {
exec(`start https://localhost:${HTTPS_PORT}/api-docs`);
}
});
module.exports = app;