Spaces:
Running

docker / extractor /server /index.js
bacteriaqh's picture
Deploy 5313b66 từ GitHub Actions
e913295 verified
Raw History Blame
4.68 kB
/**
* @fileoverview Express application entry point.
* Configures middleware, routes, and starts the server.
* @module index
*/
import express from 'express';
import helmet from 'helmet';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs-extra';
import apiRoutes from './routes/api.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Express application instance.
*/
const app = express();
/**
* Server port.
* @constant {number}
*/
const PORT = parseInt(process.env.PORT) || 3000;
// ============================================
// Ensure required directories exist
// ============================================
const uploadsDir = path.resolve(__dirname, '../uploads');
const extractedDir = path.resolve(__dirname, '../extracted');
await fs.ensureDir(uploadsDir);
await fs.ensureDir(extractedDir);
// ============================================
// Security Middleware
// ============================================
/**
* Helmet configuration for HTTP security headers.
* SECURITY: Sets various HTTP headers to protect against common attacks.
*/
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
imgSrc: ["'self'", 'data:', 'blob:'],
connectSrc: ["'self'"],
},
},
crossOriginEmbedderPolicy: false,
})
);
// ============================================
// Body Parsing Middleware
// ============================================
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));
// ============================================
// Static Files
// ============================================
const publicDir = path.resolve(__dirname, '../public');
app.use(express.static(publicDir));
// ============================================
// API Routes
// ============================================
app.use('/api', apiRoutes);
// ============================================
// Fallback route for SPA
// ============================================
app.get('*', (req, res) => {
res.sendFile(path.join(publicDir, 'index.html'));
});
// ============================================
// Global Error Handler
// ============================================
/**
* Global error handling middleware.
* Catches unhandled errors and returns consistent error response.
*
* @param {Error} err - Error object
* @param {Object} req - Express request
* @param {Object} res - Express response
* @param {Function} next - Next middleware
*/
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
// Don't leak error details in production
const message = process.env.NODE_ENV === 'production'
? 'An unexpected error occurred'
: err.message;
res.status(500).json({
error: true,
message,
code: 'INTERNAL_ERROR',
});
});
// ============================================
// Start Server
// ============================================
const HOST = process.env.HOST || '0.0.0.0';
app.listen(PORT, HOST, () => {
console.log(`
╔═══════════════════════════════════════════════════════════╗
║ ║
║ 🗜️ Archive Extractor Server ║
║ ║
║ Server running at: http://${HOST}:${PORT} ║
║ Press Ctrl+C to stop ║
║ ║
╚═══════════════════════════════════════════════════════════╝
`);
});
// ============================================
// Graceful Shutdown
// ============================================
/**
* Handles graceful shutdown on process signals.
* Cleans up resources before exiting.
*/
const gracefulShutdown = async (signal) => {
console.log(`\n${signal} received. Shutting down gracefully...`);
// Could add cleanup logic here if needed
// For example, finishing pending uploads or saving session states
process.exit(0);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
export default app;