ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add backup, monitoring, and deployment APIs
Juan Denisf677d760dd16
diff --git a/.gitignore b/.gitignoreindex 38e0e2e8..de41feea 100644--- a/.gitignore+++ b/.gitignore@@ -1 +1,2 @@/frontend/node_modules+nuldiff --git a/backend/.env.example b/backend/.env.exampleindex d9a71f57..1d5aef03 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -1,11 +1,16 @@# Flask ConfigurationFLASK_ENV=development++# IMPORTANT: Generate secure keys for production!+# Run: python -c "import secrets; print(secrets.token_hex(32))"SECRET_KEY=change-this-to-a-secure-random-string# DatabaseDATABASE_URL=sqlite:///serverkit.db# JWT Configuration+# IMPORTANT: Generate a unique key for production!+# Run: python -c "import secrets; print(secrets.token_hex(32))"JWT_SECRET_KEY=change-this-to-another-secure-random-string# CORS - comma-separated list of allowed originsdiff --git a/backend/Dockerfile b/backend/Dockerfilenew file mode 100644index 00000000..60d27066--- /dev/null+++ b/backend/Dockerfile@@ -0,0 +1,42 @@+# Backend Dockerfile for ServerKit+FROM python:3.11-slim++# Set environment variables+ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ FLASK_ENV=production++# Set working directory+WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y --no-install-recommends \+ gcc \+ libpq-dev \+ && rm -rf /var/lib/apt/lists/*++# Copy requirements first for caching+COPY requirements.txt .++# Install Python dependencies+RUN pip install --no-cache-dir -r requirements.txt \+ && pip install --no-cache-dir gunicorn gevent gevent-websocket++# Copy application code+COPY . .++# Create non-root user+RUN useradd --create-home appuser && chown -R appuser:appuser /app+USER appuser++# Expose port+EXPOSE 5000++# Health check+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/v1/health')" || exit 1++# Run with gunicorn + gevent for WebSocket support+CMD ["gunicorn", "-k", "geventwebsocket.gunicorn.workers.GeventWebSocketWorker", \+ "-w", "1", "-b", "0.0.0.0:5000", "--access-logfile", "-", "--error-logfile", "-", \+ "run:app"]diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex c1713480..61b6f6a0 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -3,11 +3,14 @@ from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyfrom flask_jwt_extended import JWTManagerfrom flask_cors import CORS+from flask_limiter import Limiter+from flask_limiter.util import get_remote_addressfrom config import configdb = SQLAlchemy()jwt = JWTManager()+limiter = Limiter(key_func=get_remote_address, default_limits=["100 per minute"])socketio = None@@ -23,8 +26,13 @@ def create_app(config_name=None):# Initialize extensionsdb.init_app(app)jwt.init_app(app)+ limiter.init_app(app)CORS(app, origins=app.config['CORS_ORIGINS'], supports_credentials=True)+ # Register security headers middleware+ from app.middleware.security import register_security_headers+ register_security_headers(app)+# Initialize SocketIOfrom app.sockets import init_socketiosocketio = init_socketio(app)@@ -71,6 +79,18 @@ def create_app(config_name=None):from app.api.databases import databases_bpapp.register_blueprint(databases_bp, url_prefix='/api/v1/databases')+ # Register blueprints - Monitoring & Alerts+ from app.api.monitoring import monitoring_bp+ app.register_blueprint(monitoring_bp, url_prefix='/api/v1/monitoring')++ # Register blueprints - Backups+ from app.api.backups import backups_bp+ app.register_blueprint(backups_bp, url_prefix='/api/v1/backups')++ # Register blueprints - Git Deployment+ from app.api.deploy import deploy_bp+ app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')+# Create database tableswith app.app_context():db.create_all()diff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex 3cafa834..4503be0a 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -1,3 +1,4 @@+from datetime import datetimefrom flask import Blueprint, request, jsonifyfrom flask_jwt_extended import (create_access_token,@@ -6,13 +7,14 @@ from flask_jwt_extended import (get_jwt_identity,get_jwt)-from app import db+from app import db, limiterfrom app.models import Userauth_bp = Blueprint('auth', __name__)@auth_bp.route('/register', methods=['POST'])[email protected]("3 per minute")def register():data = request.get_json()@@ -60,6 +62,7 @@ def register():@auth_bp.route('/login', methods=['POST'])[email protected]("5 per minute")def login():data = request.get_json()@@ -74,12 +77,27 @@ def login():user = User.query.filter_by(email=email).first()+ # Check if account is locked+ if user and user.is_locked:+ remaining = int((user.locked_until - datetime.utcnow()).total_seconds() / 60)+ return jsonify({+ 'error': f'Account is locked. Try again in {remaining} minute(s).'+ }), 429+if not user or not user.check_password(password):+ # Record failed login attempt+ if user:+ user.record_failed_login()+ db.session.commit()return jsonify({'error': 'Invalid email or password'}), 401if not user.is_active:return jsonify({'error': 'Account is deactivated'}), 403+ # Reset failed login count on successful login+ user.reset_failed_login()+ db.session.commit()+access_token = create_access_token(identity=user.id)refresh_token = create_refresh_token(identity=user.id)diff --git a/backend/app/api/backups.py b/backend/app/api/backups.pynew file mode 100644index 00000000..6d9c7f06--- /dev/null+++ b/backend/app/api/backups.py@@ -0,0 +1,228 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User, Application+from app.services.backup_service import BackupService++backups_bp = Blueprint('backups', __name__)+++def admin_required(fn):+ """Decorator to require admin role."""+ from functools import wraps++ @wraps(fn)+ def wrapper(*args, **kwargs):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403+ return fn(*args, **kwargs)+ return wrapper+++@backups_bp.route('', methods=['GET'])+@jwt_required()+def list_backups():+ """List all backups."""+ backup_type = request.args.get('type')+ backups = BackupService.list_backups(backup_type)+ return jsonify({'backups': backups}), 200+++@backups_bp.route('/stats', methods=['GET'])+@jwt_required()+def get_stats():+ """Get backup statistics."""+ stats = BackupService.get_backup_stats()+ return jsonify(stats), 200+++@backups_bp.route('/config', methods=['GET'])+@jwt_required()+@admin_required+def get_config():+ """Get backup configuration."""+ config = BackupService.get_config()+ return jsonify(config), 200+++@backups_bp.route('/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_config():+ """Update backup configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ current_config = BackupService.get_config()+ current_config.update(data)+ result = BackupService.save_config(current_config)+ return jsonify(result), 200 if result['success'] else 400+++@backups_bp.route('/application', methods=['POST'])+@jwt_required()+@admin_required+def backup_application():+ """Backup an application."""+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ app_id = data.get('application_id')+ if not app_id:+ return jsonify({'error': 'application_id is required'}), 400++ app = Application.query.get(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404++ result = BackupService.backup_application(+ app_name=app.name,+ app_path=app.path,+ include_db=data.get('include_db', False),+ db_config=data.get('db_config')+ )++ return jsonify(result), 201 if result['success'] else 400+++@backups_bp.route('/database', methods=['POST'])+@jwt_required()+@admin_required+def backup_database():+ """Backup a database."""+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ required = ['db_type', 'db_name']+ missing = [f for f in required if f not in data]+ if missing:+ return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400++ result = BackupService.backup_database(+ db_type=data['db_type'],+ db_name=data['db_name'],+ user=data.get('user'),+ password=data.get('password'),+ host=data.get('host', 'localhost')+ )++ return jsonify(result), 201 if result['success'] else 400+++@backups_bp.route('/restore/application', methods=['POST'])+@jwt_required()+@admin_required+def restore_application():+ """Restore an application from backup."""+ data = request.get_json()++ if not data or 'backup_path' not in data:+ return jsonify({'error': 'backup_path is required'}), 400++ result = BackupService.restore_application(+ backup_path=data['backup_path'],+ restore_path=data.get('restore_path')+ )++ return jsonify(result), 200 if result['success'] else 400+++@backups_bp.route('/restore/database', methods=['POST'])+@jwt_required()+@admin_required+def restore_database():+ """Restore a database from backup."""+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ required = ['backup_path', 'db_type', 'db_name']+ missing = [f for f in required if f not in data]+ if missing:+ return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400++ result = BackupService.restore_database(+ backup_path=data['backup_path'],+ db_type=data['db_type'],+ db_name=data['db_name'],+ user=data.get('user'),+ password=data.get('password'),+ host=data.get('host', 'localhost')+ )++ return jsonify(result), 200 if result['success'] else 400+++@backups_bp.route('/<path:backup_path>', methods=['DELETE'])+@jwt_required()+@admin_required+def delete_backup(backup_path):+ """Delete a backup."""+ # Ensure path is within backup directory+ full_path = f"/var/backups/serverkit/{backup_path}"+ result = BackupService.delete_backup(full_path)+ return jsonify(result), 200 if result['success'] else 400+++@backups_bp.route('/cleanup', methods=['POST'])+@jwt_required()+@admin_required+def cleanup_backups():+ """Clean up old backups."""+ data = request.get_json() or {}+ retention_days = data.get('retention_days')++ result = BackupService.cleanup_old_backups(retention_days)+ return jsonify(result), 200 if result['success'] else 400+++# Schedules+@backups_bp.route('/schedules', methods=['GET'])+@jwt_required()+@admin_required+def list_schedules():+ """List backup schedules."""+ schedules = BackupService.get_schedules()+ return jsonify({'schedules': schedules}), 200+++@backups_bp.route('/schedules', methods=['POST'])+@jwt_required()+@admin_required+def add_schedule():+ """Add a backup schedule."""+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ required = ['name', 'backup_type', 'target', 'schedule_time']+ missing = [f for f in required if f not in data]+ if missing:+ return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400++ result = BackupService.add_schedule(+ name=data['name'],+ backup_type=data['backup_type'],+ target=data['target'],+ schedule_time=data['schedule_time'],+ days=data.get('days')+ )++ return jsonify(result), 201 if result['success'] else 400+++@backups_bp.route('/schedules/<schedule_id>', methods=['DELETE'])+@jwt_required()+@admin_required+def remove_schedule(schedule_id):+ """Remove a backup schedule."""+ result = BackupService.remove_schedule(schedule_id)+ return jsonify(result), 200 if result['success'] else 400diff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex dd158f39..8c2166fb 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -35,8 +35,12 @@ def get_status():@databases_bp.route('/mysql', methods=['GET'])@jwt_required()def list_mysql_databases():- """List MySQL databases."""- root_password = request.args.get('root_password')+ """List MySQL databases.++ For security, root_password should be passed via X-DB-Password header, not query params.+ """+ # Read root_password from header for security (not exposed in URL/logs)+ root_password = request.headers.get('X-DB-Password')databases = DatabaseService.mysql_list_databases(root_password)return jsonify({'databases': databases}), 200@@ -94,8 +98,11 @@ def drop_mysql_database(name):@databases_bp.route('/mysql/<name>/tables', methods=['GET'])@jwt_required()def get_mysql_tables(name):- """Get tables in a MySQL database."""- root_password = request.args.get('root_password')+ """Get tables in a MySQL database.++ For security, root_password should be passed via X-DB-Password header.+ """+ root_password = request.headers.get('X-DB-Password')tables = DatabaseService.mysql_get_tables(name, root_password)return jsonify({'tables': tables}), 200@@ -133,8 +140,11 @@ def restore_mysql_database(name):@databases_bp.route('/mysql/users', methods=['GET'])@jwt_required()def list_mysql_users():- """List MySQL users."""- root_password = request.args.get('root_password')+ """List MySQL users.++ For security, root_password should be passed via X-DB-Password header.+ """+ root_password = request.headers.get('X-DB-Password')users = DatabaseService.mysql_list_users(root_password)return jsonify({'users': users}), 200@@ -188,9 +198,12 @@ def drop_mysql_user(username):@databases_bp.route('/mysql/users/<username>/privileges', methods=['GET'])@jwt_required()def get_mysql_user_privileges(username):- """Get privileges for a MySQL user."""+ """Get privileges for a MySQL user.++ For security, root_password should be passed via X-DB-Password header.+ """host = request.args.get('host', 'localhost')- root_password = request.args.get('root_password')+ root_password = request.headers.get('X-DB-Password')privileges = DatabaseService.mysql_get_user_privileges(username, host, root_password)return jsonify({'privileges': privileges}), 200diff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.pynew file mode 100644index 00000000..7bdb1ce4--- /dev/null+++ b/backend/app/api/deploy.py@@ -0,0 +1,218 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User, Application+from app.services.git_service import GitService++deploy_bp = Blueprint('deploy', __name__)+++def admin_required(fn):+ """Decorator to require admin role."""+ from functools import wraps++ @wraps(fn)+ def wrapper(*args, **kwargs):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403+ return fn(*args, **kwargs)+ return wrapper+++@deploy_bp.route('/apps/<int:app_id>/config', methods=['GET'])+@jwt_required()+def get_deploy_config(app_id):+ """Get deployment configuration for an app."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ config = GitService.get_app_config(app_id)+ if not config:+ return jsonify({'configured': False}), 200++ return jsonify({+ 'configured': True,+ 'config': config+ }), 200+++@deploy_bp.route('/apps/<int:app_id>/config', methods=['POST'])+@jwt_required()+@admin_required+def configure_deployment(app_id):+ """Configure Git deployment for an app."""+ app = Application.query.get(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404++ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ if 'repo_url' not in data:+ return jsonify({'error': 'repo_url is required'}), 400++ result = GitService.configure_deployment(+ app_id=app_id,+ app_path=app.path,+ repo_url=data['repo_url'],+ branch=data.get('branch', 'main'),+ auto_deploy=data.get('auto_deploy', True),+ pre_deploy_script=data.get('pre_deploy_script'),+ post_deploy_script=data.get('post_deploy_script')+ )++ return jsonify(result), 201 if result['success'] else 400+++@deploy_bp.route('/apps/<int:app_id>/config', methods=['DELETE'])+@jwt_required()+@admin_required+def remove_deployment(app_id):+ """Remove deployment configuration."""+ result = GitService.remove_deployment(app_id)+ return jsonify(result), 200 if result['success'] else 400+++@deploy_bp.route('/apps/<int:app_id>/deploy', methods=['POST'])+@jwt_required()+def trigger_deploy(app_id):+ """Trigger a deployment."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ data = request.get_json() or {}+ result = GitService.deploy(app_id, force=data.get('force', False))++ return jsonify(result), 200 if result['success'] else 400+++@deploy_bp.route('/apps/<int:app_id>/pull', methods=['POST'])+@jwt_required()+def pull_changes(app_id):+ """Pull latest changes without running deploy scripts."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ data = request.get_json() or {}+ result = GitService.pull_changes(app.path, data.get('branch'))++ return jsonify(result), 200 if result['success'] else 400+++@deploy_bp.route('/apps/<int:app_id>/git-status', methods=['GET'])+@jwt_required()+def get_git_status(app_id):+ """Get Git status for an app."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ status = GitService.get_git_status(app.path)+ return jsonify(status), 200+++@deploy_bp.route('/apps/<int:app_id>/commit', methods=['GET'])+@jwt_required()+def get_commit_info(app_id):+ """Get current commit info for an app."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ commit_info = GitService.get_commit_info(app.path)+ if commit_info:+ return jsonify({'commit': commit_info}), 200+ return jsonify({'error': 'Not a Git repository'}), 404+++@deploy_bp.route('/history', methods=['GET'])+@jwt_required()+def get_deployment_history():+ """Get deployment history."""+ app_id = request.args.get('app_id', type=int)+ limit = request.args.get('limit', 50, type=int)++ history = GitService.get_deployment_history(app_id, limit)+ return jsonify({'deployments': history}), 200+++@deploy_bp.route('/clone', methods=['POST'])+@jwt_required()+@admin_required+def clone_repository():+ """Clone a Git repository to a new location."""+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ required = ['repo_url', 'app_path']+ missing = [f for f in required if f not in data]+ if missing:+ return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400++ result = GitService.clone_repository(+ app_path=data['app_path'],+ repo_url=data['repo_url'],+ branch=data.get('branch', 'main')+ )++ return jsonify(result), 201 if result['success'] else 400+++# Webhook endpoint (no auth required)+@deploy_bp.route('/webhook/<int:app_id>/<token>', methods=['POST'])+def webhook(app_id, token):+ """Handle incoming webhook from Git provider."""+ # Get signature if provided (GitHub style)+ signature = request.headers.get('X-Hub-Signature-256')++ # Verify webhook+ if not GitService.verify_webhook(app_id, token, signature, request.data):+ return jsonify({'error': 'Invalid webhook'}), 403++ # Parse payload+ try:+ payload = request.get_json()+ except Exception:+ return jsonify({'error': 'Invalid payload'}), 400++ # Handle webhook+ result = GitService.handle_webhook(app_id, payload)++ return jsonify(result), 200 if result.get('success') else 400diff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex a8574008..a84a55c1 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -2,10 +2,26 @@ from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app import dbfrom app.models import Domain, Application, User+from app.services.nginx_service import NginxService+from app.services.ssl_service import SSLServicedomains_bp = Blueprint('domains', __name__)+def admin_required(fn):+ """Decorator to require admin role."""+ from functools import wraps++ @wraps(fn)+ def wrapper(*args, **kwargs):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403+ return fn(*args, **kwargs)+ return wrapper++@domains_bp.route('', methods=['GET'])@jwt_required()def get_domains():@@ -160,11 +176,140 @@ def enable_ssl(domain_id):if user.role != 'admin' and app.user_id != current_user_id:return jsonify({'error': 'Access denied'}), 403- # TODO: Actually request Let's Encrypt certificate+ data = request.get_json() or {}+ email = data.get('email')++ if not email:+ return jsonify({'error': 'Email is required for SSL certificate'}), 400++ # Request Let's Encrypt certificate+ result = SSLService.obtain_certificate(+ domains=[domain.name],+ email=email,+ use_nginx=True+ )++ if not result['success']:+ return jsonify({'error': result.get('error', 'Failed to obtain certificate')}), 400++ # Add SSL to Nginx site+ nginx_result = NginxService.add_ssl_to_site(+ app.name,+ result['certificate_path'],+ result['private_key_path']+ )++ if not nginx_result['success']:+ return jsonify({'error': nginx_result.get('error', 'Failed to configure Nginx')}), 400+domain.ssl_enabled = True+ domain.ssl_certificate_path = result['certificate_path']+ domain.ssl_private_key_path = result['private_key_path']db.session.commit()return jsonify({'message': 'SSL enabled for domain',+ 'domain': domain.to_dict(),+ 'certificate': result+ }), 200+++@domains_bp.route('/<int:domain_id>/ssl/disable', methods=['POST'])+@jwt_required()+def disable_ssl(domain_id):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ domain = Domain.query.get(domain_id)++ if not domain:+ return jsonify({'error': 'Domain not found'}), 404++ app = Application.query.get(domain.application_id)+ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ domain.ssl_enabled = False+ db.session.commit()++ return jsonify({+ 'message': 'SSL disabled for domain','domain': domain.to_dict()}), 200+++@domains_bp.route('/<int:domain_id>/ssl/renew', methods=['POST'])+@jwt_required()+def renew_ssl(domain_id):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ domain = Domain.query.get(domain_id)++ if not domain:+ return jsonify({'error': 'Domain not found'}), 404++ app = Application.query.get(domain.application_id)+ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ if not domain.ssl_enabled:+ return jsonify({'error': 'SSL is not enabled for this domain'}), 400++ result = SSLService.renew_certificate(domain.name)++ if result['success']:+ return jsonify({+ 'message': 'SSL certificate renewed',+ 'domain': domain.to_dict()+ }), 200++ return jsonify({'error': result.get('error', 'Failed to renew certificate')}), 400+++@domains_bp.route('/<int:domain_id>/verify', methods=['GET'])+@jwt_required()+def verify_domain(domain_id):+ """Verify domain DNS configuration."""+ import socket++ domain = Domain.query.get(domain_id)+ if not domain:+ return jsonify({'error': 'Domain not found'}), 404++ try:+ # Try to resolve the domain+ ip_address = socket.gethostbyname(domain.name)+ return jsonify({+ 'verified': True,+ 'domain': domain.name,+ 'ip_address': ip_address+ }), 200+ except socket.gaierror:+ return jsonify({+ 'verified': False,+ 'domain': domain.name,+ 'error': 'Domain could not be resolved'+ }), 200+++@domains_bp.route('/nginx/sites', methods=['GET'])+@jwt_required()+@admin_required+def list_nginx_sites():+ """List all Nginx site configurations."""+ sites = NginxService.list_sites()+ return jsonify({'sites': sites}), 200+++@domains_bp.route('/ssl/status', methods=['GET'])+@jwt_required()+@admin_required+def get_ssl_status():+ """Get overall SSL status."""+ is_installed = SSLService.is_certbot_installed()+ certificates = SSLService.list_certificates()++ return jsonify({+ 'certbot_installed': is_installed,+ 'total_certificates': len(certificates),+ 'certificates': certificates+ }), 200diff --git a/backend/app/api/monitoring.py b/backend/app/api/monitoring.pynew file mode 100644index 00000000..756d0edd--- /dev/null+++ b/backend/app/api/monitoring.py@@ -0,0 +1,180 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User+from app.services.monitoring_service import MonitoringService++monitoring_bp = Blueprint('monitoring', __name__)+++def admin_required(fn):+ """Decorator to require admin role."""+ from functools import wraps++ @wraps(fn)+ def wrapper(*args, **kwargs):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403+ return fn(*args, **kwargs)+ return wrapper+++@monitoring_bp.route('/status', methods=['GET'])+@jwt_required()+def get_status():+ """Get monitoring status and current metrics."""+ status = MonitoringService.get_status()+ return jsonify(status), 200+++@monitoring_bp.route('/metrics', methods=['GET'])+@jwt_required()+def get_metrics():+ """Get current system metrics."""+ metrics = MonitoringService.get_current_metrics()+ return jsonify(metrics), 200+++@monitoring_bp.route('/alerts/check', methods=['GET'])+@jwt_required()+def check_alerts():+ """Check current threshold violations."""+ alerts = MonitoringService.check_thresholds()+ return jsonify({'alerts': alerts}), 200+++@monitoring_bp.route('/alerts/history', methods=['GET'])+@jwt_required()+def get_alert_history():+ """Get alert history."""+ limit = request.args.get('limit', 100, type=int)+ alerts = MonitoringService.get_alert_history(limit)+ return jsonify({'alerts': alerts}), 200+++@monitoring_bp.route('/alerts/history', methods=['DELETE'])+@jwt_required()+@admin_required+def clear_alert_history():+ """Clear alert history."""+ result = MonitoringService.clear_alert_history()+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/config', methods=['GET'])+@jwt_required()+@admin_required+def get_config():+ """Get monitoring configuration."""+ config = MonitoringService.get_config()+ # Don't expose sensitive data+ if 'email' in config and 'smtp_password' in config['email']:+ config['email']['smtp_password'] = '***' if config['email']['smtp_password'] else ''+ return jsonify(config), 200+++@monitoring_bp.route('/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_config():+ """Update monitoring configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ current_config = MonitoringService.get_config()++ # Update config with new values+ if 'thresholds' in data:+ current_config['thresholds'] = {**current_config.get('thresholds', {}), **data['thresholds']}++ if 'check_interval' in data:+ current_config['check_interval'] = data['check_interval']++ if 'email' in data:+ email_config = current_config.get('email', {})+ new_email = data['email']++ # Preserve password if not provided or masked+ if new_email.get('smtp_password') in [None, '', '***']:+ new_email['smtp_password'] = email_config.get('smtp_password', '')++ current_config['email'] = {**email_config, **new_email}++ if 'webhook' in data:+ current_config['webhook'] = {**current_config.get('webhook', {}), **data['webhook']}++ result = MonitoringService.save_config(current_config)+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/thresholds', methods=['GET'])+@jwt_required()+def get_thresholds():+ """Get alert thresholds."""+ thresholds = MonitoringService.get_thresholds()+ return jsonify({'thresholds': thresholds}), 200+++@monitoring_bp.route('/thresholds', methods=['PUT'])+@jwt_required()+@admin_required+def update_thresholds():+ """Update alert thresholds."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ result = MonitoringService.set_thresholds(data)+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/start', methods=['POST'])+@jwt_required()+@admin_required+def start_monitoring():+ """Start background monitoring."""+ result = MonitoringService.start_monitoring()+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/stop', methods=['POST'])+@jwt_required()+@admin_required+def stop_monitoring():+ """Stop background monitoring."""+ result = MonitoringService.stop_monitoring()+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/test/email', methods=['POST'])+@jwt_required()+@admin_required+def test_email_alert():+ """Send a test email alert."""+ test_alerts = [{+ 'type': 'test',+ 'severity': 'info',+ 'message': 'This is a test alert from ServerKit',+ 'value': 0,+ 'threshold': 0+ }]+ result = MonitoringService.send_email_alert(test_alerts)+ return jsonify(result), 200 if result['success'] else 400+++@monitoring_bp.route('/test/webhook', methods=['POST'])+@jwt_required()+@admin_required+def test_webhook_alert():+ """Send a test webhook alert."""+ test_alerts = [{+ 'type': 'test',+ 'severity': 'info',+ 'message': 'This is a test alert from ServerKit',+ 'value': 0,+ 'threshold': 0+ }]+ result = MonitoringService.send_webhook_alert(test_alerts)+ return jsonify(result), 200 if result['success'] else 400diff --git a/backend/app/middleware/__init__.py b/backend/app/middleware/__init__.pynew file mode 100644index 00000000..93fa6f75--- /dev/null+++ b/backend/app/middleware/__init__.py@@ -0,0 +1 @@+# Middleware packagediff --git a/backend/app/middleware/security.py b/backend/app/middleware/security.pynew file mode 100644index 00000000..44780d3b--- /dev/null+++ b/backend/app/middleware/security.py@@ -0,0 +1,42 @@+"""Security middleware for adding security headers to responses."""++from flask import Flask+++def register_security_headers(app: Flask):+ """Register security headers as an after_request handler."""++ @app.after_request+ def add_security_headers(response):+ # Prevent clickjacking+ response.headers['X-Frame-Options'] = 'DENY'++ # Prevent MIME type sniffing+ response.headers['X-Content-Type-Options'] = 'nosniff'++ # XSS Protection (legacy but still useful for older browsers)+ response.headers['X-XSS-Protection'] = '1; mode=block'++ # Referrer Policy+ response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'++ # Content Security Policy+ csp_directives = [+ "default-src 'self'",+ "script-src 'self' 'unsafe-inline' 'unsafe-eval'",+ "style-src 'self' 'unsafe-inline'",+ "img-src 'self' data: https:",+ "font-src 'self'",+ "connect-src 'self' ws: wss:",+ "frame-ancestors 'none'",+ ]+ response.headers['Content-Security-Policy'] = '; '.join(csp_directives)++ # Permissions Policy (formerly Feature-Policy)+ response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'++ # HSTS - only in production and on HTTPS+ if not app.debug:+ response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'++ return responsediff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex 66be57be..75d5fd52 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -1,4 +1,4 @@-from datetime import datetime+from datetime import datetime, timedeltafrom werkzeug.security import generate_password_hash, check_password_hashfrom app import db@@ -15,9 +15,41 @@ class User(db.Model):created_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+ # Account lockout fields+ failed_login_count = db.Column(db.Integer, default=0)+ locked_until = db.Column(db.DateTime, nullable=True)+# Relationshipsapplications = db.relationship('Application', backref='owner', lazy='dynamic')+ # Lockout durations (progressive: 5 min, 15 min, 1 hour)+ LOCKOUT_DURATIONS = [5, 15, 60]+ MAX_FAILED_ATTEMPTS = 5++ @property+ def is_locked(self):+ """Check if account is currently locked."""+ if self.locked_until is None:+ return False+ return datetime.utcnow() < self.locked_until++ def record_failed_login(self):+ """Record a failed login attempt and lock account if threshold reached."""+ self.failed_login_count += 1+ if self.failed_login_count >= self.MAX_FAILED_ATTEMPTS:+ # Calculate lockout duration based on how many times they've been locked+ lockout_index = min(+ (self.failed_login_count - self.MAX_FAILED_ATTEMPTS) // self.MAX_FAILED_ATTEMPTS,+ len(self.LOCKOUT_DURATIONS) - 1+ )+ lockout_minutes = self.LOCKOUT_DURATIONS[lockout_index]+ self.locked_until = datetime.utcnow() + timedelta(minutes=lockout_minutes)++ def reset_failed_login(self):+ """Reset failed login count after successful login."""+ self.failed_login_count = 0+ self.locked_until = None+def set_password(self, password):self.password_hash = generate_password_hash(password)diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.pynew file mode 100644index 00000000..7a403642--- /dev/null+++ b/backend/app/services/backup_service.py@@ -0,0 +1,474 @@+import os+import json+import subprocess+import shutil+import tarfile+import gzip+from datetime import datetime, timedelta+from typing import Dict, List, Optional+from pathlib import Path+import threading+import time+import schedule+++class BackupService:+ """Service for automated backups of applications and databases."""++ BACKUP_BASE_DIR = '/var/backups/serverkit'+ CONFIG_DIR = '/etc/serverkit'+ BACKUP_CONFIG = os.path.join(CONFIG_DIR, 'backups.json')++ # Backup types+ TYPE_APP = 'application'+ TYPE_DATABASE = 'database'+ TYPE_FULL = 'full'++ _scheduler_thread = None+ _stop_scheduler = False++ @classmethod+ def get_backup_dir(cls, backup_type: str = None) -> str:+ """Get backup directory for type."""+ if backup_type:+ return os.path.join(cls.BACKUP_BASE_DIR, backup_type)+ return cls.BACKUP_BASE_DIR++ @classmethod+ def ensure_backup_dirs(cls) -> None:+ """Ensure backup directories exist."""+ for subdir in ['applications', 'databases', 'full', 'scheduled']:+ path = os.path.join(cls.BACKUP_BASE_DIR, subdir)+ os.makedirs(path, exist_ok=True)++ @classmethod+ def get_config(cls) -> Dict:+ """Get backup configuration."""+ if os.path.exists(cls.BACKUP_CONFIG):+ try:+ with open(cls.BACKUP_CONFIG, 'r') as f:+ return json.load(f)+ except Exception:+ pass++ return {+ 'enabled': False,+ 'retention_days': 30,+ 'schedules': [],+ 'notifications': {+ 'on_success': False,+ 'on_failure': True,+ 'email': ''+ }+ }++ @classmethod+ def save_config(cls, config: Dict) -> Dict:+ """Save backup configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.BACKUP_CONFIG, 'w') as f:+ json.dump(config, f, indent=2)+ return {'success': True, 'message': 'Configuration saved'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def backup_application(cls, app_name: str, app_path: str,+ include_db: bool = False, db_config: Dict = None) -> Dict:+ """Backup an application (files and optionally database)."""+ cls.ensure_backup_dirs()++ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')+ backup_name = f"{app_name}_{timestamp}"+ backup_dir = os.path.join(cls.BACKUP_BASE_DIR, 'applications', backup_name)++ try:+ os.makedirs(backup_dir, exist_ok=True)++ # Backup files+ files_backup = os.path.join(backup_dir, 'files.tar.gz')+ with tarfile.open(files_backup, 'w:gz') as tar:+ tar.add(app_path, arcname=os.path.basename(app_path))++ backup_info = {+ 'name': backup_name,+ 'app_name': app_name,+ 'timestamp': datetime.now().isoformat(),+ 'type': cls.TYPE_APP,+ 'files_backup': files_backup,+ 'size': os.path.getsize(files_backup)+ }++ # Backup database if requested+ if include_db and db_config:+ db_backup = cls._backup_database_internal(+ db_config.get('type', 'mysql'),+ db_config.get('name'),+ backup_dir,+ db_config+ )+ if db_backup.get('success'):+ backup_info['database_backup'] = db_backup['path']+ backup_info['database_type'] = db_config.get('type')++ # Save backup metadata+ meta_path = os.path.join(backup_dir, 'backup.json')+ with open(meta_path, 'w') as f:+ json.dump(backup_info, f, indent=2)++ return {+ 'success': True,+ 'backup': backup_info,+ 'path': backup_dir+ }++ except Exception as e:+ # Cleanup on failure+ if os.path.exists(backup_dir):+ shutil.rmtree(backup_dir, ignore_errors=True)+ return {'success': False, 'error': str(e)}++ @classmethod+ def _backup_database_internal(cls, db_type: str, db_name: str,+ backup_dir: str, config: Dict) -> Dict:+ """Internal database backup helper."""+ backup_file = os.path.join(backup_dir, f'{db_name}.sql.gz')++ try:+ if db_type == 'mysql':+ cmd = ['mysqldump']+ if config.get('user'):+ cmd.extend(['-u', config['user']])+ if config.get('password'):+ cmd.append(f"-p{config['password']}")+ if config.get('host'):+ cmd.extend(['-h', config['host']])+ cmd.append(db_name)++ with gzip.open(backup_file, 'wt') as f:+ result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True)++ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}++ elif db_type == 'postgresql':+ env = os.environ.copy()+ if config.get('password'):+ env['PGPASSWORD'] = config['password']++ cmd = ['pg_dump']+ if config.get('user'):+ cmd.extend(['-U', config['user']])+ if config.get('host'):+ cmd.extend(['-h', config['host']])+ cmd.append(db_name)++ with gzip.open(backup_file, 'wt') as f:+ result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True, env=env)++ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}++ return {'success': True, 'path': backup_file}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def backup_database(cls, db_type: str, db_name: str,+ user: str = None, password: str = None,+ host: str = 'localhost') -> Dict:+ """Backup a database."""+ cls.ensure_backup_dirs()++ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')+ backup_name = f"{db_type}_{db_name}_{timestamp}.sql.gz"+ backup_path = os.path.join(cls.BACKUP_BASE_DIR, 'databases', backup_name)++ config = {+ 'type': db_type,+ 'name': db_name,+ 'user': user,+ 'password': password,+ 'host': host+ }++ result = cls._backup_database_internal(db_type, db_name,+ os.path.dirname(backup_path), config)++ if result.get('success'):+ # Rename to final path+ os.rename(result['path'], backup_path)+ return {+ 'success': True,+ 'backup': {+ 'name': backup_name,+ 'path': backup_path,+ 'timestamp': datetime.now().isoformat(),+ 'type': cls.TYPE_DATABASE,+ 'database_type': db_type,+ 'database_name': db_name,+ 'size': os.path.getsize(backup_path)+ }+ }++ return result++ @classmethod+ def restore_application(cls, backup_path: str, restore_path: str = None) -> Dict:+ """Restore an application from backup."""+ meta_path = os.path.join(backup_path, 'backup.json')++ if not os.path.exists(meta_path):+ return {'success': False, 'error': 'Invalid backup: metadata not found'}++ try:+ with open(meta_path, 'r') as f:+ backup_info = json.load(f)++ files_backup = backup_info.get('files_backup')+ if not files_backup or not os.path.exists(files_backup):+ return {'success': False, 'error': 'Backup files not found'}++ # Determine restore path+ if not restore_path:+ restore_path = f"/var/www/{backup_info['app_name']}"++ # Backup existing if present+ if os.path.exists(restore_path):+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')+ backup_existing = f"{restore_path}.backup_{timestamp}"+ shutil.move(restore_path, backup_existing)++ # Extract backup+ with tarfile.open(files_backup, 'r:gz') as tar:+ tar.extractall(os.path.dirname(restore_path))++ return {+ 'success': True,+ 'message': f'Application restored to {restore_path}',+ 'restore_path': restore_path+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def restore_database(cls, backup_path: str, db_type: str, db_name: str,+ user: str = None, password: str = None,+ host: str = 'localhost') -> Dict:+ """Restore a database from backup."""+ if not os.path.exists(backup_path):+ return {'success': False, 'error': 'Backup file not found'}++ try:+ if db_type == 'mysql':+ cmd = ['mysql']+ if user:+ cmd.extend(['-u', user])+ if password:+ cmd.append(f"-p{password}")+ if host:+ cmd.extend(['-h', host])+ cmd.append(db_name)++ with gzip.open(backup_path, 'rt') as f:+ result = subprocess.run(cmd, stdin=f, capture_output=True, text=True)++ elif db_type == 'postgresql':+ env = os.environ.copy()+ if password:+ env['PGPASSWORD'] = password++ cmd = ['psql']+ if user:+ cmd.extend(['-U', user])+ if host:+ cmd.extend(['-h', host])+ cmd.extend(['-d', db_name])++ with gzip.open(backup_path, 'rt') as f:+ result = subprocess.run(cmd, stdin=f, capture_output=True, text=True, env=env)++ else:+ return {'success': False, 'error': f'Unknown database type: {db_type}'}++ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}++ return {'success': True, 'message': f'Database {db_name} restored'}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_backups(cls, backup_type: str = None) -> List[Dict]:+ """List all backups."""+ backups = []+ cls.ensure_backup_dirs()++ search_dirs = []+ if backup_type == 'application':+ search_dirs = [os.path.join(cls.BACKUP_BASE_DIR, 'applications')]+ elif backup_type == 'database':+ search_dirs = [os.path.join(cls.BACKUP_BASE_DIR, 'databases')]+ else:+ search_dirs = [+ os.path.join(cls.BACKUP_BASE_DIR, 'applications'),+ os.path.join(cls.BACKUP_BASE_DIR, 'databases'),+ os.path.join(cls.BACKUP_BASE_DIR, 'scheduled')+ ]++ for search_dir in search_dirs:+ if not os.path.exists(search_dir):+ continue++ for item in os.listdir(search_dir):+ item_path = os.path.join(search_dir, item)++ if os.path.isdir(item_path):+ # Application backup (directory)+ meta_path = os.path.join(item_path, 'backup.json')+ if os.path.exists(meta_path):+ try:+ with open(meta_path, 'r') as f:+ backup_info = json.load(f)+ backup_info['path'] = item_path+ backups.append(backup_info)+ except Exception:+ pass+ elif item.endswith('.sql.gz'):+ # Database backup (file)+ stat = os.stat(item_path)+ backups.append({+ 'name': item,+ 'path': item_path,+ 'type': cls.TYPE_DATABASE,+ 'size': stat.st_size,+ 'timestamp': datetime.fromtimestamp(stat.st_mtime).isoformat()+ })++ # Sort by timestamp (newest first)+ backups.sort(key=lambda x: x.get('timestamp', ''), reverse=True)++ return backups++ @classmethod+ def delete_backup(cls, backup_path: str) -> Dict:+ """Delete a backup."""+ if not backup_path.startswith(cls.BACKUP_BASE_DIR):+ return {'success': False, 'error': 'Invalid backup path'}++ try:+ if os.path.isdir(backup_path):+ shutil.rmtree(backup_path)+ elif os.path.exists(backup_path):+ os.remove(backup_path)+ else:+ return {'success': False, 'error': 'Backup not found'}++ return {'success': True, 'message': 'Backup deleted'}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def cleanup_old_backups(cls, retention_days: int = None) -> Dict:+ """Delete backups older than retention period."""+ config = cls.get_config()+ if retention_days is None:+ retention_days = config.get('retention_days', 30)++ cutoff = datetime.now() - timedelta(days=retention_days)+ deleted = 0++ try:+ for backup in cls.list_backups():+ try:+ backup_time = datetime.fromisoformat(backup.get('timestamp', ''))+ if backup_time < cutoff:+ result = cls.delete_backup(backup['path'])+ if result.get('success'):+ deleted += 1+ except Exception:+ pass++ return {+ 'success': True,+ 'deleted_count': deleted,+ 'message': f'Deleted {deleted} old backup(s)'+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def add_schedule(cls, name: str, backup_type: str, target: str,+ schedule_time: str, days: List[str] = None) -> Dict:+ """Add a backup schedule."""+ config = cls.get_config()++ schedule_entry = {+ 'id': datetime.now().strftime('%Y%m%d%H%M%S'),+ 'name': name,+ 'backup_type': backup_type,+ 'target': target,+ 'schedule_time': schedule_time,+ 'days': days or ['daily'],+ 'enabled': True,+ 'last_run': None+ }++ config.setdefault('schedules', []).append(schedule_entry)+ result = cls.save_config(config)++ if result.get('success'):+ return {'success': True, 'schedule': schedule_entry}+ return result++ @classmethod+ def remove_schedule(cls, schedule_id: str) -> Dict:+ """Remove a backup schedule."""+ config = cls.get_config()+ schedules = config.get('schedules', [])++ new_schedules = [s for s in schedules if s.get('id') != schedule_id]++ if len(new_schedules) == len(schedules):+ return {'success': False, 'error': 'Schedule not found'}++ config['schedules'] = new_schedules+ return cls.save_config(config)++ @classmethod+ def get_schedules(cls) -> List[Dict]:+ """Get all backup schedules."""+ config = cls.get_config()+ return config.get('schedules', [])++ @classmethod+ def get_backup_stats(cls) -> Dict:+ """Get backup statistics."""+ backups = cls.list_backups()++ total_size = sum(b.get('size', 0) for b in backups)+ app_backups = [b for b in backups if b.get('type') == cls.TYPE_APP]+ db_backups = [b for b in backups if b.get('type') == cls.TYPE_DATABASE]++ return {+ 'total_backups': len(backups),+ 'application_backups': len(app_backups),+ 'database_backups': len(db_backups),+ 'total_size': total_size,+ 'total_size_human': cls._format_size(total_size)+ }++ @staticmethod+ def _format_size(size: int) -> str:+ """Format size in human readable format."""+ for unit in ['B', 'KB', 'MB', 'GB', 'TB']:+ if size < 1024:+ return f"{size:.1f} {unit}"+ size /= 1024+ return f"{size:.1f} PB"diff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.pynew file mode 100644index 00000000..68fe1e5d--- /dev/null+++ b/backend/app/services/git_service.py@@ -0,0 +1,429 @@+import os+import subprocess+import json+import hmac+import hashlib+from datetime import datetime+from typing import Dict, List, Optional+from pathlib import Path+++class GitService:+ """Service for Git deployment and webhooks."""++ CONFIG_DIR = '/etc/serverkit'+ DEPLOY_CONFIG = os.path.join(CONFIG_DIR, 'deployments.json')+ DEPLOY_LOG = '/var/log/serverkit/deployments.log'++ @classmethod+ def get_config(cls) -> Dict:+ """Get deployment configuration."""+ if os.path.exists(cls.DEPLOY_CONFIG):+ try:+ with open(cls.DEPLOY_CONFIG, 'r') as f:+ return json.load(f)+ except Exception:+ pass++ return {+ 'apps': {}, # app_id -> deployment config+ 'webhook_secret': cls._generate_secret()+ }++ @classmethod+ def save_config(cls, config: Dict) -> Dict:+ """Save deployment configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.DEPLOY_CONFIG, 'w') as f:+ json.dump(config, f, indent=2)+ return {'success': True, 'message': 'Configuration saved'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def _generate_secret() -> str:+ """Generate a random webhook secret."""+ import secrets+ return secrets.token_hex(32)++ @classmethod+ def get_app_config(cls, app_id: int) -> Optional[Dict]:+ """Get deployment config for an app."""+ config = cls.get_config()+ return config.get('apps', {}).get(str(app_id))++ @classmethod+ def configure_deployment(cls, app_id: int, app_path: str,+ repo_url: str, branch: str = 'main',+ auto_deploy: bool = True,+ pre_deploy_script: str = None,+ post_deploy_script: str = None) -> Dict:+ """Configure Git deployment for an application."""+ config = cls.get_config()++ app_config = {+ 'app_id': app_id,+ 'app_path': app_path,+ 'repo_url': repo_url,+ 'branch': branch,+ 'auto_deploy': auto_deploy,+ 'pre_deploy_script': pre_deploy_script,+ 'post_deploy_script': post_deploy_script,+ 'webhook_token': cls._generate_secret()[:16],+ 'created_at': datetime.now().isoformat(),+ 'last_deploy': None,+ 'deploy_count': 0+ }++ config.setdefault('apps', {})[str(app_id)] = app_config+ result = cls.save_config(config)++ if result.get('success'):+ return {+ 'success': True,+ 'config': app_config,+ 'webhook_url': f'/api/v1/deploy/webhook/{app_id}/{app_config["webhook_token"]}'+ }+ return result++ @classmethod+ def remove_deployment(cls, app_id: int) -> Dict:+ """Remove deployment configuration for an app."""+ config = cls.get_config()++ if str(app_id) not in config.get('apps', {}):+ return {'success': False, 'error': 'Deployment not configured'}++ del config['apps'][str(app_id)]+ return cls.save_config(config)++ @classmethod+ def clone_repository(cls, app_path: str, repo_url: str, branch: str = 'main') -> Dict:+ """Clone a Git repository."""+ try:+ # Remove existing directory if exists+ if os.path.exists(app_path):+ return {'success': False, 'error': 'Directory already exists'}++ cmd = ['git', 'clone', '--branch', branch, '--single-branch', repo_url, app_path]+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)++ if result.returncode == 0:+ return {+ 'success': True,+ 'message': f'Repository cloned to {app_path}',+ 'path': app_path+ }+ return {'success': False, 'error': result.stderr}++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Clone operation timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def pull_changes(cls, app_path: str, branch: str = None) -> Dict:+ """Pull latest changes from remote."""+ if not os.path.exists(os.path.join(app_path, '.git')):+ return {'success': False, 'error': 'Not a Git repository'}++ try:+ # Fetch first+ fetch_cmd = ['git', '-C', app_path, 'fetch', '--all']+ subprocess.run(fetch_cmd, capture_output=True, text=True, timeout=60)++ # Get current branch if not specified+ if not branch:+ branch_cmd = ['git', '-C', app_path, 'rev-parse', '--abbrev-ref', 'HEAD']+ result = subprocess.run(branch_cmd, capture_output=True, text=True)+ branch = result.stdout.strip() if result.returncode == 0 else 'main'++ # Reset to remote branch (force pull)+ reset_cmd = ['git', '-C', app_path, 'reset', '--hard', f'origin/{branch}']+ result = subprocess.run(reset_cmd, capture_output=True, text=True, timeout=60)++ if result.returncode == 0:+ # Get new commit info+ commit_info = cls.get_commit_info(app_path)+ return {+ 'success': True,+ 'message': 'Changes pulled successfully',+ 'commit': commit_info+ }+ return {'success': False, 'error': result.stderr}++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Pull operation timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_commit_info(cls, app_path: str) -> Optional[Dict]:+ """Get current commit information."""+ if not os.path.exists(os.path.join(app_path, '.git')):+ return None++ try:+ # Get commit hash+ cmd = ['git', '-C', app_path, 'rev-parse', 'HEAD']+ result = subprocess.run(cmd, capture_output=True, text=True)+ commit_hash = result.stdout.strip() if result.returncode == 0 else None++ # Get commit message+ cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%B']+ result = subprocess.run(cmd, capture_output=True, text=True)+ commit_message = result.stdout.strip() if result.returncode == 0 else None++ # Get author+ cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%an <%ae>']+ result = subprocess.run(cmd, capture_output=True, text=True)+ author = result.stdout.strip() if result.returncode == 0 else None++ # Get timestamp+ cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%ci']+ result = subprocess.run(cmd, capture_output=True, text=True)+ timestamp = result.stdout.strip() if result.returncode == 0 else None++ # Get branch+ cmd = ['git', '-C', app_path, 'rev-parse', '--abbrev-ref', 'HEAD']+ result = subprocess.run(cmd, capture_output=True, text=True)+ branch = result.stdout.strip() if result.returncode == 0 else None++ return {+ 'hash': commit_hash,+ 'short_hash': commit_hash[:7] if commit_hash else None,+ 'message': commit_message,+ 'author': author,+ 'timestamp': timestamp,+ 'branch': branch+ }++ except Exception:+ return None++ @classmethod+ def deploy(cls, app_id: int, force: bool = False) -> Dict:+ """Deploy an application from Git."""+ app_config = cls.get_app_config(app_id)+ if not app_config:+ return {'success': False, 'error': 'Deployment not configured'}++ app_path = app_config['app_path']+ branch = app_config.get('branch', 'main')++ deploy_log = {+ 'app_id': app_id,+ 'started_at': datetime.now().isoformat(),+ 'status': 'in_progress',+ 'steps': []+ }++ try:+ # Pre-deploy script+ if app_config.get('pre_deploy_script'):+ deploy_log['steps'].append({'step': 'pre_deploy', 'status': 'running'})+ result = cls._run_script(app_config['pre_deploy_script'], app_path)+ deploy_log['steps'][-1].update({+ 'status': 'success' if result['success'] else 'failed',+ 'output': result.get('output', result.get('error'))+ })+ if not result['success']:+ raise Exception(f"Pre-deploy script failed: {result['error']}")++ # Pull changes+ deploy_log['steps'].append({'step': 'pull', 'status': 'running'})+ pull_result = cls.pull_changes(app_path, branch)+ deploy_log['steps'][-1].update({+ 'status': 'success' if pull_result['success'] else 'failed',+ 'commit': pull_result.get('commit')+ })+ if not pull_result['success']:+ raise Exception(f"Pull failed: {pull_result['error']}")++ # Post-deploy script+ if app_config.get('post_deploy_script'):+ deploy_log['steps'].append({'step': 'post_deploy', 'status': 'running'})+ result = cls._run_script(app_config['post_deploy_script'], app_path)+ deploy_log['steps'][-1].update({+ 'status': 'success' if result['success'] else 'failed',+ 'output': result.get('output', result.get('error'))+ })+ if not result['success']:+ raise Exception(f"Post-deploy script failed: {result['error']}")++ # Update config+ config = cls.get_config()+ config['apps'][str(app_id)]['last_deploy'] = datetime.now().isoformat()+ config['apps'][str(app_id)]['deploy_count'] = config['apps'][str(app_id)].get('deploy_count', 0) + 1+ cls.save_config(config)++ deploy_log['status'] = 'success'+ deploy_log['completed_at'] = datetime.now().isoformat()++ cls._log_deployment(deploy_log)++ return {+ 'success': True,+ 'message': 'Deployment completed successfully',+ 'deploy_log': deploy_log+ }++ except Exception as e:+ deploy_log['status'] = 'failed'+ deploy_log['error'] = str(e)+ deploy_log['completed_at'] = datetime.now().isoformat()++ cls._log_deployment(deploy_log)++ return {'success': False, 'error': str(e), 'deploy_log': deploy_log}++ @classmethod+ def _run_script(cls, script: str, working_dir: str) -> Dict:+ """Run a deployment script."""+ try:+ result = subprocess.run(+ script,+ shell=True,+ cwd=working_dir,+ capture_output=True,+ text=True,+ timeout=300+ )++ return {+ 'success': result.returncode == 0,+ 'output': result.stdout,+ 'error': result.stderr if result.returncode != 0 else None+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Script timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def verify_webhook(cls, app_id: int, token: str,+ signature: str = None, payload: bytes = None) -> bool:+ """Verify webhook authenticity."""+ app_config = cls.get_app_config(app_id)+ if not app_config:+ return False++ # Simple token verification+ if token != app_config.get('webhook_token'):+ return False++ # If signature provided (GitHub style), verify it+ if signature and payload:+ config = cls.get_config()+ secret = config.get('webhook_secret', '').encode()+ expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()+ return hmac.compare_digest(signature, expected)++ return True++ @classmethod+ def handle_webhook(cls, app_id: int, payload: Dict) -> Dict:+ """Handle incoming webhook."""+ app_config = cls.get_app_config(app_id)+ if not app_config:+ return {'success': False, 'error': 'App not configured'}++ if not app_config.get('auto_deploy', True):+ return {'success': False, 'error': 'Auto-deploy disabled'}++ # Check if push is to configured branch+ ref = payload.get('ref', '')+ branch = app_config.get('branch', 'main')++ if ref != f'refs/heads/{branch}':+ return {+ 'success': True,+ 'message': f'Ignoring push to {ref}, configured branch is {branch}'+ }++ # Trigger deployment+ return cls.deploy(app_id)++ @classmethod+ def _log_deployment(cls, deploy_log: Dict) -> None:+ """Log deployment to file."""+ try:+ log_dir = os.path.dirname(cls.DEPLOY_LOG)+ os.makedirs(log_dir, exist_ok=True)++ with open(cls.DEPLOY_LOG, 'a') as f:+ f.write(json.dumps(deploy_log) + '\n')+ except Exception:+ pass++ @classmethod+ def get_deployment_history(cls, app_id: int = None, limit: int = 50) -> List[Dict]:+ """Get deployment history."""+ history = []++ if not os.path.exists(cls.DEPLOY_LOG):+ return history++ try:+ with open(cls.DEPLOY_LOG, 'r') as f:+ lines = f.readlines()++ for line in reversed(lines[-limit * 2:]): # Read more than needed for filtering+ try:+ entry = json.loads(line.strip())+ if app_id is None or entry.get('app_id') == app_id:+ history.append(entry)+ if len(history) >= limit:+ break+ except json.JSONDecodeError:+ pass++ except Exception:+ pass++ return history++ @classmethod+ def get_git_status(cls, app_path: str) -> Dict:+ """Get Git status for a repository."""+ if not os.path.exists(os.path.join(app_path, '.git')):+ return {'error': 'Not a Git repository'}++ try:+ # Status+ cmd = ['git', '-C', app_path, 'status', '--porcelain']+ result = subprocess.run(cmd, capture_output=True, text=True)+ changes = result.stdout.strip().split('\n') if result.stdout.strip() else []++ # Remote URL+ cmd = ['git', '-C', app_path, 'remote', 'get-url', 'origin']+ result = subprocess.run(cmd, capture_output=True, text=True)+ remote_url = result.stdout.strip() if result.returncode == 0 else None++ # Behind/ahead of remote+ cmd = ['git', '-C', app_path, 'rev-list', '--left-right', '--count', 'HEAD...@{u}']+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode == 0:+ parts = result.stdout.strip().split()+ ahead = int(parts[0]) if len(parts) > 0 else 0+ behind = int(parts[1]) if len(parts) > 1 else 0+ else:+ ahead = behind = 0++ commit_info = cls.get_commit_info(app_path)++ return {+ 'is_git_repo': True,+ 'remote_url': remote_url,+ 'branch': commit_info.get('branch') if commit_info else None,+ 'commit': commit_info,+ 'changes': len(changes),+ 'has_uncommitted': len(changes) > 0,+ 'ahead': ahead,+ 'behind': behind+ }++ except Exception as e:+ return {'error': str(e)}diff --git a/backend/app/services/log_service.py b/backend/app/services/log_service.pyindex 7202709a..3167572a 100644--- a/backend/app/services/log_service.py+++ b/backend/app/services/log_service.py@@ -21,6 +21,29 @@ class LogService:'auth': '/var/log/auth.log',}+ # Allowed directories for log file access (path traversal protection)+ ALLOWED_LOG_DIRECTORIES = [+ '/var/log',+ '/home',+ '/opt',+ ]++ @classmethod+ def is_path_allowed(cls, filepath: str) -> bool:+ """Check if the filepath is within allowed directories."""+ try:+ # Resolve the absolute path to prevent traversal attacks+ real_path = os.path.realpath(filepath)++ # Check if the path starts with any allowed directory+ for allowed_dir in cls.ALLOWED_LOG_DIRECTORIES:+ if real_path.startswith(allowed_dir):+ return True++ return False+ except (ValueError, OSError):+ return False+@classmethoddef get_log_files(cls) -> List[Dict]:"""Get list of available log files."""@@ -47,6 +70,9 @@ class LogService:@classmethoddef read_log(cls, filepath: str, lines: int = 100, from_end: bool = True) -> Dict:"""Read lines from a log file."""+ if not cls.is_path_allowed(filepath):+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}+if not os.path.exists(filepath):return {'success': False, 'error': 'Log file not found'}@@ -85,6 +111,9 @@ class LogService:@classmethoddef search_log(cls, filepath: str, pattern: str, lines: int = 100) -> Dict:"""Search log file for pattern."""+ if not cls.is_path_allowed(filepath):+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}+if not os.path.exists(filepath):return {'success': False, 'error': 'Log file not found'}@@ -155,6 +184,9 @@ class LogService:@classmethoddef clear_log(cls, filepath: str) -> Dict:"""Clear/truncate a log file."""+ if not cls.is_path_allowed(filepath):+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}+if not os.path.exists(filepath):return {'success': False, 'error': 'Log file not found'}@@ -194,6 +226,10 @@ class LogService:@classmethoddef tail_log(cls, filepath: str, callback, stop_event: threading.Event = None):"""Stream log file in real-time (for WebSocket use)."""+ if not cls.is_path_allowed(filepath):+ callback({'error': 'Access denied: path not in allowed directories'})+ return+if not os.path.exists(filepath):callback({'error': 'Log file not found'})returndiff --git a/backend/app/services/monitoring_service.py b/backend/app/services/monitoring_service.pynew file mode 100644index 00000000..b08b9cbd--- /dev/null+++ b/backend/app/services/monitoring_service.py@@ -0,0 +1,386 @@+import os+import json+import psutil+import smtplib+from email.mime.text import MIMEText+from email.mime.multipart import MIMEMultipart+from datetime import datetime, timedelta+from typing import Dict, List, Optional+from pathlib import Path+import threading+import time+++class MonitoringService:+ """Service for system monitoring and alerts."""++ CONFIG_DIR = '/etc/serverkit'+ ALERTS_CONFIG = os.path.join(CONFIG_DIR, 'alerts.json')+ ALERTS_LOG = '/var/log/serverkit/alerts.log'++ # Default thresholds+ DEFAULT_THRESHOLDS = {+ 'cpu_percent': 80,+ 'memory_percent': 85,+ 'disk_percent': 90,+ 'load_average': 5.0+ }++ # Alert cooldown (don't send same alert within this period)+ ALERT_COOLDOWN = 300 # 5 minutes++ _last_alerts = {}+ _monitoring_thread = None+ _stop_monitoring = False++ @classmethod+ def get_config(cls) -> Dict:+ """Get monitoring configuration."""+ if os.path.exists(cls.ALERTS_CONFIG):+ try:+ with open(cls.ALERTS_CONFIG, 'r') as f:+ return json.load(f)+ except Exception:+ pass++ return {+ 'enabled': False,+ 'thresholds': cls.DEFAULT_THRESHOLDS.copy(),+ 'email': {+ 'enabled': False,+ 'smtp_host': '',+ 'smtp_port': 587,+ 'smtp_user': '',+ 'smtp_password': '',+ 'from_email': '',+ 'to_emails': []+ },+ 'webhook': {+ 'enabled': False,+ 'url': ''+ },+ 'check_interval': 60 # seconds+ }++ @classmethod+ def save_config(cls, config: Dict) -> Dict:+ """Save monitoring configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.ALERTS_CONFIG, 'w') as f:+ json.dump(config, f, indent=2)+ return {'success': True, 'message': 'Configuration saved'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_thresholds(cls) -> Dict:+ """Get current alert thresholds."""+ config = cls.get_config()+ return config.get('thresholds', cls.DEFAULT_THRESHOLDS)++ @classmethod+ def set_thresholds(cls, thresholds: Dict) -> Dict:+ """Set alert thresholds."""+ config = cls.get_config()+ config['thresholds'] = {**config.get('thresholds', {}), **thresholds}+ return cls.save_config(config)++ @classmethod+ def get_current_metrics(cls) -> Dict:+ """Get current system metrics."""+ cpu_percent = psutil.cpu_percent(interval=1)+ memory = psutil.virtual_memory()+ disk = psutil.disk_usage('/')++ try:+ load_avg = os.getloadavg()+ except (OSError, AttributeError):+ load_avg = (0, 0, 0)++ return {+ 'timestamp': datetime.now().isoformat(),+ 'cpu': {+ 'percent': cpu_percent,+ 'cores': psutil.cpu_count()+ },+ 'memory': {+ 'percent': memory.percent,+ 'used': memory.used,+ 'total': memory.total,+ 'available': memory.available+ },+ 'disk': {+ 'percent': disk.percent,+ 'used': disk.used,+ 'total': disk.total,+ 'free': disk.free+ },+ 'load_average': {+ '1min': load_avg[0],+ '5min': load_avg[1],+ '15min': load_avg[2]+ }+ }++ @classmethod+ def check_thresholds(cls) -> List[Dict]:+ """Check if any thresholds are exceeded."""+ metrics = cls.get_current_metrics()+ thresholds = cls.get_thresholds()+ alerts = []++ # CPU check+ if metrics['cpu']['percent'] > thresholds.get('cpu_percent', 80):+ alerts.append({+ 'type': 'cpu',+ 'severity': 'warning' if metrics['cpu']['percent'] < 95 else 'critical',+ 'message': f"CPU usage at {metrics['cpu']['percent']}% (threshold: {thresholds['cpu_percent']}%)",+ 'value': metrics['cpu']['percent'],+ 'threshold': thresholds['cpu_percent']+ })++ # Memory check+ if metrics['memory']['percent'] > thresholds.get('memory_percent', 85):+ alerts.append({+ 'type': 'memory',+ 'severity': 'warning' if metrics['memory']['percent'] < 95 else 'critical',+ 'message': f"Memory usage at {metrics['memory']['percent']}% (threshold: {thresholds['memory_percent']}%)",+ 'value': metrics['memory']['percent'],+ 'threshold': thresholds['memory_percent']+ })++ # Disk check+ if metrics['disk']['percent'] > thresholds.get('disk_percent', 90):+ alerts.append({+ 'type': 'disk',+ 'severity': 'warning' if metrics['disk']['percent'] < 95 else 'critical',+ 'message': f"Disk usage at {metrics['disk']['percent']}% (threshold: {thresholds['disk_percent']}%)",+ 'value': metrics['disk']['percent'],+ 'threshold': thresholds['disk_percent']+ })++ # Load average check+ if metrics['load_average']['1min'] > thresholds.get('load_average', 5.0):+ alerts.append({+ 'type': 'load',+ 'severity': 'warning',+ 'message': f"Load average at {metrics['load_average']['1min']:.2f} (threshold: {thresholds['load_average']})",+ 'value': metrics['load_average']['1min'],+ 'threshold': thresholds['load_average']+ })++ return alerts++ @classmethod+ def send_email_alert(cls, alerts: List[Dict]) -> Dict:+ """Send email alert notification."""+ config = cls.get_config()+ email_config = config.get('email', {})++ if not email_config.get('enabled') or not email_config.get('to_emails'):+ return {'success': False, 'error': 'Email alerts not configured'}++ try:+ # Build email content+ subject = f"[ServerKit Alert] {len(alerts)} alert(s) triggered"++ body = "The following alerts have been triggered:\n\n"+ for alert in alerts:+ body += f"• [{alert['severity'].upper()}] {alert['message']}\n"+ body += f"\nTimestamp: {datetime.now().isoformat()}"+ body += f"\nHostname: {os.uname().nodename if hasattr(os, 'uname') else 'unknown'}"++ # Create message+ msg = MIMEMultipart()+ msg['From'] = email_config['from_email']+ msg['To'] = ', '.join(email_config['to_emails'])+ msg['Subject'] = subject+ msg.attach(MIMEText(body, 'plain'))++ # Send email+ with smtplib.SMTP(email_config['smtp_host'], email_config['smtp_port']) as server:+ server.starttls()+ if email_config.get('smtp_user') and email_config.get('smtp_password'):+ server.login(email_config['smtp_user'], email_config['smtp_password'])+ server.send_message(msg)++ return {'success': True, 'message': 'Email sent'}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def send_webhook_alert(cls, alerts: List[Dict]) -> Dict:+ """Send webhook alert notification."""+ import requests++ config = cls.get_config()+ webhook_config = config.get('webhook', {})++ if not webhook_config.get('enabled') or not webhook_config.get('url'):+ return {'success': False, 'error': 'Webhook not configured'}++ try:+ payload = {+ 'source': 'serverkit',+ 'timestamp': datetime.now().isoformat(),+ 'alerts': alerts+ }++ response = requests.post(+ webhook_config['url'],+ json=payload,+ timeout=10+ )++ if response.ok:+ return {'success': True, 'message': 'Webhook sent'}+ return {'success': False, 'error': f'Webhook returned {response.status_code}'}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def process_alerts(cls, alerts: List[Dict]) -> None:+ """Process and send alerts (with cooldown)."""+ if not alerts:+ return++ config = cls.get_config()+ now = datetime.now()++ # Filter alerts by cooldown+ alerts_to_send = []+ for alert in alerts:+ alert_key = f"{alert['type']}_{alert['severity']}"+ last_sent = cls._last_alerts.get(alert_key)++ if not last_sent or (now - last_sent).total_seconds() > cls.ALERT_COOLDOWN:+ alerts_to_send.append(alert)+ cls._last_alerts[alert_key] = now++ if not alerts_to_send:+ return++ # Log alerts+ cls.log_alert(alerts_to_send)++ # Send notifications+ if config.get('email', {}).get('enabled'):+ cls.send_email_alert(alerts_to_send)++ if config.get('webhook', {}).get('enabled'):+ cls.send_webhook_alert(alerts_to_send)++ @classmethod+ def log_alert(cls, alerts: List[Dict]) -> None:+ """Log alerts to file."""+ try:+ log_dir = os.path.dirname(cls.ALERTS_LOG)+ os.makedirs(log_dir, exist_ok=True)++ with open(cls.ALERTS_LOG, 'a') as f:+ for alert in alerts:+ entry = {+ 'timestamp': datetime.now().isoformat(),+ **alert+ }+ f.write(json.dumps(entry) + '\n')+ except Exception:+ pass++ @classmethod+ def get_alert_history(cls, limit: int = 100) -> List[Dict]:+ """Get recent alert history."""+ alerts = []++ if not os.path.exists(cls.ALERTS_LOG):+ return alerts++ try:+ with open(cls.ALERTS_LOG, 'r') as f:+ lines = f.readlines()++ for line in lines[-limit:]:+ try:+ alerts.append(json.loads(line.strip()))+ except json.JSONDecodeError:+ pass++ alerts.reverse() # Most recent first++ except Exception:+ pass++ return alerts++ @classmethod+ def clear_alert_history(cls) -> Dict:+ """Clear alert history."""+ try:+ if os.path.exists(cls.ALERTS_LOG):+ os.remove(cls.ALERTS_LOG)+ return {'success': True, 'message': 'Alert history cleared'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def start_monitoring(cls) -> Dict:+ """Start background monitoring."""+ if cls._monitoring_thread and cls._monitoring_thread.is_alive():+ return {'success': False, 'error': 'Monitoring already running'}++ config = cls.get_config()+ config['enabled'] = True+ cls.save_config(config)++ cls._stop_monitoring = False+ cls._monitoring_thread = threading.Thread(target=cls._monitor_loop, daemon=True)+ cls._monitoring_thread.start()++ return {'success': True, 'message': 'Monitoring started'}++ @classmethod+ def stop_monitoring(cls) -> Dict:+ """Stop background monitoring."""+ config = cls.get_config()+ config['enabled'] = False+ cls.save_config(config)++ cls._stop_monitoring = True++ return {'success': True, 'message': 'Monitoring stopped'}++ @classmethod+ def _monitor_loop(cls) -> None:+ """Background monitoring loop."""+ while not cls._stop_monitoring:+ config = cls.get_config()+ if not config.get('enabled'):+ break++ try:+ alerts = cls.check_thresholds()+ cls.process_alerts(alerts)+ except Exception:+ pass++ time.sleep(config.get('check_interval', 60))++ @classmethod+ def get_status(cls) -> Dict:+ """Get monitoring status."""+ config = cls.get_config()+ metrics = cls.get_current_metrics()+ alerts = cls.check_thresholds()++ return {+ 'enabled': config.get('enabled', False),+ 'thresholds': config.get('thresholds', cls.DEFAULT_THRESHOLDS),+ 'check_interval': config.get('check_interval', 60),+ 'email_enabled': config.get('email', {}).get('enabled', False),+ 'webhook_enabled': config.get('webhook', {}).get('enabled', False),+ 'current_metrics': metrics,+ 'active_alerts': alerts+ }diff --git a/backend/config.py b/backend/config.pyindex d06f3ec6..474ffe04 100644--- a/backend/config.py+++ b/backend/config.py@@ -1,6 +1,16 @@import os+import sysfrom datetime import timedelta+# Default insecure keys that must be changed in production+INSECURE_SECRET_KEYS = [+ 'dev-secret-key-change-in-production',+ 'jwt-secret-key-change-in-production',+ 'change-this-to-a-secure-random-string',+ 'change-this-to-another-secure-random-string',+]++class Config:SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')@@ -24,6 +34,18 @@ class DevelopmentConfig(Config):class ProductionConfig(Config):DEBUG = False+ def __init__(self):+ # Validate that secret keys are not default values in production+ if self.SECRET_KEY in INSECURE_SECRET_KEYS:+ print("FATAL: SECRET_KEY is set to a default insecure value in production mode!", file=sys.stderr)+ print("Generate a secure key with: python -c \"import secrets; print(secrets.token_hex(32))\"", file=sys.stderr)+ sys.exit(1)++ if self.JWT_SECRET_KEY in INSECURE_SECRET_KEYS:+ print("FATAL: JWT_SECRET_KEY is set to a default insecure value in production mode!", file=sys.stderr)+ print("Generate a secure key with: python -c \"import secrets; print(secrets.token_hex(32))\"", file=sys.stderr)+ sys.exit(1)+config = {'development': DevelopmentConfig,diff --git a/backend/requirements.txt b/backend/requirements.txtindex 9441be34..4c91700b 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -31,3 +31,6 @@ python-dotenv==1.0.0# YAML parsing (for Docker Compose)PyYAML==6.0.1++# Rate limiting+Flask-Limiter==3.5.0diff --git a/backend/run.py b/backend/run.pyindex 42bc84d5..df4e7246 100644--- a/backend/run.py+++ b/backend/run.py@@ -1,4 +1,5 @@import os+import sysfrom app import create_app, get_socketioapp = create_app()@@ -6,7 +7,15 @@ socketio = get_socketio()if __name__ == '__main__':port = int(os.environ.get('PORT', 5000))- debug = os.environ.get('FLASK_ENV', 'development') == 'development'+ env = os.environ.get('FLASK_ENV', 'development')+ debug = env == 'development'- # Use SocketIO to run the app (supports WebSocket)- socketio.run(app, host='0.0.0.0', port=port, debug=debug, allow_unsafe_werkzeug=True)+ # Prevent running development server in production+ if env == 'production':+ print("ERROR: Do not run the development server in production!", file=sys.stderr)+ print("Use a production WSGI server like gunicorn instead:", file=sys.stderr)+ print(" gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 run:app", file=sys.stderr)+ sys.exit(1)++ # Use SocketIO to run the app (supports WebSocket) - only in development+ socketio.run(app, host='0.0.0.0', port=port, debug=debug)diff --git a/deploy/serverkit.service b/deploy/serverkit.servicenew file mode 100644index 00000000..10956eb8--- /dev/null+++ b/deploy/serverkit.service@@ -0,0 +1,23 @@+[Unit]+Description=ServerKit Web Server Management Dashboard+Documentation=https://github.com/yourusername/serverkit+After=network.target docker.service+Requires=docker.service++[Service]+Type=oneshot+RemainAfterExit=yes+WorkingDirectory=/opt/serverkit+ExecStart=/usr/bin/docker compose -f docker-compose.prod.yml up -d+ExecStop=/usr/bin/docker compose -f docker-compose.prod.yml down+ExecReload=/usr/bin/docker compose -f docker-compose.prod.yml restart+TimeoutStartSec=300++# Security hardening+NoNewPrivileges=true+ProtectSystem=strict+ProtectHome=read-only+ReadWritePaths=/opt/serverkit++[Install]+WantedBy=multi-user.targetdiff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlnew file mode 100644index 00000000..2c6b6fac--- /dev/null+++ b/docker-compose.prod.yml@@ -0,0 +1,74 @@+# Docker Compose - Production Configuration+version: '3.8'++services:+ backend:+ build:+ context: ./backend+ dockerfile: Dockerfile+ container_name: serverkit-backend+ environment:+ - FLASK_ENV=production+ - DATABASE_URL=${DATABASE_URL:-sqlite:///serverkit.db}+ - SECRET_KEY=${SECRET_KEY}+ - JWT_SECRET_KEY=${JWT_SECRET_KEY}+ - CORS_ORIGINS=${CORS_ORIGINS:-https://yourdomain.com}+ volumes:+ - backend-data:/app/instance+ - /var/log:/var/log:ro+ - /home:/home:ro+ - /opt:/opt:ro+ networks:+ - serverkit-network+ restart: always+ logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "3"++ frontend:+ build:+ context: ./frontend+ dockerfile: Dockerfile+ container_name: serverkit-frontend+ depends_on:+ - backend+ networks:+ - serverkit-network+ restart: always+ logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "3"++ nginx:+ image: nginx:alpine+ container_name: serverkit-nginx+ depends_on:+ - frontend+ - backend+ ports:+ - "80:80"+ - "443:443"+ volumes:+ - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro+ - ./nginx/ssl:/etc/nginx/ssl:ro+ - nginx-cache:/var/cache/nginx+ networks:+ - serverkit-network+ restart: always+ logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "3"++networks:+ serverkit-network:+ driver: bridge++volumes:+ backend-data:+ nginx-cache:diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..a0080156--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,43 @@+# Docker Compose - Development Configuration+version: '3.8'++services:+ backend:+ build:+ context: ./backend+ dockerfile: Dockerfile+ container_name: serverkit-backend+ environment:+ - FLASK_ENV=development+ - DATABASE_URL=sqlite:///serverkit.db+ - SECRET_KEY=${SECRET_KEY:-dev-secret-key-change-in-production}+ - JWT_SECRET_KEY=${JWT_SECRET_KEY:-jwt-secret-key-change-in-production}+ - CORS_ORIGINS=http://localhost:5173,http://localhost:3000+ volumes:+ - ./backend:/app+ - backend-data:/app/instance+ ports:+ - "5000:5000"+ networks:+ - serverkit-network+ restart: unless-stopped++ frontend:+ build:+ context: ./frontend+ dockerfile: Dockerfile+ container_name: serverkit-frontend+ depends_on:+ - backend+ ports:+ - "80:80"+ networks:+ - serverkit-network+ restart: unless-stopped++networks:+ serverkit-network:+ driver: bridge++volumes:+ backend-data:diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.mdnew file mode 100644index 00000000..7197c308--- /dev/null+++ b/docs/DEPLOYMENT.md@@ -0,0 +1,233 @@+# ServerKit Deployment Guide++This guide covers deploying ServerKit in production using Docker.++## Prerequisites++- Docker 20.10+ and Docker Compose 2.0++- A server with at least 1GB RAM+- A domain name (for SSL/HTTPS)+- SSL certificate (Let's Encrypt recommended)++## Quick Start (Development)++```bash+# Clone the repository+git clone https://github.com/yourusername/serverkit.git+cd serverkit++# Start with Docker Compose+docker compose up -d++# Access at http://localhost+```++## Production Deployment++### 1. Generate Secure Keys++```bash+# Generate SECRET_KEY+python -c "import secrets; print(secrets.token_hex(32))"++# Generate JWT_SECRET_KEY+python -c "import secrets; print(secrets.token_hex(32))"+```++### 2. Create Environment File++Create `.env` in the project root:++```bash+# Required - generate unique keys!+SECRET_KEY=your-generated-secret-key+JWT_SECRET_KEY=your-generated-jwt-secret-key++# Database (SQLite by default, or use PostgreSQL)+DATABASE_URL=sqlite:///serverkit.db+# DATABASE_URL=postgresql://user:pass@host:5432/serverkit++# CORS origins (your domain)+CORS_ORIGINS=https://yourdomain.com+```++### 3. SSL Certificate Setup++#### Using Let's Encrypt (Recommended)++```bash+# Create directories+mkdir -p nginx/ssl++# Install certbot and get certificate+sudo certbot certonly --standalone -d yourdomain.com++# Copy certificates+sudo cp /etc/letsencrypt/live/yourdomain.com/fullchain.pem nginx/ssl/+sudo cp /etc/letsencrypt/live/yourdomain.com/privkey.pem nginx/ssl/+```++#### Using Self-Signed (Testing Only)++```bash+mkdir -p nginx/ssl+openssl req -x509 -nodes -days 365 -newkey rsa:2048 \+ -keyout nginx/ssl/privkey.pem \+ -out nginx/ssl/fullchain.pem \+ -subj "/CN=localhost"+```++### 4. Deploy++```bash+# Build and start production containers+docker compose -f docker-compose.prod.yml up -d --build++# Check status+docker compose -f docker-compose.prod.yml ps++# View logs+docker compose -f docker-compose.prod.yml logs -f+```++### 5. Initial Setup++1. Navigate to `https://yourdomain.com`+2. Register the first admin user+3. Configure server monitoring settings++## Systemd Service (Optional)++Install as a system service for automatic startup:++```bash+# Copy the service file+sudo cp deploy/serverkit.service /etc/systemd/system/++# Copy project to /opt+sudo mkdir -p /opt/serverkit+sudo cp -r . /opt/serverkit/++# Enable and start+sudo systemctl daemon-reload+sudo systemctl enable serverkit+sudo systemctl start serverkit++# Check status+sudo systemctl status serverkit+```++## Maintenance++### Updating++```bash+cd /opt/serverkit+git pull+docker compose -f docker-compose.prod.yml up -d --build+```++### Backup Database++```bash+# SQLite+docker compose -f docker-compose.prod.yml exec backend \+ cp /app/instance/serverkit.db /app/instance/serverkit.db.backup++# Copy to host+docker cp serverkit-backend:/app/instance/serverkit.db.backup ./backup/+```++### View Logs++```bash+# All services+docker compose -f docker-compose.prod.yml logs -f++# Specific service+docker compose -f docker-compose.prod.yml logs -f backend+docker compose -f docker-compose.prod.yml logs -f nginx+```++### Restart Services++```bash+docker compose -f docker-compose.prod.yml restart+# or+sudo systemctl restart serverkit+```++## Security Checklist++- [ ] Generated unique SECRET_KEY and JWT_SECRET_KEY+- [ ] SSL/TLS certificate configured+- [ ] Firewall configured (ports 80, 443 only)+- [ ] Regular backups configured+- [ ] Monitoring/alerting set up+- [ ] Rate limiting verified working+- [ ] Security headers present (check with browser dev tools)++## Troubleshooting++### Container won't start++```bash+# Check logs+docker compose -f docker-compose.prod.yml logs backend++# Check if port is in use+sudo lsof -i :5000+sudo lsof -i :80+```++### 502 Bad Gateway++Usually means the backend isn't running:++```bash+docker compose -f docker-compose.prod.yml ps+docker compose -f docker-compose.prod.yml restart backend+```++### WebSocket connection failed++Ensure nginx is properly proxying WebSocket connections. Check the `/socket.io` location block in nginx.conf.++### SSL Certificate Issues++```bash+# Test certificate+openssl s_client -connect yourdomain.com:443 -servername yourdomain.com++# Check certificate expiry+openssl x509 -in nginx/ssl/fullchain.pem -noout -dates+```++## Architecture++```+ ┌─────────────┐+ │ Client │+ └──────┬──────┘+ │+ ┌──────▼──────┐+ │ Nginx │+ │ (SSL/TLS) │+ └──────┬──────┘+ │+ ┌───────────────┼───────────────┐+ │ │ │+ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐+ │ Frontend │ │ Backend │ │ Socket.IO │+ │ (React) │ │ (Flask) │ │ (WebSocket) │+ └─────────────┘ └──────┬──────┘ └─────────────┘+ │+ ┌──────▼──────┐+ │ SQLite/ │+ │ PostgreSQL │+ └─────────────┘+```++## Support++For issues and questions, please open an issue on GitHub.diff --git a/frontend/Dockerfile b/frontend/Dockerfilenew file mode 100644index 00000000..4884a47e--- /dev/null+++ b/frontend/Dockerfile@@ -0,0 +1,42 @@+# Frontend Dockerfile for ServerKit+# Stage 1: Build+FROM node:20-alpine AS builder++WORKDIR /app++# Copy package files+COPY package*.json ./++# Install dependencies+RUN npm ci++# Copy source code+COPY . .++# Build the application+RUN npm run build++# Stage 2: Production+FROM nginx:alpine++# Copy custom nginx config+COPY nginx.conf /etc/nginx/conf.d/default.conf++# Copy built assets from builder stage+COPY --from=builder /app/dist /usr/share/nginx/html++# Create non-root user for nginx+RUN chown -R nginx:nginx /usr/share/nginx/html && \+ chown -R nginx:nginx /var/cache/nginx && \+ chown -R nginx:nginx /var/log/nginx && \+ chown -R nginx:nginx /etc/nginx/conf.d++# Expose port+EXPOSE 80++# Health check+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1++# Start nginx+CMD ["nginx", "-g", "daemon off;"]diff --git a/frontend/nginx.conf b/frontend/nginx.confnew file mode 100644index 00000000..664191a8--- /dev/null+++ b/frontend/nginx.conf@@ -0,0 +1,62 @@+server {+ listen 80;+ server_name localhost;+ root /usr/share/nginx/html;+ index index.html;++ # Gzip compression+ gzip on;+ gzip_vary on;+ gzip_min_length 1024;+ gzip_proxied any;+ gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml;++ # Security headers+ add_header X-Frame-Options "DENY" 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;++ # SPA routing - serve index.html for all routes+ location / {+ try_files $uri $uri/ /index.html;+ }++ # Proxy API requests to backend+ location /api {+ proxy_pass http://backend:5000;+ proxy_http_version 1.1;+ 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;++ # Timeout settings+ proxy_connect_timeout 60s;+ proxy_send_timeout 60s;+ proxy_read_timeout 60s;+ }++ # WebSocket support for socket.io+ location /socket.io {+ proxy_pass http://backend: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;++ # WebSocket specific timeouts+ proxy_connect_timeout 7d;+ proxy_send_timeout 7d;+ proxy_read_timeout 7d;+ }++ # Cache static assets+ location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {+ expires 1y;+ add_header Cache-Control "public, immutable";+ }+}diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex c9f30fe9..5153433b 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,6 +1,8 @@import React from 'react';import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';import { AuthProvider, useAuth } from './contexts/AuthContext';+import { ToastProvider } from './contexts/ToastContext';+import { ToastContainer } from './components/Toast';import DashboardLayout from './layouts/DashboardLayout';import Dashboard from './pages/Dashboard';import Login from './pages/Login';@@ -9,6 +11,11 @@ import Applications from './pages/Applications';import ApplicationDetail from './pages/ApplicationDetail';import Docker from './pages/Docker';import Databases from './pages/Databases';+import Domains from './pages/Domains';+import Monitoring from './pages/Monitoring';+import Backups from './pages/Backups';+import Terminal from './pages/Terminal';+import Settings from './pages/Settings';function PrivateRoute({ children }) {const { isAuthenticated, loading } = useAuth();@@ -51,12 +58,14 @@ function AppRoutes() {<Route index element={<Dashboard />} /><Route path="apps" element={<Applications />} /><Route path="apps/:id" element={<ApplicationDetail />} />- <Route path="domains" element={<div className="page">Domains & Sites</div>} />+ <Route path="domains" element={<Domains />} /><Route path="databases" element={<Databases />} /><Route path="ssl" element={<div className="page">SSL Certificates</div>} /><Route path="docker" element={<Docker />} />- <Route path="terminal" element={<div className="page">Terminal / Logs</div>} />- <Route path="settings" element={<div className="page">Settings</div>} />+ <Route path="monitoring" element={<Monitoring />} />+ <Route path="backups" element={<Backups />} />+ <Route path="terminal" element={<Terminal />} />+ <Route path="settings" element={<Settings />} /></Route></Routes>);@@ -66,7 +75,10 @@ function App() {return (<Router><AuthProvider>- <AppRoutes />+ <ToastProvider>+ <AppRoutes />+ <ToastContainer />+ </ToastProvider></AuthProvider></Router>);diff --git a/frontend/src/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsxnew file mode 100644index 00000000..1fcb123c--- /dev/null+++ b/frontend/src/components/ConfirmDialog.jsx@@ -0,0 +1,53 @@+import React from 'react';+import { AlertTriangle, Info, AlertCircle } from 'lucide-react';++const iconMap = {+ danger: AlertTriangle,+ warning: AlertCircle,+ info: Info+};++export function ConfirmDialog({+ isOpen,+ title,+ message,+ confirmText = 'Confirm',+ cancelText = 'Cancel',+ variant = 'danger',+ onConfirm,+ onCancel+}) {+ if (!isOpen) return null;++ const Icon = iconMap[variant] || AlertTriangle;++ return (+ <div className="modal-overlay" onClick={onCancel}>+ <div className="modal confirm-dialog" onClick={e => e.stopPropagation()}>+ <div className="confirm-dialog-content">+ <div className={`confirm-dialog-icon confirm-dialog-icon-${variant}`}>+ <Icon size={32} />+ </div>+ <h2 className="confirm-dialog-title">{title}</h2>+ <p className="confirm-dialog-message">{message}</p>+ </div>+ <div className="confirm-dialog-actions">+ <button+ className="btn btn-secondary"+ onClick={onCancel}+ >+ {cancelText}+ </button>+ <button+ className={`btn btn-${variant === 'danger' ? 'danger' : 'primary'}`}+ onClick={onConfirm}+ >+ {confirmText}+ </button>+ </div>+ </div>+ </div>+ );+}++export default ConfirmDialog;diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex 2990f326..3b76a009 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -74,6 +74,24 @@ const Sidebar = () => {</NavLink></nav>+ <div className="menu-label">Operations</div>+ <nav className="nav">+ <NavLink to="/monitoring" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>+ <svg viewBox="0 0 24 24">+ <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>+ </svg>+ Monitoring+ </NavLink>+ <NavLink to="/backups" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>+ <svg viewBox="0 0 24 24">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="7 10 12 15 17 10"/>+ <line x1="12" y1="15" x2="12" y2="3"/>+ </svg>+ Backups+ </NavLink>+ </nav>+<div className="menu-label">System</div><nav className="nav"><NavLink to="/terminal" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>diff --git a/frontend/src/components/Spinner.jsx b/frontend/src/components/Spinner.jsxnew file mode 100644index 00000000..d5be3fe9--- /dev/null+++ b/frontend/src/components/Spinner.jsx@@ -0,0 +1,26 @@+import React from 'react';++export function Spinner({ size = 'md', className = '' }) {+ const sizeClasses = {+ sm: 'spinner-sm',+ md: 'spinner-md',+ lg: 'spinner-lg'+ };++ return (+ <div className={`spinner ${sizeClasses[size] || 'spinner-md'} ${className}`}>+ <div className="spinner-ring"></div>+ </div>+ );+}++export function LoadingState({ text = 'Loading...' }) {+ return (+ <div className="loading-state">+ <Spinner size="lg" />+ <span>{text}</span>+ </div>+ );+}++export default Spinner;diff --git a/frontend/src/components/Toast.jsx b/frontend/src/components/Toast.jsxnew file mode 100644index 00000000..011d864a--- /dev/null+++ b/frontend/src/components/Toast.jsx@@ -0,0 +1,42 @@+import React from 'react';+import { CheckCircle, XCircle, AlertTriangle, Info, X } from 'lucide-react';+import { useToast } from '../contexts/ToastContext';++const iconMap = {+ success: CheckCircle,+ error: XCircle,+ warning: AlertTriangle,+ info: Info+};++function ToastItem({ toast, onDismiss }) {+ const Icon = iconMap[toast.type] || Info;++ return (+ <div className={`toast toast-${toast.type}`}>+ <div className="toast-icon">+ <Icon size={18} />+ </div>+ <div className="toast-message">{toast.message}</div>+ <button className="toast-dismiss" onClick={() => onDismiss(toast.id)}>+ <X size={14} />+ </button>+ </div>+ );+}++export function ToastContainer() {+ const { toasts, removeToast } = useToast();++ if (toasts.length === 0) return null;++ return (+ <div className="toast-container">+ {toasts.map((toast) => (+ <ToastItem key={toast.id} toast={toast} onDismiss={removeToast} />+ ))}+ </div>+ );+}++export default ToastContainer;diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsxindex c8175c08..38726a08 100644--- a/frontend/src/contexts/AuthContext.jsx+++ b/frontend/src/contexts/AuthContext.jsx@@ -42,12 +42,26 @@ export function AuthProvider({ children }) {setUser(null);}+ async function updateUser(data) {+ const response = await api.updateCurrentUser(data);+ setUser(response.user);+ return response;+ }++ async function refreshUser() {+ const data = await api.getCurrentUser();+ setUser(data.user);+ return data.user;+ }+const value = {user,loading,login,register,logout,+ updateUser,+ refreshUser,isAuthenticated: !!user,isAdmin: user?.role === 'admin',};diff --git a/frontend/src/contexts/ToastContext.jsx b/frontend/src/contexts/ToastContext.jsxnew file mode 100644index 00000000..ed4ab819--- /dev/null+++ b/frontend/src/contexts/ToastContext.jsx@@ -0,0 +1,67 @@+import React, { createContext, useContext, useState, useCallback } from 'react';++const ToastContext = createContext(null);++export function useToast() {+ const context = useContext(ToastContext);+ if (!context) {+ throw new Error('useToast must be used within a ToastProvider');+ }+ return context;+}++let toastId = 0;++export function ToastProvider({ children }) {+ const [toasts, setToasts] = useState([]);++ const removeToast = useCallback((id) => {+ setToasts((prev) => prev.filter((toast) => toast.id !== id));+ }, []);++ const addToast = useCallback((message, type = 'info', duration = 5000) => {+ const id = ++toastId;+ const toast = { id, message, type };+ setToasts((prev) => [...prev, toast]);++ if (duration > 0) {+ setTimeout(() => removeToast(id), duration);+ }++ return id;+ }, [removeToast]);++ const success = useCallback((message, duration) => {+ return addToast(message, 'success', duration);+ }, [addToast]);++ const error = useCallback((message, duration) => {+ return addToast(message, 'error', duration);+ }, [addToast]);++ const warning = useCallback((message, duration) => {+ return addToast(message, 'warning', duration);+ }, [addToast]);++ const info = useCallback((message, duration) => {+ return addToast(message, 'info', duration);+ }, [addToast]);++ const value = {+ toasts,+ addToast,+ removeToast,+ success,+ error,+ warning,+ info+ };++ return (+ <ToastContext.Provider value={value}>+ {children}+ </ToastContext.Provider>+ );+}++export default ToastContext;diff --git a/frontend/src/hooks/useConfirm.js b/frontend/src/hooks/useConfirm.jsnew file mode 100644index 00000000..d57dcc65--- /dev/null+++ b/frontend/src/hooks/useConfirm.js@@ -0,0 +1,56 @@+import { useState, useCallback } from 'react';++export function useConfirm() {+ const [confirmState, setConfirmState] = useState({+ isOpen: false,+ title: '',+ message: '',+ confirmText: 'Confirm',+ cancelText: 'Cancel',+ variant: 'danger',+ resolve: null+ });++ const confirm = useCallback(({+ title = 'Confirm Action',+ message = 'Are you sure you want to proceed?',+ confirmText = 'Confirm',+ cancelText = 'Cancel',+ variant = 'danger'+ } = {}) => {+ return new Promise((resolve) => {+ setConfirmState({+ isOpen: true,+ title,+ message,+ confirmText,+ cancelText,+ variant,+ resolve+ });+ });+ }, []);++ const handleConfirm = useCallback(() => {+ if (confirmState.resolve) {+ confirmState.resolve(true);+ }+ setConfirmState(prev => ({ ...prev, isOpen: false }));+ }, [confirmState.resolve]);++ const handleCancel = useCallback(() => {+ if (confirmState.resolve) {+ confirmState.resolve(false);+ }+ setConfirmState(prev => ({ ...prev, isOpen: false }));+ }, [confirmState.resolve]);++ return {+ confirm,+ confirmState,+ handleConfirm,+ handleCancel+ };+}++export default useConfirm;diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex 07e18dca..bf058152 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -1,6 +1,7 @@import React, { useState, useEffect } from 'react';import { useParams, useNavigate } from 'react-router-dom';import api from '../services/api';+import { useToast } from '../contexts/ToastContext';const ApplicationDetail = () => {const { id } = useParams();@@ -183,6 +184,12 @@ const ApplicationDetail = () => {</button></>)}+ <button+ className={`tab ${activeTab === 'deploy' ? 'active' : ''}`}+ onClick={() => setActiveTab('deploy')}+ >+ Deploy+ </button><buttonclassName={`tab ${activeTab === 'logs' ? 'active' : ''}`}onClick={() => setActiveTab('logs')}@@ -206,6 +213,7 @@ const ApplicationDetail = () => {{activeTab === 'plugins' && isWordPressApp && <PluginsTab appId={app.id} />}{activeTab === 'themes' && isWordPressApp && <ThemesTab appId={app.id} />}{activeTab === 'backups' && isWordPressApp && <BackupsTab appId={app.id} />}+ {activeTab === 'deploy' && <DeployTab appId={app.id} appPath={app.path} />}{activeTab === 'logs' && <LogsTab app={app} />}{activeTab === 'settings' && <SettingsTab app={app} onUpdate={loadApp} />}</div>@@ -319,6 +327,7 @@ const OverviewTab = ({ app }) => {};const PackagesTab = ({ appId }) => {+ const toast = useToast();const [packages, setPackages] = useState([]);const [loading, setLoading] = useState(true);const [installing, setInstalling] = useState(false);@@ -358,8 +367,9 @@ const PackagesTab = ({ appId }) => {async function handleFreeze() {try {await api.freezePythonRequirements(appId);- alert('requirements.txt updated');+ toast.success('requirements.txt updated');} catch (err) {+ toast.error('Failed to freeze requirements');console.error('Failed to freeze requirements:', err);}}@@ -491,6 +501,7 @@ const EnvironmentTab = ({ appId }) => {};const GunicornTab = ({ appId }) => {+ const toast = useToast();const [config, setConfig] = useState('');const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);@@ -514,8 +525,9 @@ const GunicornTab = ({ appId }) => {setSaving(true);try {await api.updateGunicornConfig(appId, config);- alert('Configuration saved. Restart the app to apply changes.');+ toast.success('Configuration saved. Restart the app to apply changes.');} catch (err) {+ toast.error('Failed to save configuration');console.error('Failed to save config:', err);} finally {setSaving(false);@@ -763,6 +775,7 @@ const ThemesTab = ({ appId }) => {};const BackupsTab = ({ appId }) => {+ const toast = useToast();const [backups, setBackups] = useState([]);const [loading, setLoading] = useState(true);const [creating, setCreating] = useState(false);@@ -799,8 +812,9 @@ const BackupsTab = ({ appId }) => {try {await api.restoreWordPressBackup(appId, backupName);- alert('Backup restored successfully');+ toast.success('Backup restored successfully');} catch (err) {+ toast.error('Failed to restore backup');console.error('Failed to restore backup:', err);}}@@ -922,6 +936,446 @@ const SettingsTab = ({ app, onUpdate }) => {);};+const DeployTab = ({ appId, appPath }) => {+ const toast = useToast();+ const [config, setConfig] = useState(null);+ const [gitStatus, setGitStatus] = useState(null);+ const [history, setHistory] = useState([]);+ const [loading, setLoading] = useState(true);+ const [deploying, setDeploying] = useState(false);+ const [showConfigModal, setShowConfigModal] = useState(false);+ const [error, setError] = useState(null);++ // Config form state+ const [configForm, setConfigForm] = useState({+ repoUrl: '',+ branch: 'main',+ autoDeploy: true,+ preDeployScript: '',+ postDeployScript: ''+ });++ useEffect(() => {+ loadData();+ }, [appId]);++ async function loadData() {+ try {+ setLoading(true);+ const [configRes, historyRes] = await Promise.all([+ api.getDeployConfig(appId),+ api.getDeploymentHistory(appId, 20)+ ]);++ if (configRes.configured) {+ setConfig(configRes.config);+ setConfigForm({+ repoUrl: configRes.config.repo_url || '',+ branch: configRes.config.branch || 'main',+ autoDeploy: configRes.config.auto_deploy !== false,+ preDeployScript: configRes.config.pre_deploy_script || '',+ postDeployScript: configRes.config.post_deploy_script || ''+ });+ // Load git status if configured+ try {+ const statusRes = await api.getGitStatus(appId);+ setGitStatus(statusRes);+ } catch (e) {+ // Git status may fail if not a git repo yet+ }+ } else {+ setConfig(null);+ }++ setHistory(historyRes.deployments || []);+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ async function handleConfigureDeployment(e) {+ e.preventDefault();+ try {+ await api.configureDeployment(+ appId,+ configForm.repoUrl,+ configForm.branch,+ configForm.autoDeploy,+ configForm.preDeployScript || null,+ configForm.postDeployScript || null+ );+ setShowConfigModal(false);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleRemoveDeployment() {+ if (!confirm('Remove deployment configuration? This will not delete the repository files.')) return;+ try {+ await api.removeDeployment(appId);+ setConfig(null);+ setGitStatus(null);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleDeploy(force = false) {+ setDeploying(true);+ setError(null);+ try {+ const result = await api.triggerDeploy(appId, force);+ if (result.success) {+ toast.success('Deployment completed successfully!');+ } else {+ setError(result.error || 'Deployment failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ async function handlePull() {+ setDeploying(true);+ setError(null);+ try {+ const result = await api.pullChanges(appId);+ if (result.success) {+ toast.success('Changes pulled successfully!');+ } else {+ setError(result.error || 'Pull failed');+ }+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setDeploying(false);+ }+ }++ function formatTimestamp(timestamp) {+ return new Date(timestamp).toLocaleString();+ }++ function getStatusBadgeClass(status) {+ switch (status) {+ case 'success': return 'badge-success';+ case 'failed': return 'badge-danger';+ case 'in_progress': return 'badge-warning';+ default: return 'badge-secondary';+ }+ }++ if (loading) {+ return <div className="loading">Loading deployment configuration...</div>;+ }++ return (+ <div className="deploy-tab">+ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ {!config ? (+ <div className="deploy-setup">+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="4"/>+ <line x1="1.05" y1="12" x2="7" y2="12"/>+ <line x1="17.01" y1="12" x2="22.96" y2="12"/>+ </svg>+ <h3>Git Deployment Not Configured</h3>+ <p>Connect a Git repository to enable automatic deployments via webhooks or manual triggers.</p>+ <button className="btn btn-primary" onClick={() => setShowConfigModal(true)}>+ Configure Deployment+ </button>+ </div>+ </div>+ ) : (+ <>+ <div className="deploy-header">+ <div className="deploy-status-card">+ <div className="deploy-repo-info">+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>+ </svg>+ <div>+ <span className="repo-url">{config.repo_url}</span>+ <span className="repo-branch">Branch: {config.branch}</span>+ </div>+ </div>+ <div className="deploy-actions">+ <button+ className="btn btn-secondary btn-sm"+ onClick={handlePull}+ disabled={deploying}+ >+ Pull Only+ </button>+ <button+ className="btn btn-primary"+ onClick={() => handleDeploy(false)}+ disabled={deploying}+ >+ {deploying ? 'Deploying...' : 'Deploy Now'}+ </button>+ </div>+ </div>+ </div>++ <div className="deploy-grid">+ <div className="card">+ <h3>Configuration</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Repository</span>+ <span className="info-value mono">{config.repo_url}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Branch</span>+ <span className="info-value">{config.branch}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Auto Deploy</span>+ <span className="info-value">{config.auto_deploy ? 'Enabled' : 'Disabled'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Deploy Count</span>+ <span className="info-value">{config.deploy_count || 0}</span>+ </div>+ {config.last_deploy && (+ <div className="info-item">+ <span className="info-label">Last Deploy</span>+ <span className="info-value">{formatTimestamp(config.last_deploy)}</span>+ </div>+ )}+ </div>+ <div className="card-actions">+ <button className="btn btn-secondary btn-sm" onClick={() => setShowConfigModal(true)}>+ Edit Configuration+ </button>+ <button className="btn btn-danger btn-sm" onClick={handleRemoveDeployment}>+ Remove+ </button>+ </div>+ </div>++ {gitStatus && !gitStatus.error && (+ <div className="card">+ <h3>Git Status</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Current Branch</span>+ <span className="info-value">{gitStatus.branch}</span>+ </div>+ {gitStatus.commit && (+ <>+ <div className="info-item">+ <span className="info-label">Commit</span>+ <span className="info-value mono">{gitStatus.commit.short_hash}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Message</span>+ <span className="info-value">{gitStatus.commit.message}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Author</span>+ <span className="info-value">{gitStatus.commit.author}</span>+ </div>+ </>+ )}+ <div className="info-item">+ <span className="info-label">Uncommitted Changes</span>+ <span className="info-value">+ {gitStatus.has_uncommitted ? `${gitStatus.changes} file(s)` : 'None'}+ </span>+ </div>+ {(gitStatus.ahead > 0 || gitStatus.behind > 0) && (+ <div className="info-item">+ <span className="info-label">Remote Status</span>+ <span className="info-value">+ {gitStatus.ahead > 0 && `${gitStatus.ahead} ahead`}+ {gitStatus.ahead > 0 && gitStatus.behind > 0 && ', '}+ {gitStatus.behind > 0 && `${gitStatus.behind} behind`}+ </span>+ </div>+ )}+ </div>+ </div>+ )}++ <div className="card">+ <h3>Webhook</h3>+ <p className="hint">Use this URL in your Git provider to trigger automatic deployments on push.</p>+ <div className="webhook-url">+ <code>{window.location.origin}/api/v1/deploy/webhook/{appId}/{config.webhook_token}</code>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => {+ navigator.clipboard.writeText(+ `${window.location.origin}/api/v1/deploy/webhook/${appId}/${config.webhook_token}`+ );+ toast.success('Webhook URL copied to clipboard');+ }}+ >+ Copy+ </button>+ </div>+ </div>+ </div>++ {(config.pre_deploy_script || config.post_deploy_script) && (+ <div className="card">+ <h3>Deploy Scripts</h3>+ <div className="scripts-grid">+ {config.pre_deploy_script && (+ <div className="script-section">+ <h4>Pre-Deploy Script</h4>+ <pre className="script-code">{config.pre_deploy_script}</pre>+ </div>+ )}+ {config.post_deploy_script && (+ <div className="script-section">+ <h4>Post-Deploy Script</h4>+ <pre className="script-code">{config.post_deploy_script}</pre>+ </div>+ )}+ </div>+ </div>+ )}++ <div className="card">+ <h3>Deployment History</h3>+ {history.length === 0 ? (+ <p className="hint">No deployments yet.</p>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Status</th>+ <th>Started</th>+ <th>Completed</th>+ <th>Details</th>+ </tr>+ </thead>+ <tbody>+ {history.map((deploy, index) => (+ <tr key={index}>+ <td>+ <span className={`badge ${getStatusBadgeClass(deploy.status)}`}>+ {deploy.status}+ </span>+ </td>+ <td>{formatTimestamp(deploy.started_at)}</td>+ <td>{deploy.completed_at ? formatTimestamp(deploy.completed_at) : '-'}</td>+ <td>+ {deploy.error && <span className="text-danger">{deploy.error}</span>}+ {deploy.steps && (+ <span className="text-muted">+ {deploy.steps.length} step(s)+ </span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </>+ )}++ {/* Configure Deployment Modal */}+ {showConfigModal && (+ <div className="modal-overlay" onClick={() => setShowConfigModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>{config ? 'Edit Deployment' : 'Configure Deployment'}</h2>+ <button className="modal-close" onClick={() => setShowConfigModal(false)}>×</button>+ </div>+ <form onSubmit={handleConfigureDeployment}>+ <div className="modal-body">+ <div className="form-group">+ <label>Repository URL *</label>+ <input+ type="url"+ value={configForm.repoUrl}+ onChange={(e) => setConfigForm({...configForm, repoUrl: e.target.value})}+ placeholder="https://github.com/user/repo.git"+ required+ />+ </div>++ <div className="form-group">+ <label>Branch</label>+ <input+ type="text"+ value={configForm.branch}+ onChange={(e) => setConfigForm({...configForm, branch: e.target.value})}+ placeholder="main"+ />+ </div>++ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={configForm.autoDeploy}+ onChange={(e) => setConfigForm({...configForm, autoDeploy: e.target.checked})}+ />+ <span>Enable Auto Deploy on Webhook</span>+ </label>+ </div>++ <div className="form-group">+ <label>Pre-Deploy Script (optional)</label>+ <textarea+ value={configForm.preDeployScript}+ onChange={(e) => setConfigForm({...configForm, preDeployScript: e.target.value})}+ placeholder="npm install npm run build"+ rows={3}+ />+ <span className="form-help">Commands to run before pulling changes</span>+ </div>++ <div className="form-group">+ <label>Post-Deploy Script (optional)</label>+ <textarea+ value={configForm.postDeployScript}+ onChange={(e) => setConfigForm({...configForm, postDeployScript: e.target.value})}+ placeholder="npm install npm run build systemctl restart myapp"+ rows={3}+ />+ <span className="form-help">Commands to run after pulling changes</span>+ </div>+ </div>+ <div className="modal-footer">+ <button type="button" className="btn btn-secondary" onClick={() => setShowConfigModal(false)}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary">+ {config ? 'Update Configuration' : 'Configure Deployment'}+ </button>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>+ );+};+function formatBytes(bytes) {if (bytes === 0) return '0 Bytes';const k = 1024;diff --git a/frontend/src/pages/Backups.jsx b/frontend/src/pages/Backups.jsxnew file mode 100644index 00000000..b8457433--- /dev/null+++ b/frontend/src/pages/Backups.jsx@@ -0,0 +1,802 @@+import React, { useState, useEffect } from 'react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const Backups = () => {+ const toast = useToast();+ const [backups, setBackups] = useState([]);+ const [stats, setStats] = useState(null);+ const [schedules, setSchedules] = useState([]);+ const [config, setConfig] = useState(null);+ const [apps, setApps] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [activeTab, setActiveTab] = useState('backups');+ const [filterType, setFilterType] = useState('all');++ // Modal states+ const [showBackupModal, setShowBackupModal] = useState(false);+ const [showScheduleModal, setShowScheduleModal] = useState(false);+ const [showRestoreModal, setShowRestoreModal] = useState(false);+ const [selectedBackup, setSelectedBackup] = useState(null);++ // Backup form state+ const [backupForm, setBackupForm] = useState({+ type: 'application',+ applicationId: '',+ includeDb: false,+ dbType: 'mysql',+ dbName: '',+ dbUser: '',+ dbPassword: '',+ dbHost: 'localhost'+ });++ // Schedule form state+ const [scheduleForm, setScheduleForm] = useState({+ name: '',+ backupType: 'application',+ target: '',+ scheduleTime: '02:00',+ days: ['daily']+ });++ // Config form state+ const [configForm, setConfigForm] = useState({+ enabled: false,+ retention_days: 30+ });++ useEffect(() => {+ loadData();+ }, []);++ const loadData = async () => {+ try {+ setLoading(true);+ const [backupsRes, statsRes, schedulesRes, configRes, appsRes] = await Promise.all([+ api.getBackups(),+ api.getBackupStats(),+ api.getBackupSchedules(),+ api.getBackupConfig(),+ api.getApps()+ ]);++ setBackups(backupsRes.backups || []);+ setStats(statsRes);+ setSchedules(schedulesRes.schedules || []);+ setConfig(configRes);+ setApps(appsRes.applications || []);++ if (configRes) {+ setConfigForm({+ enabled: configRes.enabled || false,+ retention_days: configRes.retention_days || 30+ });+ }+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ };++ const handleCreateBackup = async (e) => {+ e.preventDefault();+ try {+ if (backupForm.type === 'application') {+ const dbConfig = backupForm.includeDb ? {+ type: backupForm.dbType,+ name: backupForm.dbName,+ user: backupForm.dbUser,+ password: backupForm.dbPassword,+ host: backupForm.dbHost+ } : null;+ await api.backupApplication(parseInt(backupForm.applicationId), backupForm.includeDb, dbConfig);+ } else {+ await api.backupDatabase(+ backupForm.dbType,+ backupForm.dbName,+ backupForm.dbUser,+ backupForm.dbPassword,+ backupForm.dbHost+ );+ }+ setShowBackupModal(false);+ resetBackupForm();+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleDeleteBackup = async (backupPath) => {+ if (!window.confirm('Are you sure you want to delete this backup?')) return;+ try {+ await api.deleteBackup(backupPath);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleRestore = async () => {+ if (!selectedBackup) return;+ if (!window.confirm('Are you sure you want to restore this backup? This may overwrite existing data.')) return;++ try {+ if (selectedBackup.type === 'application') {+ await api.restoreApplication(selectedBackup.path);+ } else {+ await api.restoreDatabase(+ selectedBackup.path,+ selectedBackup.database_type,+ selectedBackup.database_name+ );+ }+ setShowRestoreModal(false);+ setSelectedBackup(null);+ toast.success('Backup restored successfully');+ } catch (err) {+ toast.error(err.message);+ }+ };++ const handleAddSchedule = async (e) => {+ e.preventDefault();+ try {+ await api.addBackupSchedule(+ scheduleForm.name,+ scheduleForm.backupType,+ scheduleForm.target,+ scheduleForm.scheduleTime,+ scheduleForm.days+ );+ setShowScheduleModal(false);+ resetScheduleForm();+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleRemoveSchedule = async (scheduleId) => {+ if (!window.confirm('Are you sure you want to remove this schedule?')) return;+ try {+ await api.removeBackupSchedule(scheduleId);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleSaveConfig = async (e) => {+ e.preventDefault();+ try {+ await api.updateBackupConfig(configForm);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleCleanup = async () => {+ if (!window.confirm(`This will delete backups older than ${configForm.retention_days} days. Continue?`)) return;+ try {+ const result = await api.cleanupBackups(configForm.retention_days);+ toast.success(result.message);+ loadData();+ } catch (err) {+ toast.error(err.message);+ }+ };++ const resetBackupForm = () => {+ setBackupForm({+ type: 'application',+ applicationId: '',+ includeDb: false,+ dbType: 'mysql',+ dbName: '',+ dbUser: '',+ dbPassword: '',+ dbHost: 'localhost'+ });+ };++ const resetScheduleForm = () => {+ setScheduleForm({+ name: '',+ backupType: 'application',+ target: '',+ scheduleTime: '02:00',+ days: ['daily']+ });+ };++ const formatSize = (bytes) => {+ if (!bytes) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ let unitIndex = 0;+ let size = bytes;+ while (size >= 1024 && unitIndex < units.length - 1) {+ size /= 1024;+ unitIndex++;+ }+ return `${size.toFixed(1)} ${units[unitIndex]}`;+ };++ const formatTimestamp = (timestamp) => {+ return new Date(timestamp).toLocaleString();+ };++ const filteredBackups = filterType === 'all'+ ? backups+ : backups.filter(b => b.type === filterType);++ if (loading) {+ return <div className="page"><div className="loading">Loading backup data...</div></div>;+ }++ return (+ <div className="page backups-page">+ <div className="page-header">+ <div>+ <h1>Backups</h1>+ <p className="page-subtitle">Manage application and database backups</p>+ </div>+ <div className="page-actions">+ <button className="btn btn-secondary" onClick={() => setShowScheduleModal(true)}>+ <svg viewBox="0 0 24 24" width="16" height="16">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+ Add Schedule+ </button>+ <button className="btn btn-primary" onClick={() => setShowBackupModal(true)}>+ <svg viewBox="0 0 24 24" width="16" height="16">+ <line x1="12" y1="5" x2="12" y2="19"/>+ <line x1="5" y1="12" x2="19" y2="12"/>+ </svg>+ Create Backup+ </button>+ </div>+ </div>++ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ {/* Stats Cards */}+ <div className="stats-grid">+ <div className="stat-card">+ <div className="stat-icon backups">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="7 10 12 15 17 10"/>+ <line x1="12" y1="15" x2="12" y2="3"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Total Backups</span>+ <span className="stat-value">{stats?.total_backups || 0}</span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon apps">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Application Backups</span>+ <span className="stat-value">{stats?.application_backups || 0}</span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon databases">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <ellipse cx="12" cy="5" rx="9" ry="3"/>+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Database Backups</span>+ <span className="stat-value">{stats?.database_backups || 0}</span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon size">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <rect x="2" y="2" width="20" height="8" rx="2" ry="2"/>+ <rect x="2" y="14" width="20" height="8" rx="2" ry="2"/>+ <line x1="6" y1="6" x2="6.01" y2="6"/>+ <line x1="6" y1="18" x2="6.01" y2="18"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Total Size</span>+ <span className="stat-value">{stats?.total_size_human || '0 B'}</span>+ </div>+ </div>+ </div>++ <div className="tabs">+ <button+ className={`tab ${activeTab === 'backups' ? 'active' : ''}`}+ onClick={() => setActiveTab('backups')}+ >+ Backups+ </button>+ <button+ className={`tab ${activeTab === 'schedules' ? 'active' : ''}`}+ onClick={() => setActiveTab('schedules')}+ >+ Schedules+ </button>+ <button+ className={`tab ${activeTab === 'settings' ? 'active' : ''}`}+ onClick={() => setActiveTab('settings')}+ >+ Settings+ </button>+ </div>++ {activeTab === 'backups' && (+ <div className="card">+ <div className="card-header">+ <h3>Backup List</h3>+ <div className="card-actions">+ <select+ value={filterType}+ onChange={(e) => setFilterType(e.target.value)}+ className="filter-select"+ >+ <option value="all">All Types</option>+ <option value="application">Applications</option>+ <option value="database">Databases</option>+ </select>+ <button className="btn btn-secondary btn-sm" onClick={loadData}>+ Refresh+ </button>+ </div>+ </div>+ <div className="card-body">+ {filteredBackups.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="7 10 12 15 17 10"/>+ <line x1="12" y1="15" x2="12" y2="3"/>+ </svg>+ <h3>No Backups</h3>+ <p>No backups found. Create your first backup to get started.</p>+ <button className="btn btn-primary" onClick={() => setShowBackupModal(true)}>+ Create Backup+ </button>+ </div>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Type</th>+ <th>Size</th>+ <th>Created</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {filteredBackups.map((backup, index) => (+ <tr key={index}>+ <td>+ <div className="backup-name">+ {backup.type === 'application' ? (+ <svg viewBox="0 0 24 24" width="16" height="16" className="icon-app">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>+ </svg>+ ) : (+ <svg viewBox="0 0 24 24" width="16" height="16" className="icon-db">+ <ellipse cx="12" cy="5" rx="9" ry="3"/>+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>+ </svg>+ )}+ <span>{backup.name || backup.app_name}</span>+ </div>+ </td>+ <td>+ <span className={`badge badge-${backup.type === 'application' ? 'primary' : 'info'}`}>+ {backup.type}+ </span>+ </td>+ <td>{formatSize(backup.size)}</td>+ <td>{formatTimestamp(backup.timestamp)}</td>+ <td>+ <div className="action-buttons">+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => {+ setSelectedBackup(backup);+ setShowRestoreModal(true);+ }}+ title="Restore"+ >+ <svg viewBox="0 0 24 24" width="14" height="14">+ <polyline points="1 4 1 10 7 10"/>+ <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>+ </svg>+ </button>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleDeleteBackup(backup.path)}+ title="Delete"+ >+ <svg viewBox="0 0 24 24" width="14" height="14">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+ </button>+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ )}++ {activeTab === 'schedules' && (+ <div className="card">+ <div className="card-header">+ <h3>Backup Schedules</h3>+ <button className="btn btn-primary btn-sm" onClick={() => setShowScheduleModal(true)}>+ Add Schedule+ </button>+ </div>+ <div className="card-body">+ {schedules.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+ <h3>No Schedules</h3>+ <p>No backup schedules configured. Add a schedule for automated backups.</p>+ <button className="btn btn-primary" onClick={() => setShowScheduleModal(true)}>+ Add Schedule+ </button>+ </div>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Type</th>+ <th>Target</th>+ <th>Time</th>+ <th>Days</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {schedules.map((schedule) => (+ <tr key={schedule.id}>+ <td>{schedule.name}</td>+ <td>+ <span className={`badge badge-${schedule.backup_type === 'application' ? 'primary' : 'info'}`}>+ {schedule.backup_type}+ </span>+ </td>+ <td>{schedule.target}</td>+ <td>{schedule.schedule_time}</td>+ <td>{schedule.days?.join(', ') || 'daily'}</td>+ <td>+ <span className={`badge badge-${schedule.enabled ? 'success' : 'secondary'}`}>+ {schedule.enabled ? 'Active' : 'Disabled'}+ </span>+ </td>+ <td>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleRemoveSchedule(schedule.id)}+ title="Remove"+ >+ <svg viewBox="0 0 24 24" width="14" height="14">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ )}++ {activeTab === 'settings' && (+ <div className="card">+ <div className="card-header">+ <h3>Backup Settings</h3>+ </div>+ <div className="card-body">+ <form onSubmit={handleSaveConfig}>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={configForm.enabled}+ onChange={(e) => setConfigForm({...configForm, enabled: e.target.checked})}+ />+ <span>Enable Scheduled Backups</span>+ </label>+ </div>++ <div className="form-group">+ <label>Retention Period (days)</label>+ <input+ type="number"+ value={configForm.retention_days}+ onChange={(e) => setConfigForm({...configForm, retention_days: parseInt(e.target.value)})}+ min="1"+ max="365"+ />+ <span className="form-help">Backups older than this will be deleted during cleanup</span>+ </div>++ <div className="form-actions">+ <button type="submit" className="btn btn-primary">Save Settings</button>+ <button type="button" className="btn btn-secondary" onClick={handleCleanup}>+ Run Cleanup Now+ </button>+ </div>+ </form>+ </div>+ </div>+ )}++ {/* Create Backup Modal */}+ {showBackupModal && (+ <div className="modal-overlay" onClick={() => setShowBackupModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Create Backup</h2>+ <button className="modal-close" onClick={() => setShowBackupModal(false)}>×</button>+ </div>+ <form onSubmit={handleCreateBackup}>+ <div className="modal-body">+ <div className="form-group">+ <label>Backup Type</label>+ <select+ value={backupForm.type}+ onChange={(e) => setBackupForm({...backupForm, type: e.target.value})}+ >+ <option value="application">Application</option>+ <option value="database">Database Only</option>+ </select>+ </div>++ {backupForm.type === 'application' && (+ <>+ <div className="form-group">+ <label>Application</label>+ <select+ value={backupForm.applicationId}+ onChange={(e) => setBackupForm({...backupForm, applicationId: e.target.value})}+ required+ >+ <option value="">Select Application</option>+ {apps.map(app => (+ <option key={app.id} value={app.id}>{app.name}</option>+ ))}+ </select>+ </div>++ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={backupForm.includeDb}+ onChange={(e) => setBackupForm({...backupForm, includeDb: e.target.checked})}+ />+ <span>Include Database</span>+ </label>+ </div>+ </>+ )}++ {(backupForm.type === 'database' || backupForm.includeDb) && (+ <>+ <div className="form-group">+ <label>Database Type</label>+ <select+ value={backupForm.dbType}+ onChange={(e) => setBackupForm({...backupForm, dbType: e.target.value})}+ >+ <option value="mysql">MySQL</option>+ <option value="postgresql">PostgreSQL</option>+ </select>+ </div>++ <div className="form-group">+ <label>Database Name</label>+ <input+ type="text"+ value={backupForm.dbName}+ onChange={(e) => setBackupForm({...backupForm, dbName: e.target.value})}+ required+ />+ </div>++ <div className="form-row">+ <div className="form-group">+ <label>Username</label>+ <input+ type="text"+ value={backupForm.dbUser}+ onChange={(e) => setBackupForm({...backupForm, dbUser: e.target.value})}+ />+ </div>++ <div className="form-group">+ <label>Password</label>+ <input+ type="password"+ value={backupForm.dbPassword}+ onChange={(e) => setBackupForm({...backupForm, dbPassword: e.target.value})}+ />+ </div>+ </div>++ <div className="form-group">+ <label>Host</label>+ <input+ type="text"+ value={backupForm.dbHost}+ onChange={(e) => setBackupForm({...backupForm, dbHost: e.target.value})}+ />+ </div>+ </>+ )}+ </div>+ <div className="modal-footer">+ <button type="button" className="btn btn-secondary" onClick={() => setShowBackupModal(false)}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary">Create Backup</button>+ </div>+ </form>+ </div>+ </div>+ )}++ {/* Add Schedule Modal */}+ {showScheduleModal && (+ <div className="modal-overlay" onClick={() => setShowScheduleModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Add Backup Schedule</h2>+ <button className="modal-close" onClick={() => setShowScheduleModal(false)}>×</button>+ </div>+ <form onSubmit={handleAddSchedule}>+ <div className="modal-body">+ <div className="form-group">+ <label>Schedule Name</label>+ <input+ type="text"+ value={scheduleForm.name}+ onChange={(e) => setScheduleForm({...scheduleForm, name: e.target.value})}+ placeholder="Daily App Backup"+ required+ />+ </div>++ <div className="form-group">+ <label>Backup Type</label>+ <select+ value={scheduleForm.backupType}+ onChange={(e) => setScheduleForm({...scheduleForm, backupType: e.target.value})}+ >+ <option value="application">Application</option>+ <option value="database">Database</option>+ </select>+ </div>++ <div className="form-group">+ <label>Target</label>+ <input+ type="text"+ value={scheduleForm.target}+ onChange={(e) => setScheduleForm({...scheduleForm, target: e.target.value})}+ placeholder="App name or database name"+ required+ />+ </div>++ <div className="form-group">+ <label>Time</label>+ <input+ type="time"+ value={scheduleForm.scheduleTime}+ onChange={(e) => setScheduleForm({...scheduleForm, scheduleTime: e.target.value})}+ required+ />+ </div>+ </div>+ <div className="modal-footer">+ <button type="button" className="btn btn-secondary" onClick={() => setShowScheduleModal(false)}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary">Add Schedule</button>+ </div>+ </form>+ </div>+ </div>+ )}++ {/* Restore Modal */}+ {showRestoreModal && selectedBackup && (+ <div className="modal-overlay" onClick={() => setShowRestoreModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Restore Backup</h2>+ <button className="modal-close" onClick={() => setShowRestoreModal(false)}>×</button>+ </div>+ <div className="modal-body">+ <div className="restore-warning">+ <svg viewBox="0 0 24 24" width="48" height="48">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>+ <line x1="12" y1="9" x2="12" y2="13"/>+ <line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ <h3>Warning</h3>+ <p>Restoring this backup will overwrite existing data. This action cannot be undone.</p>+ </div>+ <div className="restore-details">+ <div className="detail-row">+ <span className="detail-label">Backup Name:</span>+ <span className="detail-value">{selectedBackup.name || selectedBackup.app_name}</span>+ </div>+ <div className="detail-row">+ <span className="detail-label">Type:</span>+ <span className="detail-value">{selectedBackup.type}</span>+ </div>+ <div className="detail-row">+ <span className="detail-label">Created:</span>+ <span className="detail-value">{formatTimestamp(selectedBackup.timestamp)}</span>+ </div>+ <div className="detail-row">+ <span className="detail-label">Size:</span>+ <span className="detail-value">{formatSize(selectedBackup.size)}</span>+ </div>+ </div>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowRestoreModal(false)}>+ Cancel+ </button>+ <button className="btn btn-danger" onClick={handleRestore}>+ Restore Backup+ </button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++export default Backups;diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsxindex 1ba707b2..ba5fab94 100644--- a/frontend/src/pages/Databases.jsx+++ b/frontend/src/pages/Databases.jsx@@ -1,5 +1,6 @@import React, { useState, useEffect } from 'react';import api from '../services/api';+import { useToast } from '../contexts/ToastContext';const Databases = () => {const [activeTab, setActiveTab] = useState('mysql');@@ -84,6 +85,7 @@ const Databases = () => {};const MySQLTab = ({ status }) => {+ const toast = useToast();const [databases, setDatabases] = useState([]);const [users, setUsers] = useState([]);const [loading, setLoading] = useState(true);@@ -121,10 +123,11 @@ const MySQLTab = ({ status }) => {try {await api.dropMySQLDatabase(name);+ toast.success(`Database "${name}" dropped successfully`);loadData();} catch (err) {console.error('Failed to drop database:', err);- alert('Failed to drop database');+ toast.error('Failed to drop database');}}@@ -132,11 +135,11 @@ const MySQLTab = ({ status }) => {try {const result = await api.backupMySQLDatabase(name);if (result.success) {- alert(`Backup created: ${result.backup_path}`);+ toast.success(`Backup created: ${result.backup_path}`);}} catch (err) {console.error('Failed to backup database:', err);- alert('Failed to create backup');+ toast.error('Failed to create backup');}}@@ -145,10 +148,11 @@ const MySQLTab = ({ status }) => {try {await api.dropMySQLUser(username, host);+ toast.success(`User "${username}" dropped successfully`);loadData();} catch (err) {console.error('Failed to drop user:', err);- alert('Failed to drop user');+ toast.error('Failed to drop user');}}@@ -308,6 +312,7 @@ const MySQLTab = ({ status }) => {};const PostgreSQLTab = ({ status }) => {+ const toast = useToast();const [databases, setDatabases] = useState([]);const [users, setUsers] = useState([]);const [loading, setLoading] = useState(true);@@ -345,10 +350,11 @@ const PostgreSQLTab = ({ status }) => {try {await api.dropPostgreSQLDatabase(name);+ toast.success(`Database "${name}" dropped successfully`);loadData();} catch (err) {console.error('Failed to drop database:', err);- alert('Failed to drop database');+ toast.error('Failed to drop database');}}@@ -356,11 +362,11 @@ const PostgreSQLTab = ({ status }) => {try {const result = await api.backupPostgreSQLDatabase(name);if (result.success) {- alert(`Backup created: ${result.backup_path}`);+ toast.success(`Backup created: ${result.backup_path}`);}} catch (err) {console.error('Failed to backup database:', err);- alert('Failed to create backup');+ toast.error('Failed to create backup');}}@@ -369,10 +375,11 @@ const PostgreSQLTab = ({ status }) => {try {await api.dropPostgreSQLUser(username);+ toast.success(`User "${username}" dropped successfully`);loadData();} catch (err) {console.error('Failed to drop user:', err);- alert('Failed to drop user');+ toast.error('Failed to drop user');}}diff --git a/frontend/src/pages/Docker.jsx b/frontend/src/pages/Docker.jsxindex fc6b8a96..0fe2ccd7 100644--- a/frontend/src/pages/Docker.jsx+++ b/frontend/src/pages/Docker.jsx@@ -1,5 +1,6 @@import React, { useState, useEffect } from 'react';import api from '../services/api';+import { useToast } from '../contexts/ToastContext';const Docker = () => {const [activeTab, setActiveTab] = useState('containers');@@ -418,6 +419,7 @@ const ContainerLogsModal = ({ container, onClose }) => {};const ImagesTab = () => {+ const toast = useToast();const [images, setImages] = useState([]);const [loading, setLoading] = useState(true);const [showPullModal, setShowPullModal] = useState(false);@@ -443,10 +445,11 @@ const ImagesTab = () => {try {await api.removeImage(imageId, true);+ toast.success('Image removed successfully');loadImages();} catch (err) {console.error('Failed to remove image:', err);- alert('Failed to remove image. It may be in use by a container.');+ toast.error('Failed to remove image. It may be in use by a container.');}}@@ -581,6 +584,7 @@ const PullImageModal = ({ onClose, onPulled }) => {};const NetworksTab = () => {+ const toast = useToast();const [networks, setNetworks] = useState([]);const [loading, setLoading] = useState(true);const [showCreateModal, setShowCreateModal] = useState(false);@@ -606,10 +610,11 @@ const NetworksTab = () => {try {await api.removeNetwork(networkId);+ toast.success('Network removed successfully');loadNetworks();} catch (err) {console.error('Failed to remove network:', err);- alert('Failed to remove network. It may be in use.');+ toast.error('Failed to remove network. It may be in use.');}}@@ -740,6 +745,7 @@ const CreateNetworkModal = ({ onClose, onCreated }) => {};const VolumesTab = () => {+ const toast = useToast();const [volumes, setVolumes] = useState([]);const [loading, setLoading] = useState(true);const [showCreateModal, setShowCreateModal] = useState(false);@@ -765,10 +771,11 @@ const VolumesTab = () => {try {await api.removeVolume(volumeName, true);+ toast.success('Volume removed successfully');loadVolumes();} catch (err) {console.error('Failed to remove volume:', err);- alert('Failed to remove volume. It may be in use.');+ toast.error('Failed to remove volume. It may be in use.');}}diff --git a/frontend/src/pages/Domains.jsx b/frontend/src/pages/Domains.jsxnew file mode 100644index 00000000..f8fe0c17--- /dev/null+++ b/frontend/src/pages/Domains.jsx@@ -0,0 +1,442 @@+import React, { useState, useEffect } from 'react';+import {+ Globe, Plus, Shield, ShieldCheck, ShieldOff, RefreshCw,+ Trash2, ExternalLink, CheckCircle, XCircle, AlertTriangle,+ Clock, Server, Lock, Unlock, Search+} from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const Domains = () => {+ const toast = useToast();+ const [domains, setDomains] = useState([]);+ const [apps, setApps] = useState([]);+ const [sslStatus, setSslStatus] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState('');++ // Modal states+ const [showAddModal, setShowAddModal] = useState(false);+ const [showSslModal, setShowSslModal] = useState(false);+ const [selectedDomain, setSelectedDomain] = useState(null);++ // Form states+ const [domainName, setDomainName] = useState('');+ const [selectedAppId, setSelectedAppId] = useState('');+ const [isPrimary, setIsPrimary] = useState(false);+ const [sslEmail, setSslEmail] = useState('');+ const [actionLoading, setActionLoading] = useState(false);++ useEffect(() => {+ loadData();+ }, []);++ async function loadData() {+ try {+ setLoading(true);+ const [domainsData, appsData, sslData] = await Promise.all([+ api.getDomains(),+ api.getApps(),+ api.getDomainsSslStatus().catch(() => null)+ ]);+ setDomains(domainsData.domains || []);+ setApps(appsData.apps || []);+ setSslStatus(sslData);+ } catch (err) {+ setError('Failed to load data');+ console.error(err);+ } finally {+ setLoading(false);+ }+ }++ async function handleAddDomain(e) {+ e.preventDefault();+ if (!domainName || !selectedAppId) return;++ try {+ setActionLoading(true);+ await api.createDomain({+ name: domainName,+ application_id: parseInt(selectedAppId),+ is_primary: isPrimary+ });+ setShowAddModal(false);+ setDomainName('');+ setSelectedAppId('');+ setIsPrimary(false);+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setActionLoading(false);+ }+ }++ async function handleDeleteDomain(domain) {+ if (!confirm(`Are you sure you want to delete ${domain.name}?`)) return;++ try {+ await api.deleteDomain(domain.id);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleEnableSsl(e) {+ e.preventDefault();+ if (!selectedDomain || !sslEmail) return;++ try {+ setActionLoading(true);+ await api.enableSsl(selectedDomain.id, sslEmail);+ setShowSslModal(false);+ setSslEmail('');+ setSelectedDomain(null);+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setActionLoading(false);+ }+ }++ async function handleDisableSsl(domain) {+ if (!confirm(`Disable SSL for ${domain.name}?`)) return;++ try {+ await api.disableSsl(domain.id);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ }++ async function handleRenewSsl(domain) {+ try {+ setActionLoading(true);+ await api.renewDomainSsl(domain.id);+ loadData();+ } catch (err) {+ setError(err.message);+ } finally {+ setActionLoading(false);+ }+ }++ async function handleVerifyDomain(domain) {+ try {+ const result = await api.verifyDomain(domain.id);+ if (result.verified) {+ toast.success(`Domain verified! IP: ${result.ip_address}`);+ } else {+ toast.error(`Domain verification failed: ${result.error}`);+ }+ } catch (err) {+ setError(err.message);+ }+ }++ function getAppName(appId) {+ const app = apps.find(a => a.id === appId);+ return app ? app.name : 'Unknown';+ }++ if (loading) {+ return <div className="loading">Loading domains...</div>;+ }++ return (+ <div>+ <header className="top-bar">+ <div>+ <h1>Domains & SSL</h1>+ <p className="subtitle">Manage your domains and SSL certificates</p>+ </div>+ <div className="top-bar-actions">+ <button className="btn btn-secondary" onClick={loadData}>+ <RefreshCw size={16} />+ Refresh+ </button>+ <button className="btn btn-primary" onClick={() => setShowAddModal(true)}>+ <Plus size={16} />+ Add Domain+ </button>+ </div>+ </header>++ {error && (+ <div className="error-banner">+ {error}+ <button onClick={() => setError('')} style={{ float: 'right', background: 'none', border: 'none', cursor: 'pointer' }}>×</button>+ </div>+ )}++ {/* SSL Status */}+ {sslStatus && (+ <div className="ssl-status-bar">+ <div className="ssl-status-item">+ <div className={`ssl-status-icon ${sslStatus.certbot_installed ? 'active' : 'inactive'}`}>+ {sslStatus.certbot_installed ? <ShieldCheck size={24} /> : <ShieldOff size={24} />}+ </div>+ <div className="ssl-status-info">+ <h4>Certbot</h4>+ <span>{sslStatus.certbot_installed ? 'Installed' : 'Not Installed'}</span>+ </div>+ </div>+ <div className="ssl-status-item">+ <div className="ssl-status-icon active">+ <Lock size={24} />+ </div>+ <div className="ssl-status-info">+ <h4>Certificates</h4>+ <span>{sslStatus.total_certificates} active</span>+ </div>+ </div>+ </div>+ )}++ {/* Domains List */}+ <h2 className="section-title">Domains</h2>++ {domains.length === 0 ? (+ <div className="empty-state">+ <Globe size={48} />+ <h3>No domains configured</h3>+ <p>Add a domain to your application to get started.</p>+ <button className="btn btn-primary" onClick={() => setShowAddModal(true)}>+ <Plus size={16} />+ Add Domain+ </button>+ </div>+ ) : (+ <div className="domain-list">+ {domains.map(domain => (+ <div key={domain.id} className="domain-item">+ <div className="domain-item-info">+ <div className={`domain-item-icon ${domain.ssl_enabled ? 'ssl' : ''}`}>+ {domain.ssl_enabled ? <ShieldCheck size={20} /> : <Globe size={20} />}+ </div>+ <div className="domain-item-details">+ <h3>+ {domain.name}+ {domain.is_primary && <span className="primary-badge">Primary</span>}+ </h3>+ <div className="domain-item-meta">+ <span className="app-link">+ <Server size={12} />+ {getAppName(domain.application_id)}+ </span>+ {domain.ssl_enabled && (+ <span className="ssl-badge">+ <Lock size={12} />+ SSL Active+ </span>+ )}+ </div>+ </div>+ </div>+ <div className="domain-item-actions">+ <a+ href={`${domain.ssl_enabled ? 'https' : 'http'}://${domain.name}`}+ target="_blank"+ rel="noopener noreferrer"+ className="btn btn-secondary btn-sm"+ >+ <ExternalLink size={14} />+ Visit+ </a>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleVerifyDomain(domain)}+ >+ <Search size={14} />+ Verify DNS+ </button>+ {domain.ssl_enabled ? (+ <>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleRenewSsl(domain)}+ disabled={actionLoading}+ >+ <RefreshCw size={14} />+ Renew SSL+ </button>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleDisableSsl(domain)}+ >+ <Unlock size={14} />+ </button>+ </>+ ) : (+ <button+ className="btn btn-primary btn-sm"+ onClick={() => {+ setSelectedDomain(domain);+ setShowSslModal(true);+ }}+ >+ <Lock size={14} />+ Enable SSL+ </button>+ )}+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleDeleteDomain(domain)}+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ ))}+ </div>+ )}++ {/* SSL Certificates */}+ {sslStatus && sslStatus.certificates && sslStatus.certificates.length > 0 && (+ <>+ <h2 className="section-title" style={{ marginTop: '40px' }}>SSL Certificates</h2>+ <div className="cert-list">+ {sslStatus.certificates.map((cert, index) => (+ <div key={index} className="cert-item">+ <div className="cert-item-info">+ <div className="cert-item-icon">+ <ShieldCheck size={20} />+ </div>+ <div className="cert-item-details">+ <h3>{cert.name}</h3>+ <div className="cert-item-meta">+ <span>+ <Globe size={12} />+ {cert.domains?.join(', ')}+ </span>+ {cert.expiry && (+ <span className={cert.expiry_valid ? 'valid' : 'expiring'}>+ <Clock size={12} />+ Expires: {cert.expiry}+ </span>+ )}+ </div>+ </div>+ </div>+ <div className="cert-status">+ {cert.expiry_valid ? (+ <span className="status-badge status-active">+ <CheckCircle size={14} />+ Valid+ </span>+ ) : (+ <span className="status-badge status-warning">+ <AlertTriangle size={14} />+ Expiring Soon+ </span>+ )}+ </div>+ </div>+ ))}+ </div>+ </>+ )}++ {/* Add Domain Modal */}+ {showAddModal && (+ <div className="modal-overlay" onClick={() => setShowAddModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Add Domain</h2>+ <button className="modal-close" onClick={() => setShowAddModal(false)}>×</button>+ </div>+ <form onSubmit={handleAddDomain}>+ <div className="form-group">+ <label>Domain Name</label>+ <input+ type="text"+ placeholder="example.com"+ value={domainName}+ onChange={e => setDomainName(e.target.value)}+ required+ />+ </div>+ <div className="form-group">+ <label>Application</label>+ <select+ value={selectedAppId}+ onChange={e => setSelectedAppId(e.target.value)}+ required+ >+ <option value="">Select an application</option>+ {apps.map(app => (+ <option key={app.id} value={app.id}>{app.name}</option>+ ))}+ </select>+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={isPrimary}+ onChange={e => setIsPrimary(e.target.checked)}+ />+ Set as primary domain+ </label>+ </div>+ <div className="modal-actions">+ <button type="button" className="btn btn-secondary" onClick={() => setShowAddModal(false)}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary" disabled={actionLoading}>+ {actionLoading ? 'Adding...' : 'Add Domain'}+ </button>+ </div>+ </form>+ </div>+ </div>+ )}++ {/* Enable SSL Modal */}+ {showSslModal && selectedDomain && (+ <div className="modal-overlay" onClick={() => setShowSslModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Enable SSL Certificate</h2>+ <button className="modal-close" onClick={() => setShowSslModal(false)}>×</button>+ </div>+ <form onSubmit={handleEnableSsl}>+ <div className="ssl-info-box">+ <ShieldCheck size={32} />+ <div>+ <h4>Free SSL from Let's Encrypt</h4>+ <p>A free SSL certificate will be obtained for <strong>{selectedDomain.name}</strong></p>+ </div>+ </div>+ <div className="form-group">+ <label>Email Address</label>+ <input+ type="email"+ placeholder="[email protected]"+ value={sslEmail}+ onChange={e => setSslEmail(e.target.value)}+ required+ />+ <p className="hint">Required for certificate expiration notifications</p>+ </div>+ <div className="modal-actions">+ <button type="button" className="btn btn-secondary" onClick={() => setShowSslModal(false)}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary" disabled={actionLoading}>+ {actionLoading ? 'Obtaining Certificate...' : 'Enable SSL'}+ </button>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>+ );+};++export default Domains;diff --git a/frontend/src/pages/Monitoring.jsx b/frontend/src/pages/Monitoring.jsxnew file mode 100644index 00000000..4acd0cf2--- /dev/null+++ b/frontend/src/pages/Monitoring.jsx@@ -0,0 +1,515 @@+import React, { useState, useEffect } from 'react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const Monitoring = () => {+ const toast = useToast();+ const [status, setStatus] = useState(null);+ const [config, setConfig] = useState(null);+ const [thresholds, setThresholds] = useState(null);+ const [alertHistory, setAlertHistory] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [activeTab, setActiveTab] = useState('overview');++ // Config form state+ const [configForm, setConfigForm] = useState({+ enabled: false,+ check_interval: 60,+ alert_email: '',+ alert_webhook: ''+ });++ // Threshold form state+ const [thresholdForm, setThresholdForm] = useState({+ cpu_percent: 90,+ memory_percent: 90,+ disk_percent: 90,+ load_average: 5.0+ });++ const [testEmail, setTestEmail] = useState('');+ const [testWebhook, setTestWebhook] = useState('');++ useEffect(() => {+ loadData();+ }, []);++ const loadData = async () => {+ try {+ setLoading(true);+ const [statusRes, configRes, thresholdsRes, historyRes] = await Promise.all([+ api.getMonitoringStatus(),+ api.getMonitoringConfig(),+ api.getMonitoringThresholds(),+ api.getAlertHistory(50)+ ]);++ setStatus(statusRes);+ setConfig(configRes);+ setThresholds(thresholdsRes.thresholds);+ setAlertHistory(historyRes.alerts || []);++ if (configRes) {+ setConfigForm({+ enabled: configRes.enabled || false,+ check_interval: configRes.check_interval || 60,+ alert_email: configRes.alert_email || '',+ alert_webhook: configRes.alert_webhook || ''+ });+ }++ if (thresholdsRes.thresholds) {+ setThresholdForm(thresholdsRes.thresholds);+ }+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ };++ const handleToggleMonitoring = async () => {+ try {+ if (status?.monitoring_active) {+ await api.stopMonitoring();+ } else {+ await api.startMonitoring();+ }+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleSaveConfig = async (e) => {+ e.preventDefault();+ try {+ await api.updateMonitoringConfig(configForm);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleSaveThresholds = async (e) => {+ e.preventDefault();+ try {+ await api.updateMonitoringThresholds(thresholdForm);+ loadData();+ } catch (err) {+ setError(err.message);+ }+ };++ const handleTestEmail = async () => {+ try {+ await api.testEmailAlert(testEmail || configForm.alert_email);+ toast.success('Test email sent successfully');+ } catch (err) {+ toast.error(err.message);+ }+ };++ const handleTestWebhook = async () => {+ try {+ await api.testWebhookAlert(testWebhook || configForm.alert_webhook);+ toast.success('Test webhook sent successfully');+ } catch (err) {+ toast.error(err.message);+ }+ };++ const getAlertSeverityClass = (severity) => {+ switch (severity) {+ case 'critical': return 'badge-danger';+ case 'warning': return 'badge-warning';+ case 'info': return 'badge-info';+ default: return 'badge-secondary';+ }+ };++ const formatTimestamp = (timestamp) => {+ return new Date(timestamp).toLocaleString();+ };++ if (loading) {+ return <div className="page"><div className="loading">Loading monitoring data...</div></div>;+ }++ return (+ <div className="page monitoring-page">+ <div className="page-header">+ <div>+ <h1>Monitoring & Alerts</h1>+ <p className="page-subtitle">System monitoring and alert configuration</p>+ </div>+ <div className="page-actions">+ <button+ className={`btn ${status?.monitoring_active ? 'btn-danger' : 'btn-primary'}`}+ onClick={handleToggleMonitoring}+ >+ {status?.monitoring_active ? (+ <>+ <svg viewBox="0 0 24 24" width="16" height="16">+ <rect x="6" y="4" width="4" height="16"/>+ <rect x="14" y="4" width="4" height="16"/>+ </svg>+ Stop Monitoring+ </>+ ) : (+ <>+ <svg viewBox="0 0 24 24" width="16" height="16">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ Start Monitoring+ </>+ )}+ </button>+ </div>+ </div>++ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ <div className="tabs">+ <button+ className={`tab ${activeTab === 'overview' ? 'active' : ''}`}+ onClick={() => setActiveTab('overview')}+ >+ Overview+ </button>+ <button+ className={`tab ${activeTab === 'alerts' ? 'active' : ''}`}+ onClick={() => setActiveTab('alerts')}+ >+ Alert History+ </button>+ <button+ className={`tab ${activeTab === 'config' ? 'active' : ''}`}+ onClick={() => setActiveTab('config')}+ >+ Configuration+ </button>+ <button+ className={`tab ${activeTab === 'thresholds' ? 'active' : ''}`}+ onClick={() => setActiveTab('thresholds')}+ >+ Thresholds+ </button>+ </div>++ {activeTab === 'overview' && (+ <div className="monitoring-overview">+ <div className="stats-grid">+ <div className="stat-card">+ <div className="stat-icon status">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <circle cx="12" cy="12" r="10"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Monitoring Status</span>+ <span className={`stat-value ${status?.monitoring_active ? 'text-success' : 'text-muted'}`}>+ {status?.monitoring_active ? 'Active' : 'Inactive'}+ </span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon alerts">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>+ <path d="M13.73 21a2 2 0 0 1-3.46 0"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Recent Alerts</span>+ <span className="stat-value">{alertHistory.length}</span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon interval">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Check Interval</span>+ <span className="stat-value">{config?.check_interval || 60}s</span>+ </div>+ </div>++ <div className="stat-card">+ <div className="stat-icon notifications">+ <svg viewBox="0 0 24 24" width="24" height="24">+ <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>+ <polyline points="22,6 12,13 2,6"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-label">Notifications</span>+ <span className="stat-value">+ {config?.alert_email ? 'Email' : ''}+ {config?.alert_email && config?.alert_webhook ? ' + ' : ''}+ {config?.alert_webhook ? 'Webhook' : ''}+ {!config?.alert_email && !config?.alert_webhook ? 'None' : ''}+ </span>+ </div>+ </div>+ </div>++ <div className="card">+ <div className="card-header">+ <h3>Current Thresholds</h3>+ </div>+ <div className="card-body">+ <div className="threshold-grid">+ <div className="threshold-item">+ <span className="threshold-label">CPU Usage</span>+ <span className="threshold-value">{thresholds?.cpu_percent || 90}%</span>+ </div>+ <div className="threshold-item">+ <span className="threshold-label">Memory Usage</span>+ <span className="threshold-value">{thresholds?.memory_percent || 90}%</span>+ </div>+ <div className="threshold-item">+ <span className="threshold-label">Disk Usage</span>+ <span className="threshold-value">{thresholds?.disk_percent || 90}%</span>+ </div>+ <div className="threshold-item">+ <span className="threshold-label">Load Average</span>+ <span className="threshold-value">{thresholds?.load_average || 5.0}</span>+ </div>+ </div>+ </div>+ </div>++ {alertHistory.length > 0 && (+ <div className="card">+ <div className="card-header">+ <h3>Recent Alerts</h3>+ </div>+ <div className="card-body">+ <div className="alert-list">+ {alertHistory.slice(0, 5).map((alert, index) => (+ <div key={index} className="alert-item">+ <span className={`badge ${getAlertSeverityClass(alert.severity)}`}>+ {alert.severity}+ </span>+ <span className="alert-message">{alert.message}</span>+ <span className="alert-time">{formatTimestamp(alert.timestamp)}</span>+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </div>+ )}++ {activeTab === 'alerts' && (+ <div className="card">+ <div className="card-header">+ <h3>Alert History</h3>+ <button className="btn btn-secondary btn-sm" onClick={loadData}>+ Refresh+ </button>+ </div>+ <div className="card-body">+ {alertHistory.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48">+ <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>+ <path d="M13.73 21a2 2 0 0 1-3.46 0"/>+ </svg>+ <h3>No Alerts</h3>+ <p>No alerts have been triggered yet.</p>+ </div>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Severity</th>+ <th>Type</th>+ <th>Message</th>+ <th>Value</th>+ <th>Threshold</th>+ <th>Time</th>+ </tr>+ </thead>+ <tbody>+ {alertHistory.map((alert, index) => (+ <tr key={index}>+ <td>+ <span className={`badge ${getAlertSeverityClass(alert.severity)}`}>+ {alert.severity}+ </span>+ </td>+ <td>{alert.type}</td>+ <td>{alert.message}</td>+ <td>{alert.value?.toFixed(1)}</td>+ <td>{alert.threshold}</td>+ <td>{formatTimestamp(alert.timestamp)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ )}++ {activeTab === 'config' && (+ <div className="card">+ <div className="card-header">+ <h3>Monitoring Configuration</h3>+ </div>+ <div className="card-body">+ <form onSubmit={handleSaveConfig}>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={configForm.enabled}+ onChange={(e) => setConfigForm({...configForm, enabled: e.target.checked})}+ />+ <span>Enable Monitoring</span>+ </label>+ </div>++ <div className="form-group">+ <label>Check Interval (seconds)</label>+ <input+ type="number"+ value={configForm.check_interval}+ onChange={(e) => setConfigForm({...configForm, check_interval: parseInt(e.target.value)})}+ min="10"+ max="3600"+ />+ </div>++ <div className="form-group">+ <label>Alert Email</label>+ <div className="input-group">+ <input+ type="email"+ value={configForm.alert_email}+ onChange={(e) => setConfigForm({...configForm, alert_email: e.target.value})}+ placeholder="[email protected]"+ />+ <button+ type="button"+ className="btn btn-secondary"+ onClick={handleTestEmail}+ disabled={!configForm.alert_email}+ >+ Test+ </button>+ </div>+ </div>++ <div className="form-group">+ <label>Webhook URL</label>+ <div className="input-group">+ <input+ type="url"+ value={configForm.alert_webhook}+ onChange={(e) => setConfigForm({...configForm, alert_webhook: e.target.value})}+ placeholder="https://hooks.slack.com/..."+ />+ <button+ type="button"+ className="btn btn-secondary"+ onClick={handleTestWebhook}+ disabled={!configForm.alert_webhook}+ >+ Test+ </button>+ </div>+ </div>++ <div className="form-actions">+ <button type="submit" className="btn btn-primary">Save Configuration</button>+ </div>+ </form>+ </div>+ </div>+ )}++ {activeTab === 'thresholds' && (+ <div className="card">+ <div className="card-header">+ <h3>Alert Thresholds</h3>+ </div>+ <div className="card-body">+ <form onSubmit={handleSaveThresholds}>+ <div className="threshold-form-grid">+ <div className="form-group">+ <label>CPU Usage (%)</label>+ <input+ type="number"+ value={thresholdForm.cpu_percent}+ onChange={(e) => setThresholdForm({...thresholdForm, cpu_percent: parseInt(e.target.value)})}+ min="1"+ max="100"+ />+ <span className="form-help">Alert when CPU exceeds this percentage</span>+ </div>++ <div className="form-group">+ <label>Memory Usage (%)</label>+ <input+ type="number"+ value={thresholdForm.memory_percent}+ onChange={(e) => setThresholdForm({...thresholdForm, memory_percent: parseInt(e.target.value)})}+ min="1"+ max="100"+ />+ <span className="form-help">Alert when memory exceeds this percentage</span>+ </div>++ <div className="form-group">+ <label>Disk Usage (%)</label>+ <input+ type="number"+ value={thresholdForm.disk_percent}+ onChange={(e) => setThresholdForm({...thresholdForm, disk_percent: parseInt(e.target.value)})}+ min="1"+ max="100"+ />+ <span className="form-help">Alert when disk exceeds this percentage</span>+ </div>++ <div className="form-group">+ <label>Load Average</label>+ <input+ type="number"+ step="0.1"+ value={thresholdForm.load_average}+ onChange={(e) => setThresholdForm({...thresholdForm, load_average: parseFloat(e.target.value)})}+ min="0.1"+ max="100"+ />+ <span className="form-help">Alert when load average exceeds this value</span>+ </div>+ </div>++ <div className="form-actions">+ <button type="submit" className="btn btn-primary">Save Thresholds</button>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>+ );+};++export default Monitoring;diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxnew file mode 100644index 00000000..8f59dc0f--- /dev/null+++ b/frontend/src/pages/Settings.jsx@@ -0,0 +1,746 @@+import React, { useState, useEffect } from 'react';+import { useAuth } from '../contexts/AuthContext';+import api from '../services/api';++const Settings = () => {+ const [activeTab, setActiveTab] = useState('profile');++ return (+ <div className="page settings-page">+ <div className="page-header">+ <div>+ <h1>Settings</h1>+ <p className="page-subtitle">Manage your account and system preferences</p>+ </div>+ </div>++ <div className="settings-layout">+ <nav className="settings-nav">+ <button+ className={`settings-nav-item ${activeTab === 'profile' ? 'active' : ''}`}+ onClick={() => setActiveTab('profile')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>+ <circle cx="12" cy="7" r="4"/>+ </svg>+ Profile+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'security' ? 'active' : ''}`}+ onClick={() => setActiveTab('security')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ Security+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'appearance' ? 'active' : ''}`}+ onClick={() => setActiveTab('appearance')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <circle cx="12" cy="12" r="5"/>+ <line x1="12" y1="1" x2="12" y2="3"/>+ <line x1="12" y1="21" x2="12" y2="23"/>+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>+ <line x1="1" y1="12" x2="3" y2="12"/>+ <line x1="21" y1="12" x2="23" y2="12"/>+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>+ </svg>+ Appearance+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'notifications' ? 'active' : ''}`}+ onClick={() => setActiveTab('notifications')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>+ <path d="M13.73 21a2 2 0 0 1-3.46 0"/>+ </svg>+ Notifications+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'system' ? 'active' : ''}`}+ onClick={() => setActiveTab('system')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>+ <line x1="8" y1="21" x2="16" y2="21"/>+ <line x1="12" y1="17" x2="12" y2="21"/>+ </svg>+ System Info+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'about' ? 'active' : ''}`}+ onClick={() => setActiveTab('about')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="16" x2="12" y2="12"/>+ <line x1="12" y1="8" x2="12.01" y2="8"/>+ </svg>+ About+ </button>+ </nav>++ <div className="settings-content">+ {activeTab === 'profile' && <ProfileSettings />}+ {activeTab === 'security' && <SecuritySettings />}+ {activeTab === 'appearance' && <AppearanceSettings />}+ {activeTab === 'notifications' && <NotificationSettings />}+ {activeTab === 'system' && <SystemInfo />}+ {activeTab === 'about' && <AboutSection />}+ </div>+ </div>+ </div>+ );+};++const ProfileSettings = () => {+ const { user, updateUser } = useAuth();+ const [formData, setFormData] = useState({+ username: '',+ email: ''+ });+ const [loading, setLoading] = useState(false);+ const [message, setMessage] = useState(null);++ useEffect(() => {+ if (user) {+ setFormData({+ username: user.username || '',+ email: user.email || ''+ });+ }+ }, [user]);++ async function handleSubmit(e) {+ e.preventDefault();+ setLoading(true);+ setMessage(null);++ try {+ await updateUser(formData);+ setMessage({ type: 'success', text: 'Profile updated successfully' });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setLoading(false);+ }+ }++ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>Profile Settings</h2>+ <p>Update your personal information</p>+ </div>++ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <form onSubmit={handleSubmit} className="settings-form">+ <div className="form-group">+ <label>Username</label>+ <input+ type="text"+ value={formData.username}+ onChange={(e) => setFormData({ ...formData, username: e.target.value })}+ required+ />+ </div>++ <div className="form-group">+ <label>Email Address</label>+ <input+ type="email"+ value={formData.email}+ onChange={(e) => setFormData({ ...formData, email: e.target.value })}+ required+ />+ </div>++ <div className="form-group">+ <label>Role</label>+ <input type="text" value={user?.role || 'user'} disabled className="input-disabled" />+ <span className="form-help">Contact an administrator to change your role</span>+ </div>++ <div className="form-group">+ <label>Member Since</label>+ <input+ type="text"+ value={user?.created_at ? new Date(user.created_at).toLocaleDateString() : '-'}+ disabled+ className="input-disabled"+ />+ </div>++ <div className="form-actions">+ <button type="submit" className="btn btn-primary" disabled={loading}>+ {loading ? 'Saving...' : 'Save Changes'}+ </button>+ </div>+ </form>+ </div>+ );+};++const SecuritySettings = () => {+ const { updateUser } = useAuth();+ const [formData, setFormData] = useState({+ currentPassword: '',+ newPassword: '',+ confirmPassword: ''+ });+ const [loading, setLoading] = useState(false);+ const [message, setMessage] = useState(null);++ async function handleSubmit(e) {+ e.preventDefault();+ setMessage(null);++ if (formData.newPassword !== formData.confirmPassword) {+ setMessage({ type: 'error', text: 'Passwords do not match' });+ return;+ }++ if (formData.newPassword.length < 8) {+ setMessage({ type: 'error', text: 'Password must be at least 8 characters' });+ return;+ }++ setLoading(true);++ try {+ await updateUser({ password: formData.newPassword });+ setMessage({ type: 'success', text: 'Password changed successfully' });+ setFormData({ currentPassword: '', newPassword: '', confirmPassword: '' });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setLoading(false);+ }+ }++ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>Security Settings</h2>+ <p>Manage your password and security preferences</p>+ </div>++ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <form onSubmit={handleSubmit} className="settings-form">+ <h3>Change Password</h3>++ <div className="form-group">+ <label>Current Password</label>+ <input+ type="password"+ value={formData.currentPassword}+ onChange={(e) => setFormData({ ...formData, currentPassword: e.target.value })}+ placeholder="Enter current password"+ />+ </div>++ <div className="form-group">+ <label>New Password</label>+ <input+ type="password"+ value={formData.newPassword}+ onChange={(e) => setFormData({ ...formData, newPassword: e.target.value })}+ placeholder="Enter new password"+ required+ />+ <span className="form-help">Minimum 8 characters</span>+ </div>++ <div className="form-group">+ <label>Confirm New Password</label>+ <input+ type="password"+ value={formData.confirmPassword}+ onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}+ placeholder="Confirm new password"+ required+ />+ </div>++ <div className="form-actions">+ <button type="submit" className="btn btn-primary" disabled={loading}>+ {loading ? 'Changing...' : 'Change Password'}+ </button>+ </div>+ </form>++ <div className="settings-card">+ <h3>Sessions</h3>+ <p>Manage your active sessions</p>+ <div className="session-item current">+ <div className="session-info">+ <svg viewBox="0 0 24 24" width="20" height="20">+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>+ <line x1="8" y1="21" x2="16" y2="21"/>+ <line x1="12" y1="17" x2="12" y2="21"/>+ </svg>+ <div>+ <span className="session-device">Current Session</span>+ <span className="session-details">This device - Active now</span>+ </div>+ </div>+ <span className="badge badge-success">Current</span>+ </div>+ </div>+ </div>+ );+};++const AppearanceSettings = () => {+ const [theme, setTheme] = useState(() => {+ return localStorage.getItem('theme') || 'dark';+ });++ function handleThemeChange(newTheme) {+ setTheme(newTheme);+ localStorage.setItem('theme', newTheme);+ document.documentElement.setAttribute('data-theme', newTheme);+ }++ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>Appearance</h2>+ <p>Customize the look and feel of your dashboard</p>+ </div>++ <div className="settings-card">+ <h3>Theme</h3>+ <p>Select your preferred color scheme</p>+ <div className="theme-options">+ <button+ className={`theme-option ${theme === 'dark' ? 'active' : ''}`}+ onClick={() => handleThemeChange('dark')}+ >+ <div className="theme-preview dark">+ <div className="preview-sidebar"></div>+ <div className="preview-content">+ <div className="preview-card"></div>+ <div className="preview-card"></div>+ </div>+ </div>+ <span>Dark</span>+ </button>+ <button+ className={`theme-option ${theme === 'light' ? 'active' : ''}`}+ onClick={() => handleThemeChange('light')}+ >+ <div className="theme-preview light">+ <div className="preview-sidebar"></div>+ <div className="preview-content">+ <div className="preview-card"></div>+ <div className="preview-card"></div>+ </div>+ </div>+ <span>Light</span>+ </button>+ <button+ className={`theme-option ${theme === 'system' ? 'active' : ''}`}+ onClick={() => handleThemeChange('system')}+ >+ <div className="theme-preview system">+ <div className="preview-sidebar"></div>+ <div className="preview-content">+ <div className="preview-card"></div>+ <div className="preview-card"></div>+ </div>+ </div>+ <span>System</span>+ </button>+ </div>+ </div>++ <div className="settings-card">+ <h3>Density</h3>+ <p>Adjust the spacing and size of elements</p>+ <div className="density-options">+ <label className="radio-option">+ <input type="radio" name="density" value="comfortable" defaultChecked />+ <span>Comfortable</span>+ </label>+ <label className="radio-option">+ <input type="radio" name="density" value="compact" />+ <span>Compact</span>+ </label>+ </div>+ </div>+ </div>+ );+};++const NotificationSettings = () => {+ const [settings, setSettings] = useState({+ emailAlerts: true,+ serverAlerts: true,+ securityAlerts: true,+ backupAlerts: false,+ deployAlerts: true+ });++ function handleToggle(key) {+ setSettings({ ...settings, [key]: !settings[key] });+ }++ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>Notification Settings</h2>+ <p>Choose what notifications you want to receive</p>+ </div>++ <div className="settings-card">+ <h3>Email Notifications</h3>+ <div className="notification-options">+ <div className="notification-item">+ <div className="notification-info">+ <span className="notification-title">Server Alerts</span>+ <span className="notification-desc">Get notified when server metrics exceed thresholds</span>+ </div>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={settings.serverAlerts}+ onChange={() => handleToggle('serverAlerts')}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>++ <div className="notification-item">+ <div className="notification-info">+ <span className="notification-title">Security Alerts</span>+ <span className="notification-desc">Get notified about security events and login attempts</span>+ </div>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={settings.securityAlerts}+ onChange={() => handleToggle('securityAlerts')}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>++ <div className="notification-item">+ <div className="notification-info">+ <span className="notification-title">Backup Notifications</span>+ <span className="notification-desc">Get notified when backups complete or fail</span>+ </div>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={settings.backupAlerts}+ onChange={() => handleToggle('backupAlerts')}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>++ <div className="notification-item">+ <div className="notification-info">+ <span className="notification-title">Deployment Notifications</span>+ <span className="notification-desc">Get notified when deployments complete or fail</span>+ </div>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={settings.deployAlerts}+ onChange={() => handleToggle('deployAlerts')}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>+ </div>+ </div>+ </div>+ );+};++const SystemInfo = () => {+ const { isAdmin } = useAuth();+ const [metrics, setMetrics] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ if (isAdmin) {+ loadMetrics();+ }+ }, [isAdmin]);++ async function loadMetrics() {+ try {+ const data = await api.getSystemMetrics();+ setMetrics(data);+ } catch (err) {+ console.error('Failed to load metrics:', err);+ } finally {+ setLoading(false);+ }+ }++ if (!isAdmin) {+ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>System Information</h2>+ <p>View system details and server information</p>+ </div>+ <div className="alert alert-warning">+ Admin access required to view system information.+ </div>+ </div>+ );+ }++ if (loading) {+ return <div className="loading">Loading system information...</div>;+ }++ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>System Information</h2>+ <p>View system details and server information</p>+ </div>++ <div className="system-info-grid">+ <div className="settings-card">+ <h3>CPU</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Usage</span>+ <span className="info-value">{metrics?.cpu?.percent?.toFixed(1) || 0}%</span>+ </div>+ <div className="info-item">+ <span className="info-label">Cores</span>+ <span className="info-value">{metrics?.cpu?.count || '-'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Load Average</span>+ <span className="info-value">+ {metrics?.cpu?.load_avg ? metrics.cpu.load_avg.map(l => l.toFixed(2)).join(', ') : '-'}+ </span>+ </div>+ </div>+ </div>++ <div className="settings-card">+ <h3>Memory</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Usage</span>+ <span className="info-value">{metrics?.memory?.percent?.toFixed(1) || 0}%</span>+ </div>+ <div className="info-item">+ <span className="info-label">Used</span>+ <span className="info-value">{formatBytes(metrics?.memory?.used)}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Total</span>+ <span className="info-value">{formatBytes(metrics?.memory?.total)}</span>+ </div>+ </div>+ </div>++ <div className="settings-card">+ <h3>Disk</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Usage</span>+ <span className="info-value">{metrics?.disk?.percent?.toFixed(1) || 0}%</span>+ </div>+ <div className="info-item">+ <span className="info-label">Used</span>+ <span className="info-value">{formatBytes(metrics?.disk?.used)}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Total</span>+ <span className="info-value">{formatBytes(metrics?.disk?.total)}</span>+ </div>+ </div>+ </div>++ <div className="settings-card">+ <h3>Network</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Bytes Sent</span>+ <span className="info-value">{formatBytes(metrics?.network?.bytes_sent)}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Bytes Received</span>+ <span className="info-value">{formatBytes(metrics?.network?.bytes_recv)}</span>+ </div>+ </div>+ </div>+ </div>++ {metrics?.system && (+ <div className="settings-card">+ <h3>System Details</h3>+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Hostname</span>+ <span className="info-value">{metrics.system.hostname || '-'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Platform</span>+ <span className="info-value">{metrics.system.platform || '-'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">OS Version</span>+ <span className="info-value">{metrics.system.version || '-'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Uptime</span>+ <span className="info-value">{formatUptime(metrics.system.uptime)}</span>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++const AboutSection = () => {+ return (+ <div className="settings-section">+ <div className="section-header">+ <h2>About ServerKit</h2>+ <p>Server management made simple</p>+ </div>++ <div className="about-card">+ <div className="about-logo">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1.5">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ </div>+ <h3>ServerKit</h3>+ <p className="version">Version 1.0.0</p>+ <p className="description">+ A modern, lightweight server management panel for managing web applications,+ databases, domains, and more. Built with Flask and React.+ </p>+ </div>++ <div className="settings-card">+ <h3>Features</h3>+ <ul className="feature-list">+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Application Management (PHP, Python, Node.js, Docker)+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Domain & SSL Certificate Management+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Database Management (MySQL, PostgreSQL)+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Docker Container Management+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ System Monitoring & Alerts+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Automated Backups+ </li>+ <li>+ <svg viewBox="0 0 24 24" width="16" height="16"><polyline points="20 6 9 17 4 12"/></svg>+ Git Deployment with Webhooks+ </li>+ </ul>+ </div>++ <div className="settings-card">+ <h3>Links</h3>+ <div className="link-list">+ <a href="https://github.com/serverkit" target="_blank" rel="noopener noreferrer" className="link-item">+ <svg viewBox="0 0 24 24" width="18" height="18">+ <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>+ </svg>+ GitHub Repository+ </a>+ <a href="#" className="link-item">+ <svg viewBox="0 0 24 24" width="18" height="18">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ </svg>+ Documentation+ </a>+ <a href="#" className="link-item">+ <svg viewBox="0 0 24 24" width="18" height="18">+ <circle cx="12" cy="12" r="10"/>+ <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>+ <line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ Support+ </a>+ </div>+ </div>++ <div className="settings-card">+ <h3>License</h3>+ <p className="license-text">+ ServerKit is open source software licensed under the MIT License.+ </p>+ </div>+ </div>+ );+};++// Helper functions+function formatBytes(bytes) {+ if (!bytes) return '-';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ let i = 0;+ while (bytes >= 1024 && i < units.length - 1) {+ bytes /= 1024;+ i++;+ }+ return `${bytes.toFixed(1)} ${units[i]}`;+}++function formatUptime(seconds) {+ if (!seconds) return '-';+ const days = Math.floor(seconds / 86400);+ const hours = Math.floor((seconds % 86400) / 3600);+ const minutes = Math.floor((seconds % 3600) / 60);++ const parts = [];+ if (days > 0) parts.push(`${days}d`);+ if (hours > 0) parts.push(`${hours}h`);+ if (minutes > 0) parts.push(`${minutes}m`);++ return parts.join(' ') || '< 1m';+}++export default Settings;diff --git a/frontend/src/pages/Terminal.jsx b/frontend/src/pages/Terminal.jsxnew file mode 100644index 00000000..e0fb2792--- /dev/null+++ b/frontend/src/pages/Terminal.jsx@@ -0,0 +1,836 @@+import React, { useState, useEffect, useRef } from 'react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const Terminal = () => {+ const [activeTab, setActiveTab] = useState('logs');++ return (+ <div className="page terminal-page">+ <div className="page-header">+ <div>+ <h1>Terminal & Logs</h1>+ <p className="page-subtitle">View logs, manage processes and services</p>+ </div>+ </div>++ <div className="tabs">+ <button+ className={`tab ${activeTab === 'logs' ? 'active' : ''}`}+ onClick={() => setActiveTab('logs')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ <line x1="16" y1="13" x2="8" y2="13"/>+ <line x1="16" y1="17" x2="8" y2="17"/>+ </svg>+ Log Files+ </button>+ <button+ className={`tab ${activeTab === 'journal' ? 'active' : ''}`}+ onClick={() => setActiveTab('journal')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16">+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>+ <line x1="9" y1="9" x2="15" y2="9"/>+ <line x1="9" y1="13" x2="15" y2="13"/>+ <line x1="9" y1="17" x2="11" y2="17"/>+ </svg>+ System Journal+ </button>+ <button+ className={`tab ${activeTab === 'processes' ? 'active' : ''}`}+ onClick={() => setActiveTab('processes')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16">+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>+ <line x1="8" y1="21" x2="16" y2="21"/>+ <line x1="12" y1="17" x2="12" y2="21"/>+ </svg>+ Processes+ </button>+ <button+ className={`tab ${activeTab === 'services' ? 'active' : ''}`}+ onClick={() => setActiveTab('services')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16">+ <circle cx="12" cy="12" r="3"/>+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>+ </svg>+ Services+ </button>+ </div>++ <div className="tab-content">+ {activeTab === 'logs' && <LogFilesTab />}+ {activeTab === 'journal' && <JournalTab />}+ {activeTab === 'processes' && <ProcessesTab />}+ {activeTab === 'services' && <ServicesTab />}+ </div>+ </div>+ );+};++const LogFilesTab = () => {+ const [logFiles, setLogFiles] = useState([]);+ const [selectedLog, setSelectedLog] = useState(null);+ const [logContent, setLogContent] = useState('');+ const [loading, setLoading] = useState(true);+ const [loadingContent, setLoadingContent] = useState(false);+ const [error, setError] = useState(null);+ const [lineCount, setLineCount] = useState(100);+ const [searchPattern, setSearchPattern] = useState('');+ const [autoRefresh, setAutoRefresh] = useState(false);+ const logViewerRef = useRef(null);+ const intervalRef = useRef(null);++ useEffect(() => {+ loadLogFiles();+ }, []);++ useEffect(() => {+ if (autoRefresh && selectedLog) {+ intervalRef.current = setInterval(() => {+ loadLogContent(selectedLog, false);+ }, 3000);+ }+ return () => {+ if (intervalRef.current) {+ clearInterval(intervalRef.current);+ }+ };+ }, [autoRefresh, selectedLog]);++ async function loadLogFiles() {+ try {+ const data = await api.getLogFiles();+ setLogFiles(data.logs || []);+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ async function loadLogContent(logPath, showLoading = true) {+ if (showLoading) setLoadingContent(true);+ try {+ let data;+ if (searchPattern.trim()) {+ data = await api.searchLog(logPath, searchPattern, lineCount);+ } else {+ data = await api.readLog(logPath, lineCount);+ }+ setLogContent(data.content || data.lines?.join('\n') || 'No content');+ setSelectedLog(logPath);++ // Scroll to bottom+ if (logViewerRef.current) {+ logViewerRef.current.scrollTop = logViewerRef.current.scrollHeight;+ }+ } catch (err) {+ setLogContent(`Error loading log: ${err.message}`);+ } finally {+ setLoadingContent(false);+ }+ }++ async function handleClearLog() {+ if (!selectedLog) return;+ if (!confirm(`Clear ${selectedLog}? This cannot be undone.`)) return;++ try {+ await api.clearLog(selectedLog);+ setLogContent('Log cleared.');+ } catch (err) {+ setError(err.message);+ }+ }++ function handleDownload() {+ if (!logContent) return;+ const blob = new Blob([logContent], { type: 'text/plain' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = selectedLog ? selectedLog.split('/').pop() : 'log.txt';+ a.click();+ URL.revokeObjectURL(url);+ }++ function getLogIcon(path) {+ if (path.includes('error')) return 'error';+ if (path.includes('access')) return 'access';+ if (path.includes('nginx')) return 'nginx';+ if (path.includes('mysql') || path.includes('postgres')) return 'database';+ return 'default';+ }++ function formatFileSize(bytes) {+ if (!bytes) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB'];+ let i = 0;+ while (bytes >= 1024 && i < units.length - 1) {+ bytes /= 1024;+ i++;+ }+ return `${bytes.toFixed(1)} ${units[i]}`;+ }++ if (loading) {+ return <div className="loading">Loading log files...</div>;+ }++ return (+ <div className="logs-container">+ {error && (+ <div className="alert alert-danger">+ {error}+ <button onClick={() => setError(null)} className="alert-close">×</button>+ </div>+ )}++ <div className="logs-layout">+ <div className="logs-sidebar">+ <div className="sidebar-header">+ <h3>Log Files</h3>+ <button className="btn btn-secondary btn-sm" onClick={loadLogFiles}>+ <svg viewBox="0 0 24 24" width="14" height="14">+ <polyline points="23 4 23 10 17 10"/>+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>+ </svg>+ </button>+ </div>+ <div className="log-files-list">+ {logFiles.length === 0 ? (+ <div className="empty-hint">No log files found</div>+ ) : (+ logFiles.map((log, index) => (+ <div+ key={index}+ className={`log-file-item ${selectedLog === log.path ? 'active' : ''}`}+ onClick={() => loadLogContent(log.path)}+ >+ <div className={`log-icon ${getLogIcon(log.path)}`}>+ <svg viewBox="0 0 24 24" width="16" height="16">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ </svg>+ </div>+ <div className="log-file-info">+ <span className="log-file-name">{log.name}</span>+ <span className="log-file-path">{log.path}</span>+ </div>+ <span className="log-file-size">{formatFileSize(log.size)}</span>+ </div>+ ))+ )}+ </div>+ </div>++ <div className="logs-viewer">+ <div className="viewer-toolbar">+ <div className="toolbar-left">+ <div className="search-input">+ <svg viewBox="0 0 24 24" width="16" height="16">+ <circle cx="11" cy="11" r="8"/>+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>+ </svg>+ <input+ type="text"+ value={searchPattern}+ onChange={(e) => setSearchPattern(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && selectedLog && loadLogContent(selectedLog)}+ placeholder="Search pattern..."+ />+ </div>+ <select+ value={lineCount}+ onChange={(e) => setLineCount(parseInt(e.target.value))}+ className="lines-select"+ >+ <option value={50}>50 lines</option>+ <option value={100}>100 lines</option>+ <option value={200}>200 lines</option>+ <option value={500}>500 lines</option>+ <option value={1000}>1000 lines</option>+ </select>+ </div>+ <div className="toolbar-right">+ <label className="auto-refresh-toggle">+ <input+ type="checkbox"+ checked={autoRefresh}+ onChange={(e) => setAutoRefresh(e.target.checked)}+ />+ <span>Auto-refresh</span>+ </label>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => selectedLog && loadLogContent(selectedLog)}+ disabled={!selectedLog || loadingContent}+ >+ Refresh+ </button>+ <button+ className="btn btn-secondary btn-sm"+ onClick={handleDownload}+ disabled={!logContent}+ >+ Download+ </button>+ <button+ className="btn btn-danger btn-sm"+ onClick={handleClearLog}+ disabled={!selectedLog}+ >+ Clear+ </button>+ </div>+ </div>++ <div className="log-content" ref={logViewerRef}>+ {!selectedLog ? (+ <div className="empty-viewer">+ <svg viewBox="0 0 24 24" width="48" height="48">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ </svg>+ <p>Select a log file to view its contents</p>+ </div>+ ) : loadingContent ? (+ <div className="loading">Loading log content...</div>+ ) : (+ <pre>{logContent}</pre>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++const JournalTab = () => {+ const [logs, setLogs] = useState('');+ const [loading, setLoading] = useState(false);+ const [unit, setUnit] = useState('');+ const [lineCount, setLineCount] = useState(100);+ const [priority, setPriority] = useState('');+ const [commonUnits] = useState([+ 'nginx', 'apache2', 'mysql', 'mariadb', 'postgresql',+ 'php-fpm', 'docker', 'sshd', 'cron', 'systemd'+ ]);++ async function loadJournalLogs() {+ setLoading(true);+ try {+ const data = await api.getJournalLogs(unit || null, lineCount);+ setLogs(data.content || data.logs || 'No logs available');+ } catch (err) {+ setLogs(`Error: ${err.message}`);+ } finally {+ setLoading(false);+ }+ }++ useEffect(() => {+ loadJournalLogs();+ }, []);++ return (+ <div className="journal-container">+ <div className="journal-controls">+ <div className="control-group">+ <label>Service/Unit</label>+ <div className="input-with-suggestions">+ <input+ type="text"+ value={unit}+ onChange={(e) => setUnit(e.target.value)}+ placeholder="All services"+ />+ <div className="quick-units">+ {commonUnits.map(u => (+ <button+ key={u}+ className={`unit-chip ${unit === u ? 'active' : ''}`}+ onClick={() => setUnit(unit === u ? '' : u)}+ >+ {u}+ </button>+ ))}+ </div>+ </div>+ </div>++ <div className="control-group">+ <label>Lines</label>+ <select value={lineCount} onChange={(e) => setLineCount(parseInt(e.target.value))}>+ <option value={50}>50</option>+ <option value={100}>100</option>+ <option value={200}>200</option>+ <option value={500}>500</option>+ </select>+ </div>++ <div className="control-group">+ <label>Priority</label>+ <select value={priority} onChange={(e) => setPriority(e.target.value)}>+ <option value="">All</option>+ <option value="0">Emergency</option>+ <option value="1">Alert</option>+ <option value="2">Critical</option>+ <option value="3">Error</option>+ <option value="4">Warning</option>+ <option value="5">Notice</option>+ <option value="6">Info</option>+ <option value="7">Debug</option>+ </select>+ </div>++ <button className="btn btn-primary" onClick={loadJournalLogs} disabled={loading}>+ {loading ? 'Loading...' : 'Load Logs'}+ </button>+ </div>++ <div className="journal-viewer">+ <pre>{loading ? 'Loading journal logs...' : logs}</pre>+ </div>+ </div>+ );+};++const ProcessesTab = () => {+ const toast = useToast();+ const [processes, setProcesses] = useState([]);+ const [loading, setLoading] = useState(true);+ const [sortBy, setSortBy] = useState('cpu');+ const [limit, setLimit] = useState(50);+ const [searchTerm, setSearchTerm] = useState('');+ const [selectedProcess, setSelectedProcess] = useState(null);++ useEffect(() => {+ loadProcesses();+ }, [sortBy, limit]);++ async function loadProcesses() {+ try {+ const data = await api.getProcesses(limit, sortBy);+ setProcesses(data.processes || []);+ } catch (err) {+ console.error('Failed to load processes:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleKillProcess(pid, force = false) {+ const confirmMsg = force+ ? `Force kill process ${pid}? This may cause data loss.`+ : `Kill process ${pid}?`;+ if (!confirm(confirmMsg)) return;++ try {+ await api.killProcess(pid, force);+ toast.success(`Process ${pid} killed successfully`);+ loadProcesses();+ setSelectedProcess(null);+ } catch (err) {+ toast.error(`Failed to kill process: ${err.message}`);+ }+ }++ const filteredProcesses = processes.filter(p =>+ p.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||+ p.command?.toLowerCase().includes(searchTerm.toLowerCase()) ||+ String(p.pid).includes(searchTerm)+ );++ if (loading) {+ return <div className="loading">Loading processes...</div>;+ }++ return (+ <div className="processes-container">+ <div className="processes-toolbar">+ <div className="toolbar-left">+ <div className="search-input">+ <svg viewBox="0 0 24 24" width="16" height="16">+ <circle cx="11" cy="11" r="8"/>+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>+ </svg>+ <input+ type="text"+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ placeholder="Search processes..."+ />+ </div>+ </div>+ <div className="toolbar-right">+ <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>+ <option value="cpu">Sort by CPU</option>+ <option value="memory">Sort by Memory</option>+ <option value="pid">Sort by PID</option>+ <option value="name">Sort by Name</option>+ </select>+ <select value={limit} onChange={(e) => setLimit(parseInt(e.target.value))}>+ <option value={25}>25 processes</option>+ <option value={50}>50 processes</option>+ <option value={100}>100 processes</option>+ </select>+ <button className="btn btn-secondary btn-sm" onClick={loadProcesses}>+ Refresh+ </button>+ </div>+ </div>++ <div className="processes-table-wrapper">+ <table className="table processes-table">+ <thead>+ <tr>+ <th>PID</th>+ <th>Name</th>+ <th>User</th>+ <th>CPU %</th>+ <th>Memory %</th>+ <th>Memory</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {filteredProcesses.map(process => (+ <tr+ key={process.pid}+ className={selectedProcess?.pid === process.pid ? 'selected' : ''}+ onClick={() => setSelectedProcess(process)}+ >+ <td className="mono">{process.pid}</td>+ <td>+ <div className="process-name">+ <span>{process.name}</span>+ </div>+ </td>+ <td>{process.user}</td>+ <td>+ <div className="usage-cell">+ <div+ className="usage-bar cpu"+ style={{ width: `${Math.min(process.cpu_percent || 0, 100)}%` }}+ />+ <span>{(process.cpu_percent || 0).toFixed(1)}%</span>+ </div>+ </td>+ <td>+ <div className="usage-cell">+ <div+ className="usage-bar memory"+ style={{ width: `${Math.min(process.memory_percent || 0, 100)}%` }}+ />+ <span>{(process.memory_percent || 0).toFixed(1)}%</span>+ </div>+ </td>+ <td>{formatMemory(process.memory_info?.rss)}</td>+ <td>+ <span className={`badge badge-${getStatusClass(process.status)}`}>+ {process.status}+ </span>+ </td>+ <td>+ <div className="action-buttons">+ <button+ className="btn btn-secondary btn-xs"+ onClick={(e) => {+ e.stopPropagation();+ handleKillProcess(process.pid);+ }}+ title="Kill"+ >+ <svg viewBox="0 0 24 24" width="12" height="12">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ <button+ className="btn btn-danger btn-xs"+ onClick={(e) => {+ e.stopPropagation();+ handleKillProcess(process.pid, true);+ }}+ title="Force Kill"+ >+ <svg viewBox="0 0 24 24" width="12" height="12">+ <polygon points="7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"/>+ <line x1="15" y1="9" x2="9" y2="15"/>+ <line x1="9" y1="9" x2="15" y2="15"/>+ </svg>+ </button>+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ {selectedProcess && (+ <div className="process-details-panel">+ <div className="panel-header">+ <h3>Process Details</h3>+ <button className="btn btn-secondary btn-sm" onClick={() => setSelectedProcess(null)}>+ Close+ </button>+ </div>+ <div className="panel-body">+ <div className="details-grid">+ <div className="detail-item">+ <span className="detail-label">PID</span>+ <span className="detail-value mono">{selectedProcess.pid}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">Name</span>+ <span className="detail-value">{selectedProcess.name}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">User</span>+ <span className="detail-value">{selectedProcess.user}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">Status</span>+ <span className="detail-value">{selectedProcess.status}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">CPU</span>+ <span className="detail-value">{(selectedProcess.cpu_percent || 0).toFixed(2)}%</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">Memory</span>+ <span className="detail-value">{formatMemory(selectedProcess.memory_info?.rss)}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">Threads</span>+ <span className="detail-value">{selectedProcess.num_threads}</span>+ </div>+ <div className="detail-item">+ <span className="detail-label">Created</span>+ <span className="detail-value">+ {selectedProcess.create_time+ ? new Date(selectedProcess.create_time * 1000).toLocaleString()+ : '-'}+ </span>+ </div>+ </div>+ {selectedProcess.command && (+ <div className="command-line">+ <span className="detail-label">Command</span>+ <code>{selectedProcess.command}</code>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );+};++const ServicesTab = () => {+ const toast = useToast();+ const [services, setServices] = useState([]);+ const [loading, setLoading] = useState(true);+ const [actionLoading, setActionLoading] = useState(null);+ const [selectedService, setSelectedService] = useState(null);+ const [serviceLogs, setServiceLogs] = useState('');+ const [showLogsModal, setShowLogsModal] = useState(false);++ useEffect(() => {+ loadServices();+ }, []);++ async function loadServices() {+ try {+ const data = await api.getServicesStatus();+ setServices(data.services || []);+ } catch (err) {+ console.error('Failed to load services:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleServiceAction(serviceName, action) {+ setActionLoading(`${serviceName}-${action}`);+ try {+ await api.controlService(serviceName, action);+ toast.success(`Service ${serviceName} ${action}ed successfully`);+ await loadServices();+ } catch (err) {+ toast.error(`Failed to ${action} ${serviceName}: ${err.message}`);+ } finally {+ setActionLoading(null);+ }+ }++ async function viewServiceLogs(serviceName) {+ setSelectedService(serviceName);+ setShowLogsModal(true);+ try {+ const data = await api.getJournalLogs(serviceName, 100);+ setServiceLogs(data.content || data.logs || 'No logs available');+ } catch (err) {+ setServiceLogs(`Error loading logs: ${err.message}`);+ }+ }++ function getServiceStatusClass(status) {+ if (status === 'running' || status === 'active') return 'success';+ if (status === 'stopped' || status === 'inactive') return 'secondary';+ if (status === 'failed') return 'danger';+ return 'warning';+ }++ if (loading) {+ return <div className="loading">Loading services...</div>;+ }++ return (+ <div className="services-container">+ <div className="services-toolbar">+ <button className="btn btn-secondary btn-sm" onClick={loadServices}>+ <svg viewBox="0 0 24 24" width="14" height="14">+ <polyline points="23 4 23 10 17 10"/>+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>+ </svg>+ Refresh+ </button>+ </div>++ <div className="services-grid">+ {services.length === 0 ? (+ <div className="empty-state">+ <p>No services found</p>+ </div>+ ) : (+ services.map(service => (+ <div key={service.name} className="service-card">+ <div className="service-header">+ <div className="service-info">+ <span className={`status-dot ${getServiceStatusClass(service.status)}`} />+ <h4>{service.name}</h4>+ </div>+ <span className={`badge badge-${getServiceStatusClass(service.status)}`}>+ {service.status}+ </span>+ </div>++ {service.description && (+ <p className="service-description">{service.description}</p>+ )}++ <div className="service-meta">+ {service.pid && (+ <span className="meta-item">+ <span className="meta-label">PID:</span> {service.pid}+ </span>+ )}+ {service.memory && (+ <span className="meta-item">+ <span className="meta-label">Memory:</span> {service.memory}+ </span>+ )}+ </div>++ <div className="service-actions">+ {service.status === 'running' || service.status === 'active' ? (+ <>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleServiceAction(service.name, 'restart')}+ disabled={actionLoading === `${service.name}-restart`}+ >+ {actionLoading === `${service.name}-restart` ? '...' : 'Restart'}+ </button>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => handleServiceAction(service.name, 'stop')}+ disabled={actionLoading === `${service.name}-stop`}+ >+ {actionLoading === `${service.name}-stop` ? '...' : 'Stop'}+ </button>+ </>+ ) : (+ <button+ className="btn btn-primary btn-sm"+ onClick={() => handleServiceAction(service.name, 'start')}+ disabled={actionLoading === `${service.name}-start`}+ >+ {actionLoading === `${service.name}-start` ? '...' : 'Start'}+ </button>+ )}+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => viewServiceLogs(service.name)}+ >+ Logs+ </button>+ </div>+ </div>+ ))+ )}+ </div>++ {/* Service Logs Modal */}+ {showLogsModal && (+ <div className="modal-overlay" onClick={() => setShowLogsModal(false)}>+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Logs: {selectedService}</h2>+ <button className="modal-close" onClick={() => setShowLogsModal(false)}>×</button>+ </div>+ <div className="modal-body">+ <div className="modal-log-viewer">+ <pre>{serviceLogs}</pre>+ </div>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowLogsModal(false)}>+ Close+ </button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++// Helper functions+function formatMemory(bytes) {+ if (!bytes) return '-';+ const units = ['B', 'KB', 'MB', 'GB'];+ let i = 0;+ while (bytes >= 1024 && i < units.length - 1) {+ bytes /= 1024;+ i++;+ }+ return `${bytes.toFixed(1)} ${units[i]}`;+}++function getStatusClass(status) {+ switch (status?.toLowerCase()) {+ case 'running':+ case 'sleeping':+ return 'success';+ case 'stopped':+ case 'zombie':+ return 'danger';+ case 'idle':+ case 'disk-sleep':+ return 'warning';+ default:+ return 'secondary';+ }+}++export default Terminal;diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 5b7289e8..942f478e 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -117,6 +117,13 @@ class ApiService {return this.request('/auth/me');}+ async updateCurrentUser(data) {+ return this.request('/auth/me', {+ method: 'PUT',+ body: data+ });+ }+// Apps endpointsasync getApps() {return this.request('/apps');@@ -187,8 +194,31 @@ class ApiService {});}- async enableSsl(domainId) {- return this.request(`/domains/${domainId}/ssl/enable`, { method: 'POST' });+ async enableSsl(domainId, email) {+ return this.request(`/domains/${domainId}/ssl/enable`, {+ method: 'POST',+ body: { email }+ });+ }++ async disableSsl(domainId) {+ return this.request(`/domains/${domainId}/ssl/disable`, { method: 'POST' });+ }++ async renewDomainSsl(domainId) {+ return this.request(`/domains/${domainId}/ssl/renew`, { method: 'POST' });+ }++ async verifyDomain(domainId) {+ return this.request(`/domains/${domainId}/verify`);+ }++ async getDomainsNginxSites() {+ return this.request('/domains/nginx/sites');+ }++ async getDomainsSslStatus() {+ return this.request('/domains/ssl/status');}// System endpoints@@ -927,6 +957,209 @@ class ApiService {async generateDatabasePassword(length = 16) {return this.request(`/databases/generate-password?length=${length}`);}++ // ========================================+ // Monitoring & Alerts endpoints+ // ========================================+ async getMonitoringStatus() {+ return this.request('/monitoring/status');+ }++ async getMonitoringMetrics() {+ return this.request('/monitoring/metrics');+ }++ async checkAlerts() {+ return this.request('/monitoring/alerts/check');+ }++ async getAlertHistory(limit = 100) {+ return this.request(`/monitoring/alerts/history?limit=${limit}`);+ }++ async getMonitoringConfig() {+ return this.request('/monitoring/config');+ }++ async updateMonitoringConfig(config) {+ return this.request('/monitoring/config', {+ method: 'PUT',+ body: config+ });+ }++ async getMonitoringThresholds() {+ return this.request('/monitoring/thresholds');+ }++ async updateMonitoringThresholds(thresholds) {+ return this.request('/monitoring/thresholds', {+ method: 'PUT',+ body: thresholds+ });+ }++ async startMonitoring() {+ return this.request('/monitoring/start', { method: 'POST' });+ }++ async stopMonitoring() {+ return this.request('/monitoring/stop', { method: 'POST' });+ }++ async testEmailAlert(email) {+ return this.request('/monitoring/test/email', {+ method: 'POST',+ body: { email }+ });+ }++ async testWebhookAlert(webhookUrl) {+ return this.request('/monitoring/test/webhook', {+ method: 'POST',+ body: { webhook_url: webhookUrl }+ });+ }++ // ========================================+ // Backup System endpoints+ // ========================================+ async getBackups(type = null) {+ const params = type ? `?type=${type}` : '';+ return this.request(`/backups${params}`);+ }++ async getBackupStats() {+ return this.request('/backups/stats');+ }++ async getBackupConfig() {+ return this.request('/backups/config');+ }++ async updateBackupConfig(config) {+ return this.request('/backups/config', {+ method: 'PUT',+ body: config+ });+ }++ async backupApplication(applicationId, includeDb = false, dbConfig = null) {+ return this.request('/backups/application', {+ method: 'POST',+ body: {+ application_id: applicationId,+ include_db: includeDb,+ db_config: dbConfig+ }+ });+ }++ async backupDatabase(dbType, dbName, user = null, password = null, host = 'localhost') {+ return this.request('/backups/database', {+ method: 'POST',+ body: { db_type: dbType, db_name: dbName, user, password, host }+ });+ }++ async restoreApplication(backupPath, restorePath = null) {+ return this.request('/backups/restore/application', {+ method: 'POST',+ body: { backup_path: backupPath, restore_path: restorePath }+ });+ }++ async restoreDatabase(backupPath, dbType, dbName, user = null, password = null, host = 'localhost') {+ return this.request('/backups/restore/database', {+ method: 'POST',+ body: { backup_path: backupPath, db_type: dbType, db_name: dbName, user, password, host }+ });+ }++ async deleteBackup(backupPath) {+ return this.request(`/backups/${encodeURIComponent(backupPath)}`, { method: 'DELETE' });+ }++ async cleanupBackups(retentionDays = null) {+ return this.request('/backups/cleanup', {+ method: 'POST',+ body: retentionDays ? { retention_days: retentionDays } : {}+ });+ }++ async getBackupSchedules() {+ return this.request('/backups/schedules');+ }++ async addBackupSchedule(name, backupType, target, scheduleTime, days = null) {+ return this.request('/backups/schedules', {+ method: 'POST',+ body: { name, backup_type: backupType, target, schedule_time: scheduleTime, days }+ });+ }++ async removeBackupSchedule(scheduleId) {+ return this.request(`/backups/schedules/${scheduleId}`, { method: 'DELETE' });+ }++ // ========================================+ // Git Deployment endpoints+ // ========================================+ async getDeployConfig(appId) {+ return this.request(`/deploy/apps/${appId}/config`);+ }++ async configureDeployment(appId, repoUrl, branch = 'main', autoDeploy = true, preDeployScript = null, postDeployScript = null) {+ return this.request(`/deploy/apps/${appId}/config`, {+ method: 'POST',+ body: {+ repo_url: repoUrl,+ branch,+ auto_deploy: autoDeploy,+ pre_deploy_script: preDeployScript,+ post_deploy_script: postDeployScript+ }+ });+ }++ async removeDeployment(appId) {+ return this.request(`/deploy/apps/${appId}/config`, { method: 'DELETE' });+ }++ async triggerDeploy(appId, force = false) {+ return this.request(`/deploy/apps/${appId}/deploy`, {+ method: 'POST',+ body: { force }+ });+ }++ async pullChanges(appId, branch = null) {+ return this.request(`/deploy/apps/${appId}/pull`, {+ method: 'POST',+ body: branch ? { branch } : {}+ });+ }++ async getGitStatus(appId) {+ return this.request(`/deploy/apps/${appId}/git-status`);+ }++ async getCommitInfo(appId) {+ return this.request(`/deploy/apps/${appId}/commit`);+ }++ async getDeploymentHistory(appId = null, limit = 50) {+ const params = new URLSearchParams({ limit });+ if (appId) params.append('app_id', appId);+ return this.request(`/deploy/history?${params}`);+ }++ async cloneRepository(appPath, repoUrl, branch = 'main') {+ return this.request('/deploy/clone', {+ method: 'POST',+ body: { app_path: appPath, repo_url: repoUrl, branch }+ });+ }}export const api = new ApiService();diff --git a/frontend/src/styles/components/_buttons.less b/frontend/src/styles/components/_buttons.lessindex c6b26238..c11c9c1c 100644--- a/frontend/src/styles/components/_buttons.less+++ b/frontend/src/styles/components/_buttons.less@@ -97,3 +97,17 @@color: @text-primary;}}++// Loading state (see _spinner.less for spinner-specific styles)+.btn-loading {+ position: relative;+ pointer-events: none;+ color: transparent !important;++ .spinner {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ }+}diff --git a/frontend/src/styles/components/_modals.less b/frontend/src/styles/components/_modals.lessindex 832b187f..e41736ee 100644--- a/frontend/src/styles/components/_modals.less+++ b/frontend/src/styles/components/_modals.less@@ -117,3 +117,58 @@color: @text-tertiary;line-height: @line-height-normal;}++// Confirmation Dialog+.confirm-dialog {+ max-width: 400px;+ text-align: center;+}++.confirm-dialog-content {+ padding: @space-8 @space-6 @space-6;+}++.confirm-dialog-icon {+ .icon-box(64px);+ border-radius: 50%;+ margin: 0 auto @space-4;++ svg {+ width: 32px;+ height: 32px;+ }++ &-danger {+ background: fade(@danger, 15%);+ color: @danger;+ }++ &-warning {+ background: fade(@warning, 15%);+ color: @warning;+ }++ &-info {+ background: fade(@accent-primary, 15%);+ color: @accent-primary;+ }+}++.confirm-dialog-title {+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ margin-bottom: @space-2;+}++.confirm-dialog-message {+ font-size: @font-size-sm;+ color: @text-secondary;+ line-height: @line-height-relaxed;+}++.confirm-dialog-actions {+ display: flex;+ gap: @space-3;+ justify-content: center;+ padding: @space-4 @space-6 @space-6;+}diff --git a/frontend/src/styles/components/_spinner.less b/frontend/src/styles/components/_spinner.lessnew file mode 100644index 00000000..4cba0b9d--- /dev/null+++ b/frontend/src/styles/components/_spinner.less@@ -0,0 +1,103 @@+// ============================================+// SPINNER STYLES+// ============================================++.spinner {+ display: inline-flex;+ align-items: center;+ justify-content: center;++ &-sm {+ width: 16px;+ height: 16px;++ .spinner-ring {+ width: 16px;+ height: 16px;+ border-width: 2px;+ }+ }++ &-md {+ width: 24px;+ height: 24px;++ .spinner-ring {+ width: 24px;+ height: 24px;+ border-width: 3px;+ }+ }++ &-lg {+ width: 40px;+ height: 40px;++ .spinner-ring {+ width: 40px;+ height: 40px;+ border-width: 4px;+ }+ }+}++.spinner-ring {+ border-radius: 50%;+ border-style: solid;+ border-color: fade(@accent-primary, 30%);+ border-top-color: @accent-primary;+ animation: spinner-rotate 0.8s linear infinite;+}++@keyframes spinner-rotate {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+}++// Loading state component+.loading-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: @space-3;+ padding: @space-8;+ color: @text-secondary;++ span {+ font-size: @font-size-sm;+ }+}++// Button loading state+.btn-loading {+ position: relative;+ pointer-events: none;+ color: transparent !important;++ .spinner {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);++ .spinner-ring {+ border-color: fade(currentColor, 30%);+ border-top-color: currentColor;+ }+ }++ &.btn-primary .spinner .spinner-ring {+ border-color: fade(#fff, 30%);+ border-top-color: #fff;+ }++ &.btn-secondary .spinner .spinner-ring {+ border-color: fade(@text-primary, 30%);+ border-top-color: @text-primary;+ }+}diff --git a/frontend/src/styles/components/_toasts.less b/frontend/src/styles/components/_toasts.lessnew file mode 100644index 00000000..582d354e--- /dev/null+++ b/frontend/src/styles/components/_toasts.less@@ -0,0 +1,111 @@+// ============================================+// TOAST NOTIFICATION STYLES+// ============================================++.toast-container {+ position: fixed;+ top: @space-4;+ right: @space-4;+ z-index: 9999;+ display: flex;+ flex-direction: column;+ gap: @space-2;+ max-width: 400px;+ pointer-events: none;+}++.toast {+ display: flex;+ align-items: flex-start;+ gap: @space-3;+ padding: @space-3 @space-4;+ border-radius: @radius-md;+ background: @bg-secondary;+ border: 1px solid @border-default;+ box-shadow: @shadow-lg;+ pointer-events: auto;+ animation: toast-slide-in 0.3s ease-out;++ &-icon {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;++ svg {+ width: 18px;+ height: 18px;+ }+ }++ &-message {+ flex: 1;+ font-size: @font-size-sm;+ line-height: 1.4;+ color: @text-primary;+ }++ &-dismiss {+ flex-shrink: 0;+ background: none;+ border: none;+ padding: @space-1;+ cursor: pointer;+ color: @text-tertiary;+ border-radius: @radius-sm;+ .transition(all);++ &:hover {+ color: @text-primary;+ background: @bg-hover;+ }+ }++ // Variants+ &-success {+ border-color: fade(@success, 30%);+ background: fade(@success, 10%);++ .toast-icon {+ color: @success;+ }+ }++ &-error {+ border-color: fade(@danger, 30%);+ background: fade(@danger, 10%);++ .toast-icon {+ color: @danger;+ }+ }++ &-warning {+ border-color: fade(@warning, 30%);+ background: fade(@warning, 10%);++ .toast-icon {+ color: @warning;+ }+ }++ &-info {+ border-color: fade(@accent-primary, 30%);+ background: fade(@accent-primary, 10%);++ .toast-icon {+ color: @accent-primary;+ }+ }+}++@keyframes toast-slide-in {+ from {+ opacity: 0;+ transform: translateX(100%);+ }+ to {+ opacity: 1;+ transform: translateX(0);+ }+}diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex fd9dc2e8..61f78479 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -37,6 +37,8 @@@import 'components/_services';@import 'components/_logs';@import 'components/_credentials';+@import 'components/_toasts';+@import 'components/_spinner';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES@@ -46,3 +48,8 @@@import 'pages/_applications';@import 'pages/_docker';@import 'pages/_databases';+@import 'pages/_domains';+@import 'pages/_monitoring';+@import 'pages/_backups';+@import 'pages/_terminal';+@import 'pages/_settings';diff --git a/frontend/src/styles/pages/_applications.less b/frontend/src/styles/pages/_applications.lessindex 0b461edb..1f2f87e1 100644--- a/frontend/src/styles/pages/_applications.less+++ b/frontend/src/styles/pages/_applications.less@@ -75,3 +75,175 @@font-size: @font-size-2xl;}}++// ============================================+// DEPLOY TAB+// ============================================++.deploy-tab {+ .flex-column-gap(@space-5);++ .deploy-setup {+ padding: @space-8 0;+ }++ .deploy-header {+ margin-bottom: @space-5;+ }++ .deploy-status-card {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: @space-4;+ padding: @space-4 @space-5;+ background: @surface-secondary;+ border: 1px solid @border-primary;+ border-radius: @border-radius-lg;++ @media (max-width: @breakpoint-md) {+ flex-direction: column;+ align-items: flex-start;+ }+ }++ .deploy-repo-info {+ display: flex;+ align-items: center;+ gap: @space-3;++ svg {+ flex-shrink: 0;+ color: @text-secondary;+ }++ > div {+ display: flex;+ flex-direction: column;+ gap: @space-1;+ }++ .repo-url {+ font-family: @font-family-mono;+ font-size: @font-size-sm;+ color: @text-primary;+ word-break: break-all;+ }++ .repo-branch {+ font-size: @font-size-xs;+ color: @text-tertiary;+ }+ }++ .deploy-actions {+ display: flex;+ gap: @space-2;+ flex-shrink: 0;+ }++ .deploy-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));+ gap: @space-5;+ }++ .webhook-url {+ display: flex;+ align-items: center;+ gap: @space-3;+ margin-top: @space-3;+ padding: @space-3;+ background: @surface-tertiary;+ border-radius: @border-radius-md;++ code {+ flex: 1;+ font-size: @font-size-xs;+ color: @text-secondary;+ word-break: break-all;+ }++ .btn {+ flex-shrink: 0;+ }+ }++ .scripts-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));+ gap: @space-4;+ }++ .script-section {+ h4 {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-secondary;+ margin-bottom: @space-2;+ }+ }++ .script-code {+ padding: @space-3;+ background: @surface-tertiary;+ border-radius: @border-radius-md;+ font-family: @font-family-mono;+ font-size: @font-size-xs;+ color: @text-secondary;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-word;+ margin: 0;+ }++ .card-actions {+ display: flex;+ gap: @space-2;+ margin-top: @space-4;+ padding-top: @space-4;+ border-top: 1px solid @border-primary;+ }++ .checkbox-label {+ display: flex;+ align-items: center;+ gap: @space-2;+ cursor: pointer;++ input[type="checkbox"] {+ width: 18px;+ height: 18px;+ cursor: pointer;+ }++ span {+ font-size: @font-size-sm;+ color: @text-primary;+ }+ }++ .form-help {+ display: block;+ margin-top: @space-1;+ font-size: @font-size-xs;+ color: @text-tertiary;+ }++ textarea {+ font-family: @font-family-mono;+ font-size: @font-size-sm;+ resize: vertical;+ min-height: 80px;+ }++ .text-danger {+ color: @danger;+ font-size: @font-size-sm;+ }++ .text-muted {+ color: @text-tertiary;+ font-size: @font-size-sm;+ }+}diff --git a/frontend/src/styles/pages/_backups.less b/frontend/src/styles/pages/_backups.lessnew file mode 100644index 00000000..64ac45f0--- /dev/null+++ b/frontend/src/styles/pages/_backups.less@@ -0,0 +1,155 @@+// Backups Page Styles++.backups-page {+ .stat-icon {+ width: 48px;+ height: 48px;+ border-radius: @radius-lg;+ display: flex;+ align-items: center;+ justify-content: center;++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }++ &.backups {+ background: rgba(34, 197, 94, 0.1);+ color: @success;+ }++ &.apps {+ background: rgba(59, 130, 246, 0.1);+ color: @primary;+ }++ &.databases {+ background: rgba(168, 85, 247, 0.1);+ color: #a855f7;+ }++ &.size {+ background: rgba(249, 115, 22, 0.1);+ color: @warning;+ }+ }++ .filter-select {+ padding: @spacing-xs @spacing-sm;+ border: 1px solid var(--border-color);+ border-radius: @radius-sm;+ background: var(--bg-secondary);+ color: var(--text-primary);+ font-size: @font-sm;+ }++ .backup-name {+ display: flex;+ align-items: center;+ gap: @spacing-sm;++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ flex-shrink: 0;+ }++ .icon-app {+ color: @primary;+ }++ .icon-db {+ color: #a855f7;+ }+ }++ .action-buttons {+ display: flex;+ gap: @spacing-xs;+ }++ .checkbox-label {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ cursor: pointer;++ input[type="checkbox"] {+ width: 18px;+ height: 18px;+ cursor: pointer;+ }++ span {+ font-size: @font-sm;+ color: var(--text-primary);+ }+ }++ .form-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: @spacing-md;+ }++ .form-help {+ display: block;+ margin-top: @spacing-xs;+ font-size: @font-xs;+ color: var(--text-tertiary);+ }++ .restore-warning {+ text-align: center;+ padding: @spacing-lg;+ background: rgba(239, 68, 68, 0.1);+ border-radius: @radius-md;+ margin-bottom: @spacing-lg;++ svg {+ stroke: @danger;+ fill: none;+ stroke-width: 2;+ margin-bottom: @spacing-sm;+ }++ h3 {+ color: @danger;+ margin-bottom: @spacing-sm;+ }++ p {+ color: var(--text-secondary);+ font-size: @font-sm;+ }+ }++ .restore-details {+ background: var(--bg-secondary);+ border-radius: @radius-md;+ padding: @spacing-md;++ .detail-row {+ display: flex;+ justify-content: space-between;+ padding: @spacing-xs 0;++ &:not(:last-child) {+ border-bottom: 1px solid var(--border-color);+ }+ }++ .detail-label {+ color: var(--text-tertiary);+ font-size: @font-sm;+ }++ .detail-value {+ font-weight: 500;+ font-size: @font-sm;+ }+ }+}diff --git a/frontend/src/styles/pages/_domains.less b/frontend/src/styles/pages/_domains.lessnew file mode 100644index 00000000..9a473f5b--- /dev/null+++ b/frontend/src/styles/pages/_domains.less@@ -0,0 +1,228 @@+// ============================================+// DOMAINS & SSL PAGE+// ============================================++// SSL Status Bar+.ssl-status-bar {+ display: flex;+ gap: @space-6;+ margin-bottom: @space-8;++ @media (max-width: @breakpoint-md) {+ flex-direction: column;+ }+}++.ssl-status-item {+ .flex-start();+ gap: @space-4;+ padding: @space-5;+ background: @bg-card;+ border: 1px solid @border-subtle;+ border-radius: @radius-xl;+ flex: 1;+}++.ssl-status-icon {+ .icon-box(48px);+ border-radius: @radius-xl - 2;++ &.active {+ background: @success-bg;+ color: @success;+ }++ &.inactive {+ background: @danger-bg;+ color: @danger;+ }+}++.ssl-status-info {+ h4 {+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ margin-bottom: @space-1;+ }++ span {+ font-size: @font-size-sm + 1;+ color: @text-secondary;+ }+}++// Domain List+.domain-list {+ .flex-column-gap(@space-3);+}++.domain-item {+ .list-item-base();+}++.domain-item-info {+ .flex-start();+ gap: @space-4;+ flex: 1;+ min-width: 0;+}++.domain-item-icon {+ .icon-box();+ background: @bg-hover;+ border-radius: @radius-lg;+ color: @text-secondary;++ &.ssl {+ background: @success-bg;+ color: @success;+ }+}++.domain-item-details {+ min-width: 0;++ h3 {+ font-size: @font-size-base;+ font-weight: @font-weight-semibold;+ color: @text-primary;+ margin-bottom: @space-1;+ .flex-start();+ gap: @space-2;+ }+}++.primary-badge {+ background: @accent-glow;+ color: @accent-primary;+ padding: @space-1 - 2 @space-2;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-weight: @font-weight-semibold;+ text-transform: uppercase;+}++.domain-item-meta {+ .flex-start();+ gap: @space-4;+ font-size: @font-size-sm;+ color: @text-tertiary;++ span {+ .flex-start();+ gap: @space-1;+ }+}++.app-link {+ color: @text-secondary;+}++.ssl-badge {+ color: @success;+}++.domain-item-actions {+ display: flex;+ gap: @space-2;+ flex-shrink: 0;+ flex-wrap: wrap;+}++// Certificate List+.cert-list {+ .flex-column-gap(@space-3);+}++.cert-item {+ .list-item-base();+}++.cert-item-info {+ .flex-start();+ gap: @space-4;+ flex: 1;+ min-width: 0;+}++.cert-item-icon {+ .icon-box();+ background: @success-bg;+ border-radius: @radius-lg;+ color: @success;+}++.cert-item-details {+ min-width: 0;++ h3 {+ font-size: @font-size-base;+ font-weight: @font-weight-semibold;+ color: @text-primary;+ margin-bottom: @space-1;+ }+}++.cert-item-meta {+ .flex-start();+ gap: @space-4;+ font-size: @font-size-sm;+ color: @text-tertiary;++ span {+ .flex-start();+ gap: @space-1;++ &.valid {+ color: @success;+ }++ &.expiring {+ color: @warning;+ }+ }+}++.cert-status {+ flex-shrink: 0;+}++// SSL Info Box (in modal)+.ssl-info-box {+ .flex-start();+ gap: @space-4;+ padding: @space-5;+ background: @success-bg;+ border: 1px solid @success-border;+ border-radius: @radius-lg;+ margin-bottom: @space-5;+ color: @success;++ h4 {+ font-size: @font-size-base;+ font-weight: @font-weight-semibold;+ margin-bottom: @space-1;+ }++ p {+ font-size: @font-size-sm;+ color: @text-secondary;++ strong {+ color: @text-primary;+ }+ }+}++// Checkbox label+.checkbox-label {+ .flex-start();+ gap: @space-2;+ cursor: pointer;++ input[type="checkbox"] {+ width: 16px;+ height: 16px;+ accent-color: @accent-primary;+ }+}diff --git a/frontend/src/styles/pages/_monitoring.less b/frontend/src/styles/pages/_monitoring.lessnew file mode 100644index 00000000..cc2e7015--- /dev/null+++ b/frontend/src/styles/pages/_monitoring.less@@ -0,0 +1,152 @@+// Monitoring Page Styles++.monitoring-page {+ .monitoring-overview {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+ }++ .threshold-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @spacing-lg;+ }++ .threshold-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @spacing-md;+ background: var(--bg-secondary);+ border-radius: @radius-md;+ }++ .threshold-label {+ color: var(--text-secondary);+ font-size: @font-sm;+ }++ .threshold-value {+ font-size: @font-lg;+ font-weight: 600;+ color: var(--primary);+ }++ .threshold-form-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: @spacing-lg;+ }++ .alert-list {+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;+ }++ .alert-item {+ display: flex;+ align-items: center;+ gap: @spacing-md;+ padding: @spacing-sm @spacing-md;+ background: var(--bg-secondary);+ border-radius: @radius-md;++ .badge {+ flex-shrink: 0;+ }++ .alert-message {+ flex: 1;+ font-size: @font-sm;+ }++ .alert-time {+ color: var(--text-tertiary);+ font-size: @font-xs;+ white-space: nowrap;+ }+ }++ .stat-icon {+ width: 48px;+ height: 48px;+ border-radius: @radius-lg;+ display: flex;+ align-items: center;+ justify-content: center;++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }++ &.status {+ background: rgba(34, 197, 94, 0.1);+ color: @success;+ }++ &.alerts {+ background: rgba(239, 68, 68, 0.1);+ color: @danger;+ }++ &.interval {+ background: rgba(59, 130, 246, 0.1);+ color: @primary;+ }++ &.notifications {+ background: rgba(168, 85, 247, 0.1);+ color: #a855f7;+ }+ }++ .text-success {+ color: @success;+ }++ .text-muted {+ color: var(--text-tertiary);+ }++ .input-group {+ display: flex;+ gap: @spacing-sm;++ input {+ flex: 1;+ }++ .btn {+ flex-shrink: 0;+ }+ }++ .checkbox-label {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ cursor: pointer;++ input[type="checkbox"] {+ width: 18px;+ height: 18px;+ cursor: pointer;+ }++ span {+ font-size: @font-sm;+ color: var(--text-primary);+ }+ }++ .form-help {+ display: block;+ margin-top: @spacing-xs;+ font-size: @font-xs;+ color: var(--text-tertiary);+ }+}diff --git a/frontend/src/styles/pages/_settings.less b/frontend/src/styles/pages/_settings.lessnew file mode 100644index 00000000..9aa87a5d--- /dev/null+++ b/frontend/src/styles/pages/_settings.less@@ -0,0 +1,517 @@+// ============================================+// SETTINGS PAGE STYLES+// ============================================++.settings-page {+ padding: @spacing-lg;+ max-width: 1200px;+ margin: 0 auto;+}++.settings-header {+ margin-bottom: @spacing-xl;++ h1 {+ font-size: 1.75rem;+ font-weight: 600;+ color: @text-primary;+ margin: 0 0 @spacing-xs 0;+ }++ p {+ color: @text-secondary;+ margin: 0;+ }+}++.settings-content {+ display: flex;+ gap: @spacing-xl;++ @media (max-width: 900px) {+ flex-direction: column;+ }+}++// Settings Navigation+.settings-nav {+ flex: 0 0 220px;++ @media (max-width: 900px) {+ flex: none;+ }++ ul {+ list-style: none;+ padding: 0;+ margin: 0;+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;++ @media (max-width: 900px) {+ flex-direction: row;+ flex-wrap: wrap;+ }+ }++ li button {+ width: 100%;+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-sm @spacing-md;+ background: transparent;+ border: none;+ border-radius: @radius-md;+ color: @text-secondary;+ font-size: 0.9rem;+ cursor: pointer;+ transition: all 0.2s ease;+ text-align: left;++ @media (max-width: 900px) {+ width: auto;+ }++ &:hover {+ background: @bg-tertiary;+ color: @text-primary;+ }++ &.active {+ background: @primary-color;+ color: white;+ }++ .nav-icon {+ font-size: 1.1rem;+ width: 20px;+ text-align: center;+ }+ }+}++// Settings Sections Container+.settings-sections {+ flex: 1;+ min-width: 0;+}++// Individual Settings Section+.settings-section {+ background: @bg-secondary;+ border: 1px solid @border-color;+ border-radius: @radius-lg;+ padding: @spacing-lg;+ margin-bottom: @spacing-lg;++ &:last-child {+ margin-bottom: 0;+ }+}++.section-header {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ margin-bottom: @spacing-lg;+ padding-bottom: @spacing-md;+ border-bottom: 1px solid @border-color;++ .section-icon {+ font-size: 1.25rem;+ color: @primary-color;+ }++ h2 {+ font-size: 1.1rem;+ font-weight: 600;+ color: @text-primary;+ margin: 0;+ }+}++// Settings Form Groups+.settings-form {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+}++.form-row {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: @spacing-md;+}++.form-group {+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;++ label {+ font-size: 0.85rem;+ font-weight: 500;+ color: @text-secondary;+ }++ input, select {+ padding: @spacing-sm @spacing-md;+ background: @bg-tertiary;+ border: 1px solid @border-color;+ border-radius: @radius-md;+ color: @text-primary;+ font-size: 0.9rem;+ transition: border-color 0.2s ease;++ &:focus {+ outline: none;+ border-color: @primary-color;+ }++ &:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }+ }++ .input-hint {+ font-size: 0.8rem;+ color: @text-muted;+ }+}++.form-actions {+ display: flex;+ gap: @spacing-sm;+ margin-top: @spacing-md;+ padding-top: @spacing-md;+ border-top: 1px solid @border-color;++ &.no-border {+ border-top: none;+ padding-top: 0;+ }+}++// Password Change Section+.password-section {+ .password-fields {+ display: flex;+ flex-direction: column;+ gap: @spacing-md;+ }++ .password-requirements {+ font-size: 0.8rem;+ color: @text-muted;+ margin-top: @spacing-xs;+ }+}++// Theme Options+.theme-options {+ display: flex;+ gap: @spacing-md;+ flex-wrap: wrap;+}++.theme-option {+ flex: 1;+ min-width: 150px;+ padding: @spacing-md;+ background: @bg-tertiary;+ border: 2px solid @border-color;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all 0.2s ease;+ text-align: center;++ &:hover {+ border-color: @primary-color;+ }++ &.active {+ border-color: @primary-color;+ background: fade(@primary-color, 10%);+ }++ .theme-icon {+ font-size: 2rem;+ margin-bottom: @spacing-sm;+ }++ .theme-name {+ font-weight: 500;+ color: @text-primary;+ margin-bottom: @spacing-xs;+ }++ .theme-desc {+ font-size: 0.8rem;+ color: @text-secondary;+ }+}++// Notification Toggles+.notification-settings {+ display: flex;+ flex-direction: column;+ gap: @spacing-md;+}++.notification-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @spacing-md;+ background: @bg-tertiary;+ border-radius: @radius-md;++ .notification-info {+ flex: 1;++ .notification-label {+ font-weight: 500;+ color: @text-primary;+ margin-bottom: @spacing-xs;+ }++ .notification-desc {+ font-size: 0.85rem;+ color: @text-secondary;+ }+ }+}++// Toggle Switch+.toggle-switch {+ position: relative;+ width: 48px;+ height: 26px;++ input {+ opacity: 0;+ width: 0;+ height: 0;++ &:checked + .toggle-slider {+ background: @primary-color;++ &::before {+ transform: translateX(22px);+ }+ }++ &:focus + .toggle-slider {+ box-shadow: 0 0 0 2px fade(@primary-color, 30%);+ }+ }++ .toggle-slider {+ position: absolute;+ cursor: pointer;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: @border-color;+ border-radius: 26px;+ transition: all 0.3s ease;++ &::before {+ content: '';+ position: absolute;+ height: 20px;+ width: 20px;+ left: 3px;+ bottom: 3px;+ background: white;+ border-radius: 50%;+ transition: transform 0.3s ease;+ }+ }+}++// System Info Grid+.system-info-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @spacing-md;+}++.info-card {+ padding: @spacing-md;+ background: @bg-tertiary;+ border-radius: @radius-md;+ text-align: center;++ .info-icon {+ font-size: 1.5rem;+ color: @primary-color;+ margin-bottom: @spacing-sm;+ }++ .info-label {+ font-size: 0.8rem;+ color: @text-secondary;+ margin-bottom: @spacing-xs;+ }++ .info-value {+ font-size: 1.25rem;+ font-weight: 600;+ color: @text-primary;+ }++ .info-bar {+ margin-top: @spacing-sm;+ height: 6px;+ background: @border-color;+ border-radius: 3px;+ overflow: hidden;++ .info-bar-fill {+ height: 100%;+ background: @primary-color;+ border-radius: 3px;+ transition: width 0.3s ease;++ &.warning {+ background: @warning-color;+ }++ &.danger {+ background: @danger-color;+ }+ }+ }+}++// About Section+.about-section {+ .app-info {+ display: flex;+ align-items: center;+ gap: @spacing-lg;+ margin-bottom: @spacing-lg;+ padding-bottom: @spacing-lg;+ border-bottom: 1px solid @border-color;++ .app-logo {+ width: 64px;+ height: 64px;+ background: @gradient-primary;+ border-radius: @radius-lg;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 2rem;+ }++ .app-details {+ .app-name {+ font-size: 1.25rem;+ font-weight: 600;+ color: @text-primary;+ margin-bottom: @spacing-xs;+ }++ .app-version {+ font-size: 0.9rem;+ color: @text-secondary;+ }+ }+ }++ .features-list {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @spacing-sm;+ margin-bottom: @spacing-lg;++ .feature-item {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-sm;+ color: @text-secondary;++ .feature-check {+ color: @success-color;+ }+ }+ }++ .about-links {+ display: flex;+ gap: @spacing-md;+ flex-wrap: wrap;++ a {+ display: flex;+ align-items: center;+ gap: @spacing-xs;+ padding: @spacing-sm @spacing-md;+ background: @bg-tertiary;+ border-radius: @radius-md;+ color: @text-secondary;+ text-decoration: none;+ transition: all 0.2s ease;++ &:hover {+ background: @primary-color;+ color: white;+ }+ }+ }+}++// Success/Error Messages+.settings-message {+ padding: @spacing-sm @spacing-md;+ border-radius: @radius-md;+ margin-bottom: @spacing-md;+ display: flex;+ align-items: center;+ gap: @spacing-sm;++ &.success {+ background: fade(@success-color, 15%);+ color: @success-color;+ border: 1px solid fade(@success-color, 30%);+ }++ &.error {+ background: fade(@danger-color, 15%);+ color: @danger-color;+ border: 1px solid fade(@danger-color, 30%);+ }+}++// Loading State+.settings-loading {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: @spacing-xxl;+ color: @text-secondary;++ .spinner {+ width: 40px;+ height: 40px;+ border: 3px solid @border-color;+ border-top-color: @primary-color;+ border-radius: 50%;+ animation: spin 1s linear infinite;+ margin-bottom: @spacing-md;+ }+}++@keyframes spin {+ to {+ transform: rotate(360deg);+ }+}diff --git a/frontend/src/styles/pages/_terminal.less b/frontend/src/styles/pages/_terminal.lessnew file mode 100644index 00000000..fa7d3d94--- /dev/null+++ b/frontend/src/styles/pages/_terminal.less@@ -0,0 +1,701 @@+// Terminal & Logs Page Styles++.terminal-page {+ .tabs {+ .tab {+ display: flex;+ align-items: center;+ gap: @spacing-sm;++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }+ }+ }+}++// ============================================+// LOG FILES TAB+// ============================================++.logs-container {+ height: calc(100vh - 280px);+ min-height: 500px;+}++.logs-layout {+ display: grid;+ grid-template-columns: 300px 1fr;+ gap: @spacing-lg;+ height: 100%;++ @media (max-width: @breakpoint-lg) {+ grid-template-columns: 1fr;+ grid-template-rows: auto 1fr;+ }+}++.logs-sidebar {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: @radius-lg;+ display: flex;+ flex-direction: column;+ overflow: hidden;++ .sidebar-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: @spacing-md;+ border-bottom: 1px solid var(--border-color);++ h3 {+ font-size: @font-sm;+ font-weight: 600;+ margin: 0;+ }+ }+}++.log-files-list {+ flex: 1;+ overflow-y: auto;+ padding: @spacing-sm;++ .empty-hint {+ padding: @spacing-lg;+ text-align: center;+ color: var(--text-tertiary);+ font-size: @font-sm;+ }+}++.log-file-item {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-sm @spacing-md;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all 0.15s ease;++ &:hover {+ background: var(--bg-tertiary);+ }++ &.active {+ background: var(--primary);+ color: white;++ .log-file-path,+ .log-file-size {+ color: rgba(255, 255, 255, 0.7);+ }++ .log-icon {+ background: rgba(255, 255, 255, 0.2);+ color: white;+ }+ }++ .log-icon {+ width: 32px;+ height: 32px;+ border-radius: @radius-sm;+ display: flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ background: var(--bg-tertiary);++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }++ &.error {+ color: @danger;+ }++ &.access {+ color: @success;+ }++ &.nginx {+ color: @primary;+ }++ &.database {+ color: #a855f7;+ }+ }++ .log-file-info {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .log-file-name {+ font-size: @font-sm;+ font-weight: 500;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .log-file-path {+ font-size: @font-xs;+ color: var(--text-tertiary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .log-file-size {+ font-size: @font-xs;+ color: var(--text-tertiary);+ flex-shrink: 0;+ }+}++.logs-viewer {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: @radius-lg;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.viewer-toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: @spacing-md;+ padding: @spacing-sm @spacing-md;+ border-bottom: 1px solid var(--border-color);+ flex-wrap: wrap;++ .toolbar-left,+ .toolbar-right {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ }+}++.search-input {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-xs @spacing-sm;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: @radius-md;++ svg {+ stroke: var(--text-tertiary);+ fill: none;+ stroke-width: 2;+ flex-shrink: 0;+ }++ input {+ border: none;+ background: none;+ padding: 0;+ font-size: @font-sm;+ width: 180px;++ &:focus {+ outline: none;+ }+ }+}++.lines-select {+ padding: @spacing-xs @spacing-sm;+ border: 1px solid var(--border-color);+ border-radius: @radius-sm;+ background: var(--bg-tertiary);+ color: var(--text-primary);+ font-size: @font-sm;+}++.auto-refresh-toggle {+ display: flex;+ align-items: center;+ gap: @spacing-xs;+ cursor: pointer;+ font-size: @font-sm;+ color: var(--text-secondary);++ input {+ cursor: pointer;+ }+}++.log-content {+ flex: 1;+ overflow: auto;+ padding: @spacing-md;+ background: #1a1a2e;++ pre {+ margin: 0;+ font-family: 'JetBrains Mono', 'Fira Code', monospace;+ font-size: 12px;+ line-height: 1.6;+ color: #e2e8f0;+ white-space: pre-wrap;+ word-break: break-all;+ }++ .empty-viewer {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ height: 100%;+ color: var(--text-tertiary);++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 1.5;+ margin-bottom: @spacing-md;+ opacity: 0.5;+ }++ p {+ font-size: @font-sm;+ }+ }+}++// ============================================+// JOURNAL TAB+// ============================================++.journal-container {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+ height: calc(100vh - 280px);+ min-height: 500px;+}++.journal-controls {+ display: flex;+ align-items: flex-end;+ gap: @spacing-lg;+ flex-wrap: wrap;++ .control-group {+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;++ label {+ font-size: @font-xs;+ font-weight: 500;+ color: var(--text-secondary);+ }++ input,+ select {+ padding: @spacing-xs @spacing-sm;+ border: 1px solid var(--border-color);+ border-radius: @radius-sm;+ background: var(--bg-secondary);+ font-size: @font-sm;+ }++ input {+ width: 200px;+ }+ }+}++.input-with-suggestions {+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;+}++.quick-units {+ display: flex;+ flex-wrap: wrap;+ gap: @spacing-xs;+}++.unit-chip {+ padding: 2px @spacing-sm;+ border: 1px solid var(--border-color);+ border-radius: @radius-full;+ background: var(--bg-secondary);+ font-size: @font-xs;+ cursor: pointer;+ transition: all 0.15s ease;++ &:hover {+ border-color: var(--primary);+ color: var(--primary);+ }++ &.active {+ background: var(--primary);+ border-color: var(--primary);+ color: white;+ }+}++.journal-viewer {+ flex: 1;+ background: #1a1a2e;+ border-radius: @radius-lg;+ overflow: auto;+ padding: @spacing-md;++ pre {+ margin: 0;+ font-family: 'JetBrains Mono', 'Fira Code', monospace;+ font-size: 12px;+ line-height: 1.6;+ color: #e2e8f0;+ white-space: pre-wrap;+ word-break: break-all;+ }+}++// ============================================+// PROCESSES TAB+// ============================================++.processes-container {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+}++.processes-toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: @spacing-md;+ flex-wrap: wrap;++ .toolbar-left,+ .toolbar-right {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ }++ select {+ padding: @spacing-xs @spacing-sm;+ border: 1px solid var(--border-color);+ border-radius: @radius-sm;+ background: var(--bg-secondary);+ font-size: @font-sm;+ }+}++.processes-table-wrapper {+ overflow-x: auto;+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: @radius-lg;+}++.processes-table {+ width: 100%;+ min-width: 800px;++ th {+ position: sticky;+ top: 0;+ background: var(--bg-secondary);+ z-index: 1;+ }++ tr {+ cursor: pointer;+ transition: background 0.15s ease;++ &:hover {+ background: var(--bg-tertiary);+ }++ &.selected {+ background: rgba(59, 130, 246, 0.1);+ }+ }++ .mono {+ font-family: 'JetBrains Mono', monospace;+ font-size: @font-xs;+ }++ .process-name {+ max-width: 200px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .usage-cell {+ position: relative;+ min-width: 100px;++ .usage-bar {+ position: absolute;+ left: 0;+ top: 50%;+ transform: translateY(-50%);+ height: 4px;+ border-radius: 2px;+ opacity: 0.3;++ &.cpu {+ background: @primary;+ }++ &.memory {+ background: #a855f7;+ }+ }++ span {+ position: relative;+ font-size: @font-xs;+ font-family: monospace;+ }+ }++ .action-buttons {+ display: flex;+ gap: @spacing-xs;+ }+}++.btn-xs {+ padding: 2px 6px;+ font-size: 11px;++ svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }+}++.process-details-panel {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: @radius-lg;+ overflow: hidden;++ .panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: @spacing-md;+ border-bottom: 1px solid var(--border-color);++ h3 {+ font-size: @font-md;+ font-weight: 600;+ margin: 0;+ }+ }++ .panel-body {+ padding: @spacing-md;+ }++ .details-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: @spacing-md;+ }++ .detail-item {+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;++ .detail-label {+ font-size: @font-xs;+ color: var(--text-tertiary);+ }++ .detail-value {+ font-size: @font-sm;+ font-weight: 500;++ &.mono {+ font-family: monospace;+ }+ }+ }++ .command-line {+ margin-top: @spacing-md;+ padding-top: @spacing-md;+ border-top: 1px solid var(--border-color);++ .detail-label {+ display: block;+ font-size: @font-xs;+ color: var(--text-tertiary);+ margin-bottom: @spacing-xs;+ }++ code {+ display: block;+ padding: @spacing-sm;+ background: var(--bg-tertiary);+ border-radius: @radius-sm;+ font-family: monospace;+ font-size: @font-xs;+ word-break: break-all;+ }+ }+}++// ============================================+// SERVICES TAB+// ============================================++.services-container {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+}++.services-toolbar {+ display: flex;+ align-items: center;+ gap: @spacing-sm;++ .btn svg {+ stroke: currentColor;+ fill: none;+ stroke-width: 2;+ }+}++.services-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: @spacing-md;+}++.service-card {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: @radius-lg;+ padding: @spacing-md;+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;++ .service-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: @spacing-md;++ .service-info {+ display: flex;+ align-items: center;+ gap: @spacing-sm;++ .status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;++ &.success {+ background: @success;+ }++ &.danger {+ background: @danger;+ }++ &.warning {+ background: @warning;+ }++ &.secondary {+ background: var(--text-tertiary);+ }+ }++ h4 {+ font-size: @font-sm;+ font-weight: 600;+ margin: 0;+ }+ }+ }++ .service-description {+ font-size: @font-xs;+ color: var(--text-secondary);+ margin: 0;+ }++ .service-meta {+ display: flex;+ gap: @spacing-md;+ font-size: @font-xs;+ color: var(--text-tertiary);++ .meta-label {+ color: var(--text-secondary);+ }+ }++ .service-actions {+ display: flex;+ gap: @spacing-xs;+ margin-top: @spacing-sm;+ padding-top: @spacing-sm;+ border-top: 1px solid var(--border-color);+ }+}++// Modal adjustments for logs+.modal-lg {+ max-width: 900px;+ width: 90%;+}++.modal-log-viewer {+ max-height: 500px;+ overflow: auto;+ background: #1a1a2e;+ border-radius: @radius-md;+ padding: @spacing-md;++ pre {+ margin: 0;+ font-family: 'JetBrains Mono', monospace;+ font-size: 12px;+ line-height: 1.6;+ color: #e2e8f0;+ white-space: pre-wrap;+ word-break: break-all;+ }+}diff --git a/nginx/nginx.conf b/nginx/nginx.confnew file mode 100644index 00000000..dd835bc5--- /dev/null+++ b/nginx/nginx.conf@@ -0,0 +1,169 @@+# ServerKit Production Nginx Configuration+user nginx;+worker_processes auto;+error_log /var/log/nginx/error.log warn;+pid /var/run/nginx.pid;++events {+ worker_connections 1024;+ use epoll;+ multi_accept on;+}++http {+ include /etc/nginx/mime.types;+ default_type application/octet-stream;++ # Logging format+ log_format main '$remote_addr - $remote_user [$time_local] "$request" '+ '$status $body_bytes_sent "$http_referer" '+ '"$http_user_agent" "$http_x_forwarded_for"';++ access_log /var/log/nginx/access.log main;++ # Performance settings+ sendfile on;+ tcp_nopush on;+ tcp_nodelay on;+ keepalive_timeout 65;+ types_hash_max_size 2048;+ client_max_body_size 100m;++ # Gzip compression+ gzip on;+ gzip_vary on;+ gzip_proxied any;+ gzip_comp_level 6;+ gzip_types text/plain text/css text/xml application/json application/javascript+ application/xml+rss application/atom+xml image/svg+xml;++ # Rate limiting zones+ limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;+ limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/m;+ limit_conn_zone $binary_remote_addr zone=conn_limit:10m;++ # Upstream servers+ upstream backend {+ server backend:5000;+ keepalive 32;+ }++ upstream frontend {+ server frontend:80;+ }++ # HTTP server - redirect to HTTPS+ server {+ listen 80;+ server_name _;++ # Allow Let's Encrypt verification+ location /.well-known/acme-challenge/ {+ root /var/www/certbot;+ }++ # Redirect all other requests to HTTPS+ location / {+ return 301 https://$host$request_uri;+ }+ }++ # HTTPS server+ server {+ listen 443 ssl http2;+ server_name _;++ # SSL Configuration+ ssl_certificate /etc/nginx/ssl/fullchain.pem;+ ssl_certificate_key /etc/nginx/ssl/privkey.pem;+ ssl_session_timeout 1d;+ ssl_session_cache shared:SSL:50m;+ ssl_session_tickets off;++ # Modern SSL configuration+ ssl_protocols TLSv1.2 TLSv1.3;+ ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;+ ssl_prefer_server_ciphers off;++ # HSTS+ add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;++ # Security headers+ add_header X-Frame-Options "DENY" 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;+ add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;++ # Content Security Policy+ add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' ws: wss:; frame-ancestors 'none';" always;++ # Connection limits+ limit_conn conn_limit 20;++ # Root location - serve frontend+ location / {+ proxy_pass http://frontend;+ proxy_http_version 1.1;+ 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;+ }++ # Auth endpoints - strict rate limiting+ location /api/v1/auth {+ limit_req zone=auth_limit burst=3 nodelay;++ proxy_pass http://backend;+ proxy_http_version 1.1;+ 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;+ }++ # API endpoints+ location /api {+ limit_req zone=api_limit burst=20 nodelay;++ proxy_pass http://backend;+ proxy_http_version 1.1;+ 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;++ # Timeouts+ proxy_connect_timeout 60s;+ proxy_send_timeout 60s;+ proxy_read_timeout 60s;+ }++ # WebSocket support for socket.io+ location /socket.io {+ proxy_pass http://backend;+ 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;++ # WebSocket specific timeouts+ proxy_connect_timeout 7d;+ proxy_send_timeout 7d;+ proxy_read_timeout 7d;+ }++ # Deny access to sensitive files+ location ~ /\. {+ deny all;+ }++ location ~* \.(env|git|gitignore|dockerignore)$ {+ deny all;+ }+ }+}