# Chalala.us - Complete Secure Website Package ## ๐Ÿ“ Project Structure ``` chalala-us/ โ”œโ”€โ”€ frontend/ โ”‚ โ””โ”€โ”€ index.html โ”œโ”€โ”€ backend/ โ”‚ โ”œโ”€โ”€ server.js โ”‚ โ”œโ”€โ”€ package.json โ”‚ โ”œโ”€โ”€ .env โ”‚ โ””โ”€โ”€ middleware/ โ”‚ โ”œโ”€โ”€ auth.js โ”‚ โ””โ”€โ”€ rateLimiter.js โ”œโ”€โ”€ database/ โ”‚ โ””โ”€โ”€ schema.sql โ””โ”€โ”€ nginx/ โ””โ”€โ”€ chalala.conf ``` --- ## ๐ŸŽจ FRONTEND - index.html ```html Chalala.us - Secure Platform

Secure Access

Enter your credentials to continue

256-bit SSL Encryption Protected

Don't have an account? Register here

Create Account

Join our secure platform

Already have an account? Login here

Welcome Back!

Your secure dashboard

Account Status

Your account is active and secure

Security Information

Last login: Just now

``` --- ## ๐Ÿ”ง BACKEND - server.js ```javascript const express = require('express'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const cors = require('cors'); const helmet = require('helmet'); const rateLimit = require('express-rate-limit'); const { body, validationResult } = require('express-validator'); const mysql = require('mysql2/promise'); require('dotenv').config(); const app = express(); // Security Middleware app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"], scriptSrc: ["'self'", "'unsafe-inline'"], }, }, })); app.use(cors({ origin: process.env.FRONTEND_URL || 'https://chalala.us', credentials: true })); app.use(express.json()); // Rate Limiting const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs message: 'Too many requests from this IP, please try again later.' }); const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5, // limit auth attempts message: 'Too many login attempts, please try again later.' }); app.use(limiter); // Database Connection Pool const pool = mysql.createPool({ host: process.env.DB_HOST || 'localhost', user: process.env.DB_USER || 'root', password: process.env.DB_PASSWORD, database: process.env.DB_NAME || 'chalala_db', waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); // JWT Secret const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-this'; // Middleware to verify JWT const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).json({ message: 'Access token required' }); } jwt.verify(token, JWT_SECRET, (err, user) => { if (err) { return res.status(403).json({ message: 'Invalid or expired token' }); } req.user = user; next(); }); }; // Routes // Health Check app.get('/api/health', (req, res) => { res.json({ status: 'ok', message: 'Server is running' }); }); // Register app.post('/api/auth/register', authLimiter, [ body('email').isEmail().normalizeEmail(), body('password').isLength({ min: 8 }), body('name').trim().isLength({ min: 2 }) ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { name, email, password } = req.body; try { // Check if user exists const [existingUsers] = await pool.execute( 'SELECT id FROM users WHERE email = ?', [email] ); if (existingUsers.length > 0) { return res.status(400).json({ message: 'Email already registered' }); } // Hash password const hashedPassword = await bcrypt.hash(password, 12); // Insert user const [result] = await pool.execute( 'INSERT INTO users (name, email, password, created_at) VALUES (?, ?, ?, NOW())', [name, email, hashedPassword] ); res.status(201).json({ message: 'User registered successfully', userId: result.insertId }); } catch (error) { console.error('Registration error:', error); res.status(500).json({ message: 'Server error during registration' }); } } ); // Login app.post('/api/auth/login', authLimiter, [ body('email').isEmail().normalizeEmail(), body('password').notEmpty() ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; try { // Get user const [users] = await pool.execute( 'SELECT id, name, email, password FROM users WHERE email = ?', [email] ); if (users.length === 0) { return res.status(401).json({ message: 'Invalid credentials' }); } const user = users[0]; // Verify password const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) { return res.status(401).json({ message: 'Invalid credentials' }); } // Update last login await pool.execute( 'UPDATE users SET last_login = NOW() WHERE id = ?', [user.id] ); // Generate JWT const token = jwt.sign( { userId: user.id, email: user.email }, JWT_SECRET, { expiresIn: '24h' } ); res.json({ message: 'Login successful', token, user: { id: user.id, name: user.name, email: user.email } }); } catch (error) { console.error('Login error:', error); res.status(500).json({ message: 'Server error during login' }); } } ); // Get User Profile (Protected Route) app.get('/api/user/profile', authenticateToken, async (req, res) => { try { const [users] = await pool.execute( 'SELECT id, name, email, created_at, last_login FROM users WHERE id = ?', [req.user.userId] ); if (users.length === 0) { return res.status(404).json({ message: 'User not found' }); } res.json({ user: users[0] }); } catch (error) { console.error('Profile fetch error:', error); res.status(500).json({ message: 'Server error' }); } }); // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ message: 'Something went wrong!' }); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`๐Ÿ”’ Secure server running on port ${PORT}`); }); ``` --- ## ๐Ÿ“ฆ BACKEND - package.json ```json { "name": "chalala-backend", "version": "1.0.0", "description": "Secure backend for Chalala.us", "main": "server.js", "scripts": { "start": "node server.js", "dev": "nodemon server.js" }, "keywords": ["secure", "authentication", "api"], "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2", "bcryptjs": "^2.4.3", "jsonwebtoken": "^9.0.2", "cors": "^2.8.5", "helmet": "^7.1.0", "express-rate-limit": "^7.1.5", "express-validator": "^7.0.1", "mysql2": "^3.6.5", "dotenv": "^16.3.1" }, "devDependencies": { "nodemon": "^3.0.2" } } ``` --- ## ๐Ÿ” BACKEND - .env ```env # Server Configuration PORT=3000 NODE_ENV=production # Database Configuration DB_HOST=localhost DB_USER=chalala_user DB_PASSWORD=your_secure_database_password_here DB_NAME=chalala_db # JWT Configuration JWT_SECRET=your_super_secret_jwt_key_minimum_32_characters_long # Frontend URL FRONTEND_URL=https://chalala.us # Security BCRYPT_ROUNDS=12 ``` --- ## ๐Ÿ—„๏ธ DATABASE - schema.sql ```sql -- Create Database CREATE DATABASE IF NOT EXISTS chalala_db; USE chalala_db; -- Users Table CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_login TIMESTAMP NULL, is_active BOOLEAN DEFAULT TRUE, INDEX idx_email (email), INDEX idx_created_at (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Sessions Table (Optional - for session management) CREATE TABLE IF NOT EXISTS sessions ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, token VARCHAR(500) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMP NOT NULL, ip_address VARCHAR(45), user_agent TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, INDEX idx_token (token), INDEX idx_user_id (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Login Attempts Table (for security monitoring) CREATE TABLE IF NOT EXISTS login_attempts ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL, ip_address VARCHAR(45) NOT NULL, success BOOLEAN DEFAULT FALSE, attempted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_email (email), INDEX idx_ip (ip_address), INDEX idx_attempted_at (attempted_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ``` --- ## ๐ŸŒ NGINX Configuration - chalala.conf ```nginx # HTTP - Redirect to HTTPS server { listen 80; server_name chalala.us www.chalala.us; return 301 https://$server_name$request_uri; } # HTTPS server { listen 443 ssl http2; server_name chalala.us www.chalala.us; # SSL Configuration ssl_certificate /etc/letsencrypt/live/chalala.us/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/chalala.us/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # Security Headers add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; # Root directory for frontend root /var/www/chalala.us/frontend; index index.html; # Frontend location / { try_files $uri $uri/ /index.html; } # Backend API location /api/ { proxy_pass http://localhost:3000; 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; } # Rate limiting limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s; limit_req zone=general burst=20 nodelay; # Logging access_log /var/log/nginx/chalala.us_access.log; error_log /var/log/nginx/chalala.us_error.log; # File upload size limit client_max_body_size 10M; # Gzip compression gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json; } ``` --- ## ๐Ÿš€ DEPLOYMENT GUIDE ### Prerequisites - Ubuntu/Debian Server (or similar) - Domain name (chalala.us) - Root or sudo access ### Step 1: Install Required Software ```bash # Update system sudo apt update && sudo apt upgrade -y # Install Node.js (v18 LTS) curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs # Install MySQL sudo apt install -y mysql-server # Install Nginx sudo apt install -y nginx # Install Certbot for SSL sudo apt install -y certbot python3-certbot-nginx # Install PM2 for process management sudo npm install -g pm2 ``` ### Step 2: Setup MySQL Database ```bash # Secure MySQL installation sudo mysql_secure_installation # Login to MySQL sudo mysql -u root -p # Create database and user CREATE DATABASE chalala_db; CREATE USER 'chalala_user'@'localhost' IDENTIFIED BY 'your_secure_password'; GRANT ALL PRIVILEGES ON chalala_db.* TO 'chalala_user'@'localhost'; FLUSH PRIVILEGES; EXIT; # Import schema mysql -u chalala_user -p chalala_db < /path/to/schema.sql ``` ### Step 3: Setup Backend ```bash # Create project directory sudo mkdir -p /var/www/chalala.us/backend cd /var/www/chalala.us/backend # Copy backend files # - server.js # - package.json # - .env # Install dependencies npm install # Configure .env file nano .env # Update all the values # Start with PM2 pm2 start server.js --name chalala-backend pm2 save pm2 startup # Check status pm2 status ``` ### Step 4: Setup Frontend ```bash # Create frontend directory sudo mkdir -p /var/www/chalala.us/frontend # Copy index.html to frontend directory # Make sure to update API_URL in the HTML file to match your domain # Set proper permissions sudo chown -R www-data:www-data /var/www/chalala.us sudo chmod -R 755 /var/www/chalala.us ``` ### Step 5: Configure Nginx ```bash # Copy nginx configuration sudo nano /etc/nginx/sites-available/chalala.us # Paste the nginx configuration from above # Create symbolic link sudo ln -s /etc/nginx/sites-available/chalala.us /etc/nginx/sites-enabled/ # Remove default configuration sudo rm /etc/nginx/sites-enabled/default # Test configuration sudo nginx -t # Restart Nginx sudo systemctl restart nginx ``` ### Step 6: Setup SSL Certificate ```bash # Get SSL certificate from Let's Encrypt sudo certbot --nginx -d chalala.us -d www.chalala.us # Follow the prompts and select option to redirect HTTP to HTTPS # Test auto-renewal sudo certbot renew --dry-run # Certbot will auto-renew before expiration ``` ### Step 7: Configure Firewall ```bash # Enable UFW firewall sudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' sudo ufw enable # Check status sudo ufw status ``` ### Step 8: Setup Monitoring and Logging ```bash # Install fail2ban for brute force protection sudo apt install -y fail2ban # Create jail for nginx sudo nano /etc/fail2ban/jail.local # Add this configuration: [nginx-limit-req] enabled = true filter = nginx-limit-req logpath = /var/log/nginx/chalala.us_error.log maxretry = 5 findtime = 600 bantime = 3600 # Restart fail2ban sudo systemctl restart fail2ban # Setup log rotation sudo nano /etc/logrotate.d/chalala # Add: /var/log/nginx/chalala.us*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate if [ -f /var/run/nginx.pid ]; then kill -USR1 `cat /var/run/nginx.pid` fi endscript } ``` --- ## ๐Ÿ”’ ADDITIONAL SECURITY MEASURES ### 1. Setup Database Backups ```bash # Create backup script sudo nano /usr/local/bin/backup-chalala-db.sh #!/bin/bash BACKUP_DIR="/var/backups/mysql" TIMESTAMP=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="chalala_db_$TIMESTAMP.sql.gz" mkdir -p $BACKUP_DIR mysqldump -u chalala_user -p'your_password' chalala_db | gzip > $BACKUP_DIR/$BACKUP_FILE # Keep only last 7 days of backups find $BACKUP_DIR -name "chalala_db_*.sql.gz" -mtime +7 -delete # Make executable sudo chmod +x /usr/local/bin/backup-chalala-db.sh # Add to crontab (daily at 2 AM) sudo crontab -e 0 2 * * * /usr/local/bin/backup-chalala-db.sh ``` ### 2. Environment Variables Security ```bash # Secure .env file sudo chmod 600 /var/www/chalala.us/backend/.env sudo chown www-data:www-data /var/www/chalala.us/backend/.env ``` ### 3. Setup Application Monitoring ```bash # PM2 monitoring pm2 install pm2-logrotate pm2 set pm2-logrotate:max_size 10M pm2 set pm2-logrotate:retain 7 # View logs pm2 logs chalala-backend # Monitor CPU/Memory pm2 monit ``` --- ## ๐Ÿ“ API ENDPOINTS ### Authentication **POST /api/auth/register** - Body: `{ "name": "John Doe", "email": "john@example.com", "password": "password123" }` - Response: `{ "message": "User registered successfully", "userId": 1 }` **POST /api/auth/login** - Body: `{ "email": "john@example.com", "password": "password123" }` - Response: `{ "token": "jwt_token", "user": { "id": 1, "name": "John Doe", "email": "john@example.com" } }` **GET /api/user/profile** - Headers: `Authorization: Bearer ` - Response: `{ "user": { "id": 1, "name": "John Doe", "email": "john@example.com", "created_at": "...", "last_login": "..." } }` **GET /api/health** - Response: `{ "status": "ok", "message": "Server is running" }` --- ## ๐Ÿงช TESTING ### Test Backend Locally ```bash # Start server npm start # Test health endpoint curl http://localhost:3000/api/health # Test registration curl -X POST http://localhost:3000/api/auth/register \ -H "Content-Type: application/json" \ -d '{"name":"Test User","email":"test@example.com","password":"password123"}' # Test login curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"password123"}' ``` --- ## ๐Ÿ›ก๏ธ SECURITY CHECKLIST โœ… HTTPS/SSL enabled โœ… Password hashing with bcrypt (12 rounds) โœ… JWT authentication with expiration โœ… Rate limiting on all endpoints โœ… SQL injection prevention (parameterized queries) โœ… XSS prevention (input sanitization) โœ… CSRF protection (SameSite cookies) โœ… Security headers (Helmet.js) โœ… CORS configuration โœ… Input validation โœ… Error handling without information leakage โœ… Database connection pooling โœ… Fail2ban for brute force protection โœ… Firewall configuration โœ… Regular backups โœ… Log monitoring โœ… Content Security Policy --- ## ๐Ÿ“ฑ UPDATING THE SITE ### Frontend Updates ```bash cd /var/www/chalala.us/frontend # Edit index.html sudo systemctl reload nginx ``` ### Backend Updates ```bash cd /var/www/chalala.us/backend # Make changes to server.js pm2 restart chalala-backend ``` --- ## ๐Ÿ†˜ TROUBLESHOOTING ### Check Backend Status ```bash pm2 status pm2 logs chalala-backend --lines 100 ``` ### Check Nginx Status ```bash sudo systemctl status nginx sudo tail -f /var/log/nginx/chalala.us_error.log ``` ### Check Database Connection ```bash mysql -u chalala_user -p chalala_db SHOW TABLES; SELECT COUNT(*) FROM users; ``` ### Test SSL Certificate ```bash sudo certbot certificates ``` --- ## ๐ŸŽฏ NEXT STEPS 1. **Email Verification**: Add email verification for new registrations 2. **Password Reset**: Implement forgot password functionality 3. **Two-Factor Authentication**: Add 2FA support 4. **User Roles**: Implement admin/user role system 5. **API Documentation**: Use Swagger/OpenAPI 6. **CDN**: Setup Cloudflare for DDoS protection 7. **Monitoring**: Setup Grafana + Prometheus 8. **Automated Testing**: Add Jest/Mocha tests --- ## ๐Ÿ“ž SUPPORT For issues or questions: - Check logs: `pm2 logs` and `/var/log/nginx/` - Database issues: Check MySQL error logs - SSL issues: Run `sudo certbot renew` - Firewall issues: Check `sudo ufw status` **Your secure website is now ready for deployment to chalala.us!** ๐Ÿš€๐Ÿ”’