9.3 KiB
9.3 KiB
SkyArtShop - Security & Production Implementation Complete
Tech Stack
- Backend: Node.js v18+ with Express.js
- Database: PostgreSQL 14+
- Session Store: connect-pg-simple (PostgreSQL-backed sessions)
- Frontend: HTML5, CSS3, JavaScript (ES6+), Bootstrap 5
- Process Manager: PM2
- Web Server: Nginx (reverse proxy)
- OS: Linux (Ubuntu/Debian)
Security Improvements Implemented
1. ✅ Environment Configuration (.env)
- Removed hardcoded credentials from
ecosystem.config.js - Created
.envfile for sensitive configuration - Added
.env.exampletemplate for deployment
Files Modified:
- Created:
.env,.env.example - Modified:
ecosystem.config.js
2. ✅ Logging System (Winston)
- Replaced all
console.log/console.errorwith structured logging - Implemented log rotation (10MB max, 5 files)
- Separate error and combined logs
- Console output for development environment
Files Created:
backend/config/logger.js
Files Modified:
- All route files:
auth.js,admin.js,public.js,users.js,upload.js - Middleware:
auth.js - Config:
database.js
3. ✅ Rate Limiting
- API rate limiter: 100 requests per 15 minutes
- Auth rate limiter: 5 login attempts per 15 minutes
- Upload rate limiter: 50 uploads per hour
Files Created:
backend/config/rateLimiter.js
Applied to:
- All
/api/*routes - Login/logout endpoints
- File upload endpoint
4. ✅ Input Validation & Sanitization
- Implemented express-validator for all inputs
- SQL injection protection via parameterized queries
- XSS protection via input escaping
- Email normalization
- Strong password requirements (8+ chars, uppercase, lowercase, number)
Files Created:
backend/middleware/validators.js
Validators Added:
- Login validation
- User creation/update validation
- Product CRUD validation
- Blog post validation
- Pagination validation
5. ✅ Security Headers (Helmet.js)
- Content Security Policy (CSP)
- HTTP Strict Transport Security (HSTS)
- X-Frame-Options
- X-Content-Type-Options
- X-XSS-Protection
Configuration:
- Modified:
backend/server.js
6. ✅ Error Handling
- Centralized error handler
- Production vs development error responses
- PostgreSQL error translation
- Async error wrapper
- Custom AppError class
Files Created:
backend/middleware/errorHandler.js
Features:
- Hide sensitive error details in production
- Log all errors with context
- Standardized error responses
- 404 handler
7. ✅ Database Transaction Support
- Transaction helper function
- Rollback on error
- Connection pooling (max 20 connections)
Files Modified:
backend/config/database.js
Added:
transaction()helper functionhealthCheck()function
8. ✅ File Upload Security
- MIME type validation
- File extension whitelist
- File size limits (5MB default)
- Filename sanitization
- Upload rate limiting
- Automatic cleanup on errors
Files Modified:
backend/routes/upload.js
Security Features:
- Only allow image types (jpeg, png, gif, webp)
- Limit filename length to 50 characters
- Generate unique filenames
- Log all upload attempts
- Clean up failed uploads
9. ✅ Health Check Endpoint
- Real database connectivity test
- Memory usage monitoring
- Uptime tracking
- Graceful degradation
Endpoint:
GET /health
Returns:
- Database connection status
- Server uptime
- Memory usage
- Timestamp
10. ✅ Graceful Shutdown
- Proper SIGTERM/SIGINT handling
- Close HTTP connections gracefully
- Close database pool
- 10-second forced shutdown timeout
Files Modified:
backend/server.js
Security Best Practices Applied
Authentication & Authorization
- ✅ Bcrypt password hashing (rounds: 12)
- ✅ Session-based authentication
- ✅ HttpOnly secure cookies (production)
- ✅ Role-based access control (RBAC)
- ✅ Session expiry (24 hours)
- ✅ Last login tracking
Input Validation
- ✅ All user inputs validated
- ✅ SQL injection prevention (parameterized queries)
- ✅ XSS prevention (input escaping)
- ✅ Email validation and normalization
- ✅ Strong password requirements
API Security
- ✅ Rate limiting on all endpoints
- ✅ CORS configuration ready
- ✅ Trust proxy for nginx reverse proxy
- ✅ Request logging with IP tracking
File Security
- ✅ File type validation
- ✅ File size limits
- ✅ Filename sanitization
- ✅ Unique filename generation
- ✅ Upload rate limiting
Error Handling
- ✅ No sensitive data in error messages
- ✅ All errors logged with context
- ✅ Production vs development error responses
- ✅ PostgreSQL error translation
Logging & Monitoring
- ✅ Structured logging (Winston)
- ✅ Log rotation
- ✅ Separate error logs
- ✅ Request logging
- ✅ Security event logging (failed logins, etc.)
Required Environment Variables
Create .env file in project root:
NODE_ENV=production
PORT=5000
HOST=0.0.0.0
DB_HOST=localhost
DB_PORT=5432
DB_NAME=skyartshop
DB_USER=skyartapp
DB_PASSWORD=your_secure_password_here
SESSION_SECRET=generate_a_random_string_at_least_32_characters_long
UPLOAD_DIR=/var/www/skyartshop/uploads
MAX_FILE_SIZE=5242880
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/gif,image/webp
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
BCRYPT_ROUNDS=12
LOG_LEVEL=info
LOG_FILE=logs/app.log
LOG_MAX_SIZE=10m
LOG_MAX_FILES=7d
Deployment Checklist
Before Production
- Generate strong
SESSION_SECRET(32+ characters) - Change all default passwords
- Set
NODE_ENV=production - Configure
CORS_ORIGINif needed - Review and adjust rate limits
- Set up SSL/TLS certificates
- Configure nginx reverse proxy
- Set up firewall rules
- Enable log rotation
- Set up monitoring/alerts
- Backup database regularly
- Test all security features
Nginx Configuration
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
Testing Commands
# Test server startup
npm start
# Check logs
tail -f backend/logs/combined.log
tail -f backend/logs/error.log
# Test health endpoint
curl http://localhost:5000/health
# Test rate limiting
for i in {1..10}; do curl http://localhost:5000/api/products; done
# Check for security vulnerabilities
npm audit
# Fix vulnerabilities
npm audit fix
Known Issues & Recommendations
Fixed Issues
- ✅ Hardcoded credentials - Moved to .env
- ✅ No input validation - Added express-validator
- ✅ No rate limiting - Implemented multi-tier rate limiting
- ✅ Console logging - Replaced with Winston
- ✅ Poor error handling - Centralized error handler
- ✅ No security headers - Added Helmet.js
- ✅ Weak file upload security - Enhanced validation
- ✅ No graceful shutdown - Implemented proper shutdown
Recommendations for Future
- CSRF Protection: Consider adding CSRF tokens for state-changing operations
- API Documentation: Add Swagger/OpenAPI documentation
- Unit Tests: Implement Jest/Mocha test suite
- Integration Tests: Add supertest for API testing
- Database Migrations: Use a migration tool (e.g., node-pg-migrate)
- Redis Session Store: For better performance in production
- Caching: Implement Redis caching for frequently accessed data
- Image Optimization: Add sharp for image resizing/optimization
- Content Delivery: Consider CDN for static assets
- Monitoring: Add APM (Application Performance Monitoring)
Database Tables Required
Ensure these tables exist in PostgreSQL:
adminusers- Admin user accountsroles- User roles and permissionsproducts- Product catalogportfolioprojects- Portfolio itemsblogposts- Blog articlespages- Static pagesuploads- File upload trackingsession- Session storage (auto-created)sitesettings- Site configurationhomepagesections- Homepage content
Support & Maintenance
Log Files Location
backend/logs/combined.log- All logsbackend/logs/error.log- Error logs only/var/log/skyartshop/pm2-*.log- PM2 process logs
Common Commands
# Start server
npm start
# Development mode with auto-restart
npm run dev
# Check PM2 status
pm2 status skyartshop
# Restart PM2
pm2 restart skyartshop
# View PM2 logs
pm2 logs skyartshop
# Stop server
pm2 stop skyartshop
Security Contacts
For security issues, please review logs at:
backend/logs/error.log- PM2 logs via
pm2 logs
Monitor for:
- Failed login attempts
- Rate limit violations
- File upload rejections
- Database errors
- Unhandled exceptions
Last Updated: December 18, 2025 Version: 2.0.0 (Production Ready)