const express = require('express'); const cors = require('cors'); const helmet = require('helmet'); const morgan = require('morgan'); const path = require('path'); const rateLimit = require('express-rate-limit'); require('dotenv').config(); // Import utilities and services const logger = require('./src/utils/logger'); const { connectDB, isDatabaseConnected } = require('./src/utils/database'); const { connectRedis } = require('./src/utils/redis'); // Create Express application const app = express(); const PORT = process.env.PORT || 5001; // Security middleware with UGA-specific headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], scriptSrc: ["'self'", "'unsafe-inline'"], fontSrc: ["'self'", "https://fonts.gstatic.com"], imgSrc: ["'self'", "data:", "https:", "http:"], connectSrc: ["'self'", "http://localhost:11434", "ws:", "wss:", "https://api.openai.com"] } }, crossOriginEmbedderPolicy: false, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } })); // CORS configuration for UGA environment app.use(cors({ origin: function (origin, callback) { // Allow requests with no origin (like mobile apps or curl requests) if (!origin) return callback(null, true); const allowedOrigins = [ 'http://localhost:3000', 'http://localhost:7860', 'https://uga.edu', 'https://*.uga.edu', 'https://huggingface.co', 'https://*.hf.space' ]; // Check if origin matches any allowed pattern const isAllowed = allowedOrigins.some(pattern => { if (pattern.includes('*')) { const regex = new RegExp(pattern.replace(/\*/g, '.*')); return regex.test(origin); } return pattern === origin; }); if (isAllowed || process.env.NODE_ENV === 'development') { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }, credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'] })); // Request logging app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) }, skip: (req) => req.url === '/health' && req.method === 'GET' })); // Rate limiting with different limits for different endpoints const generalLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs message: { success: false, error: 'Too many requests from this IP, please try again later.', retryAfter: '15 minutes' }, standardHeaders: true, legacyHeaders: false, }); const chatLimiter = rateLimit({ windowMs: 1 * 60 * 1000, // 1 minute max: 20, // limit each IP to 20 chat requests per minute message: { success: false, error: 'Chat rate limit exceeded. Please wait before sending another message.', retryAfter: '1 minute' }, standardHeaders: true, legacyHeaders: false, }); const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5, // limit each IP to 5 auth attempts per windowMs message: { success: false, error: 'Too many authentication attempts, please try again later.', retryAfter: '15 minutes' }, standardHeaders: true, legacyHeaders: false, }); // Apply rate limiting app.use('/api/auth', authLimiter); app.use('/api/chat', chatLimiter); app.use('/api', generalLimiter); // Body parsing with enhanced limits and validation app.use(express.json({ limit: '10mb', verify: (req, res, buf) => { try { JSON.parse(buf); } catch (e) { res.status(400).json({ success: false, error: 'Invalid JSON format' }); throw new Error('Invalid JSON'); } } })); app.use(express.urlencoded({ extended: true, limit: '10mb' })); // Trust proxy for proper IP detection in production if (process.env.NODE_ENV === 'production') { app.set('trust proxy', 1); } // Serve static files app.use(express.static(path.join(__dirname, 'public'))); // Database and Redis connections const initializeServices = async () => { try { // Initialize database connection await connectDB(); // Initialize Redis connection (optional) await connectRedis(); logger.info('All services initialized successfully'); } catch (error) { logger.error('Service initialization failed:', error); // Don't exit process - allow app to run without optional services } }; // Enhanced health check endpoint app.get('/health', async (req, res) => { const startTime = Date.now(); try { const health = { status: 'healthy', timestamp: new Date().toISOString(), uptime: Math.floor(process.uptime()), memory: { used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024), total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024), external: Math.round(process.memoryUsage().external / 1024 / 1024) }, services: { database: isDatabaseConnected() ? 'connected' : 'disconnected', redis: 'checking...', ollama: 'checking...' }, environment: process.env.NODE_ENV || 'development', version: process.env.npm_package_version || '1.0.0', responseTime: 0 }; // Check Redis health try { const { redisUtils } = require('./src/utils/redis'); await redisUtils.set('health_check', 'ok'); const result = await redisUtils.get('health_check'); health.services.redis = result === 'ok' ? 'connected' : 'error'; await redisUtils.del('health_check'); } catch (error) { health.services.redis = 'disconnected'; } // Check Ollama health try { const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434'; const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 3000); const response = await fetch(`${ollamaUrl}/api/tags`, { method: 'GET', signal: controller.signal }); clearTimeout(timeoutId); health.services.ollama = response.ok ? 'connected' : 'error'; } catch (error) { health.services.ollama = 'disconnected'; } // Calculate overall health status const serviceStatuses = Object.values(health.services); if (serviceStatuses.every(status => status === 'connected')) { health.status = 'healthy'; } else if (serviceStatuses.some(status => status === 'connected')) { health.status = 'degraded'; } else { health.status = 'unhealthy'; } health.responseTime = Date.now() - startTime; const statusCode = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503; res.status(statusCode).json({ success: true, data: health }); } catch (error) { logger.error('Health check failed:', error); res.status(503).json({ success: false, error: 'Health check failed', timestamp: new Date().toISOString(), responseTime: Date.now() - startTime }); } }); // API Routes with proper error handling try { // Authentication routes app.use('/api/auth', require('./src/routes/auth')); // Chat routes app.use('/api/chat', require('./src/routes/chat')); // Dashboard routes app.use('/api/dashboard', require('./src/routes/dashboard')); // Search routes app.use('/api/search', require('./src/routes/search')); // Events routes app.use('/api/events', require('./src/routes/events')); // User routes app.use('/api/user', require('./src/routes/user')); // UGA-specific routes app.use('/api/uga', require('./src/routes/uga')); // Dining routes app.use('/api/dining', require('./src/routes/dining')); // Faculty routes app.use('/api/faculty', require('./src/routes/faculty')); // Document routes app.use('/api/documents', require('./src/routes/documents')); logger.info('All API routes loaded successfully'); } catch (error) { logger.error('Failed to load API routes:', error); } // Serve dashboard app.get('/dashboard', (req, res) => { res.sendFile(path.join(__dirname, 'dashboard.html')); }); // Serve demo app.get('/demo', (req, res) => { res.sendFile(path.join(__dirname, 'demo.html')); }); // API documentation endpoint app.get('/api', (req, res) => { res.json({ success: true, message: 'UGA edi.chat Backend API', version: '1.0.0', endpoints: { authentication: { 'POST /api/auth/register': 'Register new user account', 'POST /api/auth/login': 'Login with username/password', 'POST /api/auth/logout': 'Logout user', 'GET /api/auth/me': 'Get current user profile', 'PUT /api/auth/profile': 'Update user profile', 'POST /api/auth/forgot-password': 'Request password reset', 'POST /api/auth/reset-password': 'Reset password with token', 'POST /api/auth/change-password': 'Change password', 'POST /api/auth/verify-email': 'Verify email address' }, chat: { 'POST /api/chat': 'Send chat message and get AI response', 'GET /api/chat/history': 'Get chat history', 'DELETE /api/chat/history/:id': 'Delete chat session' }, uga: { 'GET /api/uga/info': 'Get UGA information', 'GET /api/uga/calendar': 'Get academic calendar', 'GET /api/uga/directory': 'Search UGA directory' }, events: { 'GET /api/events': 'Get UGA events', 'GET /api/events/:id': 'Get specific event', 'GET /api/events/search': 'Search events' }, dining: { 'GET /api/dining/menus': 'Get dining hall menus', 'GET /api/dining/locations': 'Get dining locations', 'GET /api/dining/hours': 'Get dining hours' }, search: { 'POST /api/search': 'Perform web search', 'GET /api/search/status': 'Get search service status', 'GET /api/search/suggestions': 'Get search suggestions' }, system: { 'GET /health': 'System health check', 'GET /api/dashboard/*': 'Dashboard analytics', 'GET /dashboard': 'Dashboard interface' } }, documentation: 'Visit /dashboard for system monitoring' }); }); // Request ID middleware for tracking app.use((req, res, next) => { req.id = Math.random().toString(36).substr(2, 9); res.setHeader('X-Request-ID', req.id); next(); }); // Error handling middleware app.use((err, req, res, next) => { const errorId = req.id || Math.random().toString(36).substr(2, 9); logger.error('Unhandled error:', { errorId, message: err.message, stack: err.stack, url: req.url, method: req.method, ip: req.ip, userAgent: req.get('User-Agent') }); // Don't leak error details in production const isDevelopment = process.env.NODE_ENV === 'development'; res.status(err.status || 500).json({ success: false, error: isDevelopment ? err.message : 'Internal server error', errorId, ...(isDevelopment && { stack: err.stack }) }); }); // 404 handler app.use((req, res) => { res.status(404).json({ success: false, error: 'Endpoint not found', message: `The endpoint ${req.method} ${req.path} does not exist`, availableEndpoints: '/api' }); }); // Graceful shutdown handlers const gracefulShutdown = (signal) => { logger.info(`Received ${signal}, shutting down gracefully`); server.close((err) => { if (err) { logger.error('Error during server shutdown:', err); process.exit(1); } logger.info('Server closed successfully'); process.exit(0); }); // Force close after 30 seconds setTimeout(() => { logger.error('Forced shutdown after timeout'); process.exit(1); }, 30000); }; process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); process.on('SIGINT', () => gracefulShutdown('SIGINT')); process.on('SIGUSR2', () => gracefulShutdown('SIGUSR2')); // Nodemon restart // Handle uncaught exceptions process.on('uncaughtException', (err) => { logger.error('Uncaught Exception:', err); process.exit(1); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled Rejection at:', promise, 'reason:', reason); process.exit(1); }); // Start server const server = app.listen(PORT, '0.0.0.0', async () => { logger.info(`UGA edi.chat backend server running on port ${PORT}`); logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`); logger.info(`Database: ${process.env.MONGODB_URI ? 'MongoDB enabled' : 'No database configured'}`); logger.info(`Redis: ${process.env.REDIS_URL ? 'Redis enabled' : 'No Redis configured'}`); logger.info(`Ollama: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`); logger.info('Server started successfully'); // Initialize services after server starts await initializeServices(); logger.info('Backend initialization complete'); }); // Export for testing module.exports = { app, server };