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 email server backend, model and UI
Juan Denis9b2f20b07eb7
diff --git a/ROADMAP.md b/ROADMAP.mdindex f91f8e43..d71e4851 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -267,6 +267,23 @@ This document outlines the development roadmap for ServerKit. Features are organ---+## Phase 21: SSO & OAuth Login (Planned)++**Priority: High**++- [ ] Google OAuth 2.0 login+- [ ] GitHub OAuth login+- [ ] Generic OpenID Connect (OIDC) provider support+- [ ] SAML 2.0 support for enterprise environments+- [ ] Social login UI (provider buttons on login page)+- [ ] Account linking (connect OAuth identity to existing local account)+- [ ] Auto-provisioning of new users on first SSO login+- [ ] Configurable SSO settings (enable/disable providers, client ID/secret management)+- [ ] Enforce SSO-only login (disable password auth for team members)+- [ ] SSO session management and token refresh++---+## Version Milestones| Version | Target Features | Status |@@ -276,7 +293,7 @@ This document outlines the development roadmap for ServerKit. Features are organ| v1.1.0 | Multi-server, Git deployment | Planned || v1.2.0 | Backups, Advanced SSL, Advanced Security | Planned || v1.3.0 | Email server, API enhancements | Planned |-| v1.4.0 | Team & permissions | Planned |+| v1.4.0 | Team & permissions, SSO & OAuth login | Planned || v1.5.0 | Performance optimizations | Planned || v2.0.0 | Mobile app, Marketplace | Future |@@ -304,5 +321,5 @@ Have a feature idea? Open an issue on GitHub with the `enhancement` label.<p align="center"><strong>ServerKit Roadmap</strong><br>- Last updated: January 2026+ Last updated: March 2026</p>diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 59f03ff6..444c3112 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -151,6 +151,10 @@ def create_app(config_name=None):from app.api.cron import cron_bpapp.register_blueprint(cron_bp, url_prefix='/api/v1/cron')+ # Register blueprints - Email Server+ from app.api.email import email_bp+ app.register_blueprint(email_bp, url_prefix='/api/v1/email')+# Register blueprints - Uptime Trackingfrom app.api.uptime import uptime_bpapp.register_blueprint(uptime_bp, url_prefix='/api/v1/uptime')diff --git a/backend/app/api/email.py b/backend/app/api/email.pynew file mode 100644index 00000000..b19555f6--- /dev/null+++ b/backend/app/api/email.py@@ -0,0 +1,350 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User+from app.services.email_service import EmailService++email_bp = Blueprint('email', __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+++# ==========================================+# STATUS & CONFIG+# ==========================================++@email_bp.route('/status', methods=['GET'])+@jwt_required()+def get_email_status():+ """Get overall email server status."""+ status = EmailService.get_status()+ return jsonify(status), 200+++@email_bp.route('/config', methods=['GET'])+@jwt_required()+@admin_required+def get_config():+ """Get email configuration."""+ config = EmailService.get_config()+ return jsonify(config), 200+++@email_bp.route('/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_config():+ """Update email configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ result = EmailService.save_config(data)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# POSTFIX+# ==========================================++@email_bp.route('/postfix/install', methods=['POST'])+@jwt_required()+@admin_required+def install_postfix():+ """Install Postfix."""+ result = EmailService.install_postfix()+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/postfix/config', methods=['GET'])+@jwt_required()+@admin_required+def get_postfix_config():+ """Get Postfix configuration."""+ result = EmailService.get_postfix_config()+ return jsonify(result), 200 if result.get('success') else 400+++@email_bp.route('/postfix/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_postfix_config():+ """Update Postfix configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400+ result = EmailService.update_postfix_config(data)+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/queue', methods=['GET'])+@jwt_required()+@admin_required+def get_mail_queue():+ """Get mail queue."""+ result = EmailService.get_mail_queue()+ return jsonify(result), 200 if result.get('success') else 400+++@email_bp.route('/queue/flush', methods=['POST'])+@jwt_required()+@admin_required+def flush_mail_queue():+ """Flush mail queue."""+ result = EmailService.flush_mail_queue()+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/queue/<queue_id>', methods=['DELETE'])+@jwt_required()+@admin_required+def delete_queued_message(queue_id):+ """Delete a message from the queue."""+ result = EmailService.delete_queued_message(queue_id)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# DOVECOT+# ==========================================++@email_bp.route('/dovecot/install', methods=['POST'])+@jwt_required()+@admin_required+def install_dovecot():+ """Install Dovecot."""+ result = EmailService.install_dovecot()+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/dovecot/config', methods=['GET'])+@jwt_required()+@admin_required+def get_dovecot_config():+ """Get Dovecot configuration."""+ result = EmailService.get_dovecot_config()+ return jsonify(result), 200 if result.get('success') else 400+++# ==========================================+# EMAIL ACCOUNTS+# ==========================================++@email_bp.route('/accounts', methods=['GET'])+@jwt_required()+@admin_required+def list_accounts():+ """List all email accounts."""+ accounts = EmailService.list_accounts()+ return jsonify({'accounts': accounts}), 200+++@email_bp.route('/accounts', methods=['POST'])+@jwt_required()+@admin_required+def create_account():+ """Create a new email account."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ required = ['email', 'password', 'domain']+ for field in required:+ if field not in data:+ return jsonify({'error': f'{field} is required'}), 400++ result = EmailService.create_account(+ email=data['email'],+ password=data['password'],+ domain=data['domain'],+ quota_mb=data.get('quota_mb', 1024)+ )+ return jsonify(result), 201 if result['success'] else 400+++@email_bp.route('/accounts/<int:account_id>', methods=['PUT'])+@jwt_required()+@admin_required+def update_account(account_id):+ """Update an email account."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ result = EmailService.update_account(account_id, **data)+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/accounts/<int:account_id>', methods=['DELETE'])+@jwt_required()+@admin_required+def delete_account(account_id):+ """Delete an email account."""+ result = EmailService.delete_account(account_id)+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['PUT'])+@jwt_required()+@admin_required+def set_forwarding(account_id):+ """Set forwarding for an email account."""+ data = request.get_json()+ if not data or 'forward_to' not in data:+ return jsonify({'error': 'forward_to is required'}), 400++ result = EmailService.set_forwarding(+ account_id,+ forward_to=data['forward_to'],+ keep_copy=data.get('keep_copy', True)+ )+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# SPAMASSASSIN+# ==========================================++@email_bp.route('/spamassassin/install', methods=['POST'])+@jwt_required()+@admin_required+def install_spamassassin():+ """Install SpamAssassin."""+ result = EmailService.install_spamassassin()+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/spamassassin/config', methods=['GET'])+@jwt_required()+@admin_required+def get_spamassassin_config():+ """Get SpamAssassin configuration."""+ result = EmailService.get_spamassassin_config()+ return jsonify(result), 200 if result.get('success') else 400+++@email_bp.route('/spamassassin/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_spamassassin_config():+ """Update SpamAssassin configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400+ result = EmailService.update_spamassassin_config(data)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# DKIM / SPF / DMARC+# ==========================================++@email_bp.route('/dkim/install', methods=['POST'])+@jwt_required()+@admin_required+def install_dkim():+ """Install OpenDKIM."""+ result = EmailService.install_dkim()+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/dkim/generate', methods=['POST'])+@jwt_required()+@admin_required+def generate_dkim_key():+ """Generate DKIM key for a domain."""+ data = request.get_json()+ if not data or 'domain' not in data:+ return jsonify({'error': 'domain is required'}), 400++ result = EmailService.generate_dkim_key(+ domain=data['domain'],+ selector=data.get('selector', 'mail')+ )+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/dns/<domain>', methods=['GET'])+@jwt_required()+@admin_required+def get_dns_records(domain):+ """Get recommended DNS records for a domain."""+ result = EmailService.get_dns_records(domain)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# SERVICE CONTROL+# ==========================================++@email_bp.route('/services/<service>/start', methods=['POST'])+@jwt_required()+@admin_required+def start_service(service):+ """Start an email service."""+ result = EmailService.start_service(service)+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/services/<service>/stop', methods=['POST'])+@jwt_required()+@admin_required+def stop_service(service):+ """Stop an email service."""+ result = EmailService.stop_service(service)+ return jsonify(result), 200 if result['success'] else 400+++@email_bp.route('/services/<service>/restart', methods=['POST'])+@jwt_required()+@admin_required+def restart_service(service):+ """Restart an email service."""+ result = EmailService.restart_service(service)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# WEBMAIL+# ==========================================++@email_bp.route('/webmail/status', methods=['GET'])+@jwt_required()+def get_webmail_status():+ """Get webmail installation status."""+ status = EmailService.get_webmail_status()+ return jsonify(status), 200+++@email_bp.route('/webmail/install', methods=['POST'])+@jwt_required()+@admin_required+def install_webmail():+ """Install Roundcube webmail."""+ result = EmailService.install_webmail()+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# LOGS+# ==========================================++@email_bp.route('/logs', methods=['GET'])+@jwt_required()+@admin_required+def get_mail_logs():+ """Get mail logs."""+ lines = request.args.get('lines', 100, type=int)+ result = EmailService.get_mail_log(lines=lines)+ return jsonify(result), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex c1340a4d..c3985ad1 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -15,6 +15,7 @@ from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJobfrom app.models.environment_activity import EnvironmentActivityfrom app.models.promotion_job import PromotionJobfrom app.models.sanitization_profile import SanitizationProfile+from app.models.email_account import EmailAccount__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -22,5 +23,5 @@ __all__ = ['MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert','WordPressSite', 'DatabaseSnapshot', 'SyncJob',- 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile'+ 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile', 'EmailAccount']diff --git a/backend/app/models/email_account.py b/backend/app/models/email_account.pynew file mode 100644index 00000000..417c028c--- /dev/null+++ b/backend/app/models/email_account.py@@ -0,0 +1,36 @@+from datetime import datetime+from app import db+++class EmailAccount(db.Model):+ __tablename__ = 'email_accounts'++ id = db.Column(db.Integer, primary_key=True)+ email = db.Column(db.String(255), unique=True, nullable=False)+ domain = db.Column(db.String(255), nullable=False)+ username = db.Column(db.String(100), nullable=False)+ quota_mb = db.Column(db.Integer, default=1024)+ enabled = db.Column(db.Boolean, default=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Forwarding+ forward_to = db.Column(db.Text, nullable=True) # comma-separated addresses+ forward_keep_copy = db.Column(db.Boolean, default=True)++ def to_dict(self):+ return {+ 'id': self.id,+ 'email': self.email,+ 'domain': self.domain,+ 'username': self.username,+ 'quota_mb': self.quota_mb,+ 'enabled': self.enabled,+ 'forward_to': self.forward_to,+ 'forward_keep_copy': self.forward_keep_copy,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return f'<EmailAccount {self.email}>'diff --git a/backend/app/services/email_service.py b/backend/app/services/email_service.pynew file mode 100644index 00000000..bd6c5978--- /dev/null+++ b/backend/app/services/email_service.py@@ -0,0 +1,932 @@+"""+Email Service++Manages mail server components:+- Postfix (SMTP)+- Dovecot (IMAP/POP3)+- SpamAssassin (spam filtering)+- DKIM/SPF/DMARC (email authentication)+- Email accounts (virtual users)+- Forwarding rules+"""++import os+import json+import subprocess+import re+from datetime import datetime+from typing import Dict, List, Optional++from app import paths+from app.utils.system import (+ PackageManager,+ ServiceControl,+ run_privileged,+ is_command_available,+)+++class EmailService:+ """Service for email server management."""++ CONFIG_DIR = paths.SERVERKIT_CONFIG_DIR+ EMAIL_CONFIG = os.path.join(CONFIG_DIR, 'email.json')++ # Postfix paths+ POSTFIX_MAIN_CF = '/etc/postfix/main.cf'+ POSTFIX_MASTER_CF = '/etc/postfix/master.cf'+ VIRTUAL_MAILBOX_DOMAINS = '/etc/postfix/virtual_domains'+ VIRTUAL_MAILBOX_MAPS = '/etc/postfix/virtual_mailbox_maps'+ VIRTUAL_ALIAS_MAPS = '/etc/postfix/virtual_alias_maps'++ # Dovecot paths+ DOVECOT_CONF = '/etc/dovecot/dovecot.conf'+ DOVECOT_CONF_D = '/etc/dovecot/conf.d'++ # Mail storage+ VMAIL_DIR = '/var/vmail'+ VMAIL_UID = 5000+ VMAIL_GID = 5000++ # OpenDKIM+ DKIM_KEY_DIR = '/etc/opendkim/keys'+ DKIM_KEY_TABLE = '/etc/opendkim/key.table'+ DKIM_SIGNING_TABLE = '/etc/opendkim/signing.table'+ DKIM_TRUSTED_HOSTS = '/etc/opendkim/trusted.hosts'++ # ==========================================+ # STATUS & CONFIG+ # ==========================================++ @classmethod+ def get_config(cls) -> Dict:+ """Get email server configuration."""+ if os.path.exists(cls.EMAIL_CONFIG):+ try:+ with open(cls.EMAIL_CONFIG, 'r') as f:+ return json.load(f)+ except Exception:+ pass++ return {+ 'postfix': {'enabled': False},+ 'dovecot': {'enabled': False},+ 'spamassassin': {'enabled': False},+ 'dkim': {'enabled': False},+ }++ @classmethod+ def save_config(cls, config: Dict) -> Dict:+ """Save email server configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.EMAIL_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_status(cls) -> Dict:+ """Get overall email server status."""+ if os.name == 'nt':+ return {+ 'postfix': {'installed': False, 'running': False},+ 'dovecot': {'installed': False, 'running': False},+ 'spamassassin': {'installed': False, 'running': False},+ 'opendkim': {'installed': False, 'running': False},+ 'available': False,+ }++ postfix = cls._get_service_status('postfix')+ dovecot = cls._get_service_status('dovecot')+ spamassassin = cls._get_service_status('spamassassin', cmd='spamd')+ opendkim = cls._get_service_status('opendkim')++ return {+ 'postfix': postfix,+ 'dovecot': dovecot,+ 'spamassassin': spamassassin,+ 'opendkim': opendkim,+ 'available': postfix['installed'] or dovecot['installed'],+ }++ @classmethod+ def _get_service_status(cls, service: str, cmd: str = None) -> Dict:+ """Get installation and running status for a service."""+ cmd = cmd or service+ installed = is_command_available(cmd) or PackageManager.is_installed(service)+ running = ServiceControl.is_active(service) if installed else False+ enabled = ServiceControl.is_enabled(service) if installed else False++ result = {+ 'installed': installed,+ 'running': running,+ 'enabled': enabled,+ }++ # Get version if installed+ if installed:+ result['version'] = cls._get_version(service)++ return result++ @classmethod+ def _get_version(cls, service: str) -> Optional[str]:+ """Get version string for a service."""+ try:+ if service == 'postfix':+ r = subprocess.run(['postconf', 'mail_version'], capture_output=True, text=True)+ if r.returncode == 0:+ return r.stdout.strip().split('=')[-1].strip()+ elif service == 'dovecot':+ r = subprocess.run(['dovecot', '--version'], capture_output=True, text=True)+ if r.returncode == 0:+ return r.stdout.strip().split()[0]+ elif service == 'spamassassin':+ r = subprocess.run(['spamd', '--version'], capture_output=True, text=True)+ if r.returncode == 0:+ match = re.search(r'[\d.]+', r.stdout)+ return match.group() if match else r.stdout.strip()+ elif service == 'opendkim':+ r = subprocess.run(['opendkim', '-V'], capture_output=True, text=True)+ output = r.stdout or r.stderr+ if output:+ match = re.search(r'[\d.]+', output)+ return match.group() if match else None+ except FileNotFoundError:+ pass+ return None++ # ==========================================+ # POSTFIX+ # ==========================================++ @classmethod+ def install_postfix(cls) -> Dict:+ """Install Postfix MTA."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'Postfix requires Linux'}++ # Pre-seed debconf to avoid interactive prompt+ manager = PackageManager.detect()+ if manager == 'apt':+ run_privileged(+ 'debconf-set-selections <<< "postfix postfix/main_mailer_type select Internet Site"',+ shell=True+ )+ run_privileged(+ 'debconf-set-selections <<< "postfix postfix/mailname string $(hostname -f)"',+ shell=True+ )++ result = PackageManager.install(['postfix', 'postfix-mysql'] if manager == 'apt'+ else ['postfix'])+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Installation failed'}++ ServiceControl.enable('postfix')+ ServiceControl.start('postfix')++ return {'success': True, 'message': 'Postfix installed successfully'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_postfix_config(cls) -> Dict:+ """Read key Postfix configuration values."""+ config = {}+ try:+ params = ['myhostname', 'mydomain', 'myorigin', 'inet_interfaces',+ 'mydestination', 'relay_host', 'mynetworks',+ 'smtpd_tls_cert_file', 'smtpd_tls_key_file',+ 'message_size_limit', 'mailbox_size_limit']++ for param in params:+ r = subprocess.run(['postconf', param], capture_output=True, text=True)+ if r.returncode == 0:+ key, _, value = r.stdout.strip().partition(' = ')+ config[key.strip()] = value.strip()++ return {'success': True, 'config': config}+ except FileNotFoundError:+ return {'success': False, 'error': 'postconf not found'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def update_postfix_config(cls, settings: Dict) -> Dict:+ """Update Postfix configuration parameters."""+ try:+ for key, value in settings.items():+ # Sanitize key — only allow word chars and underscores+ if not re.match(r'^[a-z_]+$', key):+ continue+ run_privileged(['postconf', '-e', f'{key}={value}'])++ ServiceControl.reload('postfix')+ return {'success': True, 'message': 'Postfix configuration updated'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_mail_queue(cls) -> Dict:+ """Get Postfix mail queue."""+ try:+ r = run_privileged(['mailq'])+ if r.returncode != 0 and 'empty' not in (r.stdout or '').lower():+ return {'success': False, 'error': r.stderr or 'Failed to get queue'}++ lines = (r.stdout or '').strip().split('\n')+ queue_items = []+ current_item = {}++ for line in lines:+ if line.startswith('-') or 'Mail queue is empty' in line:+ continue+ # Queue ID line+ match = re.match(r'^([A-F0-9]+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+)\s+(.+)', line)+ if match:+ if current_item:+ queue_items.append(current_item)+ current_item = {+ 'id': match.group(1),+ 'size': int(match.group(2)),+ 'date': match.group(3),+ 'sender': match.group(4),+ }+ elif line.strip() and current_item:+ # Recipient line+ current_item.setdefault('recipients', []).append(line.strip())++ if current_item:+ queue_items.append(current_item)++ return {'success': True, 'queue': queue_items, 'count': len(queue_items)}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def flush_mail_queue(cls) -> Dict:+ """Flush the Postfix mail queue."""+ try:+ r = run_privileged(['postqueue', '-f'])+ return {'success': True, 'message': 'Mail queue flushed'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def delete_queued_message(cls, queue_id: str) -> Dict:+ """Delete a specific message from the queue."""+ try:+ if not re.match(r'^[A-F0-9]+$', queue_id):+ return {'success': False, 'error': 'Invalid queue ID'}+ r = run_privileged(['postsuper', '-d', queue_id])+ if r.returncode != 0:+ return {'success': False, 'error': r.stderr or 'Failed to delete message'}+ return {'success': True, 'message': f'Message {queue_id} deleted'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # DOVECOT+ # ==========================================++ @classmethod+ def install_dovecot(cls) -> Dict:+ """Install Dovecot IMAP/POP3 server."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'Dovecot requires Linux'}++ manager = PackageManager.detect()+ packages = ['dovecot-core', 'dovecot-imapd', 'dovecot-pop3d',+ 'dovecot-lmtpd'] if manager == 'apt' else ['dovecot']++ result = PackageManager.install(packages)+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Installation failed'}++ # Create vmail user/group+ run_privileged(['groupadd', '-g', str(cls.VMAIL_GID), 'vmail'], timeout=10)+ run_privileged(['useradd', '-u', str(cls.VMAIL_UID), '-g', 'vmail',+ '-d', cls.VMAIL_DIR, '-s', '/usr/sbin/nologin', 'vmail'], timeout=10)+ run_privileged(['mkdir', '-p', cls.VMAIL_DIR])+ run_privileged(['chown', '-R', f'{cls.VMAIL_UID}:{cls.VMAIL_GID}', cls.VMAIL_DIR])++ ServiceControl.enable('dovecot')+ ServiceControl.start('dovecot')++ return {'success': True, 'message': 'Dovecot installed successfully'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_dovecot_config(cls) -> Dict:+ """Get Dovecot configuration summary."""+ try:+ r = subprocess.run(['doveconf', '-n'], capture_output=True, text=True)+ if r.returncode != 0:+ return {'success': False, 'error': 'Failed to read Dovecot config'}++ config = {}+ for line in r.stdout.split('\n'):+ line = line.strip()+ if '=' in line and not line.startswith('#'):+ key, _, value = line.partition('=')+ config[key.strip()] = value.strip()++ return {'success': True, 'config': config}+ except FileNotFoundError:+ return {'success': False, 'error': 'doveconf not found'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # EMAIL ACCOUNTS+ # ==========================================++ @classmethod+ def list_accounts(cls) -> List[Dict]:+ """List all email accounts from the database."""+ from app.models import EmailAccount+ accounts = EmailAccount.query.all()+ return [a.to_dict() for a in accounts]++ @classmethod+ def create_account(cls, email: str, password: str, domain: str,+ quota_mb: int = 1024) -> Dict:+ """Create a new email account."""+ from app.models import EmailAccount+ from app import db++ try:+ if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):+ return {'success': False, 'error': 'Invalid email address'}++ existing = EmailAccount.query.filter_by(email=email).first()+ if existing:+ return {'success': False, 'error': 'Email account already exists'}++ username = email.split('@')[0]++ # Create system mailbox directory+ if os.name != 'nt':+ maildir = os.path.join(cls.VMAIL_DIR, domain, username)+ run_privileged(['mkdir', '-p', maildir])+ run_privileged(['chown', '-R', f'{cls.VMAIL_UID}:{cls.VMAIL_GID}', maildir])++ # Generate password hash for Dovecot+ r = subprocess.run(+ ['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', password],+ capture_output=True, text=True+ )+ if r.returncode == 0:+ pw_hash = r.stdout.strip()+ else:+ # Fallback if doveadm not available yet+ pw_hash = password++ # Update virtual mailbox maps+ cls._update_virtual_maps(email, domain, username, pw_hash)++ account = EmailAccount(+ email=email,+ domain=domain,+ username=username,+ quota_mb=quota_mb,+ enabled=True,+ )+ db.session.add(account)+ db.session.commit()++ return {'success': True, 'data': account.to_dict(),+ 'message': f'Account {email} created'}+ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def update_account(cls, account_id: int, **kwargs) -> Dict:+ """Update an email account."""+ from app.models import EmailAccount+ from app import db++ try:+ account = EmailAccount.query.get(account_id)+ if not account:+ return {'success': False, 'error': 'Account not found'}++ password = kwargs.pop('password', None)++ for key, value in kwargs.items():+ if hasattr(account, key):+ setattr(account, key, value)++ # Update password if provided+ if password and os.name != 'nt':+ r = subprocess.run(+ ['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', password],+ capture_output=True, text=True+ )+ if r.returncode == 0:+ cls._update_virtual_maps(+ account.email, account.domain,+ account.username, r.stdout.strip()+ )++ db.session.commit()+ return {'success': True, 'data': account.to_dict()}+ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def delete_account(cls, account_id: int) -> Dict:+ """Delete an email account."""+ from app.models import EmailAccount+ from app import db++ try:+ account = EmailAccount.query.get(account_id)+ if not account:+ return {'success': False, 'error': 'Account not found'}++ email = account.email++ # Remove mailbox directory+ if os.name != 'nt':+ maildir = os.path.join(cls.VMAIL_DIR, account.domain, account.username)+ if os.path.exists(maildir):+ run_privileged(['rm', '-rf', maildir])++ db.session.delete(account)+ db.session.commit()++ # Rebuild virtual maps+ cls._rebuild_virtual_maps()++ return {'success': True, 'message': f'Account {email} deleted'}+ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def _update_virtual_maps(cls, email: str, domain: str,+ username: str, pw_hash: str) -> None:+ """Update Postfix virtual mailbox maps and Dovecot passwd file."""+ # Ensure domain is in virtual_domains+ domains_file = cls.VIRTUAL_MAILBOX_DOMAINS+ if os.path.exists(domains_file):+ with open(domains_file, 'r') as f:+ domains = f.read()+ else:+ domains = ''++ if domain not in domains:+ run_privileged(f'echo "{domain}" >> {domains_file}', shell=True)++ # Add to virtual mailbox maps+ mailbox_entry = f'{email} {domain}/{username}/\n'+ maps_file = cls.VIRTUAL_MAILBOX_MAPS+ cls._add_or_update_line(maps_file, email, mailbox_entry)++ # Update Dovecot virtual users passwd file+ passwd_file = f'/etc/dovecot/users'+ passwd_entry = (f'{email}:{pw_hash}:{cls.VMAIL_UID}:{cls.VMAIL_GID}::'+ f'{cls.VMAIL_DIR}/{domain}/{username}::\n')+ cls._add_or_update_line(passwd_file, email, passwd_entry)++ # Rebuild postfix maps+ run_privileged(['postmap', maps_file])++ @classmethod+ def _add_or_update_line(cls, filepath: str, match_key: str, new_line: str) -> None:+ """Add or update a line in a file matching the key."""+ lines = []+ found = False++ if os.path.exists(filepath):+ r = run_privileged(['cat', filepath])+ if r.returncode == 0:+ lines = r.stdout.split('\n')++ updated = []+ for line in lines:+ if line.startswith(match_key):+ updated.append(new_line.rstrip())+ found = True+ elif line.strip():+ updated.append(line)++ if not found:+ updated.append(new_line.rstrip())++ content = '\n'.join(updated) + '\n'+ run_privileged(f'echo "{content}" > {filepath}', shell=True)++ @classmethod+ def _rebuild_virtual_maps(cls) -> None:+ """Rebuild virtual maps from database."""+ from app.models import EmailAccount++ accounts = EmailAccount.query.filter_by(enabled=True).all()++ # Rebuild domains file+ domains = set(a.domain for a in accounts)+ if domains:+ content = '\n'.join(domains) + '\n'+ run_privileged(f"printf '%s' '{content}' > {cls.VIRTUAL_MAILBOX_DOMAINS}", shell=True)++ # Rebuild mailbox maps+ maps_lines = []+ for a in accounts:+ maps_lines.append(f'{a.email} {a.domain}/{a.username}/')+ if maps_lines:+ content = '\n'.join(maps_lines) + '\n'+ run_privileged(f"printf '%s' '{content}' > {cls.VIRTUAL_MAILBOX_MAPS}", shell=True)+ run_privileged(['postmap', cls.VIRTUAL_MAILBOX_MAPS])++ # ==========================================+ # FORWARDING+ # ==========================================++ @classmethod+ def set_forwarding(cls, account_id: int, forward_to: str,+ keep_copy: bool = True) -> Dict:+ """Set email forwarding for an account."""+ from app.models import EmailAccount+ from app import db++ try:+ account = EmailAccount.query.get(account_id)+ if not account:+ return {'success': False, 'error': 'Account not found'}++ account.forward_to = forward_to+ account.forward_keep_copy = keep_copy++ # Update Postfix virtual alias maps+ if os.name != 'nt' and forward_to:+ aliases = forward_to+ if keep_copy:+ aliases = f'{account.email}, {forward_to}'+ entry = f'{account.email} {aliases}\n'+ cls._add_or_update_line(cls.VIRTUAL_ALIAS_MAPS, account.email, entry)+ run_privileged(['postmap', cls.VIRTUAL_ALIAS_MAPS])++ db.session.commit()+ return {'success': True, 'data': account.to_dict()}+ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ # ==========================================+ # SPAMASSASSIN+ # ==========================================++ @classmethod+ def install_spamassassin(cls) -> Dict:+ """Install SpamAssassin."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'SpamAssassin requires Linux'}++ result = PackageManager.install(['spamassassin', 'spamc'])+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Installation failed'}++ ServiceControl.enable('spamassassin')+ ServiceControl.start('spamassassin')++ # Update SpamAssassin rules+ run_privileged(['sa-update'], timeout=120)++ return {'success': True, 'message': 'SpamAssassin installed successfully'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_spamassassin_config(cls) -> Dict:+ """Get SpamAssassin configuration."""+ config = {+ 'required_score': 5.0,+ 'rewrite_header_subject': '***SPAM***',+ 'use_bayes': True,+ 'bayes_auto_learn': True,+ }++ local_cf = '/etc/spamassassin/local.cf'+ try:+ if os.path.exists(local_cf):+ r = run_privileged(['cat', local_cf])+ if r.returncode == 0:+ for line in r.stdout.split('\n'):+ line = line.strip()+ if line.startswith('#') or not line:+ continue+ parts = line.split(None, 1)+ if len(parts) == 2:+ key, value = parts+ if key == 'required_score':+ config['required_score'] = float(value)+ elif key == 'rewrite_header':+ config['rewrite_header_subject'] = value.replace('Subject ', '')+ elif key == 'use_bayes':+ config['use_bayes'] = value == '1'+ elif key == 'bayes_auto_learn':+ config['bayes_auto_learn'] = value == '1'+ except Exception:+ pass++ return {'success': True, 'config': config}++ @classmethod+ def update_spamassassin_config(cls, settings: Dict) -> Dict:+ """Update SpamAssassin configuration."""+ try:+ local_cf = '/etc/spamassassin/local.cf'+ lines = []++ if 'required_score' in settings:+ lines.append(f"required_score {settings['required_score']}")+ if 'rewrite_header_subject' in settings:+ lines.append(f"rewrite_header Subject {settings['rewrite_header_subject']}")+ if 'use_bayes' in settings:+ lines.append(f"use_bayes {'1' if settings['use_bayes'] else '0'}")+ if 'bayes_auto_learn' in settings:+ lines.append(f"bayes_auto_learn {'1' if settings['bayes_auto_learn'] else '0'}")++ content = '\n'.join(lines) + '\n'+ run_privileged(f"printf '%s' '{content}' > {local_cf}", shell=True)++ ServiceControl.restart('spamassassin')+ return {'success': True, 'message': 'SpamAssassin configuration updated'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # DKIM / SPF / DMARC+ # ==========================================++ @classmethod+ def install_dkim(cls) -> Dict:+ """Install OpenDKIM."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'OpenDKIM requires Linux'}++ manager = PackageManager.detect()+ packages = ['opendkim', 'opendkim-tools'] if manager == 'apt' else ['opendkim']++ result = PackageManager.install(packages)+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Installation failed'}++ # Create directories+ run_privileged(['mkdir', '-p', cls.DKIM_KEY_DIR])+ run_privileged(['chown', '-R', 'opendkim:opendkim', '/etc/opendkim'])++ # Create initial config files+ for filepath in [cls.DKIM_KEY_TABLE, cls.DKIM_SIGNING_TABLE, cls.DKIM_TRUSTED_HOSTS]:+ if not os.path.exists(filepath):+ run_privileged(f'touch {filepath}', shell=True)+ run_privileged(['chown', 'opendkim:opendkim', filepath])++ # Set trusted hosts+ run_privileged(+ f"printf '127.0.0.1\\nlocalhost\\n' > {cls.DKIM_TRUSTED_HOSTS}",+ shell=True+ )++ ServiceControl.enable('opendkim')+ ServiceControl.start('opendkim')++ return {'success': True, 'message': 'OpenDKIM installed successfully'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def generate_dkim_key(cls, domain: str, selector: str = 'mail') -> Dict:+ """Generate DKIM keys for a domain."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'OpenDKIM requires Linux'}++ if not re.match(r'^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', domain):+ return {'success': False, 'error': 'Invalid domain'}+ if not re.match(r'^[a-zA-Z0-9]+$', selector):+ return {'success': False, 'error': 'Invalid selector'}++ key_dir = os.path.join(cls.DKIM_KEY_DIR, domain)+ run_privileged(['mkdir', '-p', key_dir])++ # Generate key pair+ run_privileged([+ 'opendkim-genkey',+ '-b', '2048',+ '-d', domain,+ '-D', key_dir,+ '-s', selector,+ '-v'+ ])++ run_privileged(['chown', '-R', 'opendkim:opendkim', key_dir])++ # Read the public key for DNS record+ txt_file = os.path.join(key_dir, f'{selector}.txt')+ r = run_privileged(['cat', txt_file])+ dns_record = r.stdout.strip() if r.returncode == 0 else ''++ # Update key table+ key_entry = f'{selector}._domainkey.{domain} {domain}:{selector}:{key_dir}/{selector}.private\n'+ cls._add_or_update_line(cls.DKIM_KEY_TABLE, f'{selector}._domainkey.{domain}', key_entry)++ # Update signing table+ sign_entry = f'*@{domain} {selector}._domainkey.{domain}\n'+ cls._add_or_update_line(cls.DKIM_SIGNING_TABLE, f'*@{domain}', sign_entry)++ # Add domain to trusted hosts+ run_privileged(f'echo "{domain}" >> {cls.DKIM_TRUSTED_HOSTS}', shell=True)++ ServiceControl.restart('opendkim')++ return {+ 'success': True,+ 'dns_record': dns_record,+ 'selector': selector,+ 'message': f'DKIM key generated for {domain}'+ }+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_dns_records(cls, domain: str) -> Dict:+ """Get recommended DNS records for email authentication (SPF, DKIM, DMARC)."""+ records = []++ # SPF record+ records.append({+ 'type': 'TXT',+ 'name': domain,+ 'value': 'v=spf1 mx a ~all',+ 'purpose': 'SPF - Authorize this server to send email',+ })++ # DMARC record+ records.append({+ 'type': 'TXT',+ 'name': f'_dmarc.{domain}',+ 'value': f'v=DMARC1; p=quarantine; rua=mailto:dmarc@{domain}; pct=100',+ 'purpose': 'DMARC - Email authentication policy',+ })++ # DKIM record (read from generated key)+ if os.name != 'nt':+ key_dir = os.path.join(cls.DKIM_KEY_DIR, domain)+ txt_files = []+ try:+ r = run_privileged(['ls', key_dir])+ if r.returncode == 0:+ txt_files = [f for f in r.stdout.split() if f.endswith('.txt')]+ except Exception:+ pass++ for txt_file in txt_files:+ selector = txt_file.replace('.txt', '')+ r = run_privileged(['cat', os.path.join(key_dir, txt_file)])+ if r.returncode == 0:+ records.append({+ 'type': 'TXT',+ 'name': f'{selector}._domainkey.{domain}',+ 'value': r.stdout.strip(),+ 'purpose': f'DKIM - Email signing ({selector} selector)',+ })++ # MX record+ records.append({+ 'type': 'MX',+ 'name': domain,+ 'value': f'10 mail.{domain}',+ 'purpose': 'MX - Direct email to this server',+ })++ return {'success': True, 'records': records}++ # ==========================================+ # SERVICE CONTROL+ # ==========================================++ @classmethod+ def start_service(cls, service: str) -> Dict:+ """Start an email service."""+ allowed = {'postfix', 'dovecot', 'spamassassin', 'opendkim'}+ if service not in allowed:+ return {'success': False, 'error': f'Unknown service: {service}'}++ try:+ r = ServiceControl.start(service)+ if r.returncode != 0:+ return {'success': False, 'error': r.stderr or f'Failed to start {service}'}+ return {'success': True, 'message': f'{service} started'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def stop_service(cls, service: str) -> Dict:+ """Stop an email service."""+ allowed = {'postfix', 'dovecot', 'spamassassin', 'opendkim'}+ if service not in allowed:+ return {'success': False, 'error': f'Unknown service: {service}'}++ try:+ r = ServiceControl.stop(service)+ if r.returncode != 0:+ return {'success': False, 'error': r.stderr or f'Failed to stop {service}'}+ return {'success': True, 'message': f'{service} stopped'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def restart_service(cls, service: str) -> Dict:+ """Restart an email service."""+ allowed = {'postfix', 'dovecot', 'spamassassin', 'opendkim'}+ if service not in allowed:+ return {'success': False, 'error': f'Unknown service: {service}'}++ try:+ r = ServiceControl.restart(service)+ if r.returncode != 0:+ return {'success': False, 'error': r.stderr or f'Failed to restart {service}'}+ return {'success': True, 'message': f'{service} restarted'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # WEBMAIL+ # ==========================================++ @classmethod+ def get_webmail_status(cls) -> Dict:+ """Check if Roundcube webmail is installed."""+ if os.name == 'nt':+ return {'installed': False, 'url': None}++ installed = (+ os.path.exists('/var/www/roundcube') or+ os.path.exists('/usr/share/roundcube') or+ PackageManager.is_installed('roundcube')+ )++ return {+ 'installed': installed,+ 'url': '/webmail' if installed else None,+ }++ @classmethod+ def install_webmail(cls) -> Dict:+ """Install Roundcube webmail."""+ try:+ if os.name == 'nt':+ return {'success': False, 'error': 'Roundcube requires Linux'}++ result = PackageManager.install(['roundcube', 'roundcube-plugins'])+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Installation failed'}++ return {'success': True, 'message': 'Roundcube webmail installed'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # MAIL LOGS+ # ==========================================++ @classmethod+ def get_mail_log(cls, lines: int = 100) -> Dict:+ """Get recent mail log entries."""+ log_paths = ['/var/log/mail.log', '/var/log/maillog']++ for log_path in log_paths:+ if os.path.exists(log_path):+ try:+ r = run_privileged(['tail', '-n', str(lines), log_path])+ if r.returncode == 0:+ log_lines = [l for l in r.stdout.split('\n') if l.strip()]+ return {'success': True, 'lines': log_lines,+ 'source': log_path}+ except Exception:+ continue++ # Try journalctl fallback+ try:+ r = run_privileged(['journalctl', '-u', 'postfix', '-n', str(lines), '--no-pager'])+ if r.returncode == 0:+ log_lines = [l for l in r.stdout.split('\n') if l.strip()]+ return {'success': True, 'lines': log_lines,+ 'source': 'journalctl'}+ except Exception:+ pass++ return {'success': True, 'lines': [], 'source': None}diff --git a/frontend/index.html b/frontend/index.htmlindex 4db11b39..c1fcdfa5 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -10,10 +10,22 @@<meta name="description" content="ServerKit - Server Management Dashboard" /><title>ServerKit</title><script>- // Prevent flash of unstyled content (FOUC) by setting theme before React loads+ // Prevent flash of unstyled content (FOUC) by setting theme + accent before React loads(function() {- const theme = localStorage.getItem('theme') || 'dark';- document.documentElement.setAttribute('data-theme', theme);+ var d = document.documentElement;+ d.setAttribute('data-theme', localStorage.getItem('theme') || 'dark');+ var accent = localStorage.getItem('accent_color');+ if (accent) {+ var m = accent.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);+ if (m) {+ var r = parseInt(m[1],16), g = parseInt(m[2],16), b = parseInt(m[3],16);+ var dk = function(v){ return Math.max(0, Math.round(v*0.88)); };+ d.style.setProperty('--accent-primary', accent);+ d.style.setProperty('--accent-hover', '#'+dk(r).toString(16).padStart(2,'0')+dk(g).toString(16).padStart(2,'0')+dk(b).toString(16).padStart(2,'0'));+ d.style.setProperty('--accent-glow', 'rgba('+r+','+g+','+b+',0.15)');+ d.style.setProperty('--accent-shadow', 'rgba('+r+','+g+','+b+',0.3)');+ }+ }})();</script></head>diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex cc58bfd9..bbddce44 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -35,6 +35,7 @@ import WordPressDetail from './pages/WordPressDetail';import WordPressProjects from './pages/WordPressProjects';import WordPressProject from './pages/WordPressProject';import SSLCertificates from './pages/SSLCertificates';+import Email from './pages/Email';// Page title mappingconst PAGE_TITLES = {@@ -60,6 +61,7 @@ const PAGE_TITLES = {'/backups': 'Backups','/cron': 'Cron Jobs','/security': 'Security',+ '/email': 'Email Server','/terminal': 'Terminal','/settings': 'Settings',};@@ -197,6 +199,8 @@ function AppRoutes() {<Route path="cron" element={<CronJobs />} /><Route path="security" element={<Security />} /><Route path="security/:tab" element={<Security />} />+ <Route path="email" element={<Email />} />+ <Route path="email/:tab" element={<Email />} /><Route path="terminal" element={<Terminal />} /><Route path="terminal/:tab" element={<Terminal />} /><Route path="settings" element={<Settings />} />diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex dd93a743..ce6ccef1 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -250,6 +250,13 @@ const Sidebar = () => {</svg>Security</NavLink>+ <NavLink to="/email" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>+ <svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">+ <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>+ Email Server+ </NavLink></nav><div className="nav-category">System</div>diff --git a/frontend/src/contexts/ThemeContext.jsx b/frontend/src/contexts/ThemeContext.jsxindex 6b9daead..40461d2b 100644--- a/frontend/src/contexts/ThemeContext.jsx+++ b/frontend/src/contexts/ThemeContext.jsx@@ -2,6 +2,8 @@ import React, { createContext, useContext, useState, useEffect, useCallback } frconst ThemeContext = createContext(null);+const DEFAULT_ACCENT = '#6366f1';+// Get the resolved theme based on current setting and OS preferencefunction getResolvedTheme(theme) {if (theme === 'system') {@@ -10,6 +12,40 @@ function getResolvedTheme(theme) {return theme;}+// Convert hex to { r, g, b }+function hexToRgb(hex) {+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);+ if (!result) return { r: 99, g: 102, b: 241 };+ return {+ r: parseInt(result[1], 16),+ g: parseInt(result[2], 16),+ b: parseInt(result[3], 16),+ };+}++// Derive accent color variants from a hex color+function deriveAccentVariants(hex) {+ const { r, g, b } = hexToRgb(hex);+ // Darken by ~12% for hover+ const darken = (v) => Math.max(0, Math.round(v * 0.88));+ return {+ primary: hex,+ hover: `#${darken(r).toString(16).padStart(2, '0')}${darken(g).toString(16).padStart(2, '0')}${darken(b).toString(16).padStart(2, '0')}`,+ glow: `rgba(${r}, ${g}, ${b}, 0.15)`,+ shadow: `rgba(${r}, ${g}, ${b}, 0.3)`,+ };+}++// Apply accent CSS custom properties to the document+function applyAccentToDOM(hex) {+ const variants = deriveAccentVariants(hex);+ const style = document.documentElement.style;+ style.setProperty('--accent-primary', variants.primary);+ style.setProperty('--accent-hover', variants.hover);+ style.setProperty('--accent-glow', variants.glow);+ style.setProperty('--accent-shadow', variants.shadow);+}+export function ThemeProvider({ children }) {const [theme, setThemeState] = useState(() => {return localStorage.getItem('theme') || 'dark';@@ -20,6 +56,10 @@ export function ThemeProvider({ children }) {return getResolvedTheme(stored);});+ const [accentColor, setAccentColorState] = useState(() => {+ return localStorage.getItem('accent_color') || DEFAULT_ACCENT;+ });+// Update the DOM attribute and resolved themeconst applyTheme = useCallback((newTheme) => {document.documentElement.setAttribute('data-theme', newTheme);@@ -33,6 +73,13 @@ export function ThemeProvider({ children }) {applyTheme(newTheme);}, [applyTheme]);+ // Public setter for accent color+ const setAccentColor = useCallback((hex) => {+ setAccentColorState(hex);+ localStorage.setItem('accent_color', hex);+ applyAccentToDOM(hex);+ }, []);+// Listen for OS theme changes when using 'system' themeuseEffect(() => {if (theme !== 'system') return;@@ -47,15 +94,18 @@ export function ThemeProvider({ children }) {return () => mediaQuery.removeEventListener('change', handleChange);}, [theme]);- // Apply theme on mount (handles cases where FOUC script didn't run)+ // Apply theme and accent on mountuseEffect(() => {applyTheme(theme);- }, [theme, applyTheme]);+ applyAccentToDOM(accentColor);+ }, [theme, applyTheme, accentColor]);const value = {theme, // Current setting: 'dark' | 'light' | 'system'resolvedTheme, // Actual appearance: 'dark' | 'light'setTheme, // Function to change theme+ accentColor, // Current accent hex color+ setAccentColor, // Function to change accent color};return (diff --git a/frontend/src/hooks/useDashboardLayout.js b/frontend/src/hooks/useDashboardLayout.jsnew file mode 100644index 00000000..2a94b544--- /dev/null+++ b/frontend/src/hooks/useDashboardLayout.js@@ -0,0 +1,85 @@+import { useState, useCallback } from 'react';++const STORAGE_KEY = 'dashboard_layout';++const DEFAULT_WIDGETS = [+ { id: 'cpu', label: 'CPU', visible: true },+ { id: 'ram', label: 'RAM', visible: true },+ { id: 'network', label: 'Network', visible: true },+ { id: 'disk', label: 'Disk', visible: true },+ { id: 'chart', label: 'Metrics Chart', visible: true },+ { id: 'specs', label: 'Quick Actions & Specs', visible: true },+ { id: 'processes', label: 'Processes / Containers', visible: true },+];++function loadWidgets() {+ try {+ const stored = JSON.parse(localStorage.getItem(STORAGE_KEY));+ if (!Array.isArray(stored)) return DEFAULT_WIDGETS.map(w => ({ ...w }));++ // Merge with defaults to handle new widgets added in future versions+ const storedMap = new Map(stored.map(w => [w.id, w]));+ const merged = [];++ // Keep stored order for known widgets+ for (const sw of stored) {+ const def = DEFAULT_WIDGETS.find(d => d.id === sw.id);+ if (def) {+ merged.push({ ...def, visible: sw.visible });+ }+ }++ // Append any new defaults not in stored+ for (const dw of DEFAULT_WIDGETS) {+ if (!storedMap.has(dw.id)) {+ merged.push({ ...dw });+ }+ }++ return merged;+ } catch {+ return DEFAULT_WIDGETS.map(w => ({ ...w }));+ }+}++function saveWidgets(widgets) {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(widgets.map(({ id, visible }) => ({ id, visible }))));+}++export default function useDashboardLayout() {+ const [widgets, setWidgets] = useState(loadWidgets);++ const toggleWidget = useCallback((id) => {+ setWidgets(prev => {+ const next = prev.map(w => w.id === id ? { ...w, visible: !w.visible } : w);+ saveWidgets(next);+ return next;+ });+ }, []);++ const moveWidget = useCallback((id, direction) => {+ setWidgets(prev => {+ const idx = prev.findIndex(w => w.id === id);+ if (idx < 0) return prev;+ const swapIdx = direction === 'up' ? idx - 1 : idx + 1;+ if (swapIdx < 0 || swapIdx >= prev.length) return prev;+ const next = [...prev];+ [next[idx], next[swapIdx]] = [next[swapIdx], next[idx]];+ saveWidgets(next);+ return next;+ });+ }, []);++ const resetLayout = useCallback(() => {+ const fresh = DEFAULT_WIDGETS.map(w => ({ ...w }));+ saveWidgets(fresh);+ setWidgets(fresh);+ }, []);++ const isVisible = useCallback((id) => {+ const w = widgets.find(w => w.id === id);+ return w ? w.visible : true;+ }, [widgets]);++ return { widgets, toggleWidget, moveWidget, resetLayout, isVisible };+}diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsxindex f1799f41..7124167f 100644--- a/frontend/src/pages/Dashboard.jsx+++ b/frontend/src/pages/Dashboard.jsx@@ -8,6 +8,7 @@ import {import api from '../services/api';import { useMetrics } from '../hooks/useMetrics';import MetricsGraph from '../components/MetricsGraph';+import useDashboardLayout from '../hooks/useDashboardLayout';// Refresh interval options in secondsconst REFRESH_OPTIONS = [@@ -21,6 +22,7 @@ const REFRESH_OPTIONS = [const Dashboard = () => {const navigate = useNavigate();const { metrics, loading: metricsLoading, connected, refresh: refreshMetrics } = useMetrics(true);+ const { widgets } = useDashboardLayout();const [apps, setApps] = useState([]);const [services, setServices] = useState([]);const [dbStatus, setDbStatus] = useState(null);@@ -218,147 +220,156 @@ const Dashboard = () => {{/* Grid Container */}<div className="grid-container">- {/* Metric Tiles */}- <div className="metric-tile">- <div className="tile-head">- <span className="tile-title">CPU</span>- <Zap size={16} className="tile-icon cpu" />- </div>- <div className="tile-val">{(metrics?.cpu?.percent || 0).toFixed(1)}%</div>- <div className="tile-sub">- <span>Cores: {metrics?.cpu?.count_logical || 0}</span>- <span className={metrics?.cpu?.percent > 50 ? 'trend-up' : 'trend-down'}>- {metrics?.cpu?.percent > 50 ? '▲' : '▼'} {Math.abs(metrics?.cpu?.percent - 50).toFixed(0)}%- </span>- </div>- </div>-- <div className="metric-tile">- <div className="tile-head">- <span className="tile-title">RAM</span>- <Database size={16} className="tile-icon memory" />- </div>- <div className="tile-val">{metrics?.memory?.ram?.used_human || '0 GB'}</div>- <div className="tile-sub">- <span>Total: {metrics?.memory?.ram?.total_human || '0 GB'}</span>- <span>Cached: {metrics?.memory?.ram?.cached_human || '0 GB'}</span>- </div>- </div>+ {widgets.filter(w => w.visible).map(w => {+ const WIDGET_RENDERERS = {+ cpu: () => (+ <div key="cpu" className="metric-tile">+ <div className="tile-head">+ <span className="tile-title">CPU</span>+ <Zap size={16} className="tile-icon cpu" />+ </div>+ <div className="tile-val">{(metrics?.cpu?.percent || 0).toFixed(1)}%</div>+ <div className="tile-sub">+ <span>Cores: {metrics?.cpu?.count_logical || 0}</span>+ <span className={metrics?.cpu?.percent > 50 ? 'trend-up' : 'trend-down'}>+ {metrics?.cpu?.percent > 50 ? '▲' : '▼'} {Math.abs(metrics?.cpu?.percent - 50).toFixed(0)}%+ </span>+ </div>+ </div>+ ),+ ram: () => (+ <div key="ram" className="metric-tile">+ <div className="tile-head">+ <span className="tile-title">RAM</span>+ <Database size={16} className="tile-icon memory" />+ </div>+ <div className="tile-val">{metrics?.memory?.ram?.used_human || '0 GB'}</div>+ <div className="tile-sub">+ <span>Total: {metrics?.memory?.ram?.total_human || '0 GB'}</span>+ <span>Cached: {metrics?.memory?.ram?.cached_human || '0 GB'}</span>+ </div>+ </div>+ ),+ network: () => (+ <div key="network" className="metric-tile">+ <div className="tile-head">+ <span className="tile-title">Network</span>+ <Activity size={16} className="tile-icon network" />+ </div>+ <div className="tile-val">+ {metrics?.network?.io?.bytes_sent_human || '0 B'}+ <span className="tile-val-unit">sent</span>+ </div>+ <div className="tile-sub">+ <span>In: {metrics?.network?.io?.bytes_recv_human || '0 B'}</span>+ <span>Out: {metrics?.network?.io?.bytes_sent_human || '0 B'}</span>+ </div>+ </div>+ ),+ disk: () => (+ <div key="disk" className="metric-tile">+ <div className="tile-head">+ <span className="tile-title">Disk</span>+ <HardDrive size={16} className="tile-icon disk" />+ </div>+ <div className="tile-val">+ {(metrics?.disk?.partitions?.[0]?.percent || 0).toFixed(1)}%+ <span className="tile-val-unit">used</span>+ </div>+ <div className="tile-sub">+ <span>Used: {metrics?.disk?.partitions?.[0]?.used_human || '0 GB'}</span>+ <span>Free: {metrics?.disk?.partitions?.[0]?.free_human || '0 GB'}</span>+ </div>+ </div>+ ),+ chart: () => (+ <div key="chart" className="chart-panel">+ <MetricsGraph timezone={serverTime?.timezone_id} />+ </div>+ ),+ specs: () => (+ <div key="specs" className="spec-panel">+ <h3 className="spec-panel-title">Quick Actions</h3>+ <button className="btn-action" onClick={() => navigate('/docker')}>+ <span>Restart Services</span>+ <span>►</span>+ </button>+ <button className="btn-action" onClick={() => navigate('/databases')}>+ <span>Clear Cache</span>+ <span><Zap size={14} /></span>+ </button>+ <button className="btn-action" onClick={() => navigate('/ssl')}>+ <span>Rotate SSL Certs</span>+ <span><RotateCcw size={14} /></span>+ </button>- <div className="metric-tile">- <div className="tile-head">- <span className="tile-title">Network</span>- <Activity size={16} className="tile-icon network" />- </div>- <div className="tile-val">- {metrics?.network?.io?.bytes_sent_human || '0 B'}- <span className="tile-val-unit">sent</span>- </div>- <div className="tile-sub">- <span>In: {metrics?.network?.io?.bytes_recv_human || '0 B'}</span>- <span>Out: {metrics?.network?.io?.bytes_sent_human || '0 B'}</span>- </div>- </div>-- <div className="metric-tile">- <div className="tile-head">- <span className="tile-title">Disk</span>- <HardDrive size={16} className="tile-icon disk" />- </div>- <div className="tile-val">- {(metrics?.disk?.partitions?.[0]?.percent || 0).toFixed(1)}%- <span className="tile-val-unit">used</span>- </div>- <div className="tile-sub">- <span>Used: {metrics?.disk?.partitions?.[0]?.used_human || '0 GB'}</span>- <span>Free: {metrics?.disk?.partitions?.[0]?.free_human || '0 GB'}</span>- </div>- </div>-- {/* Chart Panel */}- <div className="chart-panel">- <MetricsGraph timezone={serverTime?.timezone_id} />- </div>-- {/* Spec Panel */}- <div className="spec-panel">- <h3 className="spec-panel-title">Quick Actions</h3>- <button className="btn-action" onClick={() => navigate('/docker')}>- <span>Restart Services</span>- <span>►</span>- </button>- <button className="btn-action" onClick={() => navigate('/databases')}>- <span>Clear Cache</span>- <span><Zap size={14} /></span>- </button>- <button className="btn-action" onClick={() => navigate('/ssl')}>- <span>Rotate SSL Certs</span>- <span><RotateCcw size={14} /></span>- </button>-- <h3 className="spec-panel-title" style={{ marginTop: '1.5rem' }}>Hardware Specs</h3>- <div className="spec-row">- <span className="spec-label">Processor</span>- <span className="spec-data">{systemInfo?.cpu?.model || 'N/A'}</span>- </div>- <div className="spec-row">- <span className="spec-label">Architecture</span>- <span className="spec-data">{systemInfo?.cpu?.architecture || 'N/A'}</span>- </div>- <div className="spec-row">- <span className="spec-label">Swap Memory</span>- <span className="spec-data">{metrics?.memory?.swap?.total_human || 'N/A'}</span>- </div>- </div>-- {/* Process Table */}- <div className="table-panel">- <div className="table-header">- <span>Active Processes / Containers</span>- <button className="btn btn-sm btn-secondary" onClick={loadData}>- <RefreshCw size={14} />- </button>- </div>- <table className="data-table">- <thead>- <tr>- <th>ID</th>- <th>Name</th>- <th>Type</th>- <th>Status</th>- <th>Domain</th>- </tr>- </thead>- <tbody>- {apps.length === 0 ? (- <tr>- <td colSpan="5" style={{ textAlign: 'center', color: 'var(--text-tertiary)' }}>- No applications found- </td>- </tr>- ) : (- apps.slice(0, 6).map(app => (- <tr key={app.id} onClick={() => navigate(`/apps/${app.id}`)} style={{ cursor: 'pointer' }}>- <td>{app.id}</td>- <td>- <div className="app-name-cell">- <span className="app-icon-mini">{getStackIcon(app.app_type)}</span>- {app.name}- </div>- </td>- <td>{app.app_type}</td>- <td>- <span className={`badge badge-${app.status === 'running' ? 'running' : 'warning'}`}>- {app.status?.toUpperCase()}- </span>- </td>- <td>{app.domains?.[0]?.name || '-'}</td>- </tr>- ))- )}- </tbody>- </table>- </div>+ <h3 className="spec-panel-title" style={{ marginTop: '1.5rem' }}>Hardware Specs</h3>+ <div className="spec-row">+ <span className="spec-label">Processor</span>+ <span className="spec-data">{systemInfo?.cpu?.model || 'N/A'}</span>+ </div>+ <div className="spec-row">+ <span className="spec-label">Architecture</span>+ <span className="spec-data">{systemInfo?.cpu?.architecture || 'N/A'}</span>+ </div>+ <div className="spec-row">+ <span className="spec-label">Swap Memory</span>+ <span className="spec-data">{metrics?.memory?.swap?.total_human || 'N/A'}</span>+ </div>+ </div>+ ),+ processes: () => (+ <div key="processes" className="table-panel">+ <div className="table-header">+ <span>Active Processes / Containers</span>+ <button className="btn btn-sm btn-secondary" onClick={loadData}>+ <RefreshCw size={14} />+ </button>+ </div>+ <table className="data-table">+ <thead>+ <tr>+ <th>ID</th>+ <th>Name</th>+ <th>Type</th>+ <th>Status</th>+ <th>Domain</th>+ </tr>+ </thead>+ <tbody>+ {apps.length === 0 ? (+ <tr>+ <td colSpan="5" style={{ textAlign: 'center', color: 'var(--text-tertiary)' }}>+ No applications found+ </td>+ </tr>+ ) : (+ apps.slice(0, 6).map(app => (+ <tr key={app.id} onClick={() => navigate(`/apps/${app.id}`)} style={{ cursor: 'pointer' }}>+ <td>{app.id}</td>+ <td>+ <div className="app-name-cell">+ <span className="app-icon-mini">{getStackIcon(app.app_type)}</span>+ {app.name}+ </div>+ </td>+ <td>{app.app_type}</td>+ <td>+ <span className={`badge badge-${app.status === 'running' ? 'running' : 'warning'}`}>+ {app.status?.toUpperCase()}+ </span>+ </td>+ <td>{app.domains?.[0]?.name || '-'}</td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div>+ ),+ };+ return WIDGET_RENDERERS[w.id]?.();+ })}</div></div>);diff --git a/frontend/src/pages/Email.jsx b/frontend/src/pages/Email.jsxnew file mode 100644index 00000000..2b81d02b--- /dev/null+++ b/frontend/src/pages/Email.jsx@@ -0,0 +1,1164 @@+import { useState, useEffect } from 'react';+import useTabParam from '../hooks/useTabParam';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const VALID_TABS = ['overview', 'accounts', 'postfix', 'dovecot', 'spam', 'authentication', 'queue', 'webmail', 'logs'];++const Email = () => {+ const [activeTab, setActiveTab] = useTabParam('/email', VALID_TABS);+ const [status, setStatus] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadStatus();+ }, []);++ async function loadStatus() {+ try {+ const data = await api.getEmailStatus();+ setStatus(data);+ } catch (err) {+ console.error('Failed to load email status:', err);+ } finally {+ setLoading(false);+ }+ }++ if (loading) {+ return <div className="page"><div className="loading">Loading email server status...</div></div>;+ }++ return (+ <div className="page email-page">+ <div className="page-header">+ <div>+ <h1>Email Server</h1>+ <p className="page-subtitle">Manage Postfix, Dovecot, spam filtering, and email authentication</p>+ </div>+ </div>++ <div className="tabs-nav tabs-nav-scrollable">+ <button className={`tab-btn ${activeTab === 'overview' ? 'active' : ''}`} onClick={() => setActiveTab('overview')}>+ Overview+ </button>+ <button className={`tab-btn ${activeTab === 'accounts' ? 'active' : ''}`} onClick={() => setActiveTab('accounts')}>+ Accounts+ </button>+ <button className={`tab-btn ${activeTab === 'postfix' ? 'active' : ''}`} onClick={() => setActiveTab('postfix')}>+ Postfix (SMTP)+ </button>+ <button className={`tab-btn ${activeTab === 'dovecot' ? 'active' : ''}`} onClick={() => setActiveTab('dovecot')}>+ Dovecot (IMAP)+ </button>+ <button className={`tab-btn ${activeTab === 'spam' ? 'active' : ''}`} onClick={() => setActiveTab('spam')}>+ Spam Filter+ </button>+ <button className={`tab-btn ${activeTab === 'authentication' ? 'active' : ''}`} onClick={() => setActiveTab('authentication')}>+ DKIM/SPF/DMARC+ </button>+ <button className={`tab-btn ${activeTab === 'queue' ? 'active' : ''}`} onClick={() => setActiveTab('queue')}>+ Mail Queue+ </button>+ <button className={`tab-btn ${activeTab === 'webmail' ? 'active' : ''}`} onClick={() => setActiveTab('webmail')}>+ Webmail+ </button>+ <button className={`tab-btn ${activeTab === 'logs' ? 'active' : ''}`} onClick={() => setActiveTab('logs')}>+ Logs+ </button>+ </div>++ <div className="tab-content">+ {activeTab === 'overview' && <OverviewTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'accounts' && <AccountsTab />}+ {activeTab === 'postfix' && <PostfixTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'dovecot' && <DovecotTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'spam' && <SpamTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'authentication' && <AuthenticationTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'queue' && <QueueTab />}+ {activeTab === 'webmail' && <WebmailTab />}+ {activeTab === 'logs' && <LogsTab />}+ </div>+ </div>+ );+};+++// ==========================================+// OVERVIEW TAB+// ==========================================++const OverviewTab = ({ status, onRefresh }) => {+ const { showToast } = useToast();++ const services = [+ { key: 'postfix', label: 'Postfix', desc: 'SMTP mail transfer agent', data: status?.postfix },+ { key: 'dovecot', label: 'Dovecot', desc: 'IMAP/POP3 server', data: status?.dovecot },+ { key: 'spamassassin', label: 'SpamAssassin', desc: 'Spam filtering engine', data: status?.spamassassin },+ { key: 'opendkim', label: 'OpenDKIM', desc: 'DKIM email signing', data: status?.opendkim },+ ];++ async function handleServiceAction(service, action) {+ try {+ if (action === 'start') await api.startEmailService(service);+ else if (action === 'stop') await api.stopEmailService(service);+ else if (action === 'restart') await api.restartEmailService(service);+ showToast(`${service} ${action}ed successfully`, 'success');+ onRefresh();+ } catch (err) {+ showToast(err.message || `Failed to ${action} ${service}`, 'error');+ }+ }++ return (+ <div className="email-overview">+ <div className="services-grid">+ {services.map(svc => (+ <div key={svc.key} className="card email-service-card">+ <div className="card-body">+ <div className="email-service-header">+ <div>+ <h3>{svc.label}</h3>+ <p className="text-secondary">{svc.desc}</p>+ </div>+ <span className={`badge ${svc.data?.running ? 'badge-success' : svc.data?.installed ? 'badge-warning' : 'badge-secondary'}`}>+ {svc.data?.running ? 'Running' : svc.data?.installed ? 'Stopped' : 'Not Installed'}+ </span>+ </div>++ {svc.data?.version && (+ <div className="email-service-meta">+ <span className="text-secondary">Version: {svc.data.version}</span>+ </div>+ )}++ {svc.data?.installed && (+ <div className="email-service-actions">+ {svc.data.running ? (+ <>+ <button className="btn btn-sm btn-outline" onClick={() => handleServiceAction(svc.key, 'restart')}>+ Restart+ </button>+ <button className="btn btn-sm btn-outline btn-danger" onClick={() => handleServiceAction(svc.key, 'stop')}>+ Stop+ </button>+ </>+ ) : (+ <button className="btn btn-sm btn-primary" onClick={() => handleServiceAction(svc.key, 'start')}>+ Start+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+};+++// ==========================================+// ACCOUNTS TAB+// ==========================================++const AccountsTab = () => {+ const { showToast } = useToast();+ const [accounts, setAccounts] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showCreate, setShowCreate] = useState(false);+ const [editingForward, setEditingForward] = useState(null);+ const [formData, setFormData] = useState({ email: '', password: '', domain: '', quota_mb: 1024 });+ const [forwardData, setForwardData] = useState({ forward_to: '', keep_copy: true });++ useEffect(() => {+ loadAccounts();+ }, []);++ async function loadAccounts() {+ try {+ const data = await api.getEmailAccounts();+ setAccounts(data.accounts || []);+ } catch (err) {+ showToast('Failed to load accounts', 'error');+ } finally {+ setLoading(false);+ }+ }++ async function handleCreate(e) {+ e.preventDefault();+ try {+ const result = await api.createEmailAccount(formData);+ if (result.success) {+ showToast('Account created', 'success');+ setShowCreate(false);+ setFormData({ email: '', password: '', domain: '', quota_mb: 1024 });+ loadAccounts();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ async function handleDelete(accountId) {+ if (!confirm('Delete this email account? This cannot be undone.')) return;+ try {+ const result = await api.deleteEmailAccount(accountId);+ if (result.success) {+ showToast('Account deleted', 'success');+ loadAccounts();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ async function handleToggle(account) {+ try {+ await api.updateEmailAccount(account.id, { enabled: !account.enabled });+ showToast(`Account ${account.enabled ? 'disabled' : 'enabled'}`, 'success');+ loadAccounts();+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ async function handleForwarding(e) {+ e.preventDefault();+ try {+ const result = await api.setEmailForwarding(editingForward, forwardData);+ if (result.success) {+ showToast('Forwarding updated', 'success');+ setEditingForward(null);+ loadAccounts();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ if (loading) return <div className="loading">Loading accounts...</div>;++ return (+ <div className="email-accounts">+ <div className="section-header">+ <h2>Email Accounts</h2>+ <button className="btn btn-primary" onClick={() => setShowCreate(!showCreate)}>+ {showCreate ? 'Cancel' : 'Create Account'}+ </button>+ </div>++ {showCreate && (+ <form className="card email-create-form" onSubmit={handleCreate}>+ <div className="card-body">+ <div className="form-grid">+ <div className="form-group">+ <label>Email Address</label>+ <input+ type="email"+ className="form-control"+ value={formData.email}+ onChange={e => setFormData({ ...formData, email: e.target.value })}+ placeholder="[email protected]"+ required+ />+ </div>+ <div className="form-group">+ <label>Domain</label>+ <input+ type="text"+ className="form-control"+ value={formData.domain}+ onChange={e => setFormData({ ...formData, domain: e.target.value })}+ placeholder="example.com"+ required+ />+ </div>+ <div className="form-group">+ <label>Password</label>+ <input+ type="password"+ className="form-control"+ value={formData.password}+ onChange={e => setFormData({ ...formData, password: e.target.value })}+ placeholder="Strong password"+ required+ />+ </div>+ <div className="form-group">+ <label>Quota (MB)</label>+ <input+ type="number"+ className="form-control"+ value={formData.quota_mb}+ onChange={e => setFormData({ ...formData, quota_mb: parseInt(e.target.value) || 1024 })}+ min="100"+ />+ </div>+ </div>+ <button type="submit" className="btn btn-primary" style={{ marginTop: '16px' }}>+ Create Account+ </button>+ </div>+ </form>+ )}++ {accounts.length === 0 ? (+ <div className="card">+ <div className="card-body empty-state">+ <p>No email accounts configured yet.</p>+ </div>+ </div>+ ) : (+ <div className="table-container">+ <table className="table">+ <thead>+ <tr>+ <th>Email</th>+ <th>Domain</th>+ <th>Quota</th>+ <th>Forwarding</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {accounts.map(account => (+ <tr key={account.id}>+ <td><strong>{account.email}</strong></td>+ <td>{account.domain}</td>+ <td>{account.quota_mb} MB</td>+ <td>{account.forward_to || 'None'}</td>+ <td>+ <span className={`badge ${account.enabled ? 'badge-success' : 'badge-secondary'}`}>+ {account.enabled ? 'Active' : 'Disabled'}+ </span>+ </td>+ <td>+ <div className="btn-group">+ <button+ className="btn btn-sm btn-outline"+ onClick={() => handleToggle(account)}+ >+ {account.enabled ? 'Disable' : 'Enable'}+ </button>+ <button+ className="btn btn-sm btn-outline"+ onClick={() => {+ setEditingForward(account.id);+ setForwardData({+ forward_to: account.forward_to || '',+ keep_copy: account.forward_keep_copy !== false,+ });+ }}+ >+ Forward+ </button>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleDelete(account.id)}+ >+ Delete+ </button>+ </div>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ {editingForward && (+ <div className="modal-overlay" onClick={() => setEditingForward(null)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h3>Email Forwarding</h3>+ <button className="modal-close" onClick={() => setEditingForward(null)}>×</button>+ </div>+ <form onSubmit={handleForwarding}>+ <div className="modal-body">+ <div className="form-group">+ <label>Forward To</label>+ <input+ type="text"+ className="form-control"+ value={forwardData.forward_to}+ onChange={e => setForwardData({ ...forwardData, forward_to: e.target.value })}+ placeholder="[email protected], [email protected]"+ />+ <small className="form-help">Comma-separated email addresses. Leave empty to disable forwarding.</small>+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={forwardData.keep_copy}+ onChange={e => setForwardData({ ...forwardData, keep_copy: e.target.checked })}+ />+ Keep a copy in this mailbox+ </label>+ </div>+ </div>+ <div className="modal-footer">+ <button type="button" className="btn btn-outline" onClick={() => setEditingForward(null)}>Cancel</button>+ <button type="submit" className="btn btn-primary">Save</button>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>+ );+};+++// ==========================================+// POSTFIX TAB+// ==========================================++const PostfixTab = ({ status, onRefresh }) => {+ const { showToast } = useToast();+ const [config, setConfig] = useState(null);+ const [loading, setLoading] = useState(true);+ const [installing, setInstalling] = useState(false);++ useEffect(() => {+ if (status?.postfix?.installed) loadConfig();+ else setLoading(false);+ }, [status]);++ async function loadConfig() {+ try {+ const data = await api.getPostfixConfig();+ setConfig(data.config || {});+ } catch (err) {+ console.error('Failed to load Postfix config:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleInstall() {+ setInstalling(true);+ try {+ const result = await api.installPostfix();+ if (result.success) {+ showToast('Postfix installed', 'success');+ onRefresh();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setInstalling(false);+ }+ }++ async function handleSave() {+ try {+ const result = await api.updatePostfixConfig(config);+ if (result.success) {+ showToast('Configuration saved', 'success');+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ if (loading) return <div className="loading">Loading...</div>;++ if (!status?.postfix?.installed) {+ return (+ <div className="card">+ <div className="card-body empty-state">+ <h3>Postfix Not Installed</h3>+ <p>Postfix is a high-performance mail transfer agent (MTA) used for sending and receiving email.</p>+ <button+ className="btn btn-primary"+ onClick={handleInstall}+ disabled={installing}+ >+ {installing ? 'Installing...' : 'Install Postfix'}+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="email-postfix">+ <div className="card">+ <div className="card-header">+ <h3>Postfix Configuration</h3>+ </div>+ <div className="card-body">+ {config && (+ <div className="form-grid">+ {Object.entries(config).map(([key, value]) => (+ <div className="form-group" key={key}>+ <label>{key}</label>+ <input+ type="text"+ className="form-control"+ value={value}+ onChange={e => setConfig({ ...config, [key]: e.target.value })}+ />+ </div>+ ))}+ </div>+ )}+ <button className="btn btn-primary" onClick={handleSave} style={{ marginTop: '16px' }}>+ Save Configuration+ </button>+ </div>+ </div>+ </div>+ );+};+++// ==========================================+// DOVECOT TAB+// ==========================================++const DovecotTab = ({ status, onRefresh }) => {+ const { showToast } = useToast();+ const [config, setConfig] = useState(null);+ const [loading, setLoading] = useState(true);+ const [installing, setInstalling] = useState(false);++ useEffect(() => {+ if (status?.dovecot?.installed) loadConfig();+ else setLoading(false);+ }, [status]);++ async function loadConfig() {+ try {+ const data = await api.getDovecotConfig();+ setConfig(data.config || {});+ } catch (err) {+ console.error('Failed to load Dovecot config:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleInstall() {+ setInstalling(true);+ try {+ const result = await api.installDovecot();+ if (result.success) {+ showToast('Dovecot installed', 'success');+ onRefresh();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setInstalling(false);+ }+ }++ if (loading) return <div className="loading">Loading...</div>;++ if (!status?.dovecot?.installed) {+ return (+ <div className="card">+ <div className="card-body empty-state">+ <h3>Dovecot Not Installed</h3>+ <p>Dovecot is an IMAP and POP3 server that allows email clients to access mailboxes.</p>+ <button+ className="btn btn-primary"+ onClick={handleInstall}+ disabled={installing}+ >+ {installing ? 'Installing...' : 'Install Dovecot'}+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="email-dovecot">+ <div className="card">+ <div className="card-header">+ <h3>Dovecot Configuration</h3>+ <span className={`badge ${status?.dovecot?.running ? 'badge-success' : 'badge-warning'}`}>+ {status?.dovecot?.running ? 'Running' : 'Stopped'}+ </span>+ </div>+ <div className="card-body">+ {config && Object.keys(config).length > 0 ? (+ <div className="config-list">+ {Object.entries(config).map(([key, value]) => (+ <div className="config-item" key={key}>+ <span className="config-key">{key}</span>+ <span className="config-value">{value}</span>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-secondary">Using default Dovecot configuration.</p>+ )}+ </div>+ </div>+ </div>+ );+};+++// ==========================================+// SPAM FILTER TAB+// ==========================================++const SpamTab = ({ status, onRefresh }) => {+ const { showToast } = useToast();+ const [config, setConfig] = useState(null);+ const [loading, setLoading] = useState(true);+ const [installing, setInstalling] = useState(false);++ useEffect(() => {+ if (status?.spamassassin?.installed) loadConfig();+ else setLoading(false);+ }, [status]);++ async function loadConfig() {+ try {+ const data = await api.getSpamAssassinConfig();+ setConfig(data.config || {});+ } catch (err) {+ console.error('Failed to load SpamAssassin config:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleInstall() {+ setInstalling(true);+ try {+ const result = await api.installSpamAssassin();+ if (result.success) {+ showToast('SpamAssassin installed', 'success');+ onRefresh();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setInstalling(false);+ }+ }++ async function handleSave() {+ try {+ const result = await api.updateSpamAssassinConfig(config);+ if (result.success) {+ showToast('SpamAssassin configuration saved', 'success');+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ if (loading) return <div className="loading">Loading...</div>;++ if (!status?.spamassassin?.installed) {+ return (+ <div className="card">+ <div className="card-body empty-state">+ <h3>SpamAssassin Not Installed</h3>+ <p>SpamAssassin is a mail filter that identifies spam using content analysis and DNS blocklists.</p>+ <button+ className="btn btn-primary"+ onClick={handleInstall}+ disabled={installing}+ >+ {installing ? 'Installing...' : 'Install SpamAssassin'}+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="email-spam">+ <div className="card">+ <div className="card-header">+ <h3>SpamAssassin Configuration</h3>+ </div>+ <div className="card-body">+ {config && (+ <div className="form-grid">+ <div className="form-group">+ <label>Required Score (higher = less aggressive)</label>+ <input+ type="number"+ className="form-control"+ value={config.required_score}+ onChange={e => setConfig({ ...config, required_score: parseFloat(e.target.value) })}+ step="0.5"+ min="1"+ max="10"+ />+ </div>+ <div className="form-group">+ <label>Spam Subject Prefix</label>+ <input+ type="text"+ className="form-control"+ value={config.rewrite_header_subject}+ onChange={e => setConfig({ ...config, rewrite_header_subject: e.target.value })}+ />+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={config.use_bayes}+ onChange={e => setConfig({ ...config, use_bayes: e.target.checked })}+ />+ Enable Bayesian Filtering+ </label>+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={config.bayes_auto_learn}+ onChange={e => setConfig({ ...config, bayes_auto_learn: e.target.checked })}+ />+ Auto-learn from messages+ </label>+ </div>+ </div>+ )}+ <button className="btn btn-primary" onClick={handleSave} style={{ marginTop: '16px' }}>+ Save Configuration+ </button>+ </div>+ </div>+ </div>+ );+};+++// ==========================================+// AUTHENTICATION TAB (DKIM/SPF/DMARC)+// ==========================================++const AuthenticationTab = ({ status, onRefresh }) => {+ const { showToast } = useToast();+ const [domain, setDomain] = useState('');+ const [selector, setSelector] = useState('mail');+ const [dnsRecords, setDnsRecords] = useState(null);+ const [installing, setInstalling] = useState(false);+ const [generating, setGenerating] = useState(false);++ async function handleInstallDkim() {+ setInstalling(true);+ try {+ const result = await api.installDkim();+ if (result.success) {+ showToast('OpenDKIM installed', 'success');+ onRefresh();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setInstalling(false);+ }+ }++ async function handleGenerateKey() {+ if (!domain) {+ showToast('Please enter a domain', 'error');+ return;+ }+ setGenerating(true);+ try {+ const result = await api.generateDkimKey({ domain, selector });+ if (result.success) {+ showToast('DKIM key generated', 'success');+ loadDnsRecords();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setGenerating(false);+ }+ }++ async function loadDnsRecords() {+ if (!domain) return;+ try {+ const data = await api.getEmailDnsRecords(domain);+ setDnsRecords(data.records || []);+ } catch (err) {+ showToast('Failed to load DNS records', 'error');+ }+ }++ return (+ <div className="email-authentication">+ {!status?.opendkim?.installed && (+ <div className="card">+ <div className="card-body empty-state">+ <h3>OpenDKIM Not Installed</h3>+ <p>DKIM signs outgoing emails to prove they were sent from your server and have not been tampered with.</p>+ <button+ className="btn btn-primary"+ onClick={handleInstallDkim}+ disabled={installing}+ >+ {installing ? 'Installing...' : 'Install OpenDKIM'}+ </button>+ </div>+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>Generate DKIM Key</h3>+ </div>+ <div className="card-body">+ <div className="form-grid">+ <div className="form-group">+ <label>Domain</label>+ <input+ type="text"+ className="form-control"+ value={domain}+ onChange={e => setDomain(e.target.value)}+ placeholder="example.com"+ />+ </div>+ <div className="form-group">+ <label>Selector</label>+ <input+ type="text"+ className="form-control"+ value={selector}+ onChange={e => setSelector(e.target.value)}+ placeholder="mail"+ />+ </div>+ </div>+ <div className="btn-group" style={{ marginTop: '16px' }}>+ <button+ className="btn btn-primary"+ onClick={handleGenerateKey}+ disabled={generating || !domain}+ >+ {generating ? 'Generating...' : 'Generate Key'}+ </button>+ <button+ className="btn btn-outline"+ onClick={loadDnsRecords}+ disabled={!domain}+ >+ Show DNS Records+ </button>+ </div>+ </div>+ </div>++ {dnsRecords && dnsRecords.length > 0 && (+ <div className="card">+ <div className="card-header">+ <h3>Required DNS Records</h3>+ </div>+ <div className="card-body">+ <p className="text-secondary" style={{ marginBottom: '16px' }}>+ Add these records to your DNS settings for email authentication.+ </p>+ <div className="dns-records-list">+ {dnsRecords.map((record, i) => (+ <div key={i} className="dns-record-item">+ <div className="dns-record-header">+ <span className="badge badge-info">{record.type}</span>+ <span className="dns-record-purpose">{record.purpose}</span>+ </div>+ <div className="dns-record-details">+ <div className="dns-field">+ <span className="dns-label">Name:</span>+ <code>{record.name}</code>+ </div>+ <div className="dns-field">+ <span className="dns-label">Value:</span>+ <code className="dns-value">{record.value}</code>+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </div>+ );+};+++// ==========================================+// MAIL QUEUE TAB+// ==========================================++const QueueTab = () => {+ const { showToast } = useToast();+ const [queue, setQueue] = useState([]);+ const [loading, setLoading] = useState(true);+ const [count, setCount] = useState(0);++ useEffect(() => {+ loadQueue();+ }, []);++ async function loadQueue() {+ setLoading(true);+ try {+ const data = await api.getMailQueue();+ setQueue(data.queue || []);+ setCount(data.count || 0);+ } catch (err) {+ showToast('Failed to load mail queue', 'error');+ } finally {+ setLoading(false);+ }+ }++ async function handleFlush() {+ try {+ await api.flushMailQueue();+ showToast('Queue flushed', 'success');+ loadQueue();+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ async function handleDelete(queueId) {+ try {+ await api.deleteQueuedMessage(queueId);+ showToast('Message deleted', 'success');+ loadQueue();+ } catch (err) {+ showToast(err.message, 'error');+ }+ }++ if (loading) return <div className="loading">Loading mail queue...</div>;++ return (+ <div className="email-queue">+ <div className="section-header">+ <h2>Mail Queue ({count} messages)</h2>+ <div className="btn-group">+ <button className="btn btn-outline" onClick={loadQueue}>Refresh</button>+ <button className="btn btn-primary" onClick={handleFlush} disabled={count === 0}>+ Flush Queue+ </button>+ </div>+ </div>++ {queue.length === 0 ? (+ <div className="card">+ <div className="card-body empty-state">+ <p>Mail queue is empty.</p>+ </div>+ </div>+ ) : (+ <div className="table-container">+ <table className="table">+ <thead>+ <tr>+ <th>Queue ID</th>+ <th>Size</th>+ <th>Date</th>+ <th>Sender</th>+ <th>Recipients</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {queue.map(item => (+ <tr key={item.id}>+ <td><code>{item.id}</code></td>+ <td>{item.size} B</td>+ <td>{item.date}</td>+ <td>{item.sender}</td>+ <td>{(item.recipients || []).join(', ')}</td>+ <td>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleDelete(item.id)}+ >+ Delete+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </div>+ );+};+++// ==========================================+// WEBMAIL TAB+// ==========================================++const WebmailTab = () => {+ const { showToast } = useToast();+ const [status, setStatus] = useState(null);+ const [loading, setLoading] = useState(true);+ const [installing, setInstalling] = useState(false);++ useEffect(() => {+ loadStatus();+ }, []);++ async function loadStatus() {+ try {+ const data = await api.getWebmailStatus();+ setStatus(data);+ } catch (err) {+ console.error('Failed to load webmail status:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleInstall() {+ setInstalling(true);+ try {+ const result = await api.installWebmail();+ if (result.success) {+ showToast('Roundcube installed', 'success');+ loadStatus();+ } else {+ showToast(result.error, 'error');+ }+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setInstalling(false);+ }+ }++ if (loading) return <div className="loading">Loading...</div>;++ return (+ <div className="email-webmail">+ <div className="card">+ <div className="card-body">+ {status?.installed ? (+ <div className="webmail-status">+ <div className="email-service-header">+ <div>+ <h3>Roundcube Webmail</h3>+ <p className="text-secondary">Browser-based email client for your users</p>+ </div>+ <span className="badge badge-success">Installed</span>+ </div>+ {status.url && (+ <p style={{ marginTop: '16px' }}>+ Access webmail at: <a href={status.url} target="_blank" rel="noopener noreferrer"><strong>{status.url}</strong></a>+ </p>+ )}+ </div>+ ) : (+ <div className="empty-state">+ <h3>Roundcube Webmail</h3>+ <p>Roundcube provides a browser-based interface for users to read and send email.</p>+ <button+ className="btn btn-primary"+ onClick={handleInstall}+ disabled={installing}+ >+ {installing ? 'Installing...' : 'Install Roundcube'}+ </button>+ </div>+ )}+ </div>+ </div>+ </div>+ );+};+++// ==========================================+// LOGS TAB+// ==========================================++const LogsTab = () => {+ const [logs, setLogs] = useState([]);+ const [loading, setLoading] = useState(true);+ const [source, setSource] = useState(null);++ useEffect(() => {+ loadLogs();+ }, []);++ async function loadLogs() {+ setLoading(true);+ try {+ const data = await api.getMailLogs(200);+ setLogs(data.lines || []);+ setSource(data.source);+ } catch (err) {+ console.error('Failed to load mail logs:', err);+ } finally {+ setLoading(false);+ }+ }++ if (loading) return <div className="loading">Loading logs...</div>;++ return (+ <div className="email-logs">+ <div className="section-header">+ <h2>Mail Logs</h2>+ <div className="btn-group">+ {source && <span className="text-secondary">Source: {source}</span>}+ <button className="btn btn-outline" onClick={loadLogs}>Refresh</button>+ </div>+ </div>++ <div className="card">+ <div className="card-body">+ {logs.length === 0 ? (+ <p className="text-secondary">No mail logs available.</p>+ ) : (+ <pre className="log-output">{logs.join('\n')}</pre>+ )}+ </div>+ </div>+ </div>+ );+};++export default Email;diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 0de38ae7..614736c8 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';import useTabParam from '../hooks/useTabParam';import { useAuth } from '../contexts/AuthContext';import { useTheme } from '../contexts/ThemeContext';+import useDashboardLayout from '../hooks/useDashboardLayout';import api from '../services/api';import UsersTab from '../components/settings/UsersTab';import AuditLogTab from '../components/settings/AuditLogTab';@@ -784,8 +785,20 @@ Keep these codes in a safe place.`;);};+const ACCENT_PRESETS = [+ { label: 'Indigo', color: '#6366f1' },+ { label: 'Ocean', color: '#0ea5e9' },+ { label: 'Forest', color: '#10b981' },+ { label: 'Sunset', color: '#f97316' },+ { label: 'Rose', color: '#f43f5e' },+ { label: 'Violet', color: '#8b5cf6' },+ { label: 'Amber', color: '#f59e0b' },+ { label: 'Cyan', color: '#06b6d4' },+];+const AppearanceSettings = () => {- const { theme, setTheme } = useTheme();+ const { theme, setTheme, accentColor, setAccentColor } = useTheme();+ const { widgets, toggleWidget, moveWidget, resetLayout } = useDashboardLayout();return (<div className="settings-section">@@ -839,6 +852,79 @@ const AppearanceSettings = () => {</button></div></div>++ <div className="settings-card">+ <h3>Accent Color</h3>+ <p>Choose the primary accent color used across the interface</p>+ <div className="accent-presets">+ {ACCENT_PRESETS.map(({ label, color }) => (+ <button+ key={color}+ className={`accent-preset${accentColor === color ? ' active' : ''}`}+ onClick={() => setAccentColor(color)}+ >+ <span className="accent-swatch" style={{ background: color }} />+ <span className="accent-label">{label}</span>+ </button>+ ))}+ </div>+ <div className="accent-custom">+ <label className="accent-custom-label">Custom color</label>+ <div className="accent-custom-row">+ <input+ type="color"+ className="accent-custom-input"+ value={accentColor}+ onChange={(e) => setAccentColor(e.target.value)}+ />+ <span className="accent-custom-hex">{accentColor.toUpperCase()}</span>+ </div>+ </div>+ </div>++ <div className="settings-card">+ <h3>Dashboard Widgets</h3>+ <p>Toggle visibility and reorder widgets on the dashboard</p>+ <div className="widget-list">+ {widgets.map((widget, idx) => (+ <div key={widget.id} className={`widget-item${!widget.visible ? ' widget-item--hidden' : ''}`}>+ <div className="widget-item__info">+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={widget.visible}+ onChange={() => toggleWidget(widget.id)}+ />+ <span className="toggle-slider"></span>+ </label>+ <span className="widget-item__label">{widget.label}</span>+ </div>+ <div className="widget-item__controls">+ <button+ className="widget-move-btn"+ onClick={() => moveWidget(widget.id, 'up')}+ disabled={idx === 0}+ title="Move up"+ >+ <ChevronUp size={14} />+ </button>+ <button+ className="widget-move-btn"+ onClick={() => moveWidget(widget.id, 'down')}+ disabled={idx === widgets.length - 1}+ title="Move down"+ >+ <ChevronDown size={14} />+ </button>+ </div>+ </div>+ ))}+ </div>+ <button className="btn btn-secondary btn-sm" onClick={resetLayout} style={{ marginTop: '12px' }}>+ <RotateCcw size={14} />+ Reset to defaults+ </button>+ </div></div>);};diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 59891f48..73147a17 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -2912,6 +2912,131 @@ class ApiService {const baseUrl = this.baseUrl.replace('/api/v1', '');return `${baseUrl}/api/servers/agent/download/${os}/${arch}`;}++ // ==========================================+ // Email Server+ // ==========================================++ async getEmailStatus() {+ return this.request('/email/status');+ }++ async getEmailConfig() {+ return this.request('/email/config');+ }++ async updateEmailConfig(data) {+ return this.request('/email/config', { method: 'PUT', body: data });+ }++ // Postfix+ async installPostfix() {+ return this.request('/email/postfix/install', { method: 'POST' });+ }++ async getPostfixConfig() {+ return this.request('/email/postfix/config');+ }++ async updatePostfixConfig(data) {+ return this.request('/email/postfix/config', { method: 'PUT', body: data });+ }++ // Mail Queue+ async getMailQueue() {+ return this.request('/email/queue');+ }++ async flushMailQueue() {+ return this.request('/email/queue/flush', { method: 'POST' });+ }++ async deleteQueuedMessage(queueId) {+ return this.request(`/email/queue/${queueId}`, { method: 'DELETE' });+ }++ // Dovecot+ async installDovecot() {+ return this.request('/email/dovecot/install', { method: 'POST' });+ }++ async getDovecotConfig() {+ return this.request('/email/dovecot/config');+ }++ // Email Accounts+ async getEmailAccounts() {+ return this.request('/email/accounts');+ }++ async createEmailAccount(data) {+ return this.request('/email/accounts', { method: 'POST', body: data });+ }++ async updateEmailAccount(accountId, data) {+ return this.request(`/email/accounts/${accountId}`, { method: 'PUT', body: data });+ }++ async deleteEmailAccount(accountId) {+ return this.request(`/email/accounts/${accountId}`, { method: 'DELETE' });+ }++ async setEmailForwarding(accountId, data) {+ return this.request(`/email/accounts/${accountId}/forwarding`, { method: 'PUT', body: data });+ }++ // SpamAssassin+ async installSpamAssassin() {+ return this.request('/email/spamassassin/install', { method: 'POST' });+ }++ async getSpamAssassinConfig() {+ return this.request('/email/spamassassin/config');+ }++ async updateSpamAssassinConfig(data) {+ return this.request('/email/spamassassin/config', { method: 'PUT', body: data });+ }++ // DKIM+ async installDkim() {+ return this.request('/email/dkim/install', { method: 'POST' });+ }++ async generateDkimKey(data) {+ return this.request('/email/dkim/generate', { method: 'POST', body: data });+ }++ async getEmailDnsRecords(domain) {+ return this.request(`/email/dns/${domain}`);+ }++ // Service Control+ async startEmailService(service) {+ return this.request(`/email/services/${service}/start`, { method: 'POST' });+ }++ async stopEmailService(service) {+ return this.request(`/email/services/${service}/stop`, { method: 'POST' });+ }++ async restartEmailService(service) {+ return this.request(`/email/services/${service}/restart`, { method: 'POST' });+ }++ // Webmail+ async getWebmailStatus() {+ return this.request('/email/webmail/status');+ }++ async installWebmail() {+ return this.request('/email/webmail/install', { method: 'POST' });+ }++ // Mail Logs+ async getMailLogs(lines = 100) {+ return this.request(`/email/logs?lines=${lines}`);+ }}export const api = new ApiService();diff --git a/frontend/src/styles/_theme-variables.less b/frontend/src/styles/_theme-variables.lessindex f852c377..436ffbf4 100644--- a/frontend/src/styles/_theme-variables.less+++ b/frontend/src/styles/_theme-variables.less@@ -45,6 +45,12 @@// Grid pattern--grid-color: rgba(255, 255, 255, 0.02);++ // Accent colors (overridden at runtime by ThemeContext)+ --accent-primary: #6366f1;+ --accent-hover: #4f46e5;+ --accent-glow: rgba(99, 102, 241, 0.15);+ --accent-shadow: rgba(99, 102, 241, 0.3);}// --------------------------------------------diff --git a/frontend/src/styles/_variables.less b/frontend/src/styles/_variables.lessindex c83473fd..3d00cc82 100644--- a/frontend/src/styles/_variables.less+++ b/frontend/src/styles/_variables.less@@ -60,10 +60,17 @@// --------------------------------------------// COLORS - Accent// ---------------------------------------------@accent-primary: #6366f1;-@accent-hover: #4f46e5;-@accent-glow: rgba(99, 102, 241, 0.15);-@accent-shadow: rgba(99, 102, 241, 0.3);+// Raw values for LESS compile-time functions (fade, darken, etc.)+@accent-primary-raw: #6366f1;+@accent-hover-raw: #4f46e5;+@accent-glow-raw: rgba(99, 102, 241, 0.15);+@accent-shadow-raw: rgba(99, 102, 241, 0.3);++// Themed values using CSS custom properties (runtime-switchable)+@accent-primary: var(--accent-primary);+@accent-hover: var(--accent-hover);+@accent-glow: var(--accent-glow);+@accent-shadow: var(--accent-shadow);// --------------------------------------------// COLORS - Semanticdiff --git a/frontend/src/styles/components/_badges.less b/frontend/src/styles/components/_badges.lessindex eb3a0d84..69b8d78d 100644--- a/frontend/src/styles/components/_badges.less+++ b/frontend/src/styles/components/_badges.less@@ -138,9 +138,9 @@}&.env-development {- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);color: @accent-primary;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);}&.env-staging {diff --git a/frontend/src/styles/components/_build.less b/frontend/src/styles/components/_build.lessindex 9f48d01f..5e8c16ef 100644--- a/frontend/src/styles/components/_build.less+++ b/frontend/src/styles/components/_build.less@@ -86,7 +86,7 @@// Current Deployment Card.current-deployment {- background: linear-gradient(135deg, fade(@success, 5%), fade(@accent-primary, 5%));+ background: linear-gradient(135deg, fade(@success, 5%), fade(@accent-primary-raw, 5%));border-color: fade(@success, 30%);.deployment-current-info {diff --git a/frontend/src/styles/components/_cards.less b/frontend/src/styles/components/_cards.lessindex a10559bd..91daf1fe 100644--- a/frontend/src/styles/components/_cards.less+++ b/frontend/src/styles/components/_cards.less@@ -111,11 +111,11 @@}// Default colors- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;&.backups {- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;}diff --git a/frontend/src/styles/components/_env-vars.less b/frontend/src/styles/components/_env-vars.lessindex 3042ea96..08f1068e 100644--- a/frontend/src/styles/components/_env-vars.less+++ b/frontend/src/styles/components/_env-vars.less@@ -74,7 +74,7 @@}&:has(input:checked) {- background: fade(@accent-primary, 20%);+ background: fade(@accent-primary-raw, 20%);border-color: @accent-primary;color: @accent-primary;}diff --git a/frontend/src/styles/components/_linked-apps.less b/frontend/src/styles/components/_linked-apps.lessindex f1ce02aa..14f539ff 100644--- a/frontend/src/styles/components/_linked-apps.less+++ b/frontend/src/styles/components/_linked-apps.less@@ -151,8 +151,8 @@// Shared config info.shared-config-info {padding: @space-3;- background: fade(@accent-primary, 10%);- border: 1px solid fade(@accent-primary, 20%);+ background: fade(@accent-primary-raw, 10%);+ border: 1px solid fade(@accent-primary-raw, 20%);border-radius: @radius-md;}diff --git a/frontend/src/styles/components/_modals.less b/frontend/src/styles/components/_modals.lessindex f3c621ab..df6e3309 100644--- a/frontend/src/styles/components/_modals.less+++ b/frontend/src/styles/components/_modals.less@@ -157,7 +157,7 @@}&-info {- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);color: @accent-primary;}}diff --git a/frontend/src/styles/components/_notifications.less b/frontend/src/styles/components/_notifications.lessindex 9362fed9..0e86e8f1 100644--- a/frontend/src/styles/components/_notifications.less+++ b/frontend/src/styles/components/_notifications.less@@ -88,7 +88,7 @@&:has(input:checked) {background: @accent-glow;- border-color: fade(@accent-primary, 40%);+ border-color: fade(@accent-primary-raw, 40%);span {color: @text-primary;@@ -240,7 +240,7 @@}&.info span {- background: fade(@accent-primary, 20%);+ background: fade(@accent-primary-raw, 20%);color: @accent-primary;}diff --git a/frontend/src/styles/components/_query-runner.less b/frontend/src/styles/components/_query-runner.lessindex 863e76c3..92d819a2 100644--- a/frontend/src/styles/components/_query-runner.less+++ b/frontend/src/styles/components/_query-runner.less@@ -63,7 +63,7 @@}&.sqlite {- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);color: @accent-primary;}}@@ -197,7 +197,7 @@&.selected {background: @accent-glow;- border: 1px solid fade(@accent-primary, 30%);+ border: 1px solid fade(@accent-primary-raw, 30%);}.table-name {diff --git a/frontend/src/styles/components/_spinner.less b/frontend/src/styles/components/_spinner.lessindex 8bbbdd95..643f76b7 100644--- a/frontend/src/styles/components/_spinner.less+++ b/frontend/src/styles/components/_spinner.less@@ -44,7 +44,7 @@.spinner-ring {border-radius: 50%;border-style: solid;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);border-top-color: @accent-primary;animation: spinner-rotate 0.8s linear infinite;}diff --git a/frontend/src/styles/components/_toasts.less b/frontend/src/styles/components/_toasts.lessindex 0ca592f7..53e4d648 100644--- a/frontend/src/styles/components/_toasts.less+++ b/frontend/src/styles/components/_toasts.less@@ -90,8 +90,8 @@}&-info {- border-color: fade(@accent-primary, 30%);- background: fade(@accent-primary, 10%);+ border-color: fade(@accent-primary-raw, 30%);+ background: fade(@accent-primary-raw, 10%);.toast-icon {color: @accent-primary;diff --git a/frontend/src/styles/components/_two-factor.less b/frontend/src/styles/components/_two-factor.lessindex fe20ab46..15da133d 100644--- a/frontend/src/styles/components/_two-factor.less+++ b/frontend/src/styles/components/_two-factor.less@@ -25,7 +25,7 @@&:focus {border-color: @accent-primary;outline: none;- box-shadow: 0 0 0 3px fade(@accent-primary, 20%);+ box-shadow: 0 0 0 3px fade(@accent-primary-raw, 20%);}&::placeholder {@@ -74,7 +74,7 @@display: flex;align-items: center;justify-content: center;- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);border-radius: @radius-md;color: @accent-primary;flex-shrink: 0;diff --git a/frontend/src/styles/components/_uptime.less b/frontend/src/styles/components/_uptime.lessindex b07b3f7c..b929ec4b 100644--- a/frontend/src/styles/components/_uptime.less+++ b/frontend/src/styles/components/_uptime.less@@ -141,7 +141,7 @@justify-content: center;gap: @space-2;padding: @space-5;- background: linear-gradient(135deg, fade(@accent-primary, 5%), fade(@success, 5%));+ background: linear-gradient(135deg, fade(@accent-primary-raw, 5%), fade(@success, 5%));border: 1px solid @border-subtle;border-radius: @radius-lg;margin-bottom: @space-6;diff --git a/frontend/src/styles/components/_users.less b/frontend/src/styles/components/_users.lessindex 12150650..eda0f84f 100644--- a/frontend/src/styles/components/_users.less+++ b/frontend/src/styles/components/_users.less@@ -13,7 +13,7 @@display: flex;gap: @space-4;padding: @space-4;- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);border-radius: @radius-md;margin-bottom: @space-6;diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex 9ba196cc..7b5fbd8c 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -78,4 +78,5 @@@import 'pages/_wordpress';@import 'pages/_wordpress-pipeline';@import 'pages/_ssl';+@import 'pages/_email';@import 'pages/_setup-wizard';diff --git a/frontend/src/styles/pages/_applications.less b/frontend/src/styles/pages/_applications.lessindex 60001ef3..ca0031db 100644--- a/frontend/src/styles/pages/_applications.less+++ b/frontend/src/styles/pages/_applications.less@@ -177,7 +177,7 @@align-items: center;padding: @space-3 @space-4;background: @accent-glow;- border: 1px solid fade(@accent-primary, 30%);+ border: 1px solid fade(@accent-primary-raw, 30%);border-radius: @radius-lg;gap: @space-4;flex-wrap: wrap;@@ -303,7 +303,7 @@&.selected {background: @accent-glow;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);}&:hover {@@ -536,7 +536,7 @@&.selected {background: @accent-glow;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);}}diff --git a/frontend/src/styles/pages/_backups.less b/frontend/src/styles/pages/_backups.lessindex 8c4e6dfc..9f59922f 100644--- a/frontend/src/styles/pages/_backups.less+++ b/frontend/src/styles/pages/_backups.less@@ -11,7 +11,7 @@}&.apps {- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;}diff --git a/frontend/src/styles/pages/_cron.less b/frontend/src/styles/pages/_cron.lessindex 80f17b40..7f4a44d7 100644--- a/frontend/src/styles/pages/_cron.less+++ b/frontend/src/styles/pages/_cron.less@@ -33,7 +33,7 @@// Stats icons.stat-icon {&.cron {- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;}diff --git a/frontend/src/styles/pages/_email.less b/frontend/src/styles/pages/_email.lessnew file mode 100644index 00000000..632f8ac3--- /dev/null+++ b/frontend/src/styles/pages/_email.less@@ -0,0 +1,265 @@+// ============================================+// EMAIL SERVER PAGE STYLES+// ============================================++.email-page {+ .tabs-nav {+ display: flex;+ gap: @space-2;+ margin-bottom: @space-6;+ border-bottom: 1px solid @border-subtle;+ padding-bottom: @space-2;+ overflow-x: auto;++ .tab-btn {+ padding: @space-2 @space-4;+ border: none;+ background: none;+ color: @text-secondary;+ cursor: pointer;+ border-radius: @radius-md;+ white-space: nowrap;+ transition: all 0.2s;++ &:hover {+ background: @bg-hover;+ color: @text-primary;+ }++ &.active {+ background: @accent-primary;+ color: white;+ }+ }+ }+}++// Service overview cards+.email-overview {+ .services-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));+ gap: @space-4;+ }+}++.email-service-card {+ .card-body {+ padding: @space-6;+ }+}++.email-service-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: @space-4;++ h3 {+ margin: 0 0 @space-1 0;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0;+ font-size: @font-size-sm;+ }+}++.email-service-meta {+ margin-top: @space-3;+ font-size: @font-size-sm;+}++.email-service-actions {+ display: flex;+ gap: @space-2;+ margin-top: @space-4;+ padding-top: @space-4;+ border-top: 1px solid @border-subtle;+}++// Accounts section+.email-accounts {+ .section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-4;++ h2 {+ margin: 0;+ }+ }+}++.email-create-form {+ margin-bottom: @space-4;++ .form-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: @space-4;+ }+}++// Postfix / Dovecot config+.email-postfix,+.email-dovecot,+.email-spam {+ .form-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));+ gap: @space-4;+ }+}++// Config list (read-only)+.config-list {+ display: flex;+ flex-direction: column;+ gap: @space-2;+}++.config-item {+ display: flex;+ gap: @space-4;+ padding: @space-2 0;+ border-bottom: 1px solid @border-subtle;+ font-size: @font-size-sm;++ &:last-child {+ border-bottom: none;+ }++ .config-key {+ color: @text-secondary;+ min-width: 200px;+ font-family: @font-mono;+ font-size: @font-size-xs;+ }++ .config-value {+ color: @text-primary;+ word-break: break-all;+ }+}++// DNS records+.dns-records-list {+ display: flex;+ flex-direction: column;+ gap: @space-4;+}++.dns-record-item {+ padding: @space-4;+ background: @bg-elevated;+ border-radius: @radius-md;+ border: 1px solid @border-subtle;+}++.dns-record-header {+ display: flex;+ align-items: center;+ gap: @space-3;+ margin-bottom: @space-3;+}++.dns-record-purpose {+ font-size: @font-size-sm;+ color: @text-secondary;+}++.dns-record-details {+ display: flex;+ flex-direction: column;+ gap: @space-2;+}++.dns-field {+ display: flex;+ align-items: flex-start;+ gap: @space-2;++ .dns-label {+ font-size: @font-size-sm;+ color: @text-tertiary;+ min-width: 50px;+ }++ code {+ font-family: @font-mono;+ font-size: @font-size-xs;+ color: @text-primary;+ background: @bg-secondary;+ padding: @space-1 @space-2;+ border-radius: @radius-sm;+ word-break: break-all;+ }+}++// Mail queue+.email-queue {+ .section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-4;++ h2 {+ margin: 0;+ }+ }+}++// Webmail+.email-webmail {+ .webmail-status {+ padding: @space-2;+ }+}++// Logs+.email-logs {+ .section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-4;++ h2 {+ margin: 0;+ }+ }++ .log-output {+ font-family: @font-mono;+ font-size: @font-size-xs;+ line-height: @line-height-relaxed;+ color: @text-primary;+ background: @bg-body;+ padding: @space-4;+ border-radius: @radius-md;+ border: 1px solid @border-subtle;+ max-height: 600px;+ overflow: auto;+ white-space: pre-wrap;+ word-break: break-all;+ margin: 0;+ }+}++// Authentication tab+.email-authentication {+ display: flex;+ flex-direction: column;+ gap: @space-4;++ .form-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: @space-4;+ }+}diff --git a/frontend/src/styles/pages/_file-manager.less b/frontend/src/styles/pages/_file-manager.lessindex bc912ffe..6ea76407 100644--- a/frontend/src/styles/pages/_file-manager.less+++ b/frontend/src/styles/pages/_file-manager.less@@ -380,7 +380,7 @@&.active {background: @accent-glow;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);color: @accent-primary;}}diff --git a/frontend/src/styles/pages/_git.less b/frontend/src/styles/pages/_git.lessindex 36563561..1aa00f7f 100644--- a/frontend/src/styles/pages/_git.less+++ b/frontend/src/styles/pages/_git.less@@ -1068,7 +1068,7 @@}&.active {- background: fade(@accent-primary, 5%);+ background: fade(@accent-primary-raw, 5%);}.branch-info {diff --git a/frontend/src/styles/pages/_monitoring.less b/frontend/src/styles/pages/_monitoring.lessindex 1d458f64..16039516 100644--- a/frontend/src/styles/pages/_monitoring.less+++ b/frontend/src/styles/pages/_monitoring.less@@ -85,7 +85,7 @@}&.interval {- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;}diff --git a/frontend/src/styles/pages/_security.less b/frontend/src/styles/pages/_security.lessindex 9c3e1847..0ad68cb1 100644--- a/frontend/src/styles/pages/_security.less+++ b/frontend/src/styles/pages/_security.less@@ -68,8 +68,8 @@}&.info {- border-color: fade(@accent-primary, 30%);- .stat-icon { color: @accent-primary; background: fade(@accent-primary, 15%); }+ border-color: fade(@accent-primary-raw, 30%);+ .stat-icon { color: @accent-primary; background: fade(@accent-primary-raw, 15%); }}}@@ -160,7 +160,7 @@align-items: center;justify-content: center;border-radius: @radius-md;- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @accent-primary;margin-bottom: @space-3;}@@ -787,7 +787,7 @@}&.recommendations {- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);padding: @space-4;border-radius: @radius-md;diff --git a/frontend/src/styles/pages/_servers.less b/frontend/src/styles/pages/_servers.lessindex 65ad2eb4..79cf2c08 100644--- a/frontend/src/styles/pages/_servers.less+++ b/frontend/src/styles/pages/_servers.less@@ -1185,7 +1185,7 @@&.critical { background: fade(@danger, 15%); color: @danger; }&.high { background: fade(@warning, 15%); color: @warning; }- &.medium { background: fade(@accent-primary, 15%); color: @accent-primary; }+ &.medium { background: fade(@accent-primary-raw, 15%); color: @accent-primary; }&.low { background: @bg-hover; color: @text-tertiary; }}diff --git a/frontend/src/styles/pages/_settings.less b/frontend/src/styles/pages/_settings.lessindex 47d9d863..508dcc47 100644--- a/frontend/src/styles/pages/_settings.less+++ b/frontend/src/styles/pages/_settings.less@@ -316,7 +316,7 @@&.active {border-color: @accent-primary;- background: fade(@accent-primary, 5%);+ background: fade(@accent-primary-raw, 5%);}span {@@ -482,7 +482,7 @@}&:focus + .toggle-slider {- box-shadow: 0 0 0 2px fade(@accent-primary, 30%);+ box-shadow: 0 0 0 2px fade(@accent-primary-raw, 30%);}}@@ -696,8 +696,8 @@// Star Prompt Card.star-prompt-card {position: relative;- background: linear-gradient(135deg, @accent-glow 0%, fade(@accent-primary, 8%) 100%);- border: 1px solid fade(@accent-primary, 30%);+ background: linear-gradient(135deg, @accent-glow 0%, fade(@accent-primary-raw, 8%) 100%);+ border: 1px solid fade(@accent-primary-raw, 30%);border-radius: @radius-lg;padding: @space-6;display: flex;@@ -974,3 +974,162 @@font-weight: @font-weight-medium;}}++// ============================================+// ACCENT COLOR PRESETS+// ============================================++.accent-presets {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: @space-2;+ margin-bottom: @space-4;++ @media (max-width: @breakpoint-sm) {+ grid-template-columns: repeat(2, 1fr);+ }+}++.accent-preset {+ display: flex;+ align-items: center;+ gap: @space-2;+ padding: @space-2 @space-3;+ background: transparent;+ border: 2px solid @border-subtle;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover {+ border-color: @border-active;+ }++ &.active {+ border-color: @accent-primary;+ background: @bg-hover;+ }+}++.accent-swatch {+ width: 20px;+ height: 20px;+ border-radius: @radius-full;+ flex-shrink: 0;+}++.accent-label {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-primary;+}++.accent-custom {+ padding-top: @space-3;+ border-top: 1px solid @border-subtle;+}++.accent-custom-label {+ display: block;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-secondary;+ margin-bottom: @space-2;+}++.accent-custom-row {+ display: flex;+ align-items: center;+ gap: @space-3;+}++.accent-custom-input {+ width: 40px;+ height: 32px;+ padding: 0;+ border: 1px solid @border-subtle;+ border-radius: @radius-md;+ background: transparent;+ cursor: pointer;++ &::-webkit-color-swatch-wrapper {+ padding: 2px;+ }++ &::-webkit-color-swatch {+ border: none;+ border-radius: @radius-sm;+ }+}++.accent-custom-hex {+ font-family: @font-mono;+ font-size: @font-size-sm;+ color: @text-secondary;+}++// ============================================+// DASHBOARD WIDGET CONFIG+// ============================================++.widget-list {+ display: flex;+ flex-direction: column;+ gap: @space-2;+}++.widget-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-3 @space-4;+ background: @bg-hover;+ border-radius: @radius-md;+ transition: opacity @transition-fast;++ &--hidden {+ opacity: 0.5;+ }+}++.widget-item__info {+ display: flex;+ align-items: center;+ gap: @space-3;+}++.widget-item__label {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-primary;+}++.widget-item__controls {+ display: flex;+ gap: @space-1;+}++.widget-move-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ background: transparent;+ border: 1px solid @border-subtle;+ border-radius: @radius-sm;+ color: @text-secondary;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover:not(:disabled) {+ background: @bg-card;+ color: @text-primary;+ border-color: @border-active;+ }++ &:disabled {+ opacity: 0.3;+ cursor: not-allowed;+ }+}diff --git a/frontend/src/styles/pages/_setup-wizard.less b/frontend/src/styles/pages/_setup-wizard.lessindex a8e10a93..b5a8b148 100644--- a/frontend/src/styles/pages/_setup-wizard.less+++ b/frontend/src/styles/pages/_setup-wizard.less@@ -73,7 +73,7 @@&.completed {border-color: @accent-primary;- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);color: @accent-primary;}}@@ -151,7 +151,7 @@&.selected {border-color: @accent-primary;- background: fade(@accent-primary, 8%);+ background: fade(@accent-primary-raw, 8%);}.option-card-icon {@@ -218,7 +218,7 @@&.detected {border-color: @accent-primary;- background: fade(@accent-primary, 8%);+ background: fade(@accent-primary-raw, 8%);}.tier-card-header {@@ -360,7 +360,7 @@display: inline-flex;align-items: center;padding: @space-1 @space-3;- background: fade(@accent-primary, 12%);+ background: fade(@accent-primary-raw, 12%);color: @accent-primary;border-radius: @radius-full;font-size: @font-size-sm;@@ -432,7 +432,7 @@display: flex;gap: @space-4;padding: @space-4;- background: fade(@accent-primary, 10%);+ background: fade(@accent-primary-raw, 10%);border-radius: @radius-md;margin-bottom: @space-6;diff --git a/frontend/src/styles/pages/_wordpress-pipeline.less b/frontend/src/styles/pages/_wordpress-pipeline.lessindex b069f115..1e0bbe8b 100644--- a/frontend/src/styles/pages/_wordpress-pipeline.less+++ b/frontend/src/styles/pages/_wordpress-pipeline.less@@ -392,7 +392,7 @@&:hover:not(:disabled) {border-color: @color-primary;color: @color-primary;- background: fade(@color-primary, 5%);+ background: fade(@accent-primary-raw, 5%);}&:disabled {@@ -456,7 +456,7 @@min-width: 20px;height: 20px;padding: 0 6px;- background: fade(@color-primary, 12%);+ background: fade(@accent-primary-raw, 12%);color: @color-primary;border-radius: 10px;font-size: 11px;@@ -596,7 +596,7 @@}.wp-env-badge.env-multidev {- background: fade(@color-primary, 12%);+ background: fade(@accent-primary-raw, 12%);color: @color-primary;}@@ -609,8 +609,8 @@align-items: center;gap: @space-2;padding: @space-3;- background: fade(@color-primary, 8%);- border: 1px solid fade(@color-primary, 25%);+ background: fade(@accent-primary-raw, 8%);+ border: 1px solid fade(@accent-primary-raw, 25%);border-radius: @radius-md;svg {@@ -734,7 +734,7 @@color: @text-tertiary;&.env {- background: fade(@color-primary, 10%);+ background: fade(@accent-primary-raw, 10%);color: @color-primary;}}@@ -881,7 +881,7 @@&:has(input:checked) {border-color: @color-primary;- background: fade(@color-primary, 5%);+ background: fade(@accent-primary-raw, 5%);}input[type="radio"] {@@ -978,7 +978,7 @@color: @color-info;}&.primary {- background: fade(@color-primary, 12%);+ background: fade(@accent-primary-raw, 12%);color: @color-primary;}&.default {@@ -1388,7 +1388,7 @@}&.default {- border-color: fade(@color-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);border-left: 3px solid @color-primary;}}@@ -1425,7 +1425,7 @@}&.default {- background: fade(@color-primary, 12%);+ background: fade(@accent-primary-raw, 12%);color: @color-primary;}}@@ -2201,8 +2201,8 @@align-items: center;gap: @space-3;padding: @space-3 @space-4;- background: fade(@color-primary, 8%);- border: 1px solid fade(@color-primary, 20%);+ background: fade(@accent-primary-raw, 8%);+ border: 1px solid fade(@accent-primary-raw, 20%);border-radius: @radius-md;margin-bottom: @space-4;}diff --git a/frontend/src/styles/pages/_wordpress.less b/frontend/src/styles/pages/_wordpress.lessindex 9773761d..c062bd72 100644--- a/frontend/src/styles/pages/_wordpress.less+++ b/frontend/src/styles/pages/_wordpress.less@@ -1273,7 +1273,7 @@&:focus {outline: none;border-color: @color-primary;- box-shadow: 0 0 0 3px fade(@color-primary, 15%);+ box-shadow: 0 0 0 3px fade(@accent-primary-raw, 15%);}&::placeholder {diff --git a/frontend/src/styles/pages/_workflow.less b/frontend/src/styles/pages/_workflow.lessindex 064d36a5..a2892b44 100644--- a/frontend/src/styles/pages/_workflow.less+++ b/frontend/src/styles/pages/_workflow.less@@ -329,9 +329,9 @@}&.palette-item-service:hover {- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);color: @accent-primary;- border-color: fade(@accent-primary, 30%);+ border-color: fade(@accent-primary-raw, 30%);}}@@ -447,8 +447,8 @@display: inline-flex;align-items: center;padding: 2px @space-2;- background: fade(@accent-primary, 15%);- border: 1px solid fade(@accent-primary, 30%);+ background: fade(@accent-primary-raw, 15%);+ border: 1px solid fade(@accent-primary-raw, 30%);border-radius: @radius-full;font-size: @font-size-xs;font-family: @font-mono;@@ -990,8 +990,8 @@color: white;&:hover {- background: darken(@accent-primary, 5%);- border-color: darken(@accent-primary, 5%);+ background: darken(@accent-primary-raw, 5%);+ border-color: darken(@accent-primary-raw, 5%);color: white;}}@@ -1191,7 +1191,7 @@&:hover {border-color: @accent-primary;- background: fade(@accent-primary, 5%);+ background: fade(@accent-primary-raw, 5%);}}@@ -1369,7 +1369,7 @@transition: background @transition-fast;&:hover {- background: darken(@accent-primary, 5%);+ background: darken(@accent-primary-raw, 5%);}}}@@ -1587,7 +1587,7 @@border-color: @accent-primary;.workflow-node-header {- background: fade(@accent-primary, 15%);+ background: fade(@accent-primary-raw, 15%);}}