Skip to content

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.

cutover(email): serverkit-email leaves the tree (plan 52 Phase 2, D8)

Juan Denis43fec8030cd7
diff --git a/backend/app/data/registry_index.json b/backend/app/data/registry_index.json
index 35623110..438a7066 100644
--- a/backend/app/data/registry_index.json
+++ b/backend/app/data/registry_index.json
@@ -118,7 +118,7 @@
"category": "integration",
"author": "ServerKit",
"first_party": true,
- "bundled": true,
+ "bundled": false,
"permissions": [
"shell",
"filesystem",
@@ -126,8 +126,11 @@
],
"min_panel_version": "1.7.0",
"max_panel_version": null,
- "repo": "https://github.com/jhd3197/ServerKit",
- "logo": "assets/serverkit-email/logo.png"
+ "repo": "https://github.com/jhd3197/serverkit-email",
+ "logo": "assets/serverkit-email/logo.png",
+ "source": "https://github.com/jhd3197/serverkit-email/releases/download/v1.0.0/serverkit-email-1.0.0.zip",
+ "sha256": "896fea2df5dd5097b70e9401264555078acc6eaea9a8a57382b7e4be92ac381b",
+ "homepage": "https://github.com/jhd3197/serverkit-email"
},
{
"slug": "serverkit-ftp",
diff --git a/backend/app/plugins/serverkit-email/__init__.py b/backend/app/plugins/serverkit-email/__init__.py
deleted file mode 100644
index 51e67b6d..00000000
--- a/backend/app/plugins/serverkit-email/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""ServerKit Email extension backend package."""
diff --git a/backend/app/plugins/serverkit-email/dkim_service.py b/backend/app/plugins/serverkit-email/dkim_service.py
deleted file mode 100644
index e79ca0d8..00000000
--- a/backend/app/plugins/serverkit-email/dkim_service.py
+++ /dev/null
@@ -1,271 +0,0 @@
-"""OpenDKIM management service for DKIM signing."""
-import os
-import re
-import subprocess
-from typing import Dict
-
-from app.utils.system import (PackageManager, ServiceControl, run_checked,
- run_privileged)
-
-
-class DKIMService:
- """Service for managing OpenDKIM (DKIM email signing)."""
-
- OPENDKIM_CONF = '/etc/opendkim.conf'
- OPENDKIM_DIR = '/etc/opendkim'
- OPENDKIM_KEYS_DIR = '/etc/opendkim/keys'
- KEY_TABLE = '/etc/opendkim/KeyTable'
- SIGNING_TABLE = '/etc/opendkim/SigningTable'
- TRUSTED_HOSTS = '/etc/opendkim/TrustedHosts'
-
- OPENDKIM_CONF_CONTENT = """# OpenDKIM configuration - Managed by ServerKit
-Syslog yes
-SyslogSuccess yes
-LogWhy yes
-Canonicalization relaxed/simple
-Mode sv
-SubDomains no
-AutoRestart yes
-AutoRestartRate 10/1M
-Background yes
-DNSTimeout 5
-SignatureAlgorithm rsa-sha256
-KeyTable refile:/etc/opendkim/KeyTable
-SigningTable refile:/etc/opendkim/SigningTable
-ExternalIgnoreList /etc/opendkim/TrustedHosts
-InternalHosts /etc/opendkim/TrustedHosts
-Socket inet:8891@localhost
-PidFile /run/opendkim/opendkim.pid
-OversignHeaders From
-UserID opendkim
-UMask 007
-"""
-
- TRUSTED_HOSTS_DEFAULT = """# Trusted hosts - Managed by ServerKit
-127.0.0.1
-::1
-localhost
-"""
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get OpenDKIM installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- try:
- result = run_checked(['which', 'opendkim'], timeout=None)
- installed = result['success']
- if not installed:
- installed = PackageManager.is_installed('opendkim')
- if installed:
- running = ServiceControl.is_active('opendkim')
- enabled = ServiceControl.is_enabled('opendkim')
- result = run_checked(['opendkim', '-V'], timeout=None, merge_stderr=True)
- match = re.search(r'OpenDKIM\s+Filter\s+v(\S+)', result['output'])
- if match:
- version = match.group(1)
- except (subprocess.SubprocessError, FileNotFoundError):
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install OpenDKIM."""
- try:
- result = PackageManager.install(['opendkim', 'opendkim-tools'], timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install OpenDKIM'}
-
- # Create directories
- run_privileged(['mkdir', '-p', cls.OPENDKIM_KEYS_DIR])
- run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
-
- # Create config files
- run_privileged(['tee', cls.OPENDKIM_CONF], input=cls.OPENDKIM_CONF_CONTENT)
- run_privileged(['tee', cls.TRUSTED_HOSTS], input=cls.TRUSTED_HOSTS_DEFAULT)
- run_privileged(['touch', cls.KEY_TABLE])
- run_privileged(['touch', cls.SIGNING_TABLE])
-
- # Set permissions
- run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
- run_privileged(['chmod', '700', cls.OPENDKIM_KEYS_DIR])
-
- # Create PID directory
- run_privileged(['mkdir', '-p', '/run/opendkim'])
- run_privileged(['chown', 'opendkim:opendkim', '/run/opendkim'])
-
- # Add postfix to opendkim group
- run_privileged(['usermod', '-aG', 'opendkim', 'postfix'])
-
- ServiceControl.enable('opendkim')
- ServiceControl.start('opendkim', timeout=30)
-
- return {'success': True, 'message': 'OpenDKIM installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def generate_key(cls, domain: str, selector: str = 'default') -> Dict:
- """Generate DKIM key pair for a domain."""
- try:
- key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
- run_privileged(['mkdir', '-p', key_dir])
-
- # Generate key
- result = run_privileged([
- 'opendkim-genkey',
- '-s', selector,
- '-d', domain,
- '-D', key_dir,
- '-b', '2048',
- ])
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Key generation failed'}
-
- # Set permissions
- run_privileged(['chown', '-R', 'opendkim:opendkim', key_dir])
- run_privileged(['chmod', '600', os.path.join(key_dir, f'{selector}.private')])
-
- # Read the public key TXT record
- txt_file = os.path.join(key_dir, f'{selector}.txt')
- result = run_privileged(['cat', txt_file])
- public_key_record = result.stdout.strip() if result.returncode == 0 else ''
-
- # Extract just the key value from the TXT record
- key_match = re.search(r'p=([A-Za-z0-9+/=\s]+)', public_key_record)
- public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '') if key_match else ''
-
- return {
- 'success': True,
- 'domain': domain,
- 'selector': selector,
- 'private_key_path': os.path.join(key_dir, f'{selector}.private'),
- 'public_key': public_key,
- 'dns_record': public_key_record,
- 'dns_name': f'{selector}._domainkey.{domain}',
- 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def add_domain(cls, domain: str, selector: str = 'default') -> Dict:
- """Add domain to KeyTable and SigningTable."""
- try:
- key_path = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.private')
-
- # Add to KeyTable
- key_entry = f'{selector}._domainkey.{domain} {domain}:{selector}:{key_path}\n'
- result = run_privileged(['cat', cls.KEY_TABLE])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.KEY_TABLE], input=key_entry)
-
- # Add to SigningTable
- signing_entry = f'*@{domain} {selector}._domainkey.{domain}\n'
- result = run_privileged(['cat', cls.SIGNING_TABLE])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.SIGNING_TABLE], input=signing_entry)
-
- # Add to TrustedHosts
- result = run_privileged(['cat', cls.TRUSTED_HOSTS])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.TRUSTED_HOSTS], input=f'*.{domain}\n')
-
- # Reload OpenDKIM
- ServiceControl.restart('opendkim', timeout=30)
-
- return {'success': True, 'message': f'Domain {domain} added to DKIM'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_domain(cls, domain: str) -> Dict:
- """Remove domain from DKIM configuration."""
- try:
- # Remove from KeyTable
- result = run_privileged(['cat', cls.KEY_TABLE])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.KEY_TABLE], input='\n'.join(lines) + '\n')
-
- # Remove from SigningTable
- result = run_privileged(['cat', cls.SIGNING_TABLE])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.SIGNING_TABLE], input='\n'.join(lines) + '\n')
-
- # Remove from TrustedHosts
- result = run_privileged(['cat', cls.TRUSTED_HOSTS])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.TRUSTED_HOSTS], input='\n'.join(lines) + '\n')
-
- # Remove key files
- key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
- run_privileged(['rm', '-rf', key_dir])
-
- ServiceControl.restart('opendkim', timeout=30)
-
- return {'success': True, 'message': f'Domain {domain} removed from DKIM'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_dns_record(cls, domain: str, selector: str = 'default') -> Dict:
- """Get the DKIM DNS TXT record content for a domain."""
- try:
- txt_file = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.txt')
- result = run_privileged(['cat', txt_file])
- if result.returncode != 0:
- return {'success': False, 'error': 'DKIM key not found'}
-
- record = result.stdout.strip()
- key_match = re.search(r'p=([A-Za-z0-9+/=\s"]+)', record)
- public_key = ''
- if key_match:
- public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '')
-
- return {
- 'success': True,
- 'dns_name': f'{selector}._domainkey.{domain}',
- 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
- 'raw_record': record,
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def verify_key(cls, domain: str, selector: str = 'default') -> Dict:
- """Verify DKIM key configuration."""
- try:
- result = run_privileged([
- 'opendkim-testkey',
- '-d', domain,
- '-s', selector,
- '-vvv',
- ])
- success = result.returncode == 0
- output = (result.stdout or '') + (result.stderr or '')
- return {
- 'success': success,
- 'verified': success and 'key OK' in output,
- 'output': output,
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload OpenDKIM."""
- try:
- result = ServiceControl.restart('opendkim', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'OpenDKIM restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/dovecot_service.py b/backend/app/plugins/serverkit-email/dovecot_service.py
deleted file mode 100644
index b108a123..00000000
--- a/backend/app/plugins/serverkit-email/dovecot_service.py
+++ /dev/null
@@ -1,374 +0,0 @@
-"""Dovecot IMAP/POP3 server management service."""
-import os
-import re
-import subprocess
-from typing import Dict, Optional
-
-from app.utils.system import (PackageManager, ServiceControl, is_command_available,
- run_privileged)
-from app import paths
-
-
-class DovecotService:
- """Service for managing Dovecot (IMAP/POP3 server)."""
-
- DOVECOT_CONF_DIR = '/etc/dovecot'
- DOVECOT_CONF = '/etc/dovecot/dovecot.conf'
- DOVECOT_AUTH_CONF = '/etc/dovecot/conf.d/10-auth.conf'
- DOVECOT_MAIL_CONF = '/etc/dovecot/conf.d/10-mail.conf'
- DOVECOT_MASTER_CONF = '/etc/dovecot/conf.d/10-master.conf'
- DOVECOT_SSL_CONF = '/etc/dovecot/conf.d/10-ssl.conf'
- DOVECOT_PASSWD_FILE = '/etc/dovecot/users'
- AUTH_PASSWDFILE_CONF = '/etc/dovecot/conf.d/auth-passwdfile.conf.ext'
-
- MAIL_CONF_CONTENT = """# Dovecot mail configuration - Managed by ServerKit
-mail_location = maildir:{vmail_dir}/%d/%n/Maildir
-namespace inbox {{
- inbox = yes
- separator = /
-}}
-mail_uid = {vmail_uid}
-mail_gid = {vmail_gid}
-mail_privileged_group = vmail
-first_valid_uid = {vmail_uid}
-last_valid_uid = {vmail_uid}
-"""
-
- AUTH_CONF_CONTENT = """# Dovecot auth configuration - Managed by ServerKit
-disable_plaintext_auth = yes
-auth_mechanisms = plain login
-!include auth-passwdfile.conf.ext
-"""
-
- AUTH_PASSWDFILE_CONTENT = """# Password file auth - Managed by ServerKit
-passdb {{
- driver = passwd-file
- args = scheme=SHA512-CRYPT /etc/dovecot/users
-}}
-userdb {{
- driver = static
- args = uid={vmail_uid} gid={vmail_gid} home={vmail_dir}/%d/%n
-}}
-"""
-
- MASTER_CONF_CONTENT = """# Dovecot master configuration - Managed by ServerKit
-service imap-login {
- inet_listener imap {
- port = 0
- }
- inet_listener imaps {
- port = 993
- ssl = yes
- }
-}
-service pop3-login {
- inet_listener pop3 {
- port = 0
- }
- inet_listener pop3s {
- port = 995
- ssl = yes
- }
-}
-service lmtp {
- unix_listener /var/spool/postfix/private/dovecot-lmtp {
- mode = 0600
- user = postfix
- group = postfix
- }
-}
-service auth {
- unix_listener /var/spool/postfix/private/auth {
- mode = 0666
- user = postfix
- group = postfix
- }
- unix_listener auth-userdb {
- mode = 0600
- user = vmail
- group = vmail
- }
- user = dovecot
-}
-service auth-worker {
- user = vmail
-}
-"""
-
- SSL_CONF_CONTENT = """# Dovecot SSL configuration - Managed by ServerKit
-ssl = required
-ssl_cert = <{tls_cert}
-ssl_key = <{tls_key}
-ssl_min_protocol = TLSv1.2
-ssl_prefer_server_ciphers = yes
-"""
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get Dovecot installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- # `which` searches $PATH only, and dovecot lives in /usr/sbin — absent
- # from the panel unit's PATH — so it reported a false negative on a host
- # where dovecot was installed. is_command_available() also searches the
- # sbin dirs.
- try:
- installed = is_command_available('dovecot')
- if not installed:
- installed = PackageManager.is_installed('dovecot-core') or PackageManager.is_installed('dovecot')
- except Exception:
- installed = False
-
- if installed:
- try:
- running = ServiceControl.is_active('dovecot')
- enabled = ServiceControl.is_enabled('dovecot')
- except (subprocess.SubprocessError, FileNotFoundError):
- # No systemctl (container, non-systemd init), or systemd not
- # answering inside PROBE_TIMEOUT: "could not check", not "not
- # running" — and never a 500. Wider than FileNotFoundError on
- # purpose: is_enabled already swallows the missing binary, but
- # the probe timeout in both wrappers still raises
- # TimeoutExpired straight through get_status and out of
- # /api/v1/email/status. The sibling services in this extension
- # catch the same pair.
- running = None
- enabled = None
- # Its own try: failing to read the version says nothing about
- # whether dovecot is installed. Collapsing the two is how
- # FirewallService._check_ufw reported a working firewall as absent.
- try:
- result = run_privileged(['dovecot', '--version'])
- version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout or '')
- if version_match:
- version = version_match.group(1)
- except Exception:
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install Dovecot packages."""
- try:
- manager = PackageManager.detect()
- if manager == 'apt':
- packages = ['dovecot-core', 'dovecot-imapd', 'dovecot-pop3d', 'dovecot-lmtpd', 'dovecot-sieve']
- else:
- packages = ['dovecot']
-
- result = PackageManager.install(packages, timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install Dovecot'}
-
- # Create empty passwd file
- run_privileged(['touch', cls.DOVECOT_PASSWD_FILE])
- run_privileged(['chown', 'vmail:dovecot', cls.DOVECOT_PASSWD_FILE])
- run_privileged(['chmod', '640', cls.DOVECOT_PASSWD_FILE])
-
- ServiceControl.enable('dovecot')
-
- return {'success': True, 'message': 'Dovecot installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure(cls, tls_cert: str = None, tls_key: str = None) -> Dict:
- """Write Dovecot configuration files."""
- try:
- cert = tls_cert or '/etc/ssl/certs/ssl-cert-snakeoil.pem'
- key = tls_key or '/etc/ssl/private/ssl-cert-snakeoil.key'
-
- # 10-mail.conf
- mail_conf = cls.MAIL_CONF_CONTENT.format(
- vmail_dir=paths.VMAIL_DIR,
- vmail_uid=paths.VMAIL_UID,
- vmail_gid=paths.VMAIL_GID,
- )
- run_privileged(['tee', cls.DOVECOT_MAIL_CONF], input=mail_conf)
-
- # 10-auth.conf
- run_privileged(['tee', cls.DOVECOT_AUTH_CONF], input=cls.AUTH_CONF_CONTENT)
-
- # auth-passwdfile.conf.ext
- auth_passwd = cls.AUTH_PASSWDFILE_CONTENT.format(
- vmail_uid=paths.VMAIL_UID,
- vmail_gid=paths.VMAIL_GID,
- vmail_dir=paths.VMAIL_DIR,
- )
- run_privileged(['tee', cls.AUTH_PASSWDFILE_CONF], input=auth_passwd)
-
- # 10-master.conf
- run_privileged(['tee', cls.DOVECOT_MASTER_CONF], input=cls.MASTER_CONF_CONTENT)
-
- # 10-ssl.conf
- ssl_conf = cls.SSL_CONF_CONTENT.format(tls_cert=cert, tls_key=key)
- run_privileged(['tee', cls.DOVECOT_SSL_CONF], input=ssl_conf)
-
- # Restart to apply
- ServiceControl.restart('dovecot', timeout=30)
-
- return {'success': True, 'message': 'Dovecot configured successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def create_mailbox(cls, email: str, password: str, domain: str, username: str, quota_mb: int = 1024) -> Dict:
- """Create a virtual mailbox with password entry."""
- try:
- # Generate password hash using doveadm
- result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', password])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to hash password'}
-
- password_hash = result.stdout.strip()
-
- # Build passwd-file entry
- # Format: user@domain:{scheme}hash:uid:gid:home::userdb_quota_rule=*:storage=NM
- entry = f'{email}:{password_hash}:{paths.VMAIL_UID}:{paths.VMAIL_GID}:{paths.VMAIL_DIR}/{domain}/{username}::userdb_quota_rule=*:storage={quota_mb}M'
-
- # Append to passwd file
- run_privileged(['tee', '-a', cls.DOVECOT_PASSWD_FILE], input=entry + '\n')
-
- # Create Maildir
- maildir = os.path.join(paths.VMAIL_DIR, domain, username, 'Maildir')
- run_privileged(['mkdir', '-p', f'{maildir}/cur', f'{maildir}/new', f'{maildir}/tmp'])
- run_privileged(['chown', '-R', f'{paths.VMAIL_UID}:{paths.VMAIL_GID}',
- os.path.join(paths.VMAIL_DIR, domain, username)])
-
- return {'success': True, 'message': f'Mailbox {email} created'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def delete_mailbox(cls, email: str, domain: str, username: str, remove_files: bool = False) -> Dict:
- """Delete a virtual mailbox."""
- try:
- # Remove from passwd file
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
- new_lines = [l for l in lines if not l.startswith(f'{email}:')]
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- # Optionally remove Maildir
- if remove_files:
- mailbox_path = os.path.join(paths.VMAIL_DIR, domain, username)
- run_privileged(['rm', '-rf', mailbox_path])
-
- return {'success': True, 'message': f'Mailbox {email} deleted'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def change_password(cls, email: str, new_password: str) -> Dict:
- """Change a mailbox password."""
- try:
- # Generate new hash
- result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', new_password])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to hash password'}
-
- new_hash = result.stdout.strip()
-
- # Read current file
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
-
- updated = False
- new_lines = []
- for line in lines:
- if line.startswith(f'{email}:'):
- parts = line.split(':')
- parts[1] = new_hash
- new_lines.append(':'.join(parts))
- updated = True
- else:
- new_lines.append(line)
-
- if not updated:
- return {'success': False, 'error': f'Account {email} not found'}
-
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- return {'success': True, 'message': 'Password changed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def set_quota(cls, email: str, quota_mb: int) -> Dict:
- """Update mailbox quota."""
- try:
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
-
- updated = False
- new_lines = []
- for line in lines:
- if line.startswith(f'{email}:'):
- # Replace quota in the userdb_quota_rule field
- line = re.sub(r'userdb_quota_rule=\*:storage=\d+M',
- f'userdb_quota_rule=*:storage={quota_mb}M', line)
- new_lines.append(line)
- updated = True
- else:
- new_lines.append(line)
-
- if not updated:
- return {'success': False, 'error': f'Account {email} not found'}
-
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- return {'success': True, 'message': f'Quota set to {quota_mb}MB'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_quota_usage(cls, email: str) -> Dict:
- """Get mailbox quota usage."""
- try:
- result = run_privileged(['doveadm', 'quota', 'get', '-u', email])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to get quota'}
-
- # Parse output
- usage = {'storage_used': 0, 'storage_limit': 0, 'message_count': 0}
- for line in result.stdout.splitlines():
- parts = line.split()
- if len(parts) >= 4 and parts[0] == 'STORAGE':
- usage['storage_used'] = int(parts[1]) // 1024 # KB to MB
- usage['storage_limit'] = int(parts[2]) // 1024 if parts[2] != '-' else 0
- elif len(parts) >= 4 and parts[0] == 'MESSAGE':
- usage['message_count'] = int(parts[1])
-
- return {'success': True, **usage}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload Dovecot configuration."""
- try:
- result = ServiceControl.reload('dovecot', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'Dovecot reloaded'}
- return {'success': False, 'error': result.stderr or 'Reload failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def restart(cls) -> Dict:
- """Restart Dovecot."""
- try:
- result = ServiceControl.restart('dovecot', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'Dovecot restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/email.py b/backend/app/plugins/serverkit-email/email.py
deleted file mode 100644
index 45afdf28..00000000
--- a/backend/app/plugins/serverkit-email/email.py
+++ /dev/null
@@ -1,426 +0,0 @@
-"""Email Server API endpoints for managing mail services, domains, accounts, and DNS.
-
-Lives in the serverkit-email extension (app.plugins.serverkit-email.email after
-install). Intra-extension modules are imported relatively; core services
-(postfix relay, DNS, relay-config, RBAC) are imported absolutely — the mail
-server extends the core, never the other way around.
-"""
-from flask import Blueprint, request, jsonify
-
-from app.middleware.rbac import admin_required, viewer_required
-from app.services.dns_provider_service import DNSProviderService
-from app.services.postfix_service import PostfixService
-from app.services.email_relay_service import EmailRelayService
-from .email_service import EmailService
-from .spamassassin_service import SpamAssassinService
-from .roundcube_service import RoundcubeService
-
-email_bp = Blueprint('email', __name__)
-
-
-# ── Status & Installation ──
-
-@email_bp.route('/status', methods=['GET'])
-@viewer_required
-def get_status():
- """Get aggregate email server status."""
- roundcube = RoundcubeService.get_status()
- status = EmailService.get_status()
- status['roundcube'] = roundcube
- return jsonify(status), 200
-
-
-@email_bp.route('/install', methods=['POST'])
-@admin_required
-def install():
- """Install and configure all email components."""
- data = request.get_json() or {}
- hostname = data.get('hostname')
- result = EmailService.install_all(hostname)
- return jsonify(result), 200 if result.get('success') else 500
-
-
-@email_bp.route('/service/<component>/<action>', methods=['POST'])
-@admin_required
-def control_service(component, action):
- """Start/stop/restart an email component."""
- result = EmailService.control_service(component, action)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Domains ──
-
-@email_bp.route('/domains', methods=['GET'])
-@viewer_required
-def list_domains():
- """List all email domains."""
- domains = EmailService.get_domains()
- return jsonify({'domains': domains}), 200
-
-
-@email_bp.route('/domains', methods=['POST'])
-@admin_required
-def add_domain():
- """Add an email domain."""
- data = request.get_json()
- if not data or not data.get('name'):
- return jsonify({'success': False, 'error': 'Domain name is required'}), 400
- result = EmailService.add_domain(
- data['name'],
- dns_provider_id=data.get('dns_provider_id'),
- dns_zone_id=data.get('dns_zone_id'),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/domains/<int:domain_id>', methods=['GET'])
-@viewer_required
-def get_domain(domain_id):
- """Get domain details."""
- result = EmailService.get_domain(domain_id)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 404
-
-
-@email_bp.route('/domains/<int:domain_id>', methods=['DELETE'])
-@admin_required
-def remove_domain(domain_id):
- """Remove an email domain."""
- result = EmailService.remove_domain(domain_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/domains/<int:domain_id>/verify-dns', methods=['POST'])
-@viewer_required
-def verify_dns(domain_id):
- """Verify DNS records for a domain."""
- result = EmailService.verify_dns(domain_id)
- return jsonify(result), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/deploy-dns', methods=['POST'])
-@admin_required
-def deploy_dns(domain_id):
- """Deploy DNS records via provider API."""
- from app.models.email import EmailDomain
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return jsonify({'success': False, 'error': 'Domain not found'}), 404
- if not domain.dns_provider_id or not domain.dns_zone_id:
- return jsonify({'success': False, 'error': 'No DNS provider configured for this domain'}), 400
- result = DNSProviderService.deploy_email_records(
- domain.dns_provider_id,
- domain.dns_zone_id,
- domain.name,
- domain.dkim_selector or 'default',
- domain.dkim_public_key or '',
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Accounts ──
-
-@email_bp.route('/domains/<int:domain_id>/accounts', methods=['GET'])
-@viewer_required
-def list_accounts(domain_id):
- """List email accounts for a domain."""
- accounts = EmailService.get_accounts(domain_id)
- return jsonify({'accounts': accounts}), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/accounts', methods=['POST'])
-@admin_required
-def create_account(domain_id):
- """Create an email account."""
- data = request.get_json()
- if not data:
- return jsonify({'success': False, 'error': 'Request body required'}), 400
- username = data.get('username')
- password = data.get('password')
- if not username or not password:
- return jsonify({'success': False, 'error': 'Username and password are required'}), 400
- result = EmailService.add_account(
- domain_id,
- username,
- password,
- quota_mb=data.get('quota_mb', 1024),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['GET'])
-@viewer_required
-def get_account(account_id):
- """Get account details."""
- from app.models.email import EmailAccount
- account = EmailAccount.query.get(account_id)
- if not account:
- return jsonify({'success': False, 'error': 'Account not found'}), 404
- return jsonify({'success': True, 'account': account.to_dict()}), 200
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['PUT'])
-@admin_required
-def update_account(account_id):
- """Update account settings."""
- data = request.get_json() or {}
- result = EmailService.update_account(
- account_id,
- quota_mb=data.get('quota_mb'),
- is_active=data.get('is_active'),
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
-@admin_required
-def delete_account(account_id):
- """Delete an email account."""
- result = EmailService.delete_account(account_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>/password', methods=['POST'])
-@admin_required
-def change_password(account_id):
- """Change account password."""
- data = request.get_json()
- if not data or not data.get('password'):
- return jsonify({'success': False, 'error': 'New password is required'}), 400
- result = EmailService.change_password(account_id, data['password'])
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Aliases ──
-
-@email_bp.route('/domains/<int:domain_id>/aliases', methods=['GET'])
-@viewer_required
-def list_aliases(domain_id):
- """List email aliases for a domain."""
- aliases = EmailService.get_aliases(domain_id)
- return jsonify({'aliases': aliases}), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/aliases', methods=['POST'])
-@admin_required
-def create_alias(domain_id):
- """Create an email alias."""
- data = request.get_json()
- if not data or not data.get('source') or not data.get('destination'):
- return jsonify({'success': False, 'error': 'Source and destination are required'}), 400
- result = EmailService.add_alias(domain_id, data['source'], data['destination'])
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/aliases/<int:alias_id>', methods=['DELETE'])
-@admin_required
-def delete_alias(alias_id):
- """Delete an email alias."""
- result = EmailService.remove_alias(alias_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Forwarding Rules ──
-
-@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['GET'])
-@viewer_required
-def list_forwarding(account_id):
- """List forwarding rules for an account."""
- rules = EmailService.get_forwarding(account_id)
- return jsonify({'rules': rules}), 200
-
-
-@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['POST'])
-@admin_required
-def create_forwarding(account_id):
- """Create a forwarding rule."""
- data = request.get_json()
- if not data or not data.get('destination'):
- return jsonify({'success': False, 'error': 'Destination is required'}), 400
- result = EmailService.add_forwarding(
- account_id,
- data['destination'],
- keep_copy=data.get('keep_copy', True),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/forwarding/<int:rule_id>', methods=['PUT'])
-@admin_required
-def update_forwarding(rule_id):
- """Update a forwarding rule."""
- data = request.get_json() or {}
- result = EmailService.update_forwarding(
- rule_id,
- destination=data.get('destination'),
- keep_copy=data.get('keep_copy'),
- is_active=data.get('is_active'),
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/forwarding/<int:rule_id>', methods=['DELETE'])
-@admin_required
-def delete_forwarding(rule_id):
- """Delete a forwarding rule."""
- result = EmailService.remove_forwarding(rule_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── DNS Providers ──
-# Moved to core (app/api/dns_providers.py, same /api/v1/email/dns-providers
-# paths): the Connections page and wildcard TLS need them without this
-# extension installed.
-
-
-# ── Outbound SMTP Relay (smarthost) ──
-
-@email_bp.route('/relay', methods=['GET'])
-@viewer_required
-def get_relay():
- """Get the outbound SMTP relay configuration (password masked)."""
- return jsonify(EmailRelayService.get_config()), 200
-
-
-@email_bp.route('/relay', methods=['PUT'])
-@admin_required
-def save_relay():
- """Save the relay configuration and apply it to Postfix (if installed)."""
- data = request.get_json() or {}
- if not data.get('host'):
- return jsonify({'success': False, 'error': 'A relay host is required'}), 400
- result = EmailRelayService.save_config(data)
- return jsonify(result), 200
-
-
-@email_bp.route('/relay/test', methods=['POST'])
-@admin_required
-def test_relay():
- """Open a real SMTP connection to validate the relay credentials."""
- data = request.get_json() or {}
- result = EmailRelayService.test(data)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/relay', methods=['DELETE'])
-@admin_required
-def disable_relay():
- """Disable the outbound relay (revert Postfix to direct delivery)."""
- result = EmailRelayService.disable()
- return jsonify(result), 200
-
-
-# ── SpamAssassin Config ──
-
-@email_bp.route('/spam/config', methods=['GET'])
-@viewer_required
-def get_spam_config():
- """Get SpamAssassin configuration."""
- result = SpamAssassinService.get_config()
- return jsonify(result), 200
-
-
-@email_bp.route('/spam/config', methods=['PUT'])
-@admin_required
-def update_spam_config():
- """Update SpamAssassin configuration."""
- data = request.get_json()
- if not data:
- return jsonify({'success': False, 'error': 'Request body required'}), 400
- result = SpamAssassinService.configure(data)
- if result.get('success'):
- SpamAssassinService.reload()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/spam/update-rules', methods=['POST'])
-@admin_required
-def update_spam_rules():
- """Update SpamAssassin rules."""
- result = SpamAssassinService.update_rules()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Roundcube Webmail ──
-
-@email_bp.route('/webmail/status', methods=['GET'])
-@viewer_required
-def webmail_status():
- """Get Roundcube webmail status."""
- result = RoundcubeService.get_status()
- return jsonify(result), 200
-
-
-@email_bp.route('/webmail/install', methods=['POST'])
-@admin_required
-def webmail_install():
- """Install Roundcube webmail."""
- data = request.get_json() or {}
- result = RoundcubeService.install(
- imap_host=data.get('imap_host', 'host.docker.internal'),
- smtp_host=data.get('smtp_host', 'host.docker.internal'),
- domain=(data.get('domain') or '').strip() or None,
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/webmail/service/<action>', methods=['POST'])
-@admin_required
-def webmail_control(action):
- """Start/stop/restart Roundcube."""
- actions = {
- 'start': RoundcubeService.start,
- 'stop': RoundcubeService.stop,
- 'restart': RoundcubeService.restart,
- }
- if action not in actions:
- return jsonify({'success': False, 'error': 'Invalid action'}), 400
- result = actions[action]()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/webmail/configure-proxy', methods=['POST'])
-@admin_required
-def webmail_configure_proxy():
- """Configure Nginx reverse proxy for Roundcube."""
- data = request.get_json()
- if not data or not data.get('domain'):
- return jsonify({'success': False, 'error': 'Domain is required'}), 400
- result = RoundcubeService.configure_nginx_proxy(data['domain'])
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Mail Queue & Logs ──
-
-@email_bp.route('/queue', methods=['GET'])
-@viewer_required
-def get_queue():
- """Get Postfix mail queue."""
- result = PostfixService.get_queue()
- return jsonify(result), 200
-
-
-@email_bp.route('/queue/flush', methods=['POST'])
-@admin_required
-def flush_queue():
- """Flush the mail queue."""
- result = PostfixService.flush_queue()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/queue/<queue_id>', methods=['DELETE'])
-@admin_required
-def delete_queue_item(queue_id):
- """Delete a message from the queue."""
- result = PostfixService.delete_from_queue(queue_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/logs', methods=['GET'])
-@viewer_required
-def get_logs():
- """Get mail logs."""
- lines = request.args.get('lines', 100, type=int)
- result = PostfixService.get_logs(lines)
- return jsonify(result), 200
diff --git a/backend/app/plugins/serverkit-email/email_service.py b/backend/app/plugins/serverkit-email/email_service.py
deleted file mode 100644
index fdadf70a..00000000
--- a/backend/app/plugins/serverkit-email/email_service.py
+++ /dev/null
@@ -1,550 +0,0 @@
-"""Email service orchestrator — delegates to sub-services for each component."""
-import logging
-import subprocess
-from typing import Dict, List, Optional
-
-from app import db
-from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule
-from app.services.postfix_service import PostfixService
-from app.utils.system import PackageManager, ServiceControl, run_checked
-from .dovecot_service import DovecotService
-from .dkim_service import DKIMService
-from .spamassassin_service import SpamAssassinService
-from .roundcube_service import RoundcubeService
-
-logger = logging.getLogger(__name__)
-
-
-class EmailService:
- """High-level email service that coordinates Postfix, Dovecot, DKIM, and SpamAssassin."""
-
- COMPONENTS = {
- 'postfix': PostfixService,
- 'dovecot': DovecotService,
- 'opendkim': DKIMService,
- 'spamassassin': SpamAssassinService,
- }
-
- # ── Status ──
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get aggregate email server status."""
- postfix = PostfixService.get_status()
- dovecot = DovecotService.get_status()
- dkim = DKIMService.get_status()
- spam = SpamAssassinService.get_status()
-
- all_installed = postfix['installed'] and dovecot['installed']
- # bool(): a component whose probe could not run reports running=None
- # (see DovecotService.get_status), and `True and None` is None — the
- # top-level flag is documented as a boolean, so keep it one. The
- # honest per-component tri-state is still in the nested dicts.
- all_running = bool(postfix.get('running', False) and dovecot.get('running', False))
-
- return {
- 'installed': all_installed,
- 'running': all_running,
- 'postfix': postfix,
- 'dovecot': dovecot,
- 'dkim': dkim,
- 'spamassassin': spam,
- }
-
- # ── Installation ──
-
- @classmethod
- def install_all(cls, hostname: str = None) -> Dict:
- """Install and configure all email components."""
- results = {}
-
- # 1. Install Postfix
- results['postfix'] = PostfixService.install(hostname=hostname)
- if not results['postfix'].get('success'):
- return {'success': False, 'error': 'Postfix installation failed', 'results': results}
-
- # 2. Configure Postfix
- postfix_config = PostfixService.configure(hostname=hostname)
- if not postfix_config.get('success'):
- logger.warning(f"Postfix configuration warning: {postfix_config.get('error')}")
-
- # 3. Install Dovecot
- results['dovecot'] = DovecotService.install()
- if not results['dovecot'].get('success'):
- return {'success': False, 'error': 'Dovecot installation failed', 'results': results}
-
- # 4. Configure Dovecot
- dovecot_config = DovecotService.configure()
- if not dovecot_config.get('success'):
- logger.warning(f"Dovecot configuration warning: {dovecot_config.get('error')}")
-
- # 5. Install OpenDKIM
- results['dkim'] = DKIMService.install()
- if not results['dkim'].get('success'):
- logger.warning(f"DKIM installation warning: {results['dkim'].get('error')}")
-
- # 6. Install SpamAssassin
- results['spamassassin'] = SpamAssassinService.install()
- if not results['spamassassin'].get('success'):
- logger.warning(f"SpamAssassin installation warning: {results['spamassassin'].get('error')}")
-
- all_ok = all(r.get('success') for r in results.values())
- return {
- 'success': all_ok,
- 'message': 'All email components installed' if all_ok else 'Some components had issues',
- 'results': results,
- }
-
- # ── Service Control ──
-
- @classmethod
- def control_service(cls, component: str, action: str) -> Dict:
- """Start/stop/restart an email component."""
- if component not in cls.COMPONENTS and component != 'roundcube':
- return {'success': False, 'error': f'Unknown component: {component}'}
-
- if action not in ('start', 'stop', 'restart', 'reload'):
- return {'success': False, 'error': f'Invalid action: {action}'}
-
- try:
- if component == 'roundcube':
- actions = {
- 'start': RoundcubeService.start,
- 'stop': RoundcubeService.stop,
- 'restart': RoundcubeService.restart,
- 'reload': RoundcubeService.restart,
- }
- return actions[action]()
-
- service_name = component
- if action == 'start':
- result = ServiceControl.start(service_name, timeout=30)
- elif action == 'stop':
- result = ServiceControl.stop(service_name, timeout=30)
- elif action == 'restart':
- result = ServiceControl.restart(service_name, timeout=30)
- elif action == 'reload':
- result = ServiceControl.reload(service_name, timeout=30)
-
- if result.returncode == 0:
- return {'success': True, 'message': f'{component} {action} successful'}
- return {'success': False, 'error': result.stderr or f'{action} failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- # ── Domains ──
-
- @classmethod
- def get_domains(cls) -> List[Dict]:
- """List all email domains."""
- domains = EmailDomain.query.all()
- return [d.to_dict() for d in domains]
-
- @classmethod
- def add_domain(cls, name: str, dns_provider_id: int = None, dns_zone_id: str = None) -> Dict:
- """Add an email domain."""
- try:
- existing = EmailDomain.query.filter_by(name=name).first()
- if existing:
- return {'success': False, 'error': f'Domain {name} already exists'}
-
- domain = EmailDomain(
- name=name,
- dns_provider_id=dns_provider_id,
- dns_zone_id=dns_zone_id,
- )
- db.session.add(domain)
- db.session.commit()
-
- # Add to Postfix virtual domains
- PostfixService.add_domain(name)
-
- # Generate DKIM key
- dkim_result = DKIMService.generate_key(name)
- if dkim_result.get('success'):
- domain.dkim_selector = 'default'
- domain.dkim_private_key_path = dkim_result.get('private_key_path')
- domain.dkim_public_key = dkim_result.get('public_key')
- domain.spf_record = f'v=spf1 mx a ~all'
- domain.dmarc_record = f'v=DMARC1; p=quarantine; rua=mailto:dmarc@{name}; pct=100'
- DKIMService.add_domain(name)
- db.session.commit()
-
- return {'success': True, 'domain': domain.to_dict(), 'message': f'Domain {name} added'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_domain(cls, domain_id: int) -> Dict:
- """Get domain details."""
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
- return {'success': True, 'domain': domain.to_dict()}
-
- @classmethod
- def remove_domain(cls, domain_id: int) -> Dict:
- """Remove an email domain and all its accounts/aliases."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- domain_name = domain.name
-
- # Remove accounts from Dovecot/Postfix
- for account in domain.accounts:
- DovecotService.delete_mailbox(account.email, domain_name, account.username, remove_files=True)
- PostfixService.remove_mailbox(account.email)
-
- # Remove aliases from Postfix
- for alias in domain.aliases:
- PostfixService.remove_alias(alias.source)
-
- # Remove from DKIM
- DKIMService.remove_domain(domain_name)
-
- # Remove from Postfix virtual domains
- PostfixService.remove_domain(domain_name)
-
- # Delete from database
- db.session.delete(domain)
- db.session.commit()
-
- return {'success': True, 'message': f'Domain {domain_name} removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def verify_dns(cls, domain_id: int) -> Dict:
- """Verify DNS records for a domain."""
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- results = {}
- name = domain.name
-
- # Check MX record
- try:
- result = run_checked(['dig', '+short', 'MX', name], timeout=10)
- results['mx'] = {
- 'found': bool(result['output'].strip()),
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['mx'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check SPF record
- try:
- result = run_checked(['dig', '+short', 'TXT', name], timeout=10)
- spf_found = 'v=spf1' in result['output']
- results['spf'] = {
- 'found': spf_found,
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['spf'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check DKIM record
- selector = domain.dkim_selector or 'default'
- try:
- dkim_name = f'{selector}._domainkey.{name}'
- result = run_checked(['dig', '+short', 'TXT', dkim_name], timeout=10)
- dkim_found = 'v=DKIM1' in result['output']
- results['dkim'] = {
- 'found': dkim_found,
- 'value': result['output'].strip() or None,
- 'name': dkim_name,
- }
- except Exception:
- results['dkim'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check DMARC record
- try:
- dmarc_name = f'_dmarc.{name}'
- result = run_checked(['dig', '+short', 'TXT', dmarc_name], timeout=10)
- dmarc_found = 'v=DMARC1' in result['output']
- results['dmarc'] = {
- 'found': dmarc_found,
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['dmarc'] = {'found': False, 'error': 'DNS lookup failed'}
-
- all_ok = all(r.get('found') for r in results.values())
- return {
- 'success': True,
- 'domain': name,
- 'all_verified': all_ok,
- 'records': results,
- }
-
- # ── Accounts ──
-
- @classmethod
- def get_accounts(cls, domain_id: int) -> List[Dict]:
- """List email accounts for a domain."""
- accounts = EmailAccount.query.filter_by(domain_id=domain_id).all()
- return [a.to_dict() for a in accounts]
-
- @classmethod
- def add_account(cls, domain_id: int, username: str, password: str, quota_mb: int = 1024) -> Dict:
- """Create an email account."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- email = f'{username}@{domain.name}'
-
- existing = EmailAccount.query.filter_by(email=email).first()
- if existing:
- return {'success': False, 'error': f'Account {email} already exists'}
-
- # Create mailbox in Dovecot
- dovecot_result = DovecotService.create_mailbox(email, password, domain.name, username, quota_mb)
- if not dovecot_result.get('success'):
- return dovecot_result
-
- # Add to Postfix virtual mailboxes
- PostfixService.add_mailbox(email, domain.name, username)
-
- # Get password hash for storage
- password_hash = dovecot_result.get('password_hash', 'stored_in_dovecot')
-
- account = EmailAccount(
- email=email,
- username=username,
- password_hash=password_hash,
- domain_id=domain_id,
- quota_mb=quota_mb,
- )
- db.session.add(account)
- db.session.commit()
-
- return {'success': True, 'account': 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, quota_mb: int = None, is_active: bool = None) -> Dict:
- """Update account settings."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- if quota_mb is not None:
- account.quota_mb = quota_mb
- DovecotService.set_quota(account.email, quota_mb)
-
- if is_active is not None:
- account.is_active = is_active
-
- db.session.commit()
- return {'success': True, 'account': account.to_dict(), 'message': 'Account updated'}
- 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."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- email = account.email
- domain_name = account.domain.name if account.domain else ''
- username = account.username
-
- # Remove from Dovecot
- DovecotService.delete_mailbox(email, domain_name, username, remove_files=True)
-
- # Remove from Postfix
- PostfixService.remove_mailbox(email)
-
- db.session.delete(account)
- db.session.commit()
-
- return {'success': True, 'message': f'Account {email} deleted'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def change_password(cls, account_id: int, new_password: str) -> Dict:
- """Change an account password."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- result = DovecotService.change_password(account.email, new_password)
- if not result.get('success'):
- return result
-
- account.password_hash = 'updated_in_dovecot'
- db.session.commit()
-
- return {'success': True, 'message': 'Password changed successfully'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- # ── Aliases ──
-
- @classmethod
- def get_aliases(cls, domain_id: int) -> List[Dict]:
- """List email aliases for a domain."""
- aliases = EmailAlias.query.filter_by(domain_id=domain_id).all()
- return [a.to_dict() for a in aliases]
-
- @classmethod
- def add_alias(cls, domain_id: int, source: str, destination: str) -> Dict:
- """Create an email alias."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- # Add @ domain if not already qualified
- if '@' not in source:
- source = f'{source}@{domain.name}'
-
- alias = EmailAlias(
- source=source,
- destination=destination,
- domain_id=domain_id,
- )
- db.session.add(alias)
- db.session.commit()
-
- # Add to Postfix virtual aliases
- PostfixService.add_alias(source, destination)
-
- return {'success': True, 'alias': alias.to_dict(), 'message': f'Alias {source} created'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_alias(cls, alias_id: int) -> Dict:
- """Delete an email alias."""
- try:
- alias = EmailAlias.query.get(alias_id)
- if not alias:
- return {'success': False, 'error': 'Alias not found'}
-
- PostfixService.remove_alias(alias.source)
-
- db.session.delete(alias)
- db.session.commit()
-
- return {'success': True, 'message': 'Alias removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- # ── Forwarding Rules ──
-
- @classmethod
- def get_forwarding(cls, account_id: int) -> List[Dict]:
- """List forwarding rules for an account."""
- rules = EmailForwardingRule.query.filter_by(account_id=account_id).all()
- return [r.to_dict() for r in rules]
-
- @classmethod
- def add_forwarding(cls, account_id: int, destination: str, keep_copy: bool = True) -> Dict:
- """Create a forwarding rule."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- rule = EmailForwardingRule(
- account_id=account_id,
- destination=destination,
- keep_copy=keep_copy,
- )
- db.session.add(rule)
- db.session.commit()
-
- # Update Postfix aliases for forwarding
- cls._sync_forwarding_aliases(account)
-
- return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule created'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def update_forwarding(cls, rule_id: int, destination: str = None,
- keep_copy: bool = None, is_active: bool = None) -> Dict:
- """Update a forwarding rule."""
- try:
- rule = EmailForwardingRule.query.get(rule_id)
- if not rule:
- return {'success': False, 'error': 'Forwarding rule not found'}
-
- if destination is not None:
- rule.destination = destination
- if keep_copy is not None:
- rule.keep_copy = keep_copy
- if is_active is not None:
- rule.is_active = is_active
-
- db.session.commit()
-
- # Re-sync Postfix aliases
- cls._sync_forwarding_aliases(rule.account)
-
- return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule updated'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_forwarding(cls, rule_id: int) -> Dict:
- """Delete a forwarding rule."""
- try:
- rule = EmailForwardingRule.query.get(rule_id)
- if not rule:
- return {'success': False, 'error': 'Forwarding rule not found'}
-
- account = rule.account
- db.session.delete(rule)
- db.session.commit()
-
- # Re-sync Postfix aliases
- cls._sync_forwarding_aliases(account)
-
- return {'success': True, 'message': 'Forwarding rule removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _sync_forwarding_aliases(cls, account: EmailAccount):
- """Sync forwarding rules to Postfix virtual aliases for an account."""
- active_rules = [r for r in account.forwarding_rules if r.is_active]
-
- if not active_rules:
- # Remove any forwarding alias
- PostfixService.remove_alias(account.email)
- return
-
- # Build destination list
- destinations = [r.destination for r in active_rules]
- # If any rule wants to keep a copy, include the original mailbox
- if any(r.keep_copy for r in active_rules):
- destinations.append(account.email)
-
- # Remove old alias and add new one
- PostfixService.remove_alias(account.email)
- PostfixService.add_alias(account.email, ', '.join(destinations))
diff --git a/backend/app/plugins/serverkit-email/plugin.json b/backend/app/plugins/serverkit-email/plugin.json
deleted file mode 100644
index cae41e3e..00000000
--- a/backend/app/plugins/serverkit-email/plugin.json
+++ /dev/null
@@ -1,51 +0,0 @@
-{
- "name": "serverkit-email",
- "display_name": "Email Server",
- "version": "1.0.0",
- "description": "Full mail-server stack with Postfix/Dovecot, domains, mailboxes, aliases, DKIM/SPF/DMARC, SpamAssassin filtering, and Roundcube webmail. Most panels never run a mail server, so it ships as an opt-in extension.",
- "author": "ServerKit",
- "license": "MIT",
- "category": "integration",
- "homepage": "https://github.com/jhd3197/ServerKit",
- "permissions": [
- "shell",
- "filesystem",
- "network"
- ],
- "min_panel_version": "1.7.0",
- "entry_point": "email:email_bp",
- "url_prefix": "/api/v1/email",
- "icon": "<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\"/>",
- "contributions": {
- "nav": [
- {
- "id": "email",
- "label": "Email Server",
- "route": "/email",
- "category": "operations",
- "icon": "<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\"/>"
- }
- ],
- "routes": [
- {
- "path": "email",
- "component": "EmailPage"
- },
- {
- "path": "email/:tab",
- "component": "EmailPage"
- }
- ],
- "page_titles": {
- "/email": "Email Server"
- },
- "command_palette": [
- {
- "label": "Email",
- "path": "/email",
- "category": "Pages",
- "keywords": "smtp postfix dovecot mail imap dkim webmail"
- }
- ]
- }
-}
\ No newline at end of file
diff --git a/backend/app/plugins/serverkit-email/roundcube_service.py b/backend/app/plugins/serverkit-email/roundcube_service.py
deleted file mode 100644
index fb0f2d6f..00000000
--- a/backend/app/plugins/serverkit-email/roundcube_service.py
+++ /dev/null
@@ -1,198 +0,0 @@
-"""Roundcube webmail management service (Docker-based)."""
-import subprocess
-from typing import Dict
-
-from app.utils.system import run_checked, run_privileged, is_command_available
-
-
-class RoundcubeService:
- """Service for managing Roundcube webmail via Docker."""
-
- CONTAINER_NAME = 'serverkit-roundcube'
- VOLUME_NAME = 'roundcube_data'
- IMAGE = 'roundcube/roundcubemail:latest'
- HOST_PORT = 9000
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get Roundcube container status."""
- if not is_command_available('docker'):
- return {'installed': False, 'running': False, 'error': 'Docker not available'}
-
- try:
- result = run_checked(
- ['docker', 'inspect', '--format', '{{.State.Status}}', cls.CONTAINER_NAME],
- timeout=None)
- if not result['success']:
- return {'installed': False, 'running': False}
-
- status = result['output'].strip()
- return {
- 'installed': True,
- 'running': status == 'running',
- 'status': status,
- 'port': cls.HOST_PORT,
- }
- except Exception as e:
- return {'installed': False, 'running': False, 'error': str(e)}
-
- @classmethod
- def install(cls, imap_host: str = 'host.docker.internal',
- smtp_host: str = 'host.docker.internal',
- domain: str = None) -> Dict:
- """Install Roundcube via Docker container."""
- if not is_command_available('docker'):
- return {'success': False, 'error': 'Docker is not installed'}
-
- try:
- # Remove existing container if any
- run_checked(['docker', 'rm', '-f', cls.CONTAINER_NAME], timeout=None)
-
- # Create volume
- run_checked(['docker', 'volume', 'create', cls.VOLUME_NAME], timeout=None)
-
- # Run container
- result = run_checked([
- 'docker', 'run', '-d',
- '--name', cls.CONTAINER_NAME,
- '--restart', 'unless-stopped',
- '--add-host', 'host.docker.internal:host-gateway',
- '-p', f'{cls.HOST_PORT}:80',
- '-e', f'ROUNDCUBEMAIL_DEFAULT_HOST=ssl://{imap_host}',
- '-e', f'ROUNDCUBEMAIL_SMTP_SERVER=tls://{smtp_host}',
- '-e', 'ROUNDCUBEMAIL_DEFAULT_PORT=993',
- '-e', 'ROUNDCUBEMAIL_SMTP_PORT=587',
- '-e', 'ROUNDCUBEMAIL_UPLOAD_MAX_FILESIZE=25M',
- '-e', 'ROUNDCUBEMAIL_SKIN=elastic',
- '-v', f'{cls.VOLUME_NAME}:/var/roundcube/db',
- cls.IMAGE,
- ], timeout=None)
-
- if not result['success']:
- return {'success': False,
- 'error': result['error'] or 'Failed to start container'}
-
- # Build a public URL: prefer a supplied domain, then auto-generate
- # webmail.<panel_domain>, and only fall back to localhost:port.
- from app.services.site_domain_service import SiteDomainService
- public_url = None
- warning = None
- if domain:
- public_url = f'http://{domain}'
- proxy_res = cls.configure_nginx_proxy(domain)
- if not proxy_res.get('success'):
- warning = proxy_res.get('error')
- else:
- panel_origin = SiteDomainService.panel_origin()
- panel_host = None
- if panel_origin:
- from urllib.parse import urlparse
- panel_host = urlparse(panel_origin).hostname
- if panel_host:
- webmail_domain = f'webmail.{panel_host}'
- public_url = f'http://{webmail_domain}'
- proxy_res = cls.configure_nginx_proxy(webmail_domain)
- if not proxy_res.get('success'):
- warning = proxy_res.get('error')
-
- if not public_url:
- public_url = f'http://localhost:{cls.HOST_PORT}'
-
- result = {
- 'success': True,
- 'message': 'Roundcube installed successfully',
- 'port': cls.HOST_PORT,
- 'url': public_url,
- }
- if warning:
- result['warning'] = warning
- return result
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def uninstall(cls) -> Dict:
- """Stop and remove Roundcube container."""
- try:
- run_checked(['docker', 'rm', '-f', cls.CONTAINER_NAME], timeout=None)
- return {'success': True, 'message': 'Roundcube uninstalled'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def start(cls) -> Dict:
- """Start Roundcube container."""
- try:
- result = run_checked(['docker', 'start', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube started'}
- return {'success': False, 'error': result['error'] or 'Start failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def stop(cls) -> Dict:
- """Stop Roundcube container."""
- try:
- result = run_checked(['docker', 'stop', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube stopped'}
- return {'success': False, 'error': result['error'] or 'Stop failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def restart(cls) -> Dict:
- """Restart Roundcube container."""
- try:
- result = run_checked(['docker', 'restart', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube restarted'}
- return {'success': False, 'error': result['error'] or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure_nginx_proxy(cls, domain: str) -> Dict:
- """Create Nginx reverse proxy config for Roundcube."""
- try:
- from app.services.nginx_service import NginxService
-
- config = f"""# Roundcube Webmail - Managed by ServerKit
-server {{
- listen 80;
- server_name {domain};
-
- location / {{
- proxy_pass http://127.0.0.1:{cls.HOST_PORT};
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- client_max_body_size 25m;
- }}
-}}
-"""
- site_name = f'roundcube-{domain.replace(".", "-")}'
- config_path = f'/etc/nginx/sites-available/{site_name}'
- enabled_path = f'/etc/nginx/sites-enabled/{site_name}'
-
- run_privileged(['tee', config_path], input=config)
- run_privileged(['ln', '-sf', config_path, enabled_path])
-
- # Test and reload
- test = run_privileged(['nginx', '-t'])
- if test.returncode != 0:
- # Rollback
- run_privileged(['rm', '-f', enabled_path])
- return {'success': False, 'error': f'Nginx config test failed: {test.stderr}'}
-
- run_privileged(['systemctl', 'reload', 'nginx'])
-
- return {
- 'success': True,
- 'message': f'Nginx proxy configured for {domain}',
- 'url': f'http://{domain}',
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/backend/app/plugins/serverkit-email/spamassassin_service.py b/backend/app/plugins/serverkit-email/spamassassin_service.py
deleted file mode 100644
index 85516e42..00000000
--- a/backend/app/plugins/serverkit-email/spamassassin_service.py
+++ /dev/null
@@ -1,254 +0,0 @@
-"""SpamAssassin management service."""
-import os
-import re
-import subprocess
-from typing import Dict
-
-from app.utils.system import (PackageManager, ServiceControl, run_checked,
- run_privileged)
-
-
-class SpamAssassinService:
- """Service for managing SpamAssassin spam filtering."""
-
- SPAMASSASSIN_CONF = '/etc/spamassassin/local.cf'
- SPAMASSASSIN_DEFAULT = '/etc/default/spamassassin'
- SPAMASS_MILTER_DEFAULT = '/etc/default/spamass-milter'
-
- LOCAL_CF_TEMPLATE = """# SpamAssassin local configuration - Managed by ServerKit
-required_score {required_score}
-report_safe {report_safe}
-rewrite_header Subject {rewrite_subject}
-use_bayes {use_bayes}
-bayes_auto_learn {bayes_auto_learn}
-bayes_auto_learn_threshold_nonspam 0.1
-bayes_auto_learn_threshold_spam 12.0
-skip_rbl_checks {skip_rbl_checks}
-use_razor2 0
-use_pyzor 0
-
-# Network checks
-dns_available yes
-
-# Trusted networks
-trusted_networks 127.0.0.0/8
-internal_networks 127.0.0.0/8
-"""
-
- DEFAULT_CONFIG = {
- 'required_score': 5.0,
- 'report_safe': 0,
- 'rewrite_subject': '[SPAM]',
- 'use_bayes': 1,
- 'bayes_auto_learn': 1,
- 'skip_rbl_checks': 0,
- }
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get SpamAssassin installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- milter_installed = False
- milter_running = False
-
- try:
- installed = PackageManager.is_installed('spamassassin')
- if installed:
- running = ServiceControl.is_active('spamassassin')
- enabled = ServiceControl.is_enabled('spamassassin')
- result = run_checked(['spamassassin', '--version'], timeout=None)
- match = re.search(r'version\s+(\S+)', result['output'])
- if match:
- version = match.group(1)
-
- # Check milter
- milter_installed = PackageManager.is_installed('spamass-milter')
- if milter_installed:
- milter_running = ServiceControl.is_active('spamass-milter')
- except (subprocess.SubprocessError, FileNotFoundError):
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- 'milter_installed': milter_installed,
- 'milter_running': milter_running,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install SpamAssassin and spamass-milter."""
- try:
- manager = PackageManager.detect()
- if manager == 'apt':
- packages = ['spamassassin', 'spamass-milter', 'spamc']
- else:
- packages = ['spamassassin', 'spamass-milter-postfix']
-
- result = PackageManager.install(packages, timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install SpamAssassin'}
-
- # Enable spamd on Debian/Ubuntu
- if manager == 'apt' and os.path.exists(cls.SPAMASSASSIN_DEFAULT):
- result = run_privileged(['cat', cls.SPAMASSASSIN_DEFAULT])
- content = result.stdout or ''
- content = re.sub(r'ENABLED=0', 'ENABLED=1', content)
- content = re.sub(r'CRON=0', 'CRON=1', content)
- run_privileged(['tee', cls.SPAMASSASSIN_DEFAULT], input=content)
-
- # Configure milter to listen on port 8893
- milter_config = 'OPTIONS="-u spamass-milter -i 127.0.0.1 -p inet:8893@localhost -- --socket=/var/run/spamassassin/spamd.sock"\n'
- if os.path.exists(cls.SPAMASS_MILTER_DEFAULT):
- run_privileged(['tee', cls.SPAMASS_MILTER_DEFAULT], input=milter_config)
-
- # Write default config
- cls.configure(cls.DEFAULT_CONFIG)
-
- # Update rules
- run_privileged(['sa-update'], timeout=120)
-
- ServiceControl.enable('spamassassin')
- ServiceControl.start('spamassassin', timeout=30)
-
- if PackageManager.is_installed('spamass-milter'):
- ServiceControl.enable('spamass-milter')
- ServiceControl.start('spamass-milter', timeout=30)
-
- return {'success': True, 'message': 'SpamAssassin installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure(cls, settings: Dict = None) -> Dict:
- """Write SpamAssassin configuration."""
- try:
- config = dict(cls.DEFAULT_CONFIG)
- if settings:
- config.update(settings)
- content = cls.LOCAL_CF_TEMPLATE.format(**config)
- run_privileged(['tee', cls.SPAMASSASSIN_CONF], input=content)
- return {'success': True, 'message': 'SpamAssassin configured'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_config(cls) -> Dict:
- """Get current SpamAssassin configuration."""
- try:
- if not os.path.exists(cls.SPAMASSASSIN_CONF):
- return {'success': True, 'config': dict(cls.DEFAULT_CONFIG)}
-
- result = run_privileged(['cat', cls.SPAMASSASSIN_CONF])
- content = result.stdout or ''
-
- config = dict(cls.DEFAULT_CONFIG)
-
- # Parse values
- score_match = re.search(r'required_score\s+(\S+)', content)
- if score_match:
- config['required_score'] = float(score_match.group(1))
-
- report_match = re.search(r'report_safe\s+(\d+)', content)
- if report_match:
- config['report_safe'] = int(report_match.group(1))
-
- subject_match = re.search(r'rewrite_header Subject\s+(.+)', content)
- if subject_match:
- config['rewrite_subject'] = subject_match.group(1).strip()
-
- bayes_match = re.search(r'use_bayes\s+(\d+)', content)
- if bayes_match:
- config['use_bayes'] = int(bayes_match.group(1))
-
- auto_learn_match = re.search(r'bayes_auto_learn\s+(\d+)', content)
- if auto_learn_match:
- config['bayes_auto_learn'] = int(auto_learn_match.group(1))
-
- rbl_match = re.search(r'skip_rbl_checks\s+(\d+)', content)
- if rbl_match:
- config['skip_rbl_checks'] = int(rbl_match.group(1))
-
- return {'success': True, 'config': config}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def update_rules(cls) -> Dict:
- """Update SpamAssassin rules."""
- try:
- result = run_privileged(['sa-update'], timeout=120)
- # sa-update returns 0 for updates, 1 for no updates, 2+ for errors
- if result.returncode <= 1:
- ServiceControl.restart('spamassassin', timeout=30)
- return {
- 'success': True,
- 'message': 'Rules updated' if result.returncode == 0 else 'Rules already up to date',
- 'updated': result.returncode == 0,
- }
- return {'success': False, 'error': result.stderr or 'Update failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def train_spam(cls, message_path: str) -> Dict:
- """Train SpamAssassin with a spam message."""
- try:
- result = run_privileged(['sa-learn', '--spam', message_path])
- if result.returncode == 0:
- return {'success': True, 'message': 'Message learned as spam'}
- return {'success': False, 'error': result.stderr or 'Training failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def train_ham(cls, message_path: str) -> Dict:
- """Train SpamAssassin with a ham (non-spam) message."""
- try:
- result = run_privileged(['sa-learn', '--ham', message_path])
- if result.returncode == 0:
- return {'success': True, 'message': 'Message learned as ham'}
- return {'success': False, 'error': result.stderr or 'Training failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_stats(cls) -> Dict:
- """Get SpamAssassin Bayes statistics."""
- try:
- result = run_privileged(['sa-learn', '--dump', 'magic'])
- output = result.stdout or ''
- stats = {
- 'nspam': 0,
- 'nham': 0,
- 'ntokens': 0,
- }
- for line in output.splitlines():
- parts = line.split()
- if len(parts) >= 4:
- if parts[2] == 'nspam':
- stats['nspam'] = int(parts[1])
- elif parts[2] == 'nham':
- stats['nham'] = int(parts[1])
- elif parts[2] == 'ntokens':
- stats['ntokens'] = int(parts[1])
-
- return {'success': True, 'stats': stats}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload SpamAssassin."""
- try:
- result = ServiceControl.restart('spamassassin', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'SpamAssassin restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/backend/app/services/extension_migration.py b/backend/app/services/extension_migration.py
index 81cf3455..544d90b3 100644
--- a/backend/app/services/extension_migration.py
+++ b/backend/app/services/extension_migration.py
@@ -107,7 +107,6 @@ def _email_was_configured():
# actually used the feature (D3/#34). Fresh installs and panels that never used
# the feature just see it in the Marketplace.
GATED_BUILTIN_SLUGS = {
- 'serverkit-email': _email_was_configured,
'serverkit-git': _gitea_was_used,
}
@@ -140,6 +139,9 @@ def _scanners_dir_populated():
# unmarked so the next boot retries; panels without the host tool just see
# the extension in the Marketplace.
REGISTRY_GATED_SLUGS = {
+ # serverkit-email left the tree (plan 52 Phase 2 cutover): its gated
+ # auto-install rides the registry now, same predicate as before.
+ 'serverkit-email': _email_was_configured,
'serverkit-fail2ban': _has_command('fail2ban-client'),
'serverkit-clamav': _has_command('clamscan'),
'serverkit-lynis': _has_command('lynis'),
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 5ab46065..a1f47254 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -379,6 +379,27 @@ def scoping_rbac(app):
# ServerKit clone's suite must pass without the extension source.
+def sibling_extension_dir(slug, env_var=None):
+ """A standalone extension repo's checkout dir, or None (plan 52 cutover).
+
+ Resolution mirrors _wp_ext_tests_dir: an explicit env override first
+ (SERVERKIT_<SLUG>_DIR, dashes/prefix dropped), then the default sibling
+ checkout next to the ServerKit workspace. Suites that exercise an
+ extracted extension mount it from here and skip cleanly when absent.
+ """
+ env_name = env_var or 'SERVERKIT_{}_DIR'.format(
+ slug.replace('serverkit-', '').replace('-', '_').upper())
+ env = os.environ.get(env_name)
+ candidates = [env] if env else []
+ candidates.append(os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__))))), slug))
+ for cand in candidates:
+ if cand and os.path.isfile(os.path.join(cand, 'plugin.json')):
+ return cand
+ return None
+
+
def _wp_ext_tests_dir():
"""The standalone serverkit-wordpress repo's tests/ dir, or None."""
env = os.environ.get('SERVERKIT_WORDPRESS_DIR')
diff --git a/backend/tests/test_email_dovecot_probe.py b/backend/tests/test_email_dovecot_probe.py
index d2725404..afa44df6 100644
--- a/backend/tests/test_email_dovecot_probe.py
+++ b/backend/tests/test_email_dovecot_probe.py
@@ -22,8 +22,16 @@ from pathlib import Path
import pytest
-_DOVECOT = (Path(__file__).resolve().parent.parent
- / 'app' / 'plugins' / 'serverkit-email' / 'dovecot_service.py')
+from tests.conftest import sibling_extension_dir
+
+_EMAIL_DIR = sibling_extension_dir('serverkit-email')
+_DOVECOT = (Path(_EMAIL_DIR) / 'backend' / 'dovecot_service.py'
+ if _EMAIL_DIR else None)
+
+pytestmark = pytest.mark.skipif(
+ _DOVECOT is None or not _DOVECOT.is_file(),
+ reason='serverkit-email checkout not available '
+ '(set SERVERKIT_EMAIL_DIR to its checkout)')
def _load():
diff --git a/backend/tests/test_email_extraction.py b/backend/tests/test_email_extraction.py
index ce9ae38a..bec3ab25 100644
--- a/backend/tests/test_email_extraction.py
+++ b/backend/tests/test_email_extraction.py
@@ -1,7 +1,8 @@
-"""Prove the Email extraction (Phase 4, #35).
+"""Prove the Email extraction (Phase 4, #35; standalone repo since plan 52 Ph2).
-A core panel no longer carries the mail-server API; installing the serverkit-email
-builtin registers `/api/v1/email` and its routes respond (which also exercises the
+A core panel no longer carries the mail-server API; installing serverkit-email
+(now a standalone repo — mounted from the sibling checkout, skip when absent)
+registers `/api/v1/email` and its routes respond (which also exercises the
extension's relative-import rewiring). Uninstall removes it again.
"""
import sys
@@ -10,6 +11,7 @@ import pytest
import app as app_pkg
from app.models.plugin import InstalledPlugin
+from tests.conftest import sibling_extension_dir
from app.services import plugin_service
# Installs plugins, and plugin_service hot-loads their blueprints onto the
@@ -62,12 +64,27 @@ def install_dirs(tmp_path, monkeypatch):
del sys.modules[name]
-def test_install_email_extension_registers_routes(app, client, auth_headers, install_dirs):
- # The real builtin folder is discovered from the repo's builtin-extensions/.
+def _install_email_from_sibling(monkeypatch):
+ src = sibling_extension_dir(SLUG)
+ if not src:
+ pytest.skip('serverkit-email checkout not available '
+ '(set SERVERKIT_EMAIL_DIR to its checkout)')
+ # The sibling repo pins min_panel_version to the first SDK-1.4.0 release;
+ # the working tree may still carry the previous version string.
+ from app.utils import version as version_mod
+ monkeypatch.setattr(version_mod, 'get_panel_version', lambda: '1.9.11')
+ monkeypatch.setattr(plugin_service, 'get_panel_version',
+ lambda: '1.9.11', raising=False)
+ return plugin_service.install_from_path(src, force=True)
+
+
+def test_email_is_no_longer_a_builtin(app):
available = {e['slug'] for e in plugin_service.list_builtin_extensions()}
- assert SLUG in available, 'serverkit-email builtin folder should exist'
+ assert SLUG not in available, 'serverkit-email left the tree (plan 52 Ph2)'
+
- plugin = plugin_service.install_builtin_extension('serverkit-email')
+def test_install_email_extension_registers_routes(app, client, auth_headers, install_dirs, monkeypatch):
+ plugin = _install_email_from_sibling(monkeypatch)
assert plugin.status == InstalledPlugin.STATUS_ACTIVE
assert plugin.has_backend is True
assert plugin.url_prefix == '/api/v1/email'
@@ -79,7 +96,7 @@ def test_install_email_extension_registers_routes(app, client, auth_headers, ins
assert resp.status_code not in (404, 503), resp.status_code
-def test_uninstall_removes_email_plugin(app, install_dirs):
- plugin = plugin_service.install_builtin_extension('serverkit-email')
+def test_uninstall_removes_email_plugin(app, install_dirs, monkeypatch):
+ plugin = _install_email_from_sibling(monkeypatch)
assert plugin_service.uninstall_plugin(plugin.id) is True
assert InstalledPlugin.query.filter_by(slug=SLUG).first() is None
diff --git a/builtin-extensions/serverkit-email/backend/__init__.py b/builtin-extensions/serverkit-email/backend/__init__.py
deleted file mode 100644
index 51e67b6d..00000000
--- a/builtin-extensions/serverkit-email/backend/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""ServerKit Email extension backend package."""
diff --git a/builtin-extensions/serverkit-email/backend/dkim_service.py b/builtin-extensions/serverkit-email/backend/dkim_service.py
deleted file mode 100644
index e79ca0d8..00000000
--- a/builtin-extensions/serverkit-email/backend/dkim_service.py
+++ /dev/null
@@ -1,271 +0,0 @@
-"""OpenDKIM management service for DKIM signing."""
-import os
-import re
-import subprocess
-from typing import Dict
-
-from app.utils.system import (PackageManager, ServiceControl, run_checked,
- run_privileged)
-
-
-class DKIMService:
- """Service for managing OpenDKIM (DKIM email signing)."""
-
- OPENDKIM_CONF = '/etc/opendkim.conf'
- OPENDKIM_DIR = '/etc/opendkim'
- OPENDKIM_KEYS_DIR = '/etc/opendkim/keys'
- KEY_TABLE = '/etc/opendkim/KeyTable'
- SIGNING_TABLE = '/etc/opendkim/SigningTable'
- TRUSTED_HOSTS = '/etc/opendkim/TrustedHosts'
-
- OPENDKIM_CONF_CONTENT = """# OpenDKIM configuration - Managed by ServerKit
-Syslog yes
-SyslogSuccess yes
-LogWhy yes
-Canonicalization relaxed/simple
-Mode sv
-SubDomains no
-AutoRestart yes
-AutoRestartRate 10/1M
-Background yes
-DNSTimeout 5
-SignatureAlgorithm rsa-sha256
-KeyTable refile:/etc/opendkim/KeyTable
-SigningTable refile:/etc/opendkim/SigningTable
-ExternalIgnoreList /etc/opendkim/TrustedHosts
-InternalHosts /etc/opendkim/TrustedHosts
-Socket inet:8891@localhost
-PidFile /run/opendkim/opendkim.pid
-OversignHeaders From
-UserID opendkim
-UMask 007
-"""
-
- TRUSTED_HOSTS_DEFAULT = """# Trusted hosts - Managed by ServerKit
-127.0.0.1
-::1
-localhost
-"""
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get OpenDKIM installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- try:
- result = run_checked(['which', 'opendkim'], timeout=None)
- installed = result['success']
- if not installed:
- installed = PackageManager.is_installed('opendkim')
- if installed:
- running = ServiceControl.is_active('opendkim')
- enabled = ServiceControl.is_enabled('opendkim')
- result = run_checked(['opendkim', '-V'], timeout=None, merge_stderr=True)
- match = re.search(r'OpenDKIM\s+Filter\s+v(\S+)', result['output'])
- if match:
- version = match.group(1)
- except (subprocess.SubprocessError, FileNotFoundError):
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install OpenDKIM."""
- try:
- result = PackageManager.install(['opendkim', 'opendkim-tools'], timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install OpenDKIM'}
-
- # Create directories
- run_privileged(['mkdir', '-p', cls.OPENDKIM_KEYS_DIR])
- run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
-
- # Create config files
- run_privileged(['tee', cls.OPENDKIM_CONF], input=cls.OPENDKIM_CONF_CONTENT)
- run_privileged(['tee', cls.TRUSTED_HOSTS], input=cls.TRUSTED_HOSTS_DEFAULT)
- run_privileged(['touch', cls.KEY_TABLE])
- run_privileged(['touch', cls.SIGNING_TABLE])
-
- # Set permissions
- run_privileged(['chown', '-R', 'opendkim:opendkim', cls.OPENDKIM_DIR])
- run_privileged(['chmod', '700', cls.OPENDKIM_KEYS_DIR])
-
- # Create PID directory
- run_privileged(['mkdir', '-p', '/run/opendkim'])
- run_privileged(['chown', 'opendkim:opendkim', '/run/opendkim'])
-
- # Add postfix to opendkim group
- run_privileged(['usermod', '-aG', 'opendkim', 'postfix'])
-
- ServiceControl.enable('opendkim')
- ServiceControl.start('opendkim', timeout=30)
-
- return {'success': True, 'message': 'OpenDKIM installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def generate_key(cls, domain: str, selector: str = 'default') -> Dict:
- """Generate DKIM key pair for a domain."""
- try:
- key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
- run_privileged(['mkdir', '-p', key_dir])
-
- # Generate key
- result = run_privileged([
- 'opendkim-genkey',
- '-s', selector,
- '-d', domain,
- '-D', key_dir,
- '-b', '2048',
- ])
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Key generation failed'}
-
- # Set permissions
- run_privileged(['chown', '-R', 'opendkim:opendkim', key_dir])
- run_privileged(['chmod', '600', os.path.join(key_dir, f'{selector}.private')])
-
- # Read the public key TXT record
- txt_file = os.path.join(key_dir, f'{selector}.txt')
- result = run_privileged(['cat', txt_file])
- public_key_record = result.stdout.strip() if result.returncode == 0 else ''
-
- # Extract just the key value from the TXT record
- key_match = re.search(r'p=([A-Za-z0-9+/=\s]+)', public_key_record)
- public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '') if key_match else ''
-
- return {
- 'success': True,
- 'domain': domain,
- 'selector': selector,
- 'private_key_path': os.path.join(key_dir, f'{selector}.private'),
- 'public_key': public_key,
- 'dns_record': public_key_record,
- 'dns_name': f'{selector}._domainkey.{domain}',
- 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def add_domain(cls, domain: str, selector: str = 'default') -> Dict:
- """Add domain to KeyTable and SigningTable."""
- try:
- key_path = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.private')
-
- # Add to KeyTable
- key_entry = f'{selector}._domainkey.{domain} {domain}:{selector}:{key_path}\n'
- result = run_privileged(['cat', cls.KEY_TABLE])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.KEY_TABLE], input=key_entry)
-
- # Add to SigningTable
- signing_entry = f'*@{domain} {selector}._domainkey.{domain}\n'
- result = run_privileged(['cat', cls.SIGNING_TABLE])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.SIGNING_TABLE], input=signing_entry)
-
- # Add to TrustedHosts
- result = run_privileged(['cat', cls.TRUSTED_HOSTS])
- if domain not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.TRUSTED_HOSTS], input=f'*.{domain}\n')
-
- # Reload OpenDKIM
- ServiceControl.restart('opendkim', timeout=30)
-
- return {'success': True, 'message': f'Domain {domain} added to DKIM'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_domain(cls, domain: str) -> Dict:
- """Remove domain from DKIM configuration."""
- try:
- # Remove from KeyTable
- result = run_privileged(['cat', cls.KEY_TABLE])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.KEY_TABLE], input='\n'.join(lines) + '\n')
-
- # Remove from SigningTable
- result = run_privileged(['cat', cls.SIGNING_TABLE])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.SIGNING_TABLE], input='\n'.join(lines) + '\n')
-
- # Remove from TrustedHosts
- result = run_privileged(['cat', cls.TRUSTED_HOSTS])
- lines = [l for l in (result.stdout or '').splitlines() if domain not in l]
- run_privileged(['tee', cls.TRUSTED_HOSTS], input='\n'.join(lines) + '\n')
-
- # Remove key files
- key_dir = os.path.join(cls.OPENDKIM_KEYS_DIR, domain)
- run_privileged(['rm', '-rf', key_dir])
-
- ServiceControl.restart('opendkim', timeout=30)
-
- return {'success': True, 'message': f'Domain {domain} removed from DKIM'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_dns_record(cls, domain: str, selector: str = 'default') -> Dict:
- """Get the DKIM DNS TXT record content for a domain."""
- try:
- txt_file = os.path.join(cls.OPENDKIM_KEYS_DIR, domain, f'{selector}.txt')
- result = run_privileged(['cat', txt_file])
- if result.returncode != 0:
- return {'success': False, 'error': 'DKIM key not found'}
-
- record = result.stdout.strip()
- key_match = re.search(r'p=([A-Za-z0-9+/=\s"]+)', record)
- public_key = ''
- if key_match:
- public_key = key_match.group(1).replace(' ', '').replace('\n', '').replace('\t', '').replace('"', '')
-
- return {
- 'success': True,
- 'dns_name': f'{selector}._domainkey.{domain}',
- 'dns_value': f'v=DKIM1; k=rsa; p={public_key}',
- 'raw_record': record,
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def verify_key(cls, domain: str, selector: str = 'default') -> Dict:
- """Verify DKIM key configuration."""
- try:
- result = run_privileged([
- 'opendkim-testkey',
- '-d', domain,
- '-s', selector,
- '-vvv',
- ])
- success = result.returncode == 0
- output = (result.stdout or '') + (result.stderr or '')
- return {
- 'success': success,
- 'verified': success and 'key OK' in output,
- 'output': output,
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload OpenDKIM."""
- try:
- result = ServiceControl.restart('opendkim', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'OpenDKIM restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/builtin-extensions/serverkit-email/backend/dovecot_service.py b/builtin-extensions/serverkit-email/backend/dovecot_service.py
deleted file mode 100644
index b108a123..00000000
--- a/builtin-extensions/serverkit-email/backend/dovecot_service.py
+++ /dev/null
@@ -1,374 +0,0 @@
-"""Dovecot IMAP/POP3 server management service."""
-import os
-import re
-import subprocess
-from typing import Dict, Optional
-
-from app.utils.system import (PackageManager, ServiceControl, is_command_available,
- run_privileged)
-from app import paths
-
-
-class DovecotService:
- """Service for managing Dovecot (IMAP/POP3 server)."""
-
- DOVECOT_CONF_DIR = '/etc/dovecot'
- DOVECOT_CONF = '/etc/dovecot/dovecot.conf'
- DOVECOT_AUTH_CONF = '/etc/dovecot/conf.d/10-auth.conf'
- DOVECOT_MAIL_CONF = '/etc/dovecot/conf.d/10-mail.conf'
- DOVECOT_MASTER_CONF = '/etc/dovecot/conf.d/10-master.conf'
- DOVECOT_SSL_CONF = '/etc/dovecot/conf.d/10-ssl.conf'
- DOVECOT_PASSWD_FILE = '/etc/dovecot/users'
- AUTH_PASSWDFILE_CONF = '/etc/dovecot/conf.d/auth-passwdfile.conf.ext'
-
- MAIL_CONF_CONTENT = """# Dovecot mail configuration - Managed by ServerKit
-mail_location = maildir:{vmail_dir}/%d/%n/Maildir
-namespace inbox {{
- inbox = yes
- separator = /
-}}
-mail_uid = {vmail_uid}
-mail_gid = {vmail_gid}
-mail_privileged_group = vmail
-first_valid_uid = {vmail_uid}
-last_valid_uid = {vmail_uid}
-"""
-
- AUTH_CONF_CONTENT = """# Dovecot auth configuration - Managed by ServerKit
-disable_plaintext_auth = yes
-auth_mechanisms = plain login
-!include auth-passwdfile.conf.ext
-"""
-
- AUTH_PASSWDFILE_CONTENT = """# Password file auth - Managed by ServerKit
-passdb {{
- driver = passwd-file
- args = scheme=SHA512-CRYPT /etc/dovecot/users
-}}
-userdb {{
- driver = static
- args = uid={vmail_uid} gid={vmail_gid} home={vmail_dir}/%d/%n
-}}
-"""
-
- MASTER_CONF_CONTENT = """# Dovecot master configuration - Managed by ServerKit
-service imap-login {
- inet_listener imap {
- port = 0
- }
- inet_listener imaps {
- port = 993
- ssl = yes
- }
-}
-service pop3-login {
- inet_listener pop3 {
- port = 0
- }
- inet_listener pop3s {
- port = 995
- ssl = yes
- }
-}
-service lmtp {
- unix_listener /var/spool/postfix/private/dovecot-lmtp {
- mode = 0600
- user = postfix
- group = postfix
- }
-}
-service auth {
- unix_listener /var/spool/postfix/private/auth {
- mode = 0666
- user = postfix
- group = postfix
- }
- unix_listener auth-userdb {
- mode = 0600
- user = vmail
- group = vmail
- }
- user = dovecot
-}
-service auth-worker {
- user = vmail
-}
-"""
-
- SSL_CONF_CONTENT = """# Dovecot SSL configuration - Managed by ServerKit
-ssl = required
-ssl_cert = <{tls_cert}
-ssl_key = <{tls_key}
-ssl_min_protocol = TLSv1.2
-ssl_prefer_server_ciphers = yes
-"""
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get Dovecot installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- # `which` searches $PATH only, and dovecot lives in /usr/sbin — absent
- # from the panel unit's PATH — so it reported a false negative on a host
- # where dovecot was installed. is_command_available() also searches the
- # sbin dirs.
- try:
- installed = is_command_available('dovecot')
- if not installed:
- installed = PackageManager.is_installed('dovecot-core') or PackageManager.is_installed('dovecot')
- except Exception:
- installed = False
-
- if installed:
- try:
- running = ServiceControl.is_active('dovecot')
- enabled = ServiceControl.is_enabled('dovecot')
- except (subprocess.SubprocessError, FileNotFoundError):
- # No systemctl (container, non-systemd init), or systemd not
- # answering inside PROBE_TIMEOUT: "could not check", not "not
- # running" — and never a 500. Wider than FileNotFoundError on
- # purpose: is_enabled already swallows the missing binary, but
- # the probe timeout in both wrappers still raises
- # TimeoutExpired straight through get_status and out of
- # /api/v1/email/status. The sibling services in this extension
- # catch the same pair.
- running = None
- enabled = None
- # Its own try: failing to read the version says nothing about
- # whether dovecot is installed. Collapsing the two is how
- # FirewallService._check_ufw reported a working firewall as absent.
- try:
- result = run_privileged(['dovecot', '--version'])
- version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout or '')
- if version_match:
- version = version_match.group(1)
- except Exception:
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install Dovecot packages."""
- try:
- manager = PackageManager.detect()
- if manager == 'apt':
- packages = ['dovecot-core', 'dovecot-imapd', 'dovecot-pop3d', 'dovecot-lmtpd', 'dovecot-sieve']
- else:
- packages = ['dovecot']
-
- result = PackageManager.install(packages, timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install Dovecot'}
-
- # Create empty passwd file
- run_privileged(['touch', cls.DOVECOT_PASSWD_FILE])
- run_privileged(['chown', 'vmail:dovecot', cls.DOVECOT_PASSWD_FILE])
- run_privileged(['chmod', '640', cls.DOVECOT_PASSWD_FILE])
-
- ServiceControl.enable('dovecot')
-
- return {'success': True, 'message': 'Dovecot installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure(cls, tls_cert: str = None, tls_key: str = None) -> Dict:
- """Write Dovecot configuration files."""
- try:
- cert = tls_cert or '/etc/ssl/certs/ssl-cert-snakeoil.pem'
- key = tls_key or '/etc/ssl/private/ssl-cert-snakeoil.key'
-
- # 10-mail.conf
- mail_conf = cls.MAIL_CONF_CONTENT.format(
- vmail_dir=paths.VMAIL_DIR,
- vmail_uid=paths.VMAIL_UID,
- vmail_gid=paths.VMAIL_GID,
- )
- run_privileged(['tee', cls.DOVECOT_MAIL_CONF], input=mail_conf)
-
- # 10-auth.conf
- run_privileged(['tee', cls.DOVECOT_AUTH_CONF], input=cls.AUTH_CONF_CONTENT)
-
- # auth-passwdfile.conf.ext
- auth_passwd = cls.AUTH_PASSWDFILE_CONTENT.format(
- vmail_uid=paths.VMAIL_UID,
- vmail_gid=paths.VMAIL_GID,
- vmail_dir=paths.VMAIL_DIR,
- )
- run_privileged(['tee', cls.AUTH_PASSWDFILE_CONF], input=auth_passwd)
-
- # 10-master.conf
- run_privileged(['tee', cls.DOVECOT_MASTER_CONF], input=cls.MASTER_CONF_CONTENT)
-
- # 10-ssl.conf
- ssl_conf = cls.SSL_CONF_CONTENT.format(tls_cert=cert, tls_key=key)
- run_privileged(['tee', cls.DOVECOT_SSL_CONF], input=ssl_conf)
-
- # Restart to apply
- ServiceControl.restart('dovecot', timeout=30)
-
- return {'success': True, 'message': 'Dovecot configured successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def create_mailbox(cls, email: str, password: str, domain: str, username: str, quota_mb: int = 1024) -> Dict:
- """Create a virtual mailbox with password entry."""
- try:
- # Generate password hash using doveadm
- result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', password])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to hash password'}
-
- password_hash = result.stdout.strip()
-
- # Build passwd-file entry
- # Format: user@domain:{scheme}hash:uid:gid:home::userdb_quota_rule=*:storage=NM
- entry = f'{email}:{password_hash}:{paths.VMAIL_UID}:{paths.VMAIL_GID}:{paths.VMAIL_DIR}/{domain}/{username}::userdb_quota_rule=*:storage={quota_mb}M'
-
- # Append to passwd file
- run_privileged(['tee', '-a', cls.DOVECOT_PASSWD_FILE], input=entry + '\n')
-
- # Create Maildir
- maildir = os.path.join(paths.VMAIL_DIR, domain, username, 'Maildir')
- run_privileged(['mkdir', '-p', f'{maildir}/cur', f'{maildir}/new', f'{maildir}/tmp'])
- run_privileged(['chown', '-R', f'{paths.VMAIL_UID}:{paths.VMAIL_GID}',
- os.path.join(paths.VMAIL_DIR, domain, username)])
-
- return {'success': True, 'message': f'Mailbox {email} created'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def delete_mailbox(cls, email: str, domain: str, username: str, remove_files: bool = False) -> Dict:
- """Delete a virtual mailbox."""
- try:
- # Remove from passwd file
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
- new_lines = [l for l in lines if not l.startswith(f'{email}:')]
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- # Optionally remove Maildir
- if remove_files:
- mailbox_path = os.path.join(paths.VMAIL_DIR, domain, username)
- run_privileged(['rm', '-rf', mailbox_path])
-
- return {'success': True, 'message': f'Mailbox {email} deleted'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def change_password(cls, email: str, new_password: str) -> Dict:
- """Change a mailbox password."""
- try:
- # Generate new hash
- result = run_privileged(['doveadm', 'pw', '-s', 'SHA512-CRYPT', '-p', new_password])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to hash password'}
-
- new_hash = result.stdout.strip()
-
- # Read current file
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
-
- updated = False
- new_lines = []
- for line in lines:
- if line.startswith(f'{email}:'):
- parts = line.split(':')
- parts[1] = new_hash
- new_lines.append(':'.join(parts))
- updated = True
- else:
- new_lines.append(line)
-
- if not updated:
- return {'success': False, 'error': f'Account {email} not found'}
-
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- return {'success': True, 'message': 'Password changed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def set_quota(cls, email: str, quota_mb: int) -> Dict:
- """Update mailbox quota."""
- try:
- result = run_privileged(['cat', cls.DOVECOT_PASSWD_FILE])
- lines = (result.stdout or '').splitlines()
-
- updated = False
- new_lines = []
- for line in lines:
- if line.startswith(f'{email}:'):
- # Replace quota in the userdb_quota_rule field
- line = re.sub(r'userdb_quota_rule=\*:storage=\d+M',
- f'userdb_quota_rule=*:storage={quota_mb}M', line)
- new_lines.append(line)
- updated = True
- else:
- new_lines.append(line)
-
- if not updated:
- return {'success': False, 'error': f'Account {email} not found'}
-
- run_privileged(['tee', cls.DOVECOT_PASSWD_FILE], input='\n'.join(new_lines) + '\n')
-
- return {'success': True, 'message': f'Quota set to {quota_mb}MB'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_quota_usage(cls, email: str) -> Dict:
- """Get mailbox quota usage."""
- try:
- result = run_privileged(['doveadm', 'quota', 'get', '-u', email])
- if result.returncode != 0:
- return {'success': False, 'error': 'Failed to get quota'}
-
- # Parse output
- usage = {'storage_used': 0, 'storage_limit': 0, 'message_count': 0}
- for line in result.stdout.splitlines():
- parts = line.split()
- if len(parts) >= 4 and parts[0] == 'STORAGE':
- usage['storage_used'] = int(parts[1]) // 1024 # KB to MB
- usage['storage_limit'] = int(parts[2]) // 1024 if parts[2] != '-' else 0
- elif len(parts) >= 4 and parts[0] == 'MESSAGE':
- usage['message_count'] = int(parts[1])
-
- return {'success': True, **usage}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload Dovecot configuration."""
- try:
- result = ServiceControl.reload('dovecot', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'Dovecot reloaded'}
- return {'success': False, 'error': result.stderr or 'Reload failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def restart(cls) -> Dict:
- """Restart Dovecot."""
- try:
- result = ServiceControl.restart('dovecot', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'Dovecot restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/builtin-extensions/serverkit-email/backend/email.py b/builtin-extensions/serverkit-email/backend/email.py
deleted file mode 100644
index 45afdf28..00000000
--- a/builtin-extensions/serverkit-email/backend/email.py
+++ /dev/null
@@ -1,426 +0,0 @@
-"""Email Server API endpoints for managing mail services, domains, accounts, and DNS.
-
-Lives in the serverkit-email extension (app.plugins.serverkit-email.email after
-install). Intra-extension modules are imported relatively; core services
-(postfix relay, DNS, relay-config, RBAC) are imported absolutely — the mail
-server extends the core, never the other way around.
-"""
-from flask import Blueprint, request, jsonify
-
-from app.middleware.rbac import admin_required, viewer_required
-from app.services.dns_provider_service import DNSProviderService
-from app.services.postfix_service import PostfixService
-from app.services.email_relay_service import EmailRelayService
-from .email_service import EmailService
-from .spamassassin_service import SpamAssassinService
-from .roundcube_service import RoundcubeService
-
-email_bp = Blueprint('email', __name__)
-
-
-# ── Status & Installation ──
-
-@email_bp.route('/status', methods=['GET'])
-@viewer_required
-def get_status():
- """Get aggregate email server status."""
- roundcube = RoundcubeService.get_status()
- status = EmailService.get_status()
- status['roundcube'] = roundcube
- return jsonify(status), 200
-
-
-@email_bp.route('/install', methods=['POST'])
-@admin_required
-def install():
- """Install and configure all email components."""
- data = request.get_json() or {}
- hostname = data.get('hostname')
- result = EmailService.install_all(hostname)
- return jsonify(result), 200 if result.get('success') else 500
-
-
-@email_bp.route('/service/<component>/<action>', methods=['POST'])
-@admin_required
-def control_service(component, action):
- """Start/stop/restart an email component."""
- result = EmailService.control_service(component, action)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Domains ──
-
-@email_bp.route('/domains', methods=['GET'])
-@viewer_required
-def list_domains():
- """List all email domains."""
- domains = EmailService.get_domains()
- return jsonify({'domains': domains}), 200
-
-
-@email_bp.route('/domains', methods=['POST'])
-@admin_required
-def add_domain():
- """Add an email domain."""
- data = request.get_json()
- if not data or not data.get('name'):
- return jsonify({'success': False, 'error': 'Domain name is required'}), 400
- result = EmailService.add_domain(
- data['name'],
- dns_provider_id=data.get('dns_provider_id'),
- dns_zone_id=data.get('dns_zone_id'),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/domains/<int:domain_id>', methods=['GET'])
-@viewer_required
-def get_domain(domain_id):
- """Get domain details."""
- result = EmailService.get_domain(domain_id)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 404
-
-
-@email_bp.route('/domains/<int:domain_id>', methods=['DELETE'])
-@admin_required
-def remove_domain(domain_id):
- """Remove an email domain."""
- result = EmailService.remove_domain(domain_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/domains/<int:domain_id>/verify-dns', methods=['POST'])
-@viewer_required
-def verify_dns(domain_id):
- """Verify DNS records for a domain."""
- result = EmailService.verify_dns(domain_id)
- return jsonify(result), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/deploy-dns', methods=['POST'])
-@admin_required
-def deploy_dns(domain_id):
- """Deploy DNS records via provider API."""
- from app.models.email import EmailDomain
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return jsonify({'success': False, 'error': 'Domain not found'}), 404
- if not domain.dns_provider_id or not domain.dns_zone_id:
- return jsonify({'success': False, 'error': 'No DNS provider configured for this domain'}), 400
- result = DNSProviderService.deploy_email_records(
- domain.dns_provider_id,
- domain.dns_zone_id,
- domain.name,
- domain.dkim_selector or 'default',
- domain.dkim_public_key or '',
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Accounts ──
-
-@email_bp.route('/domains/<int:domain_id>/accounts', methods=['GET'])
-@viewer_required
-def list_accounts(domain_id):
- """List email accounts for a domain."""
- accounts = EmailService.get_accounts(domain_id)
- return jsonify({'accounts': accounts}), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/accounts', methods=['POST'])
-@admin_required
-def create_account(domain_id):
- """Create an email account."""
- data = request.get_json()
- if not data:
- return jsonify({'success': False, 'error': 'Request body required'}), 400
- username = data.get('username')
- password = data.get('password')
- if not username or not password:
- return jsonify({'success': False, 'error': 'Username and password are required'}), 400
- result = EmailService.add_account(
- domain_id,
- username,
- password,
- quota_mb=data.get('quota_mb', 1024),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['GET'])
-@viewer_required
-def get_account(account_id):
- """Get account details."""
- from app.models.email import EmailAccount
- account = EmailAccount.query.get(account_id)
- if not account:
- return jsonify({'success': False, 'error': 'Account not found'}), 404
- return jsonify({'success': True, 'account': account.to_dict()}), 200
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['PUT'])
-@admin_required
-def update_account(account_id):
- """Update account settings."""
- data = request.get_json() or {}
- result = EmailService.update_account(
- account_id,
- quota_mb=data.get('quota_mb'),
- is_active=data.get('is_active'),
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
-@admin_required
-def delete_account(account_id):
- """Delete an email account."""
- result = EmailService.delete_account(account_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/accounts/<int:account_id>/password', methods=['POST'])
-@admin_required
-def change_password(account_id):
- """Change account password."""
- data = request.get_json()
- if not data or not data.get('password'):
- return jsonify({'success': False, 'error': 'New password is required'}), 400
- result = EmailService.change_password(account_id, data['password'])
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Aliases ──
-
-@email_bp.route('/domains/<int:domain_id>/aliases', methods=['GET'])
-@viewer_required
-def list_aliases(domain_id):
- """List email aliases for a domain."""
- aliases = EmailService.get_aliases(domain_id)
- return jsonify({'aliases': aliases}), 200
-
-
-@email_bp.route('/domains/<int:domain_id>/aliases', methods=['POST'])
-@admin_required
-def create_alias(domain_id):
- """Create an email alias."""
- data = request.get_json()
- if not data or not data.get('source') or not data.get('destination'):
- return jsonify({'success': False, 'error': 'Source and destination are required'}), 400
- result = EmailService.add_alias(domain_id, data['source'], data['destination'])
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/aliases/<int:alias_id>', methods=['DELETE'])
-@admin_required
-def delete_alias(alias_id):
- """Delete an email alias."""
- result = EmailService.remove_alias(alias_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Forwarding Rules ──
-
-@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['GET'])
-@viewer_required
-def list_forwarding(account_id):
- """List forwarding rules for an account."""
- rules = EmailService.get_forwarding(account_id)
- return jsonify({'rules': rules}), 200
-
-
-@email_bp.route('/accounts/<int:account_id>/forwarding', methods=['POST'])
-@admin_required
-def create_forwarding(account_id):
- """Create a forwarding rule."""
- data = request.get_json()
- if not data or not data.get('destination'):
- return jsonify({'success': False, 'error': 'Destination is required'}), 400
- result = EmailService.add_forwarding(
- account_id,
- data['destination'],
- keep_copy=data.get('keep_copy', True),
- )
- return jsonify(result), 201 if result.get('success') else 400
-
-
-@email_bp.route('/forwarding/<int:rule_id>', methods=['PUT'])
-@admin_required
-def update_forwarding(rule_id):
- """Update a forwarding rule."""
- data = request.get_json() or {}
- result = EmailService.update_forwarding(
- rule_id,
- destination=data.get('destination'),
- keep_copy=data.get('keep_copy'),
- is_active=data.get('is_active'),
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/forwarding/<int:rule_id>', methods=['DELETE'])
-@admin_required
-def delete_forwarding(rule_id):
- """Delete a forwarding rule."""
- result = EmailService.remove_forwarding(rule_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── DNS Providers ──
-# Moved to core (app/api/dns_providers.py, same /api/v1/email/dns-providers
-# paths): the Connections page and wildcard TLS need them without this
-# extension installed.
-
-
-# ── Outbound SMTP Relay (smarthost) ──
-
-@email_bp.route('/relay', methods=['GET'])
-@viewer_required
-def get_relay():
- """Get the outbound SMTP relay configuration (password masked)."""
- return jsonify(EmailRelayService.get_config()), 200
-
-
-@email_bp.route('/relay', methods=['PUT'])
-@admin_required
-def save_relay():
- """Save the relay configuration and apply it to Postfix (if installed)."""
- data = request.get_json() or {}
- if not data.get('host'):
- return jsonify({'success': False, 'error': 'A relay host is required'}), 400
- result = EmailRelayService.save_config(data)
- return jsonify(result), 200
-
-
-@email_bp.route('/relay/test', methods=['POST'])
-@admin_required
-def test_relay():
- """Open a real SMTP connection to validate the relay credentials."""
- data = request.get_json() or {}
- result = EmailRelayService.test(data)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/relay', methods=['DELETE'])
-@admin_required
-def disable_relay():
- """Disable the outbound relay (revert Postfix to direct delivery)."""
- result = EmailRelayService.disable()
- return jsonify(result), 200
-
-
-# ── SpamAssassin Config ──
-
-@email_bp.route('/spam/config', methods=['GET'])
-@viewer_required
-def get_spam_config():
- """Get SpamAssassin configuration."""
- result = SpamAssassinService.get_config()
- return jsonify(result), 200
-
-
-@email_bp.route('/spam/config', methods=['PUT'])
-@admin_required
-def update_spam_config():
- """Update SpamAssassin configuration."""
- data = request.get_json()
- if not data:
- return jsonify({'success': False, 'error': 'Request body required'}), 400
- result = SpamAssassinService.configure(data)
- if result.get('success'):
- SpamAssassinService.reload()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/spam/update-rules', methods=['POST'])
-@admin_required
-def update_spam_rules():
- """Update SpamAssassin rules."""
- result = SpamAssassinService.update_rules()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Roundcube Webmail ──
-
-@email_bp.route('/webmail/status', methods=['GET'])
-@viewer_required
-def webmail_status():
- """Get Roundcube webmail status."""
- result = RoundcubeService.get_status()
- return jsonify(result), 200
-
-
-@email_bp.route('/webmail/install', methods=['POST'])
-@admin_required
-def webmail_install():
- """Install Roundcube webmail."""
- data = request.get_json() or {}
- result = RoundcubeService.install(
- imap_host=data.get('imap_host', 'host.docker.internal'),
- smtp_host=data.get('smtp_host', 'host.docker.internal'),
- domain=(data.get('domain') or '').strip() or None,
- )
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/webmail/service/<action>', methods=['POST'])
-@admin_required
-def webmail_control(action):
- """Start/stop/restart Roundcube."""
- actions = {
- 'start': RoundcubeService.start,
- 'stop': RoundcubeService.stop,
- 'restart': RoundcubeService.restart,
- }
- if action not in actions:
- return jsonify({'success': False, 'error': 'Invalid action'}), 400
- result = actions[action]()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/webmail/configure-proxy', methods=['POST'])
-@admin_required
-def webmail_configure_proxy():
- """Configure Nginx reverse proxy for Roundcube."""
- data = request.get_json()
- if not data or not data.get('domain'):
- return jsonify({'success': False, 'error': 'Domain is required'}), 400
- result = RoundcubeService.configure_nginx_proxy(data['domain'])
- return jsonify(result), 200 if result.get('success') else 400
-
-
-# ── Mail Queue & Logs ──
-
-@email_bp.route('/queue', methods=['GET'])
-@viewer_required
-def get_queue():
- """Get Postfix mail queue."""
- result = PostfixService.get_queue()
- return jsonify(result), 200
-
-
-@email_bp.route('/queue/flush', methods=['POST'])
-@admin_required
-def flush_queue():
- """Flush the mail queue."""
- result = PostfixService.flush_queue()
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/queue/<queue_id>', methods=['DELETE'])
-@admin_required
-def delete_queue_item(queue_id):
- """Delete a message from the queue."""
- result = PostfixService.delete_from_queue(queue_id)
- return jsonify(result), 200 if result.get('success') else 400
-
-
-@email_bp.route('/logs', methods=['GET'])
-@viewer_required
-def get_logs():
- """Get mail logs."""
- lines = request.args.get('lines', 100, type=int)
- result = PostfixService.get_logs(lines)
- return jsonify(result), 200
diff --git a/builtin-extensions/serverkit-email/backend/email_service.py b/builtin-extensions/serverkit-email/backend/email_service.py
deleted file mode 100644
index fdadf70a..00000000
--- a/builtin-extensions/serverkit-email/backend/email_service.py
+++ /dev/null
@@ -1,550 +0,0 @@
-"""Email service orchestrator — delegates to sub-services for each component."""
-import logging
-import subprocess
-from typing import Dict, List, Optional
-
-from app import db
-from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule
-from app.services.postfix_service import PostfixService
-from app.utils.system import PackageManager, ServiceControl, run_checked
-from .dovecot_service import DovecotService
-from .dkim_service import DKIMService
-from .spamassassin_service import SpamAssassinService
-from .roundcube_service import RoundcubeService
-
-logger = logging.getLogger(__name__)
-
-
-class EmailService:
- """High-level email service that coordinates Postfix, Dovecot, DKIM, and SpamAssassin."""
-
- COMPONENTS = {
- 'postfix': PostfixService,
- 'dovecot': DovecotService,
- 'opendkim': DKIMService,
- 'spamassassin': SpamAssassinService,
- }
-
- # ── Status ──
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get aggregate email server status."""
- postfix = PostfixService.get_status()
- dovecot = DovecotService.get_status()
- dkim = DKIMService.get_status()
- spam = SpamAssassinService.get_status()
-
- all_installed = postfix['installed'] and dovecot['installed']
- # bool(): a component whose probe could not run reports running=None
- # (see DovecotService.get_status), and `True and None` is None — the
- # top-level flag is documented as a boolean, so keep it one. The
- # honest per-component tri-state is still in the nested dicts.
- all_running = bool(postfix.get('running', False) and dovecot.get('running', False))
-
- return {
- 'installed': all_installed,
- 'running': all_running,
- 'postfix': postfix,
- 'dovecot': dovecot,
- 'dkim': dkim,
- 'spamassassin': spam,
- }
-
- # ── Installation ──
-
- @classmethod
- def install_all(cls, hostname: str = None) -> Dict:
- """Install and configure all email components."""
- results = {}
-
- # 1. Install Postfix
- results['postfix'] = PostfixService.install(hostname=hostname)
- if not results['postfix'].get('success'):
- return {'success': False, 'error': 'Postfix installation failed', 'results': results}
-
- # 2. Configure Postfix
- postfix_config = PostfixService.configure(hostname=hostname)
- if not postfix_config.get('success'):
- logger.warning(f"Postfix configuration warning: {postfix_config.get('error')}")
-
- # 3. Install Dovecot
- results['dovecot'] = DovecotService.install()
- if not results['dovecot'].get('success'):
- return {'success': False, 'error': 'Dovecot installation failed', 'results': results}
-
- # 4. Configure Dovecot
- dovecot_config = DovecotService.configure()
- if not dovecot_config.get('success'):
- logger.warning(f"Dovecot configuration warning: {dovecot_config.get('error')}")
-
- # 5. Install OpenDKIM
- results['dkim'] = DKIMService.install()
- if not results['dkim'].get('success'):
- logger.warning(f"DKIM installation warning: {results['dkim'].get('error')}")
-
- # 6. Install SpamAssassin
- results['spamassassin'] = SpamAssassinService.install()
- if not results['spamassassin'].get('success'):
- logger.warning(f"SpamAssassin installation warning: {results['spamassassin'].get('error')}")
-
- all_ok = all(r.get('success') for r in results.values())
- return {
- 'success': all_ok,
- 'message': 'All email components installed' if all_ok else 'Some components had issues',
- 'results': results,
- }
-
- # ── Service Control ──
-
- @classmethod
- def control_service(cls, component: str, action: str) -> Dict:
- """Start/stop/restart an email component."""
- if component not in cls.COMPONENTS and component != 'roundcube':
- return {'success': False, 'error': f'Unknown component: {component}'}
-
- if action not in ('start', 'stop', 'restart', 'reload'):
- return {'success': False, 'error': f'Invalid action: {action}'}
-
- try:
- if component == 'roundcube':
- actions = {
- 'start': RoundcubeService.start,
- 'stop': RoundcubeService.stop,
- 'restart': RoundcubeService.restart,
- 'reload': RoundcubeService.restart,
- }
- return actions[action]()
-
- service_name = component
- if action == 'start':
- result = ServiceControl.start(service_name, timeout=30)
- elif action == 'stop':
- result = ServiceControl.stop(service_name, timeout=30)
- elif action == 'restart':
- result = ServiceControl.restart(service_name, timeout=30)
- elif action == 'reload':
- result = ServiceControl.reload(service_name, timeout=30)
-
- if result.returncode == 0:
- return {'success': True, 'message': f'{component} {action} successful'}
- return {'success': False, 'error': result.stderr or f'{action} failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- # ── Domains ──
-
- @classmethod
- def get_domains(cls) -> List[Dict]:
- """List all email domains."""
- domains = EmailDomain.query.all()
- return [d.to_dict() for d in domains]
-
- @classmethod
- def add_domain(cls, name: str, dns_provider_id: int = None, dns_zone_id: str = None) -> Dict:
- """Add an email domain."""
- try:
- existing = EmailDomain.query.filter_by(name=name).first()
- if existing:
- return {'success': False, 'error': f'Domain {name} already exists'}
-
- domain = EmailDomain(
- name=name,
- dns_provider_id=dns_provider_id,
- dns_zone_id=dns_zone_id,
- )
- db.session.add(domain)
- db.session.commit()
-
- # Add to Postfix virtual domains
- PostfixService.add_domain(name)
-
- # Generate DKIM key
- dkim_result = DKIMService.generate_key(name)
- if dkim_result.get('success'):
- domain.dkim_selector = 'default'
- domain.dkim_private_key_path = dkim_result.get('private_key_path')
- domain.dkim_public_key = dkim_result.get('public_key')
- domain.spf_record = f'v=spf1 mx a ~all'
- domain.dmarc_record = f'v=DMARC1; p=quarantine; rua=mailto:dmarc@{name}; pct=100'
- DKIMService.add_domain(name)
- db.session.commit()
-
- return {'success': True, 'domain': domain.to_dict(), 'message': f'Domain {name} added'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_domain(cls, domain_id: int) -> Dict:
- """Get domain details."""
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
- return {'success': True, 'domain': domain.to_dict()}
-
- @classmethod
- def remove_domain(cls, domain_id: int) -> Dict:
- """Remove an email domain and all its accounts/aliases."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- domain_name = domain.name
-
- # Remove accounts from Dovecot/Postfix
- for account in domain.accounts:
- DovecotService.delete_mailbox(account.email, domain_name, account.username, remove_files=True)
- PostfixService.remove_mailbox(account.email)
-
- # Remove aliases from Postfix
- for alias in domain.aliases:
- PostfixService.remove_alias(alias.source)
-
- # Remove from DKIM
- DKIMService.remove_domain(domain_name)
-
- # Remove from Postfix virtual domains
- PostfixService.remove_domain(domain_name)
-
- # Delete from database
- db.session.delete(domain)
- db.session.commit()
-
- return {'success': True, 'message': f'Domain {domain_name} removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def verify_dns(cls, domain_id: int) -> Dict:
- """Verify DNS records for a domain."""
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- results = {}
- name = domain.name
-
- # Check MX record
- try:
- result = run_checked(['dig', '+short', 'MX', name], timeout=10)
- results['mx'] = {
- 'found': bool(result['output'].strip()),
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['mx'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check SPF record
- try:
- result = run_checked(['dig', '+short', 'TXT', name], timeout=10)
- spf_found = 'v=spf1' in result['output']
- results['spf'] = {
- 'found': spf_found,
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['spf'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check DKIM record
- selector = domain.dkim_selector or 'default'
- try:
- dkim_name = f'{selector}._domainkey.{name}'
- result = run_checked(['dig', '+short', 'TXT', dkim_name], timeout=10)
- dkim_found = 'v=DKIM1' in result['output']
- results['dkim'] = {
- 'found': dkim_found,
- 'value': result['output'].strip() or None,
- 'name': dkim_name,
- }
- except Exception:
- results['dkim'] = {'found': False, 'error': 'DNS lookup failed'}
-
- # Check DMARC record
- try:
- dmarc_name = f'_dmarc.{name}'
- result = run_checked(['dig', '+short', 'TXT', dmarc_name], timeout=10)
- dmarc_found = 'v=DMARC1' in result['output']
- results['dmarc'] = {
- 'found': dmarc_found,
- 'value': result['output'].strip() or None,
- }
- except Exception:
- results['dmarc'] = {'found': False, 'error': 'DNS lookup failed'}
-
- all_ok = all(r.get('found') for r in results.values())
- return {
- 'success': True,
- 'domain': name,
- 'all_verified': all_ok,
- 'records': results,
- }
-
- # ── Accounts ──
-
- @classmethod
- def get_accounts(cls, domain_id: int) -> List[Dict]:
- """List email accounts for a domain."""
- accounts = EmailAccount.query.filter_by(domain_id=domain_id).all()
- return [a.to_dict() for a in accounts]
-
- @classmethod
- def add_account(cls, domain_id: int, username: str, password: str, quota_mb: int = 1024) -> Dict:
- """Create an email account."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- email = f'{username}@{domain.name}'
-
- existing = EmailAccount.query.filter_by(email=email).first()
- if existing:
- return {'success': False, 'error': f'Account {email} already exists'}
-
- # Create mailbox in Dovecot
- dovecot_result = DovecotService.create_mailbox(email, password, domain.name, username, quota_mb)
- if not dovecot_result.get('success'):
- return dovecot_result
-
- # Add to Postfix virtual mailboxes
- PostfixService.add_mailbox(email, domain.name, username)
-
- # Get password hash for storage
- password_hash = dovecot_result.get('password_hash', 'stored_in_dovecot')
-
- account = EmailAccount(
- email=email,
- username=username,
- password_hash=password_hash,
- domain_id=domain_id,
- quota_mb=quota_mb,
- )
- db.session.add(account)
- db.session.commit()
-
- return {'success': True, 'account': 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, quota_mb: int = None, is_active: bool = None) -> Dict:
- """Update account settings."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- if quota_mb is not None:
- account.quota_mb = quota_mb
- DovecotService.set_quota(account.email, quota_mb)
-
- if is_active is not None:
- account.is_active = is_active
-
- db.session.commit()
- return {'success': True, 'account': account.to_dict(), 'message': 'Account updated'}
- 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."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- email = account.email
- domain_name = account.domain.name if account.domain else ''
- username = account.username
-
- # Remove from Dovecot
- DovecotService.delete_mailbox(email, domain_name, username, remove_files=True)
-
- # Remove from Postfix
- PostfixService.remove_mailbox(email)
-
- db.session.delete(account)
- db.session.commit()
-
- return {'success': True, 'message': f'Account {email} deleted'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def change_password(cls, account_id: int, new_password: str) -> Dict:
- """Change an account password."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- result = DovecotService.change_password(account.email, new_password)
- if not result.get('success'):
- return result
-
- account.password_hash = 'updated_in_dovecot'
- db.session.commit()
-
- return {'success': True, 'message': 'Password changed successfully'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- # ── Aliases ──
-
- @classmethod
- def get_aliases(cls, domain_id: int) -> List[Dict]:
- """List email aliases for a domain."""
- aliases = EmailAlias.query.filter_by(domain_id=domain_id).all()
- return [a.to_dict() for a in aliases]
-
- @classmethod
- def add_alias(cls, domain_id: int, source: str, destination: str) -> Dict:
- """Create an email alias."""
- try:
- domain = EmailDomain.query.get(domain_id)
- if not domain:
- return {'success': False, 'error': 'Domain not found'}
-
- # Add @ domain if not already qualified
- if '@' not in source:
- source = f'{source}@{domain.name}'
-
- alias = EmailAlias(
- source=source,
- destination=destination,
- domain_id=domain_id,
- )
- db.session.add(alias)
- db.session.commit()
-
- # Add to Postfix virtual aliases
- PostfixService.add_alias(source, destination)
-
- return {'success': True, 'alias': alias.to_dict(), 'message': f'Alias {source} created'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_alias(cls, alias_id: int) -> Dict:
- """Delete an email alias."""
- try:
- alias = EmailAlias.query.get(alias_id)
- if not alias:
- return {'success': False, 'error': 'Alias not found'}
-
- PostfixService.remove_alias(alias.source)
-
- db.session.delete(alias)
- db.session.commit()
-
- return {'success': True, 'message': 'Alias removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- # ── Forwarding Rules ──
-
- @classmethod
- def get_forwarding(cls, account_id: int) -> List[Dict]:
- """List forwarding rules for an account."""
- rules = EmailForwardingRule.query.filter_by(account_id=account_id).all()
- return [r.to_dict() for r in rules]
-
- @classmethod
- def add_forwarding(cls, account_id: int, destination: str, keep_copy: bool = True) -> Dict:
- """Create a forwarding rule."""
- try:
- account = EmailAccount.query.get(account_id)
- if not account:
- return {'success': False, 'error': 'Account not found'}
-
- rule = EmailForwardingRule(
- account_id=account_id,
- destination=destination,
- keep_copy=keep_copy,
- )
- db.session.add(rule)
- db.session.commit()
-
- # Update Postfix aliases for forwarding
- cls._sync_forwarding_aliases(account)
-
- return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule created'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def update_forwarding(cls, rule_id: int, destination: str = None,
- keep_copy: bool = None, is_active: bool = None) -> Dict:
- """Update a forwarding rule."""
- try:
- rule = EmailForwardingRule.query.get(rule_id)
- if not rule:
- return {'success': False, 'error': 'Forwarding rule not found'}
-
- if destination is not None:
- rule.destination = destination
- if keep_copy is not None:
- rule.keep_copy = keep_copy
- if is_active is not None:
- rule.is_active = is_active
-
- db.session.commit()
-
- # Re-sync Postfix aliases
- cls._sync_forwarding_aliases(rule.account)
-
- return {'success': True, 'rule': rule.to_dict(), 'message': 'Forwarding rule updated'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def remove_forwarding(cls, rule_id: int) -> Dict:
- """Delete a forwarding rule."""
- try:
- rule = EmailForwardingRule.query.get(rule_id)
- if not rule:
- return {'success': False, 'error': 'Forwarding rule not found'}
-
- account = rule.account
- db.session.delete(rule)
- db.session.commit()
-
- # Re-sync Postfix aliases
- cls._sync_forwarding_aliases(account)
-
- return {'success': True, 'message': 'Forwarding rule removed'}
- except Exception as e:
- db.session.rollback()
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def _sync_forwarding_aliases(cls, account: EmailAccount):
- """Sync forwarding rules to Postfix virtual aliases for an account."""
- active_rules = [r for r in account.forwarding_rules if r.is_active]
-
- if not active_rules:
- # Remove any forwarding alias
- PostfixService.remove_alias(account.email)
- return
-
- # Build destination list
- destinations = [r.destination for r in active_rules]
- # If any rule wants to keep a copy, include the original mailbox
- if any(r.keep_copy for r in active_rules):
- destinations.append(account.email)
-
- # Remove old alias and add new one
- PostfixService.remove_alias(account.email)
- PostfixService.add_alias(account.email, ', '.join(destinations))
diff --git a/builtin-extensions/serverkit-email/backend/roundcube_service.py b/builtin-extensions/serverkit-email/backend/roundcube_service.py
deleted file mode 100644
index fb0f2d6f..00000000
--- a/builtin-extensions/serverkit-email/backend/roundcube_service.py
+++ /dev/null
@@ -1,198 +0,0 @@
-"""Roundcube webmail management service (Docker-based)."""
-import subprocess
-from typing import Dict
-
-from app.utils.system import run_checked, run_privileged, is_command_available
-
-
-class RoundcubeService:
- """Service for managing Roundcube webmail via Docker."""
-
- CONTAINER_NAME = 'serverkit-roundcube'
- VOLUME_NAME = 'roundcube_data'
- IMAGE = 'roundcube/roundcubemail:latest'
- HOST_PORT = 9000
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get Roundcube container status."""
- if not is_command_available('docker'):
- return {'installed': False, 'running': False, 'error': 'Docker not available'}
-
- try:
- result = run_checked(
- ['docker', 'inspect', '--format', '{{.State.Status}}', cls.CONTAINER_NAME],
- timeout=None)
- if not result['success']:
- return {'installed': False, 'running': False}
-
- status = result['output'].strip()
- return {
- 'installed': True,
- 'running': status == 'running',
- 'status': status,
- 'port': cls.HOST_PORT,
- }
- except Exception as e:
- return {'installed': False, 'running': False, 'error': str(e)}
-
- @classmethod
- def install(cls, imap_host: str = 'host.docker.internal',
- smtp_host: str = 'host.docker.internal',
- domain: str = None) -> Dict:
- """Install Roundcube via Docker container."""
- if not is_command_available('docker'):
- return {'success': False, 'error': 'Docker is not installed'}
-
- try:
- # Remove existing container if any
- run_checked(['docker', 'rm', '-f', cls.CONTAINER_NAME], timeout=None)
-
- # Create volume
- run_checked(['docker', 'volume', 'create', cls.VOLUME_NAME], timeout=None)
-
- # Run container
- result = run_checked([
- 'docker', 'run', '-d',
- '--name', cls.CONTAINER_NAME,
- '--restart', 'unless-stopped',
- '--add-host', 'host.docker.internal:host-gateway',
- '-p', f'{cls.HOST_PORT}:80',
- '-e', f'ROUNDCUBEMAIL_DEFAULT_HOST=ssl://{imap_host}',
- '-e', f'ROUNDCUBEMAIL_SMTP_SERVER=tls://{smtp_host}',
- '-e', 'ROUNDCUBEMAIL_DEFAULT_PORT=993',
- '-e', 'ROUNDCUBEMAIL_SMTP_PORT=587',
- '-e', 'ROUNDCUBEMAIL_UPLOAD_MAX_FILESIZE=25M',
- '-e', 'ROUNDCUBEMAIL_SKIN=elastic',
- '-v', f'{cls.VOLUME_NAME}:/var/roundcube/db',
- cls.IMAGE,
- ], timeout=None)
-
- if not result['success']:
- return {'success': False,
- 'error': result['error'] or 'Failed to start container'}
-
- # Build a public URL: prefer a supplied domain, then auto-generate
- # webmail.<panel_domain>, and only fall back to localhost:port.
- from app.services.site_domain_service import SiteDomainService
- public_url = None
- warning = None
- if domain:
- public_url = f'http://{domain}'
- proxy_res = cls.configure_nginx_proxy(domain)
- if not proxy_res.get('success'):
- warning = proxy_res.get('error')
- else:
- panel_origin = SiteDomainService.panel_origin()
- panel_host = None
- if panel_origin:
- from urllib.parse import urlparse
- panel_host = urlparse(panel_origin).hostname
- if panel_host:
- webmail_domain = f'webmail.{panel_host}'
- public_url = f'http://{webmail_domain}'
- proxy_res = cls.configure_nginx_proxy(webmail_domain)
- if not proxy_res.get('success'):
- warning = proxy_res.get('error')
-
- if not public_url:
- public_url = f'http://localhost:{cls.HOST_PORT}'
-
- result = {
- 'success': True,
- 'message': 'Roundcube installed successfully',
- 'port': cls.HOST_PORT,
- 'url': public_url,
- }
- if warning:
- result['warning'] = warning
- return result
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def uninstall(cls) -> Dict:
- """Stop and remove Roundcube container."""
- try:
- run_checked(['docker', 'rm', '-f', cls.CONTAINER_NAME], timeout=None)
- return {'success': True, 'message': 'Roundcube uninstalled'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def start(cls) -> Dict:
- """Start Roundcube container."""
- try:
- result = run_checked(['docker', 'start', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube started'}
- return {'success': False, 'error': result['error'] or 'Start failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def stop(cls) -> Dict:
- """Stop Roundcube container."""
- try:
- result = run_checked(['docker', 'stop', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube stopped'}
- return {'success': False, 'error': result['error'] or 'Stop failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def restart(cls) -> Dict:
- """Restart Roundcube container."""
- try:
- result = run_checked(['docker', 'restart', cls.CONTAINER_NAME], timeout=None)
- if result['success']:
- return {'success': True, 'message': 'Roundcube restarted'}
- return {'success': False, 'error': result['error'] or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure_nginx_proxy(cls, domain: str) -> Dict:
- """Create Nginx reverse proxy config for Roundcube."""
- try:
- from app.services.nginx_service import NginxService
-
- config = f"""# Roundcube Webmail - Managed by ServerKit
-server {{
- listen 80;
- server_name {domain};
-
- location / {{
- proxy_pass http://127.0.0.1:{cls.HOST_PORT};
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- client_max_body_size 25m;
- }}
-}}
-"""
- site_name = f'roundcube-{domain.replace(".", "-")}'
- config_path = f'/etc/nginx/sites-available/{site_name}'
- enabled_path = f'/etc/nginx/sites-enabled/{site_name}'
-
- run_privileged(['tee', config_path], input=config)
- run_privileged(['ln', '-sf', config_path, enabled_path])
-
- # Test and reload
- test = run_privileged(['nginx', '-t'])
- if test.returncode != 0:
- # Rollback
- run_privileged(['rm', '-f', enabled_path])
- return {'success': False, 'error': f'Nginx config test failed: {test.stderr}'}
-
- run_privileged(['systemctl', 'reload', 'nginx'])
-
- return {
- 'success': True,
- 'message': f'Nginx proxy configured for {domain}',
- 'url': f'http://{domain}',
- }
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/builtin-extensions/serverkit-email/backend/spamassassin_service.py b/builtin-extensions/serverkit-email/backend/spamassassin_service.py
deleted file mode 100644
index 85516e42..00000000
--- a/builtin-extensions/serverkit-email/backend/spamassassin_service.py
+++ /dev/null
@@ -1,254 +0,0 @@
-"""SpamAssassin management service."""
-import os
-import re
-import subprocess
-from typing import Dict
-
-from app.utils.system import (PackageManager, ServiceControl, run_checked,
- run_privileged)
-
-
-class SpamAssassinService:
- """Service for managing SpamAssassin spam filtering."""
-
- SPAMASSASSIN_CONF = '/etc/spamassassin/local.cf'
- SPAMASSASSIN_DEFAULT = '/etc/default/spamassassin'
- SPAMASS_MILTER_DEFAULT = '/etc/default/spamass-milter'
-
- LOCAL_CF_TEMPLATE = """# SpamAssassin local configuration - Managed by ServerKit
-required_score {required_score}
-report_safe {report_safe}
-rewrite_header Subject {rewrite_subject}
-use_bayes {use_bayes}
-bayes_auto_learn {bayes_auto_learn}
-bayes_auto_learn_threshold_nonspam 0.1
-bayes_auto_learn_threshold_spam 12.0
-skip_rbl_checks {skip_rbl_checks}
-use_razor2 0
-use_pyzor 0
-
-# Network checks
-dns_available yes
-
-# Trusted networks
-trusted_networks 127.0.0.0/8
-internal_networks 127.0.0.0/8
-"""
-
- DEFAULT_CONFIG = {
- 'required_score': 5.0,
- 'report_safe': 0,
- 'rewrite_subject': '[SPAM]',
- 'use_bayes': 1,
- 'bayes_auto_learn': 1,
- 'skip_rbl_checks': 0,
- }
-
- @classmethod
- def get_status(cls) -> Dict:
- """Get SpamAssassin installation and running status."""
- installed = False
- running = False
- enabled = False
- version = None
- milter_installed = False
- milter_running = False
-
- try:
- installed = PackageManager.is_installed('spamassassin')
- if installed:
- running = ServiceControl.is_active('spamassassin')
- enabled = ServiceControl.is_enabled('spamassassin')
- result = run_checked(['spamassassin', '--version'], timeout=None)
- match = re.search(r'version\s+(\S+)', result['output'])
- if match:
- version = match.group(1)
-
- # Check milter
- milter_installed = PackageManager.is_installed('spamass-milter')
- if milter_installed:
- milter_running = ServiceControl.is_active('spamass-milter')
- except (subprocess.SubprocessError, FileNotFoundError):
- pass
-
- return {
- 'installed': installed,
- 'running': running,
- 'enabled': enabled,
- 'version': version,
- 'milter_installed': milter_installed,
- 'milter_running': milter_running,
- }
-
- @classmethod
- def install(cls) -> Dict:
- """Install SpamAssassin and spamass-milter."""
- try:
- manager = PackageManager.detect()
- if manager == 'apt':
- packages = ['spamassassin', 'spamass-milter', 'spamc']
- else:
- packages = ['spamassassin', 'spamass-milter-postfix']
-
- result = PackageManager.install(packages, timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or 'Failed to install SpamAssassin'}
-
- # Enable spamd on Debian/Ubuntu
- if manager == 'apt' and os.path.exists(cls.SPAMASSASSIN_DEFAULT):
- result = run_privileged(['cat', cls.SPAMASSASSIN_DEFAULT])
- content = result.stdout or ''
- content = re.sub(r'ENABLED=0', 'ENABLED=1', content)
- content = re.sub(r'CRON=0', 'CRON=1', content)
- run_privileged(['tee', cls.SPAMASSASSIN_DEFAULT], input=content)
-
- # Configure milter to listen on port 8893
- milter_config = 'OPTIONS="-u spamass-milter -i 127.0.0.1 -p inet:8893@localhost -- --socket=/var/run/spamassassin/spamd.sock"\n'
- if os.path.exists(cls.SPAMASS_MILTER_DEFAULT):
- run_privileged(['tee', cls.SPAMASS_MILTER_DEFAULT], input=milter_config)
-
- # Write default config
- cls.configure(cls.DEFAULT_CONFIG)
-
- # Update rules
- run_privileged(['sa-update'], timeout=120)
-
- ServiceControl.enable('spamassassin')
- ServiceControl.start('spamassassin', timeout=30)
-
- if PackageManager.is_installed('spamass-milter'):
- ServiceControl.enable('spamass-milter')
- ServiceControl.start('spamass-milter', timeout=30)
-
- return {'success': True, 'message': 'SpamAssassin installed successfully'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def configure(cls, settings: Dict = None) -> Dict:
- """Write SpamAssassin configuration."""
- try:
- config = dict(cls.DEFAULT_CONFIG)
- if settings:
- config.update(settings)
- content = cls.LOCAL_CF_TEMPLATE.format(**config)
- run_privileged(['tee', cls.SPAMASSASSIN_CONF], input=content)
- return {'success': True, 'message': 'SpamAssassin configured'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_config(cls) -> Dict:
- """Get current SpamAssassin configuration."""
- try:
- if not os.path.exists(cls.SPAMASSASSIN_CONF):
- return {'success': True, 'config': dict(cls.DEFAULT_CONFIG)}
-
- result = run_privileged(['cat', cls.SPAMASSASSIN_CONF])
- content = result.stdout or ''
-
- config = dict(cls.DEFAULT_CONFIG)
-
- # Parse values
- score_match = re.search(r'required_score\s+(\S+)', content)
- if score_match:
- config['required_score'] = float(score_match.group(1))
-
- report_match = re.search(r'report_safe\s+(\d+)', content)
- if report_match:
- config['report_safe'] = int(report_match.group(1))
-
- subject_match = re.search(r'rewrite_header Subject\s+(.+)', content)
- if subject_match:
- config['rewrite_subject'] = subject_match.group(1).strip()
-
- bayes_match = re.search(r'use_bayes\s+(\d+)', content)
- if bayes_match:
- config['use_bayes'] = int(bayes_match.group(1))
-
- auto_learn_match = re.search(r'bayes_auto_learn\s+(\d+)', content)
- if auto_learn_match:
- config['bayes_auto_learn'] = int(auto_learn_match.group(1))
-
- rbl_match = re.search(r'skip_rbl_checks\s+(\d+)', content)
- if rbl_match:
- config['skip_rbl_checks'] = int(rbl_match.group(1))
-
- return {'success': True, 'config': config}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def update_rules(cls) -> Dict:
- """Update SpamAssassin rules."""
- try:
- result = run_privileged(['sa-update'], timeout=120)
- # sa-update returns 0 for updates, 1 for no updates, 2+ for errors
- if result.returncode <= 1:
- ServiceControl.restart('spamassassin', timeout=30)
- return {
- 'success': True,
- 'message': 'Rules updated' if result.returncode == 0 else 'Rules already up to date',
- 'updated': result.returncode == 0,
- }
- return {'success': False, 'error': result.stderr or 'Update failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def train_spam(cls, message_path: str) -> Dict:
- """Train SpamAssassin with a spam message."""
- try:
- result = run_privileged(['sa-learn', '--spam', message_path])
- if result.returncode == 0:
- return {'success': True, 'message': 'Message learned as spam'}
- return {'success': False, 'error': result.stderr or 'Training failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def train_ham(cls, message_path: str) -> Dict:
- """Train SpamAssassin with a ham (non-spam) message."""
- try:
- result = run_privileged(['sa-learn', '--ham', message_path])
- if result.returncode == 0:
- return {'success': True, 'message': 'Message learned as ham'}
- return {'success': False, 'error': result.stderr or 'Training failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_stats(cls) -> Dict:
- """Get SpamAssassin Bayes statistics."""
- try:
- result = run_privileged(['sa-learn', '--dump', 'magic'])
- output = result.stdout or ''
- stats = {
- 'nspam': 0,
- 'nham': 0,
- 'ntokens': 0,
- }
- for line in output.splitlines():
- parts = line.split()
- if len(parts) >= 4:
- if parts[2] == 'nspam':
- stats['nspam'] = int(parts[1])
- elif parts[2] == 'nham':
- stats['nham'] = int(parts[1])
- elif parts[2] == 'ntokens':
- stats['ntokens'] = int(parts[1])
-
- return {'success': True, 'stats': stats}
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
- @classmethod
- def reload(cls) -> Dict:
- """Reload SpamAssassin."""
- try:
- result = ServiceControl.restart('spamassassin', timeout=30)
- if result.returncode == 0:
- return {'success': True, 'message': 'SpamAssassin restarted'}
- return {'success': False, 'error': result.stderr or 'Restart failed'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
diff --git a/builtin-extensions/serverkit-email/frontend/index.jsx b/builtin-extensions/serverkit-email/frontend/index.jsx
deleted file mode 100644
index 8d791800..00000000
--- a/builtin-extensions/serverkit-email/frontend/index.jsx
+++ /dev/null
@@ -1,18 +0,0 @@
-// Email Server, contributed through the extension system. Both halves live in
-// this extension: the mail-server backend (Postfix/Dovecot/DKIM/SpamAssassin/
-// Roundcube orchestration + the /api/v1/email blueprint) under backend/, and
-// the full page here (pages/Email.jsx + styles/email.scss + its own API
-// client in services/email.js). Imports go through 'serverkit-sdk' so the
-// same source works baked in-tree (the panel's build-time glob) and as a
-// runtime-ESM bundle once the extension leaves the tree (plan 52 Phase 2).
-//
-// The SCSS side-effect import compiles the page styles through this
-// extension's own module graph — the host's main.scss no longer carries an
-// _email partial.
-import './styles/email.scss';
-
-import Email from './pages/Email';
-
-export function EmailPage() {
- return <Email />;
-}
diff --git a/builtin-extensions/serverkit-email/frontend/pages/Email.jsx b/builtin-extensions/serverkit-email/frontend/pages/Email.jsx
deleted file mode 100644
index 6ac631ef..00000000
--- a/builtin-extensions/serverkit-email/frontend/pages/Email.jsx
+++ /dev/null
@@ -1,1070 +0,0 @@
-// Email Server — management page for the serverkit-email extension.
-//
-// NOTE: This file was reconstructed after a data-loss corruption. The original
-// was ~63KB; this is a coherent, functional, on-style rebuild — not a
-// byte-for-byte restore. It is wired to the real ApiService email methods
-// (see frontend/src/services/api/system.js, the `/email/*` endpoints) and
-// covers the same surface area: server/service status, mail domains with
-// SPF/DKIM/DMARC/PTR presence pills + DNS verify/deploy, accounts, aliases,
-// outbound relay (smarthost), SpamAssassin, webmail, and the mail queue.
-import { useState, useEffect, useCallback, useMemo } from 'react';
-import {
- RefreshCw, Plus, Trash2, ShieldCheck, Server, Globe, Users,
- Send, Filter, Inbox, ExternalLink, CheckCircle2, XCircle, HelpCircle, Search,
-} from 'lucide-react';
-import api from '../services/email';
-import {
- Pill, MetricCard, KpiBand, DataTable, DataTableFooter, ListToolbar,
- SearchField, PageLayout, Button, Input, EmptyState, useToast, useConfirm,
- useTabParam, useTableSort, useColumnVisibility, useTranslation,
- useTableChrome, GridViewPicker, GridChips, GridFilterButton,
- GridToolsMenu, GridFilterDrawer,
-} from 'serverkit-sdk';
-
-const VALID_TABS = ['overview', 'domains', 'accounts', 'relay', 'spam', 'webmail', 'queue'];
-
-// A sort-only preset still has to say so: `apply` clears the live rules from
-// whatever was selected before, and an absent `columnFilters` would leave the
-// previous view's filters silently in place.
-const NO_RULES = { match: 'all', rules: [] };
-
-// DNS record checks surfaced as presence pills. `state` is one of
-// 'ok' | 'missing' | 'unknown' and maps to a DS Pill colour + dot.
-const DNS_RECORDS = [
- { key: 'spf', label: 'SPF' },
- { key: 'dkim', label: 'DKIM' },
- { key: 'dmarc', label: 'DMARC' },
- { key: 'ptr', label: 'PTR' },
- { key: 'mx', label: 'MX' },
-];
-
-function dnsPillKind(state) {
- if (state === 'ok') return 'green';
- if (state === 'missing') return 'red';
- return 'gray';
-}
-
-// Derive a per-record status map from a domain record and an optional live
-// verify result. Falls back to "does the stored record string exist" when we
-// have not run a live DNS check yet.
-function deriveDnsStatus(domain, verify) {
- const out = {};
- for (const { key } of DNS_RECORDS) {
- if (verify && verify[key]) {
- out[key] = verify[key].valid || verify[key].present ? 'ok' : 'missing';
- } else if (key === 'spf') {
- out[key] = domain?.spf_record ? 'ok' : 'unknown';
- } else if (key === 'dkim') {
- out[key] = domain?.dkim_public_key ? 'ok' : 'unknown';
- } else if (key === 'dmarc') {
- out[key] = domain?.dmarc_record ? 'ok' : 'unknown';
- } else {
- out[key] = 'unknown';
- }
- }
- return out;
-}
-
-function DnsIcon({ state }) {
- if (state === 'ok') return <CheckCircle2 size={12} aria-hidden="true" />;
- if (state === 'missing') return <XCircle size={12} aria-hidden="true" />;
- return <HelpCircle size={12} aria-hidden="true" />;
-}
-
-export default function Email() {
- const { t } = useTranslation();
- const [activeTab] = useTabParam('/email', VALID_TABS);
-
- const [status, setStatus] = useState(null);
- const [domains, setDomains] = useState([]);
- const [loading, setLoading] = useState(true);
-
- const loadStatus = useCallback(async () => {
- try {
- const res = await api.getEmailStatus();
- setStatus(res?.status || res || null);
- } catch {
- setStatus(null);
- }
- }, []);
-
- const loadDomains = useCallback(async () => {
- try {
- const res = await api.getEmailDomains();
- setDomains(res?.domains || res || []);
- } catch {
- setDomains([]);
- }
- }, []);
-
- useEffect(() => {
- let alive = true;
- (async () => {
- await Promise.all([loadStatus(), loadDomains()]);
- if (alive) setLoading(false);
- })();
- return () => { alive = false; };
- }, [loadStatus, loadDomains]);
-
- const installed = status?.installed ?? status?.is_installed ?? (status != null && status.components != null);
-
- const tabs = VALID_TABS.map((t) => ({
- to: `/email/${t}`,
- label: t.charAt(0).toUpperCase() + t.slice(1),
- end: false,
- }));
-
- return (
- <PageLayout
- navLabel="Email Server"
- tabs={tabs}
- actions={(
- <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadDomains(); }}>
- <RefreshCw size={14} /> {t('common.actions.refresh', 'Refresh')}
- </Button>
- )}
- >
- <div className="sk-email">
- {loading ? (
- <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>
- ) : (
- <>
- {activeTab === 'overview' && (
- <OverviewTab status={status} installed={installed} onChange={loadStatus} />
- )}
- {activeTab === 'domains' && (
- <DomainsTab domains={domains} onChange={loadDomains} />
- )}
- {activeTab === 'accounts' && (
- <AccountsTab domains={domains} />
- )}
- {activeTab === 'relay' && <RelayTab />}
- {activeTab === 'spam' && <SpamTab />}
- {activeTab === 'webmail' && <WebmailTab />}
- {activeTab === 'queue' && <QueueTab />}
- </>
- )}
- </div>
- </PageLayout>
- );
-}
-
-// ---------- Overview ----------
-function OverviewTab({ status, installed, onChange }) {
- const { t } = useTranslation();
- const toast = useToast();
- const [installError, setInstallError] = useState(null);
- const components = status?.components || {};
- const names = Object.keys(components);
-
- // install_all answers {error, results: {postfix: {success, error}, ...}},
- // and the API client hangs that body off the thrown error as err.data. Dig
- // the failing components' stderr out of `results` so the user sees WHICH
- // component failed and why instead of a bare "Install failed". More than
- // one can fail in a single call: the installer only returns early on
- // postfix and dovecot, and lets dkim/spamassassin fall through.
- const installFailures = (err) => Object.entries(err?.data?.results || {})
- .filter(([, r]) => r && r.success === false)
- .map(([component, r]) => `${component}: ${r.error || 'unknown error'}`);
-
- const install = async () => {
- setInstallError(null);
- try {
- await api.installEmailServer();
- toast.success(t('app.email.emailServerInstallStarted', 'Email server install started'));
- onChange();
- } catch (err) {
- // err.message is the server's top-line reason ("Postfix
- // installation failed"); the failures carry the actual stderr.
- const summary = err?.message || 'Install failed';
- const failures = installFailures(err);
- // The toast stays one line — the inline block below keeps the full
- // detail on screen after the toast has gone.
- setInstallError([summary, ...failures].join('\n'));
- toast.error(failures.length ? `${summary} — ${failures[0]}` : summary);
- }
- };
-
- const control = async (component, action) => {
- try {
- await api.controlEmailService(component, action);
- toast.success(`${component}: ${action}`);
- onChange();
- } catch {
- toast.error(t('app.email.failedTo', 'Failed to {{action}} {{component}}', { action: action, component: component }));
- }
- };
-
- if (!installed) {
- return (
- <div className="sk-email__hero">
- <EmptyState
- icon={Server}
- title={t('app.email.mailServerNotInstalled', 'Mail server not installed')}
- description={t('app.email.mostPanelsNeverRunAMail', 'Most panels never run a mail server, install it when you need it.')}
- action={(
- <Button size="sm" onClick={install}>
- <Plus size={14} /> {t('app.email.installMailServer', 'Install mail server')}
- </Button>
- )}
- />
- <p className="sk-email__hero-note">
- {t('app.email.aDeliverabilityPreflightPtrPort25', 'A deliverability preflight (PTR, port 25, RBL) gates outbound sending before mail can leave this host.')}
- </p>
- {installError && (
- <p className="sk-email__hero-error" role="alert">{installError}</p>
- )}
- </div>
- );
- }
-
- const serviceRows = names.map((name) => {
- const running = components[name]?.running ?? components[name] === 'running';
- return { id: name, name, running };
- });
-
- const serviceColumns = [
- { key: 'component', headerKey: 'app.email.component', header: 'Component', sortable: true, hideable: false, sortValue: (r) => r.name, render: (r) => r.name },
- {
- key: 'state',
- headerKey: 'common.labels.state', header: 'State',
- sortable: true,
- sortValue: (r) => (r.running ? 1 : 0),
- render: (r) => <Pill kind={r.running ? 'green' : 'red'}>{r.running ? 'Running' : 'Stopped'}</Pill>,
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (r) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => control(r.name, r.running ? 'restart' : 'start')}>
- {r.running ? 'Restart' : 'Start'}
- </Button>
- {r.running && (
- <Button variant="ghost" size="sm" onClick={() => control(r.name, 'stop')}>{t('common.actions.stop', 'Stop')}</Button>
- )}
- </div>
- ),
- },
- ];
-
- return (
- <section className="sk-email__section">
- <KpiBand>
- <MetricCard label={t('common.labels.domains', 'Domains')} value={status?.domains_count ?? 0} tone="accent" icon={<Globe size={16} />} />
- <MetricCard label={t('app.email.accounts', 'Accounts')} value={status?.accounts_count ?? 0} tone="cyan" icon={<Users size={16} />} />
- <MetricCard label={t('app.email.queue', 'Queue')} value={status?.queue_count ?? 0} tone="amber" icon={<Inbox size={16} />} />
- </KpiBand>
-
- <h2 className="sk-email__section-title"><Server size={16} /> {t('common.labels.services', 'Services')}</h2>
- <DataTable
- columns={serviceColumns}
- data={serviceRows}
- keyField="id"
- storageKey="serverkit-table-email-components"
- footer={<DataTableFooter shown={serviceRows.length} total={serviceRows.length} noun="service" />}
- emptyTitle="No service components reported."
- emptyMessage=""
- />
- </section>
- );
-}
-
-// ---------- Domains ----------
-function DomainsTab({ domains, onChange }) {
- const { t } = useTranslation();
- const toast = useToast();
- const { confirm } = useConfirm();
- const [newDomain, setNewDomain] = useState('');
- const [verifying, setVerifying] = useState({});
- const [dnsResults, setDnsResults] = useState({});
-
- const add = async (e) => {
- e.preventDefault();
- if (!newDomain.trim()) return;
- try {
- await api.addEmailDomain({ name: newDomain.trim() });
- toast.success(t('app.email.domainAdded', 'Domain added'));
- setNewDomain('');
- onChange();
- } catch {
- toast.error(t('app.email.couldNotAddDomain', 'Could not add domain'));
- }
- };
-
- const remove = async (domain) => {
- const ok = await confirm({
- title: t('app.email.deleteDomain', 'Delete domain'),
- message: t('app.email.deleteAndAllOfItsAccounts', 'Delete {{name}} and all of its accounts and aliases?', { name: domain.name }),
- confirmLabel: t('common.actions.delete', 'Delete'),
- danger: true,
- });
- if (!ok) return;
- try {
- await api.deleteEmailDomain(domain.id);
- toast.success(t('app.email.domainDeleted', 'Domain deleted'));
- onChange();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const verify = async (domain) => {
- setVerifying((v) => ({ ...v, [domain.id]: true }));
- try {
- const res = await api.verifyEmailDNS(domain.id);
- setDnsResults((r) => ({ ...r, [domain.id]: res?.records || res || {} }));
- toast.success(t('app.email.dnsChecked', 'DNS checked'));
- } catch {
- toast.error(t('app.email.dnsCheckFailed', 'DNS check failed'));
- } finally {
- setVerifying((v) => ({ ...v, [domain.id]: false }));
- }
- };
-
- const deploy = async (domain) => {
- try {
- await api.deployEmailDNS(domain.id);
- toast.success(t('app.email.dnsRecordsDeployedToProvider', 'DNS records deployed to provider'));
- } catch {
- toast.error(t('app.email.deployFailedNoLinkedDnsProvider', 'Deploy failed (no linked DNS provider?)'));
- }
- };
-
- return (
- <section className="sk-email__section">
- <form className="sk-email__add" onSubmit={add}>
- <Input
- value={newDomain}
- onChange={(e) => setNewDomain(e.target.value)}
- placeholder="example.com"
- aria-label={t('app.email.newMailDomain', 'New mail domain')}
- />
- <Button type="submit" size="sm"><Plus size={14} /> {t('app.email.addDomain', 'Add domain')}</Button>
- </form>
-
- {domains.length === 0 ? (
- <div className="sk-email__empty">
- <Globe size={24} aria-hidden="true" />
- <p>{t('app.email.noMailDomainsYet', 'No mail domains yet.')}</p>
- </div>
- ) : (
- <ul className="sk-email__domains">
- {domains.map((domain) => {
- const dns = deriveDnsStatus(domain, dnsResults[domain.id]);
- return (
- <li key={domain.id} className="sk-email__domain">
- <div className="sk-email__domain-head">
- <span className="sk-email__domain-name">{domain.name}</span>
- <Pill kind={domain.is_active ? 'green' : 'gray'}>
- {domain.is_active ? 'Active' : 'Disabled'}
- </Pill>
- </div>
-
- <div className="sk-email__dns">
- {DNS_RECORDS.map(({ key, label }) => (
- <Pill key={key} kind={dnsPillKind(dns[key])} title={`${label}: ${dns[key]}`}>
- <DnsIcon state={dns[key]} /> {label}
- </Pill>
- ))}
- </div>
-
- <div className="sk-email__domain-meta">
- <span>{domain.accounts_count ?? 0} accounts</span>
- <span>{domain.aliases_count ?? 0} aliases</span>
- {domain.dkim_selector && <span>{t('app.email.dkimSelector', 'DKIM selector:')} {domain.dkim_selector}</span>}
- </div>
-
- <div className="sk-email__actions">
- <Button
- variant="outline"
- size="sm"
- onClick={() => verify(domain)}
- disabled={verifying[domain.id]}
- >
- <ShieldCheck size={14} /> {verifying[domain.id] ? 'Checking…' : 'Verify DNS'}
- </Button>
- <Button variant="outline" size="sm" onClick={() => deploy(domain)}>
- <ExternalLink size={14} /> {t('app.email.deployDns', 'Deploy DNS')}
- </Button>
- <Button variant="ghost" size="sm" onClick={() => remove(domain)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </section>
- );
-}
-
-// ---------- Accounts ----------
-
-// Percent of an account's own quota in use, so a 200 MB mailbox on a 250 MB
-// quota outranks a 2 GB one on 20 GB. null — not 0 — when no quota is set:
-// an unlimited mailbox can never be "nearly full", and the rule engine drops
-// nulls from every numeric comparison rather than reading them as empty.
-function quotaPercent(account) {
- const total = account?.quota_mb ?? 0;
- if (!total) return null;
- return Math.round(((account.quota_used_mb ?? 0) / total) * 100);
-}
-
-// Built-in saved views for the accounts table.
-//
-// The rules match on what the State column's `value` accessor returns (the
-// label the pill shows), NOT on the 1/0 its sortValue produces — filtering a
-// string against a numeric rank is the one mistake that makes a preset match
-// zero rows while looking perfectly correct.
-const ACCOUNT_VIEWS = [
- { name: 'Active first', state: { search: '', sorts: [{ key: 'state', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- { name: 'Largest quota', state: { search: '', sorts: [{ key: 'quota', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- {
- // A disabled mailbox still exists and still holds its mail — it just
- // cannot authenticate. This is the list you audit after an offboarding.
- name: 'Disabled',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'email', direction: 'asc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'ac1', field: 'state', op: 'any', value: ['Disabled'] }],
- },
- },
- },
- {
- // Mailboxes about to start rejecting deliveries. Same 85% threshold the
- // fleet uses for disk pressure, and `gt` on a null keeps the unlimited
- // mailboxes out instead of ranking them as 0%.
- name: 'Nearly full',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'used', direction: 'desc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'ac2', field: 'used', op: 'gt', value: 85 }],
- },
- },
- },
-];
-
-function AccountsTab({ domains }) {
- const { t } = useTranslation();
- const toast = useToast();
- const { confirm } = useConfirm();
- const [domainId, setDomainId] = useState(domains[0]?.id ? String(domains[0].id) : '');
- const [accounts, setAccounts] = useState([]);
- const [loading, setLoading] = useState(false);
- const [search, setSearch] = useState('');
- const [form, setForm] = useState({ username: '', password: '', quota_mb: 1024 });
- const { sorts, setSorts } = useTableSort({ storageKey: 'serverkit-table-email-accounts-sort' });
- const { hiddenKeys, setHiddenKeys } = useColumnVisibility({ storageKey: 'serverkit-table-email-accounts-cols' });
-
- // The only view state this tab owns privately. Everything else — sorts,
- // hidden columns, column order, the column rules — is the shared envelope
- // useTableChrome captures for us. The selected domain deliberately stays
- // OUT of it: it is which list you are looking at, not how you are looking
- // at it, and a saved view that silently jumped domains would be a trap.
- const viewPageState = useMemo(() => ({ search }), [search]);
- const applyViewPageState = useCallback((saved) => {
- if (saved.search !== undefined) setSearch(saved.search);
- }, []);
-
- const load = useCallback(async () => {
- if (!domainId) { setAccounts([]); return; }
- setLoading(true);
- try {
- const res = await api.getEmailAccounts(domainId);
- setAccounts(res?.accounts || res || []);
- } catch {
- setAccounts([]);
- } finally {
- setLoading(false);
- }
- }, [domainId]);
-
- useEffect(() => { load(); }, [load]);
-
- const create = async (e) => {
- e.preventDefault();
- if (!form.username.trim() || !form.password) return;
- try {
- await api.createEmailAccount(domainId, form);
- toast.success(t('app.email.accountCreated', 'Account created'));
- setForm({ username: '', password: '', quota_mb: 1024 });
- load();
- } catch {
- toast.error(t('app.email.createFailed', 'Create failed'));
- }
- };
-
- const remove = async (account) => {
- const ok = await confirm({
- title: t('app.email.deleteAccount', 'Delete account'),
- message: t('app.email.delete3', 'Delete {{email}}?', { email: account.email }),
- confirmLabel: t('common.actions.delete', 'Delete'),
- danger: true,
- });
- if (!ok) return;
- try {
- await api.deleteEmailAccount(account.id);
- toast.success(t('app.email.accountDeleted', 'Account deleted'));
- load();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const filtered = useMemo(() => {
- const q = search.trim().toLowerCase();
- if (!q) return accounts;
- return accounts.filter((a) => (a.email || '').toLowerCase().includes(q));
- }, [accounts, search]);
-
- const accountColumns = [
- {
- key: 'email',
- headerKey: 'app.email.address', header: 'Address',
- sortable: true,
- hideable: false,
- sortValue: (a) => a.email || '',
- render: (a) => <span className="sk-email__mono">{a.email}</span>,
- },
- {
- key: 'quota',
- headerKey: 'app.email.quota', header: 'Quota',
- sortable: true,
- type: 'num',
- unit: ' MB',
- // The allocation, which is what "Largest quota" orders by. How full
- // it is lives in its own column below.
- value: (a) => a.quota_mb ?? 0,
- sortValue: (a) => a.quota_mb ?? 0,
- render: (a) => `${a.quota_used_mb ?? 0} / ${a.quota_mb ?? 0} MB`,
- },
- {
- key: 'used',
- headerKey: 'app.email.used', header: 'Used',
- sortable: true,
- type: 'num',
- unit: '%',
- value: quotaPercent,
- sortValue: quotaPercent,
- render: (a) => {
- const pct = quotaPercent(a);
- return pct == null ? '—' : `${pct}%`;
- },
- },
- {
- key: 'state',
- headerKey: 'common.labels.state', header: 'State',
- sortable: true,
- // Filter on the label the pill shows; keep the 1/0 sortValue so
- // "Active first" still puts active first when the column sorts desc.
- type: 'enum',
- value: (a) => (a.is_active ? 'Active' : 'Disabled'),
- sortValue: (a) => (a.is_active ? 1 : 0),
- render: (a) => <Pill kind={a.is_active ? 'green' : 'gray'}>{a.is_active ? 'Active' : 'Disabled'}</Pill>,
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (a) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => remove(a)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- ),
- },
- ];
-
- // Each tab is its own route, so only one picker is ever mounted — this
- // chrome is scoped to the accounts table alone and keeps its own page key.
- const chrome = useTableChrome({
- columns: accountColumns,
- rows: filtered,
- viewPageKey: 'email-accounts',
- builtinViews: ACCOUNT_VIEWS,
- noun: 'accounts',
- sorts,
- setSorts,
- hiddenKeys,
- setHiddenKeys,
- pageState: viewPageState,
- applyPage: applyViewPageState,
- });
-
- if (domains.length === 0) {
- return (
- <div className="sk-email__empty">
- <Users size={24} aria-hidden="true" />
- <p>{t('app.email.addAMailDomainFirst', 'Add a mail domain first.')}</p>
- </div>
- );
- }
-
- return (
- <section className="sk-email__section">
- {/* One row of chrome: the view name and the table's own controls.
- What stays in the toolbar below is not chrome — the domain
- select is WHICH list you are looking at. */}
- <GridViewPicker
- views={chrome.views}
- label="accounts"
- onCreate={chrome.createView}
- actions={(
- <>
- <GridFilterButton
- count={chrome.filterCount}
- onClick={() => chrome.setDrawerOpen(true)}
- />
- <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
- </>
- )}
- />
- <ListToolbar className="sk-email__filters">
- <label>
- {t('common.labels.domain', 'Domain')}
- <select value={domainId} onChange={(e) => setDomainId(e.target.value)}>
- {domains.map((d) => <option key={d.id} value={String(d.id)}>{d.name}</option>)}
- </select>
- </label>
- <label className="search-box">
- <Search size={16} />
- <Input
- type="text"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder={t('app.email.searchAccountsByAddress', 'Search accounts by address…')}
- aria-label={t('app.email.searchAccounts', 'Search accounts')}
- />
- </label>
- </ListToolbar>
-
- <GridChips {...chrome.chipProps} />
-
- <form className="sk-email__add" onSubmit={create}>
- <Input
- value={form.username}
- onChange={(e) => setForm({ ...form, username: e.target.value })}
- placeholder="username"
- aria-label={t('app.email.mailboxUsername', 'Mailbox username')}
- />
- <Input
- type="password"
- value={form.password}
- onChange={(e) => setForm({ ...form, password: e.target.value })}
- placeholder="password"
- aria-label={t('app.email.mailboxPassword', 'Mailbox password')}
- />
- <Input
- type="number"
- value={form.quota_mb}
- onChange={(e) => setForm({ ...form, quota_mb: Number(e.target.value) })}
- placeholder={t('app.email.quotaMb', 'Quota (MB)')}
- aria-label={t('app.email.quotaInMb', 'Quota in MB')}
- />
- <Button type="submit" size="sm"><Plus size={14} /> {t('common.actions.create', 'Create')}</Button>
- </form>
-
- <DataTable
- columns={chrome.columns}
- data={filtered}
- keyField="id"
- sorts={sorts}
- onSortsChange={setSorts}
- {...chrome.tableProps}
- loading={loading}
- footer={<DataTableFooter shown={filtered.length} total={accounts.length} noun="account" />}
- emptyTitle={accounts.length === 0 ? 'No accounts in this domain.' : 'No accounts match this search.'}
- emptyMessage=""
- />
-
- <GridFilterDrawer {...chrome.drawerProps} />
- </section>
- );
-}
-
-// ---------- Relay (smarthost) ----------
-function RelayTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [relay, setRelay] = useState({ host: '', port: 587, username: '', password: '', enabled: false });
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- let alive = true;
- api.getEmailRelay()
- .then((res) => { if (alive) setRelay((r) => ({ ...r, ...(res?.relay || res || {}) })); })
- .catch(() => { /* defaults */ })
- .finally(() => { if (alive) setLoading(false); });
- return () => { alive = false; };
- }, []);
-
- const save = async (e) => {
- e.preventDefault();
- try {
- await api.updateEmailRelay(relay);
- toast.success(t('app.email.relaySaved', 'Relay saved'));
- } catch {
- toast.error(t('app.email.saveFailed', 'Save failed'));
- }
- };
-
- const test = async () => {
- try {
- await api.testEmailRelay(relay);
- toast.success(t('app.email.relayReachable', 'Relay reachable'));
- } catch {
- toast.error(t('app.email.relayTestFailed', 'Relay test failed'));
- }
- };
-
- const disable = async () => {
- try {
- await api.disableEmailRelay();
- setRelay((r) => ({ ...r, enabled: false }));
- toast.success(t('app.email.relayDisabled', 'Relay disabled'));
- } catch {
- toast.error(t('app.email.failedToDisableRelay', 'Failed to disable relay'));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Send size={16} /> {t('app.email.outboundRelaySmarthost', 'Outbound relay (smarthost)')}</h2>
- <form className="sk-email__form" onSubmit={save}>
- <label>{t('app.email.host', 'Host')}<Input value={relay.host || ''} onChange={(e) => setRelay({ ...relay, host: e.target.value })} placeholder="smtp.provider.com" /></label>
- <label>{t('common.labels.port', 'Port')}<Input type="number" value={relay.port || 587} onChange={(e) => setRelay({ ...relay, port: Number(e.target.value) })} /></label>
- <label>{t('common.labels.username', 'Username')}<Input value={relay.username || ''} onChange={(e) => setRelay({ ...relay, username: e.target.value })} /></label>
- <label>{t('common.labels.password', 'Password')}<Input type="password" value={relay.password || ''} onChange={(e) => setRelay({ ...relay, password: e.target.value })} /></label>
- <label className="sk-email__check">
- <input type="checkbox" checked={!!relay.enabled} onChange={(e) => setRelay({ ...relay, enabled: e.target.checked })} />
- {t('app.email.enableRelay', 'Enable relay')}
- </label>
- <div className="sk-email__actions">
- <Button type="submit" size="sm">{t('common.actions.save', 'Save')}</Button>
- <Button type="button" variant="outline" size="sm" onClick={test}>{t('common.actions.test', 'Test')}</Button>
- <Button type="button" variant="ghost" size="sm" onClick={disable}>{t('common.actions.disable', 'Disable')}</Button>
- </div>
- </form>
- </section>
- );
-}
-
-// ---------- Spam ----------
-function SpamTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [config, setConfig] = useState({ enabled: true, required_score: 5 });
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- let alive = true;
- api.getSpamConfig()
- .then((res) => { if (alive) setConfig((c) => ({ ...c, ...(res?.config || res || {}) })); })
- .catch(() => { /* defaults */ })
- .finally(() => { if (alive) setLoading(false); });
- return () => { alive = false; };
- }, []);
-
- const save = async (e) => {
- e.preventDefault();
- try {
- await api.updateSpamConfig(config);
- toast.success(t('app.email.spamConfigSaved', 'Spam config saved'));
- } catch {
- toast.error(t('app.email.saveFailed', 'Save failed'));
- }
- };
-
- const updateRules = async () => {
- try {
- await api.updateSpamRules();
- toast.success(t('app.email.ruleUpdateStarted', 'Rule update started'));
- } catch {
- toast.error(t('app.email.ruleUpdateFailed', 'Rule update failed'));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Filter size={16} /> {t('app.email.spamassassin', 'SpamAssassin')}</h2>
- <form className="sk-email__form" onSubmit={save}>
- <label className="sk-email__check">
- <input type="checkbox" checked={!!config.enabled} onChange={(e) => setConfig({ ...config, enabled: e.target.checked })} />
- {t('app.email.enableSpamFiltering', 'Enable spam filtering')}
- </label>
- <label>{t('app.email.requiredScore', 'Required score')}<Input type="number" step="0.1" value={config.required_score ?? 5} onChange={(e) => setConfig({ ...config, required_score: Number(e.target.value) })} /></label>
- <div className="sk-email__actions">
- <Button type="submit" size="sm">{t('common.actions.save', 'Save')}</Button>
- <Button type="button" variant="outline" size="sm" onClick={updateRules}>{t('app.email.updateRules', 'Update rules')}</Button>
- </div>
- </form>
- </section>
- );
-}
-
-// ---------- Webmail ----------
-function WebmailTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [state, setState] = useState(null);
- const [loading, setLoading] = useState(true);
-
- const load = useCallback(async () => {
- try {
- const res = await api.getWebmailStatus();
- setState(res?.status || res || null);
- } catch {
- setState(null);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => { load(); }, [load]);
-
- const install = async () => {
- try {
- await api.installWebmail();
- toast.success(t('app.email.webmailInstallStarted', 'Webmail install started'));
- load();
- } catch {
- toast.error(t('app.email.installFailed', 'Install failed'));
- }
- };
-
- const control = async (action) => {
- try {
- await api.controlWebmail(action);
- toast.success(t('app.email.webmail', 'Webmail: {{action}}', { action: action }));
- load();
- } catch {
- toast.error(t('app.email.failedToWebmail', 'Failed to {{action}} webmail', { action: action }));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- const installed = state?.installed ?? state?.is_installed;
- const running = state?.running;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Inbox size={16} /> {t('app.email.roundcubeWebmail', 'Roundcube webmail')}</h2>
- {!installed ? (
- <div className="sk-email__empty">
- <p>{t('app.email.webmailIsNotInstalled', 'Webmail is not installed.')}</p>
- <Button size="sm" onClick={install}><Plus size={14} /> {t('app.email.installWebmail', 'Install webmail')}</Button>
- </div>
- ) : (
- <div className="sk-email__actions">
- <Pill kind={running ? 'green' : 'red'}>{running ? 'Running' : 'Stopped'}</Pill>
- <Button variant="outline" size="sm" onClick={() => control(running ? 'restart' : 'start')}>
- {running ? 'Restart' : 'Start'}
- </Button>
- {running && <Button variant="ghost" size="sm" onClick={() => control('stop')}>{t('common.actions.stop', 'Stop')}</Button>}
- </div>
- )}
- </section>
- );
-}
-
-// ---------- Mail queue ----------
-
-// Built-in saved views for the queue.
-//
-// The queue payload is `mailq` output — a queue id, a byte size, a sender and
-// its recipients. There is no status field, so nothing here pretends there is
-// one: the only rule-based preset filters on `size`, which is a real integer on
-// every row (see PostfixService.get_queue).
-const QUEUE_VIEWS = [
- { name: 'Largest first', state: { search: '', sorts: [{ key: 'size', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- { name: 'By sender', state: { search: '', sorts: [{ key: 'sender', direction: 'asc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- {
- // What a backed-up queue is usually full of. 100 KB is the line between
- // a plain message (a few KB) and one carrying an attachment; Postfix's
- // own message_size_limit is 25 MB, so this is well inside real traffic.
- name: 'Large messages',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'size', direction: 'desc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'q1', field: 'size', op: 'gt', value: 102400 }],
- },
- },
- },
-];
-
-function QueueTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [queue, setQueue] = useState([]);
- const [loading, setLoading] = useState(true);
- const [search, setSearch] = useState('');
- const { sorts, setSorts } = useTableSort({ storageKey: 'serverkit-table-email-queue-sort' });
- const { hiddenKeys, setHiddenKeys } = useColumnVisibility({ storageKey: 'serverkit-table-email-queue-cols' });
-
- // Search is all this tab owns privately; the rest of the view state is the
- // shared envelope useTableChrome captures.
- const viewPageState = useMemo(() => ({ search }), [search]);
- const applyViewPageState = useCallback((saved) => {
- if (saved.search !== undefined) setSearch(saved.search);
- }, []);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const res = await api.getMailQueue();
- setQueue(res?.queue || res || []);
- } catch {
- setQueue([]);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => { load(); }, [load]);
-
- const flush = async () => {
- try {
- await api.flushMailQueue();
- toast.success(t('app.email.queueFlushed', 'Queue flushed'));
- load();
- } catch {
- toast.error(t('app.email.flushFailed', 'Flush failed'));
- }
- };
-
- const remove = async (id) => {
- try {
- await api.deleteMailQueueItem(id);
- load();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const filtered = queue.filter((item) => {
- const q = search.trim().toLowerCase();
- if (!q) return true;
- const id = String(item.id || item.queue_id || '').toLowerCase();
- const sender = String(item.sender || '').toLowerCase();
- const recipient = String(item.recipient || '').toLowerCase();
- return id.includes(q) || sender.includes(q) || recipient.includes(q);
- });
-
- const queueColumns = [
- {
- key: 'id',
- header: 'ID',
- sortable: true,
- hideable: false,
- sortValue: (item) => item.id || item.queue_id || '',
- render: (item) => <span className="sk-email__mono">{item.id || item.queue_id}</span>,
- },
- { key: 'sender', headerKey: 'app.email.sender', header: 'Sender', sortable: true, sortValue: (item) => item.sender || null, render: (item) => item.sender || '-' },
- { key: 'recipient', headerKey: 'app.email.recipient', header: 'Recipient', sortable: true, sortValue: (item) => item.recipient || null, render: (item) => item.recipient || '-' },
- {
- key: 'size',
- headerKey: 'common.labels.size', header: 'Size',
- sortable: true,
- // Bytes, straight off mailq. Typed explicitly because a preset
- // filters on it — inference would land on 'num' here anyway, but
- // only for as long as every loaded row happens to carry a size.
- type: 'num',
- unit: ' bytes',
- value: (item) => item.size ?? null,
- sortValue: (item) => item.size ?? null,
- render: (item) => item.size || '-',
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (item) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => remove(item.id || item.queue_id)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- ),
- },
- ];
-
- const chrome = useTableChrome({
- columns: queueColumns,
- rows: filtered,
- viewPageKey: 'email-queue',
- builtinViews: QUEUE_VIEWS,
- noun: 'messages',
- sorts,
- setSorts,
- hiddenKeys,
- setHiddenKeys,
- pageState: viewPageState,
- applyPage: applyViewPageState,
- });
-
- return (
- <section className="sk-email__section">
- {/* Everything that acts on the queue rides the view line, in the
- same order the topbar pages use: action, search, filter, "⋮".
- Refresh is not repeated as a button — it is in the "⋮". */}
- <GridViewPicker
- views={chrome.views}
- label="messages"
- onCreate={chrome.createView}
- actions={(
- <>
- <Button variant="outline" size="sm" onClick={flush}>{t('app.email.flushQueue', 'Flush queue')}</Button>
- <SearchField
- value={search}
- onSearch={setSearch}
- placeholder={t('app.email.searchQueueBySenderRecipientOr', 'Search queue by sender, recipient, or ID…')}
- />
- <GridFilterButton
- count={chrome.filterCount}
- onClick={() => chrome.setDrawerOpen(true)}
- />
- <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
- </>
- )}
- />
-
- <GridChips {...chrome.chipProps} />
-
- <DataTable
- columns={chrome.columns}
- data={filtered}
- keyField={(item) => item.id || item.queue_id}
- sorts={sorts}
- onSortsChange={setSorts}
- {...chrome.tableProps}
- loading={loading}
- footer={<DataTableFooter shown={filtered.length} total={queue.length} noun="message" />}
- emptyTitle={queue.length === 0 ? 'The mail queue is empty.' : 'No messages match this search.'}
- emptyMessage=""
- />
-
- <GridFilterDrawer {...chrome.drawerProps} />
- </section>
- );
-}
diff --git a/builtin-extensions/serverkit-email/frontend/services/email.js b/builtin-extensions/serverkit-email/frontend/services/email.js
deleted file mode 100644
index 78e811ab..00000000
--- a/builtin-extensions/serverkit-email/frontend/services/email.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// The extension's own /api/v1/email client, built on the panel's ApiClient
-// via the SDK singleton (JWT refresh, workspace headers, error normalization
-// included) — moved out of the host's services/api/system.js with the page.
-//
-// Two email surfaces deliberately STAY core and are not duplicated here:
-// the DNS-provider connections (/email/dns-providers — a core blueprint that
-// keeps its historical prefix) and the Settings → Connections relay tile's
-// calls. The relay methods below are this extension's own copies for the
-// Relay tab; the page and the Settings tile hit the same endpoints.
-import { api } from 'serverkit-sdk';
-
-const emailApi = {
- // Server
- getEmailStatus: () => api.request('/email/status'),
- installEmailServer: (data = {}) => api.request('/email/install', { method: 'POST', body: JSON.stringify(data) }),
- controlEmailService: (component, action) => api.request(`/email/service/${component}/${action}`, { method: 'POST' }),
-
- // Domains
- getEmailDomains: () => api.request('/email/domains'),
- addEmailDomain: (data) => api.request('/email/domains', { method: 'POST', body: JSON.stringify(data) }),
- getEmailDomain: (domainId) => api.request(`/email/domains/${domainId}`),
- deleteEmailDomain: (domainId) => api.request(`/email/domains/${domainId}`, { method: 'DELETE' }),
- verifyEmailDNS: (domainId) => api.request(`/email/domains/${domainId}/verify-dns`, { method: 'POST' }),
- deployEmailDNS: (domainId) => api.request(`/email/domains/${domainId}/deploy-dns`, { method: 'POST' }),
-
- // Accounts
- getEmailAccounts: (domainId) => api.request(`/email/domains/${domainId}/accounts`),
- createEmailAccount: (domainId, data) => api.request(`/email/domains/${domainId}/accounts`, { method: 'POST', body: JSON.stringify(data) }),
- getEmailAccount: (accountId) => api.request(`/email/accounts/${accountId}`),
- updateEmailAccount: (accountId, data) => api.request(`/email/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify(data) }),
- deleteEmailAccount: (accountId) => api.request(`/email/accounts/${accountId}`, { method: 'DELETE' }),
- changeEmailPassword: (accountId, password) => api.request(`/email/accounts/${accountId}/password`, { method: 'POST', body: JSON.stringify({ password }) }),
-
- // Aliases
- getEmailAliases: (domainId) => api.request(`/email/domains/${domainId}/aliases`),
- createEmailAlias: (domainId, data) => api.request(`/email/domains/${domainId}/aliases`, { method: 'POST', body: JSON.stringify(data) }),
- deleteEmailAlias: (aliasId) => api.request(`/email/aliases/${aliasId}`, { method: 'DELETE' }),
-
- // Forwarding
- getEmailForwarding: (accountId) => api.request(`/email/accounts/${accountId}/forwarding`),
- createEmailForwarding: (accountId, data) => api.request(`/email/accounts/${accountId}/forwarding`, { method: 'POST', body: JSON.stringify(data) }),
- updateEmailForwarding: (ruleId, data) => api.request(`/email/forwarding/${ruleId}`, { method: 'PUT', body: JSON.stringify(data) }),
- deleteEmailForwarding: (ruleId) => api.request(`/email/forwarding/${ruleId}`, { method: 'DELETE' }),
-
- // Outbound SMTP relay (smarthost)
- getEmailRelay: () => api.request('/email/relay'),
- updateEmailRelay: (data) => api.request('/email/relay', { method: 'PUT', body: JSON.stringify(data) }),
- testEmailRelay: (data) => api.request('/email/relay/test', { method: 'POST', body: JSON.stringify(data) }),
- disableEmailRelay: () => api.request('/email/relay', { method: 'DELETE' }),
-
- // SpamAssassin
- getSpamConfig: () => api.request('/email/spam/config'),
- updateSpamConfig: (data) => api.request('/email/spam/config', { method: 'PUT', body: JSON.stringify(data) }),
- updateSpamRules: () => api.request('/email/spam/update-rules', { method: 'POST' }),
-
- // Roundcube webmail
- getWebmailStatus: () => api.request('/email/webmail/status'),
- installWebmail: (data = {}) => api.request('/email/webmail/install', { method: 'POST', body: JSON.stringify(data) }),
- controlWebmail: (action) => api.request(`/email/webmail/service/${action}`, { method: 'POST' }),
- configureWebmailProxy: (domain) => api.request('/email/webmail/configure-proxy', { method: 'POST', body: JSON.stringify({ domain }) }),
-
- // Mail queue & logs
- getMailQueue: () => api.request('/email/queue'),
- flushMailQueue: () => api.request('/email/queue/flush', { method: 'POST' }),
- deleteMailQueueItem: (queueId) => api.request(`/email/queue/${queueId}`, { method: 'DELETE' }),
- getMailLogs: (lines = 100) => api.request(`/email/logs?lines=${lines}`),
-};
-
-export default emailApi;
diff --git a/builtin-extensions/serverkit-email/frontend/styles/email.scss b/builtin-extensions/serverkit-email/frontend/styles/email.scss
deleted file mode 100644
index 299ecb8c..00000000
--- a/builtin-extensions/serverkit-email/frontend/styles/email.scss
+++ /dev/null
@@ -1,277 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-email/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// EMAIL SERVER PAGE (redesign — infra console look, REDESIGN_MAP #18):
-// status Pills on the Services list, MetricCard KPI strip (Overview),
-// dense .sk-dtable lists (services / accounts / queue), mono-uppercase
-// eyebrow section headers, token surfaces. Domains stay as a designed
-// card list. Class namespace = `sk-email` (the rebuilt Email.jsx emits it).
-//
-// Mail-volume chart, reputation/RBL ring, structured activity feed,
-// per-mailbox storage gauges and per-message retry are intentionally
-// absent — no backend yet (REDESIGN_MAP §5).
-// ============================================
-
-.sk-email {
- padding: $space-6;
-
- // ── Sections stack with breathing room ──────────────────
- &__section {
- display: flex;
- flex-direction: column;
- gap: $space-5;
- }
-
- // ── Mono-uppercase eyebrow section headers ──────────────
- &__section-title {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin: 0;
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
-
- svg { color: var(--text-dim); }
- }
-
- // ── Empty / loading placeholders (shared look) ──────────
- &__empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6 $space-5;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- text-align: center;
- color: var(--text-dim);
- font-size: $font-size-sm;
-
- svg { color: var(--text-faint); }
-
- p { margin: 0; }
- }
-
- // ── Not-installed hero (EmptyState + preflight note) ─────
- &__hero {
- max-width: 560px;
- margin: $space-6 auto 0;
-
- .empty-state {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- padding: $space-8 $space-6;
- }
- }
-
- &__hero-note {
- margin: $space-4 0 0;
- padding: $space-3 $space-4;
- background: var(--accent-bg);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 11.5px;
- line-height: 1.55;
- color: var(--text-dim);
- text-align: center;
- }
-
- // Inline install failure (component + stderr from the API) — same card
- // chrome as the hero note, in the danger tone. pre-line keeps one failing
- // component per line; anywhere stops a long unbroken stderr token from
- // widening the hero.
- &__hero-error {
- margin: $space-3 0 0;
- padding: $space-3 $space-4;
- background: var(--red-bg);
- border: 1px solid var(--red);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 11.5px;
- line-height: 1.55;
- color: var(--red);
- white-space: pre-line;
- overflow-wrap: anywhere;
- text-align: left;
- }
-
- // ── Action clusters (row actions, form buttons, toolbars) ─
- &__actions {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
- }
-
- // Right-align the DataTable actions column
- &__actions-col { text-align: right; }
-
- &__actions-cell {
- text-align: right;
-
- .sk-email__actions { justify-content: flex-end; }
- }
-
- // ── Filters toolbar (domain select + search) ────────────
- // The row layout is the shared ListToolbar (.sk-listhead); this class
- // rides along on it to keep the eyebrow labels, select chrome and
- // search-box sizing below.
- &__filters {
- > label {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- select {
- padding: 6px 10px;
- background: var(--surface-2);
- border: 1px solid var(--border);
- border-radius: $radius-md;
- color: var(--text);
- font-family: $font-mono;
- font-size: $font-size-sm;
- cursor: pointer;
-
- &:focus {
- outline: none;
- border-color: var(--accent);
- }
- }
-
- // The global .search-box keeps its own chrome; just let it grow.
- .search-box {
- flex: 1;
- min-width: 220px;
- max-width: 360px;
- }
- }
-
- // ── Inline create/add forms (domain + account) ──────────
- &__add,
- &__form {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- gap: $space-3;
- padding: $space-4 $space-5;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
-
- label {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
- }
-
- &__form { flex-direction: column; align-items: stretch; }
-
- // Checkbox rows keep sentence case (not eyebrow uppercase)
- &__check {
- flex-direction: row;
- align-items: center;
- gap: $space-2;
- font-family: inherit;
- font-size: $font-size-sm;
- font-weight: $font-weight-normal;
- letter-spacing: normal;
- text-transform: none;
- color: var(--text-dim);
- cursor: pointer;
-
- input[type='checkbox'] {
- width: 15px;
- height: 15px;
- accent-color: var(--accent);
- }
- }
-
- // ── Domains card list (kept as designed cards) ──────────
- &__domains {
- list-style: none;
- margin: 0;
- padding: 0;
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- }
-
- &__domain {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- padding: 15px 16px;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- transition: border-color $transition-fast;
-
- &:hover { border-color: var(--border-strong); }
- }
-
- &__domain-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- }
-
- &__domain-name {
- font-family: var(--mono);
- font-size: 13.5px;
- font-weight: $font-weight-semibold;
- color: var(--text);
- overflow-wrap: anywhere;
- }
-
- &__dns {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- }
-
- &__domain-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-3;
- padding-top: $space-3;
- border-top: 1px solid var(--border-soft);
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--text-faint);
- }
-
- // ── Mono cell emphasis (queue ids, addresses) ───────────
- &__mono {
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--text);
- overflow-wrap: anywhere;
- }
-}
diff --git a/builtin-extensions/serverkit-email/plugin.json b/builtin-extensions/serverkit-email/plugin.json
deleted file mode 100644
index 80b652bf..00000000
--- a/builtin-extensions/serverkit-email/plugin.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "name": "serverkit-email",
- "display_name": "Email Server",
- "version": "1.0.0",
- "description": "Full mail-server stack with Postfix/Dovecot, domains, mailboxes, aliases, DKIM/SPF/DMARC, SpamAssassin filtering, and Roundcube webmail. Most panels never run a mail server, so it ships as an opt-in extension.",
- "author": "ServerKit",
- "license": "MIT",
- "category": "integration",
- "homepage": "https://github.com/jhd3197/ServerKit",
- "permissions": ["shell", "filesystem", "network"],
- "min_panel_version": "1.7.0",
- "entry_point": "email:email_bp",
- "url_prefix": "/api/v1/email",
- "icon": "<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\"/>",
- "contributions": {
- "nav": [
- {
- "id": "email",
- "label": "Email Server",
- "route": "/email",
- "category": "operations",
- "icon": "<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\"/>"
- }
- ],
- "routes": [
- { "path": "email", "component": "EmailPage" },
- { "path": "email/:tab", "component": "EmailPage" }
- ],
- "page_titles": {
- "/email": "Email Server"
- },
- "command_palette": [
- {
- "label": "Email",
- "path": "/email",
- "category": "Pages",
- "keywords": "smtp postfix dovecot mail imap dkim webmail"
- }
- ]
- }
-}
diff --git a/frontend/src/plugins/serverkit-email/index.jsx b/frontend/src/plugins/serverkit-email/index.jsx
deleted file mode 100644
index 8d791800..00000000
--- a/frontend/src/plugins/serverkit-email/index.jsx
+++ /dev/null
@@ -1,18 +0,0 @@
-// Email Server, contributed through the extension system. Both halves live in
-// this extension: the mail-server backend (Postfix/Dovecot/DKIM/SpamAssassin/
-// Roundcube orchestration + the /api/v1/email blueprint) under backend/, and
-// the full page here (pages/Email.jsx + styles/email.scss + its own API
-// client in services/email.js). Imports go through 'serverkit-sdk' so the
-// same source works baked in-tree (the panel's build-time glob) and as a
-// runtime-ESM bundle once the extension leaves the tree (plan 52 Phase 2).
-//
-// The SCSS side-effect import compiles the page styles through this
-// extension's own module graph — the host's main.scss no longer carries an
-// _email partial.
-import './styles/email.scss';
-
-import Email from './pages/Email';
-
-export function EmailPage() {
- return <Email />;
-}
diff --git a/frontend/src/plugins/serverkit-email/pages/Email.jsx b/frontend/src/plugins/serverkit-email/pages/Email.jsx
deleted file mode 100644
index 6ac631ef..00000000
--- a/frontend/src/plugins/serverkit-email/pages/Email.jsx
+++ /dev/null
@@ -1,1070 +0,0 @@
-// Email Server — management page for the serverkit-email extension.
-//
-// NOTE: This file was reconstructed after a data-loss corruption. The original
-// was ~63KB; this is a coherent, functional, on-style rebuild — not a
-// byte-for-byte restore. It is wired to the real ApiService email methods
-// (see frontend/src/services/api/system.js, the `/email/*` endpoints) and
-// covers the same surface area: server/service status, mail domains with
-// SPF/DKIM/DMARC/PTR presence pills + DNS verify/deploy, accounts, aliases,
-// outbound relay (smarthost), SpamAssassin, webmail, and the mail queue.
-import { useState, useEffect, useCallback, useMemo } from 'react';
-import {
- RefreshCw, Plus, Trash2, ShieldCheck, Server, Globe, Users,
- Send, Filter, Inbox, ExternalLink, CheckCircle2, XCircle, HelpCircle, Search,
-} from 'lucide-react';
-import api from '../services/email';
-import {
- Pill, MetricCard, KpiBand, DataTable, DataTableFooter, ListToolbar,
- SearchField, PageLayout, Button, Input, EmptyState, useToast, useConfirm,
- useTabParam, useTableSort, useColumnVisibility, useTranslation,
- useTableChrome, GridViewPicker, GridChips, GridFilterButton,
- GridToolsMenu, GridFilterDrawer,
-} from 'serverkit-sdk';
-
-const VALID_TABS = ['overview', 'domains', 'accounts', 'relay', 'spam', 'webmail', 'queue'];
-
-// A sort-only preset still has to say so: `apply` clears the live rules from
-// whatever was selected before, and an absent `columnFilters` would leave the
-// previous view's filters silently in place.
-const NO_RULES = { match: 'all', rules: [] };
-
-// DNS record checks surfaced as presence pills. `state` is one of
-// 'ok' | 'missing' | 'unknown' and maps to a DS Pill colour + dot.
-const DNS_RECORDS = [
- { key: 'spf', label: 'SPF' },
- { key: 'dkim', label: 'DKIM' },
- { key: 'dmarc', label: 'DMARC' },
- { key: 'ptr', label: 'PTR' },
- { key: 'mx', label: 'MX' },
-];
-
-function dnsPillKind(state) {
- if (state === 'ok') return 'green';
- if (state === 'missing') return 'red';
- return 'gray';
-}
-
-// Derive a per-record status map from a domain record and an optional live
-// verify result. Falls back to "does the stored record string exist" when we
-// have not run a live DNS check yet.
-function deriveDnsStatus(domain, verify) {
- const out = {};
- for (const { key } of DNS_RECORDS) {
- if (verify && verify[key]) {
- out[key] = verify[key].valid || verify[key].present ? 'ok' : 'missing';
- } else if (key === 'spf') {
- out[key] = domain?.spf_record ? 'ok' : 'unknown';
- } else if (key === 'dkim') {
- out[key] = domain?.dkim_public_key ? 'ok' : 'unknown';
- } else if (key === 'dmarc') {
- out[key] = domain?.dmarc_record ? 'ok' : 'unknown';
- } else {
- out[key] = 'unknown';
- }
- }
- return out;
-}
-
-function DnsIcon({ state }) {
- if (state === 'ok') return <CheckCircle2 size={12} aria-hidden="true" />;
- if (state === 'missing') return <XCircle size={12} aria-hidden="true" />;
- return <HelpCircle size={12} aria-hidden="true" />;
-}
-
-export default function Email() {
- const { t } = useTranslation();
- const [activeTab] = useTabParam('/email', VALID_TABS);
-
- const [status, setStatus] = useState(null);
- const [domains, setDomains] = useState([]);
- const [loading, setLoading] = useState(true);
-
- const loadStatus = useCallback(async () => {
- try {
- const res = await api.getEmailStatus();
- setStatus(res?.status || res || null);
- } catch {
- setStatus(null);
- }
- }, []);
-
- const loadDomains = useCallback(async () => {
- try {
- const res = await api.getEmailDomains();
- setDomains(res?.domains || res || []);
- } catch {
- setDomains([]);
- }
- }, []);
-
- useEffect(() => {
- let alive = true;
- (async () => {
- await Promise.all([loadStatus(), loadDomains()]);
- if (alive) setLoading(false);
- })();
- return () => { alive = false; };
- }, [loadStatus, loadDomains]);
-
- const installed = status?.installed ?? status?.is_installed ?? (status != null && status.components != null);
-
- const tabs = VALID_TABS.map((t) => ({
- to: `/email/${t}`,
- label: t.charAt(0).toUpperCase() + t.slice(1),
- end: false,
- }));
-
- return (
- <PageLayout
- navLabel="Email Server"
- tabs={tabs}
- actions={(
- <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadDomains(); }}>
- <RefreshCw size={14} /> {t('common.actions.refresh', 'Refresh')}
- </Button>
- )}
- >
- <div className="sk-email">
- {loading ? (
- <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>
- ) : (
- <>
- {activeTab === 'overview' && (
- <OverviewTab status={status} installed={installed} onChange={loadStatus} />
- )}
- {activeTab === 'domains' && (
- <DomainsTab domains={domains} onChange={loadDomains} />
- )}
- {activeTab === 'accounts' && (
- <AccountsTab domains={domains} />
- )}
- {activeTab === 'relay' && <RelayTab />}
- {activeTab === 'spam' && <SpamTab />}
- {activeTab === 'webmail' && <WebmailTab />}
- {activeTab === 'queue' && <QueueTab />}
- </>
- )}
- </div>
- </PageLayout>
- );
-}
-
-// ---------- Overview ----------
-function OverviewTab({ status, installed, onChange }) {
- const { t } = useTranslation();
- const toast = useToast();
- const [installError, setInstallError] = useState(null);
- const components = status?.components || {};
- const names = Object.keys(components);
-
- // install_all answers {error, results: {postfix: {success, error}, ...}},
- // and the API client hangs that body off the thrown error as err.data. Dig
- // the failing components' stderr out of `results` so the user sees WHICH
- // component failed and why instead of a bare "Install failed". More than
- // one can fail in a single call: the installer only returns early on
- // postfix and dovecot, and lets dkim/spamassassin fall through.
- const installFailures = (err) => Object.entries(err?.data?.results || {})
- .filter(([, r]) => r && r.success === false)
- .map(([component, r]) => `${component}: ${r.error || 'unknown error'}`);
-
- const install = async () => {
- setInstallError(null);
- try {
- await api.installEmailServer();
- toast.success(t('app.email.emailServerInstallStarted', 'Email server install started'));
- onChange();
- } catch (err) {
- // err.message is the server's top-line reason ("Postfix
- // installation failed"); the failures carry the actual stderr.
- const summary = err?.message || 'Install failed';
- const failures = installFailures(err);
- // The toast stays one line — the inline block below keeps the full
- // detail on screen after the toast has gone.
- setInstallError([summary, ...failures].join('\n'));
- toast.error(failures.length ? `${summary} — ${failures[0]}` : summary);
- }
- };
-
- const control = async (component, action) => {
- try {
- await api.controlEmailService(component, action);
- toast.success(`${component}: ${action}`);
- onChange();
- } catch {
- toast.error(t('app.email.failedTo', 'Failed to {{action}} {{component}}', { action: action, component: component }));
- }
- };
-
- if (!installed) {
- return (
- <div className="sk-email__hero">
- <EmptyState
- icon={Server}
- title={t('app.email.mailServerNotInstalled', 'Mail server not installed')}
- description={t('app.email.mostPanelsNeverRunAMail', 'Most panels never run a mail server, install it when you need it.')}
- action={(
- <Button size="sm" onClick={install}>
- <Plus size={14} /> {t('app.email.installMailServer', 'Install mail server')}
- </Button>
- )}
- />
- <p className="sk-email__hero-note">
- {t('app.email.aDeliverabilityPreflightPtrPort25', 'A deliverability preflight (PTR, port 25, RBL) gates outbound sending before mail can leave this host.')}
- </p>
- {installError && (
- <p className="sk-email__hero-error" role="alert">{installError}</p>
- )}
- </div>
- );
- }
-
- const serviceRows = names.map((name) => {
- const running = components[name]?.running ?? components[name] === 'running';
- return { id: name, name, running };
- });
-
- const serviceColumns = [
- { key: 'component', headerKey: 'app.email.component', header: 'Component', sortable: true, hideable: false, sortValue: (r) => r.name, render: (r) => r.name },
- {
- key: 'state',
- headerKey: 'common.labels.state', header: 'State',
- sortable: true,
- sortValue: (r) => (r.running ? 1 : 0),
- render: (r) => <Pill kind={r.running ? 'green' : 'red'}>{r.running ? 'Running' : 'Stopped'}</Pill>,
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (r) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => control(r.name, r.running ? 'restart' : 'start')}>
- {r.running ? 'Restart' : 'Start'}
- </Button>
- {r.running && (
- <Button variant="ghost" size="sm" onClick={() => control(r.name, 'stop')}>{t('common.actions.stop', 'Stop')}</Button>
- )}
- </div>
- ),
- },
- ];
-
- return (
- <section className="sk-email__section">
- <KpiBand>
- <MetricCard label={t('common.labels.domains', 'Domains')} value={status?.domains_count ?? 0} tone="accent" icon={<Globe size={16} />} />
- <MetricCard label={t('app.email.accounts', 'Accounts')} value={status?.accounts_count ?? 0} tone="cyan" icon={<Users size={16} />} />
- <MetricCard label={t('app.email.queue', 'Queue')} value={status?.queue_count ?? 0} tone="amber" icon={<Inbox size={16} />} />
- </KpiBand>
-
- <h2 className="sk-email__section-title"><Server size={16} /> {t('common.labels.services', 'Services')}</h2>
- <DataTable
- columns={serviceColumns}
- data={serviceRows}
- keyField="id"
- storageKey="serverkit-table-email-components"
- footer={<DataTableFooter shown={serviceRows.length} total={serviceRows.length} noun="service" />}
- emptyTitle="No service components reported."
- emptyMessage=""
- />
- </section>
- );
-}
-
-// ---------- Domains ----------
-function DomainsTab({ domains, onChange }) {
- const { t } = useTranslation();
- const toast = useToast();
- const { confirm } = useConfirm();
- const [newDomain, setNewDomain] = useState('');
- const [verifying, setVerifying] = useState({});
- const [dnsResults, setDnsResults] = useState({});
-
- const add = async (e) => {
- e.preventDefault();
- if (!newDomain.trim()) return;
- try {
- await api.addEmailDomain({ name: newDomain.trim() });
- toast.success(t('app.email.domainAdded', 'Domain added'));
- setNewDomain('');
- onChange();
- } catch {
- toast.error(t('app.email.couldNotAddDomain', 'Could not add domain'));
- }
- };
-
- const remove = async (domain) => {
- const ok = await confirm({
- title: t('app.email.deleteDomain', 'Delete domain'),
- message: t('app.email.deleteAndAllOfItsAccounts', 'Delete {{name}} and all of its accounts and aliases?', { name: domain.name }),
- confirmLabel: t('common.actions.delete', 'Delete'),
- danger: true,
- });
- if (!ok) return;
- try {
- await api.deleteEmailDomain(domain.id);
- toast.success(t('app.email.domainDeleted', 'Domain deleted'));
- onChange();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const verify = async (domain) => {
- setVerifying((v) => ({ ...v, [domain.id]: true }));
- try {
- const res = await api.verifyEmailDNS(domain.id);
- setDnsResults((r) => ({ ...r, [domain.id]: res?.records || res || {} }));
- toast.success(t('app.email.dnsChecked', 'DNS checked'));
- } catch {
- toast.error(t('app.email.dnsCheckFailed', 'DNS check failed'));
- } finally {
- setVerifying((v) => ({ ...v, [domain.id]: false }));
- }
- };
-
- const deploy = async (domain) => {
- try {
- await api.deployEmailDNS(domain.id);
- toast.success(t('app.email.dnsRecordsDeployedToProvider', 'DNS records deployed to provider'));
- } catch {
- toast.error(t('app.email.deployFailedNoLinkedDnsProvider', 'Deploy failed (no linked DNS provider?)'));
- }
- };
-
- return (
- <section className="sk-email__section">
- <form className="sk-email__add" onSubmit={add}>
- <Input
- value={newDomain}
- onChange={(e) => setNewDomain(e.target.value)}
- placeholder="example.com"
- aria-label={t('app.email.newMailDomain', 'New mail domain')}
- />
- <Button type="submit" size="sm"><Plus size={14} /> {t('app.email.addDomain', 'Add domain')}</Button>
- </form>
-
- {domains.length === 0 ? (
- <div className="sk-email__empty">
- <Globe size={24} aria-hidden="true" />
- <p>{t('app.email.noMailDomainsYet', 'No mail domains yet.')}</p>
- </div>
- ) : (
- <ul className="sk-email__domains">
- {domains.map((domain) => {
- const dns = deriveDnsStatus(domain, dnsResults[domain.id]);
- return (
- <li key={domain.id} className="sk-email__domain">
- <div className="sk-email__domain-head">
- <span className="sk-email__domain-name">{domain.name}</span>
- <Pill kind={domain.is_active ? 'green' : 'gray'}>
- {domain.is_active ? 'Active' : 'Disabled'}
- </Pill>
- </div>
-
- <div className="sk-email__dns">
- {DNS_RECORDS.map(({ key, label }) => (
- <Pill key={key} kind={dnsPillKind(dns[key])} title={`${label}: ${dns[key]}`}>
- <DnsIcon state={dns[key]} /> {label}
- </Pill>
- ))}
- </div>
-
- <div className="sk-email__domain-meta">
- <span>{domain.accounts_count ?? 0} accounts</span>
- <span>{domain.aliases_count ?? 0} aliases</span>
- {domain.dkim_selector && <span>{t('app.email.dkimSelector', 'DKIM selector:')} {domain.dkim_selector}</span>}
- </div>
-
- <div className="sk-email__actions">
- <Button
- variant="outline"
- size="sm"
- onClick={() => verify(domain)}
- disabled={verifying[domain.id]}
- >
- <ShieldCheck size={14} /> {verifying[domain.id] ? 'Checking…' : 'Verify DNS'}
- </Button>
- <Button variant="outline" size="sm" onClick={() => deploy(domain)}>
- <ExternalLink size={14} /> {t('app.email.deployDns', 'Deploy DNS')}
- </Button>
- <Button variant="ghost" size="sm" onClick={() => remove(domain)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </section>
- );
-}
-
-// ---------- Accounts ----------
-
-// Percent of an account's own quota in use, so a 200 MB mailbox on a 250 MB
-// quota outranks a 2 GB one on 20 GB. null — not 0 — when no quota is set:
-// an unlimited mailbox can never be "nearly full", and the rule engine drops
-// nulls from every numeric comparison rather than reading them as empty.
-function quotaPercent(account) {
- const total = account?.quota_mb ?? 0;
- if (!total) return null;
- return Math.round(((account.quota_used_mb ?? 0) / total) * 100);
-}
-
-// Built-in saved views for the accounts table.
-//
-// The rules match on what the State column's `value` accessor returns (the
-// label the pill shows), NOT on the 1/0 its sortValue produces — filtering a
-// string against a numeric rank is the one mistake that makes a preset match
-// zero rows while looking perfectly correct.
-const ACCOUNT_VIEWS = [
- { name: 'Active first', state: { search: '', sorts: [{ key: 'state', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- { name: 'Largest quota', state: { search: '', sorts: [{ key: 'quota', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- {
- // A disabled mailbox still exists and still holds its mail — it just
- // cannot authenticate. This is the list you audit after an offboarding.
- name: 'Disabled',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'email', direction: 'asc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'ac1', field: 'state', op: 'any', value: ['Disabled'] }],
- },
- },
- },
- {
- // Mailboxes about to start rejecting deliveries. Same 85% threshold the
- // fleet uses for disk pressure, and `gt` on a null keeps the unlimited
- // mailboxes out instead of ranking them as 0%.
- name: 'Nearly full',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'used', direction: 'desc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'ac2', field: 'used', op: 'gt', value: 85 }],
- },
- },
- },
-];
-
-function AccountsTab({ domains }) {
- const { t } = useTranslation();
- const toast = useToast();
- const { confirm } = useConfirm();
- const [domainId, setDomainId] = useState(domains[0]?.id ? String(domains[0].id) : '');
- const [accounts, setAccounts] = useState([]);
- const [loading, setLoading] = useState(false);
- const [search, setSearch] = useState('');
- const [form, setForm] = useState({ username: '', password: '', quota_mb: 1024 });
- const { sorts, setSorts } = useTableSort({ storageKey: 'serverkit-table-email-accounts-sort' });
- const { hiddenKeys, setHiddenKeys } = useColumnVisibility({ storageKey: 'serverkit-table-email-accounts-cols' });
-
- // The only view state this tab owns privately. Everything else — sorts,
- // hidden columns, column order, the column rules — is the shared envelope
- // useTableChrome captures for us. The selected domain deliberately stays
- // OUT of it: it is which list you are looking at, not how you are looking
- // at it, and a saved view that silently jumped domains would be a trap.
- const viewPageState = useMemo(() => ({ search }), [search]);
- const applyViewPageState = useCallback((saved) => {
- if (saved.search !== undefined) setSearch(saved.search);
- }, []);
-
- const load = useCallback(async () => {
- if (!domainId) { setAccounts([]); return; }
- setLoading(true);
- try {
- const res = await api.getEmailAccounts(domainId);
- setAccounts(res?.accounts || res || []);
- } catch {
- setAccounts([]);
- } finally {
- setLoading(false);
- }
- }, [domainId]);
-
- useEffect(() => { load(); }, [load]);
-
- const create = async (e) => {
- e.preventDefault();
- if (!form.username.trim() || !form.password) return;
- try {
- await api.createEmailAccount(domainId, form);
- toast.success(t('app.email.accountCreated', 'Account created'));
- setForm({ username: '', password: '', quota_mb: 1024 });
- load();
- } catch {
- toast.error(t('app.email.createFailed', 'Create failed'));
- }
- };
-
- const remove = async (account) => {
- const ok = await confirm({
- title: t('app.email.deleteAccount', 'Delete account'),
- message: t('app.email.delete3', 'Delete {{email}}?', { email: account.email }),
- confirmLabel: t('common.actions.delete', 'Delete'),
- danger: true,
- });
- if (!ok) return;
- try {
- await api.deleteEmailAccount(account.id);
- toast.success(t('app.email.accountDeleted', 'Account deleted'));
- load();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const filtered = useMemo(() => {
- const q = search.trim().toLowerCase();
- if (!q) return accounts;
- return accounts.filter((a) => (a.email || '').toLowerCase().includes(q));
- }, [accounts, search]);
-
- const accountColumns = [
- {
- key: 'email',
- headerKey: 'app.email.address', header: 'Address',
- sortable: true,
- hideable: false,
- sortValue: (a) => a.email || '',
- render: (a) => <span className="sk-email__mono">{a.email}</span>,
- },
- {
- key: 'quota',
- headerKey: 'app.email.quota', header: 'Quota',
- sortable: true,
- type: 'num',
- unit: ' MB',
- // The allocation, which is what "Largest quota" orders by. How full
- // it is lives in its own column below.
- value: (a) => a.quota_mb ?? 0,
- sortValue: (a) => a.quota_mb ?? 0,
- render: (a) => `${a.quota_used_mb ?? 0} / ${a.quota_mb ?? 0} MB`,
- },
- {
- key: 'used',
- headerKey: 'app.email.used', header: 'Used',
- sortable: true,
- type: 'num',
- unit: '%',
- value: quotaPercent,
- sortValue: quotaPercent,
- render: (a) => {
- const pct = quotaPercent(a);
- return pct == null ? '—' : `${pct}%`;
- },
- },
- {
- key: 'state',
- headerKey: 'common.labels.state', header: 'State',
- sortable: true,
- // Filter on the label the pill shows; keep the 1/0 sortValue so
- // "Active first" still puts active first when the column sorts desc.
- type: 'enum',
- value: (a) => (a.is_active ? 'Active' : 'Disabled'),
- sortValue: (a) => (a.is_active ? 1 : 0),
- render: (a) => <Pill kind={a.is_active ? 'green' : 'gray'}>{a.is_active ? 'Active' : 'Disabled'}</Pill>,
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (a) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => remove(a)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- ),
- },
- ];
-
- // Each tab is its own route, so only one picker is ever mounted — this
- // chrome is scoped to the accounts table alone and keeps its own page key.
- const chrome = useTableChrome({
- columns: accountColumns,
- rows: filtered,
- viewPageKey: 'email-accounts',
- builtinViews: ACCOUNT_VIEWS,
- noun: 'accounts',
- sorts,
- setSorts,
- hiddenKeys,
- setHiddenKeys,
- pageState: viewPageState,
- applyPage: applyViewPageState,
- });
-
- if (domains.length === 0) {
- return (
- <div className="sk-email__empty">
- <Users size={24} aria-hidden="true" />
- <p>{t('app.email.addAMailDomainFirst', 'Add a mail domain first.')}</p>
- </div>
- );
- }
-
- return (
- <section className="sk-email__section">
- {/* One row of chrome: the view name and the table's own controls.
- What stays in the toolbar below is not chrome — the domain
- select is WHICH list you are looking at. */}
- <GridViewPicker
- views={chrome.views}
- label="accounts"
- onCreate={chrome.createView}
- actions={(
- <>
- <GridFilterButton
- count={chrome.filterCount}
- onClick={() => chrome.setDrawerOpen(true)}
- />
- <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
- </>
- )}
- />
- <ListToolbar className="sk-email__filters">
- <label>
- {t('common.labels.domain', 'Domain')}
- <select value={domainId} onChange={(e) => setDomainId(e.target.value)}>
- {domains.map((d) => <option key={d.id} value={String(d.id)}>{d.name}</option>)}
- </select>
- </label>
- <label className="search-box">
- <Search size={16} />
- <Input
- type="text"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder={t('app.email.searchAccountsByAddress', 'Search accounts by address…')}
- aria-label={t('app.email.searchAccounts', 'Search accounts')}
- />
- </label>
- </ListToolbar>
-
- <GridChips {...chrome.chipProps} />
-
- <form className="sk-email__add" onSubmit={create}>
- <Input
- value={form.username}
- onChange={(e) => setForm({ ...form, username: e.target.value })}
- placeholder="username"
- aria-label={t('app.email.mailboxUsername', 'Mailbox username')}
- />
- <Input
- type="password"
- value={form.password}
- onChange={(e) => setForm({ ...form, password: e.target.value })}
- placeholder="password"
- aria-label={t('app.email.mailboxPassword', 'Mailbox password')}
- />
- <Input
- type="number"
- value={form.quota_mb}
- onChange={(e) => setForm({ ...form, quota_mb: Number(e.target.value) })}
- placeholder={t('app.email.quotaMb', 'Quota (MB)')}
- aria-label={t('app.email.quotaInMb', 'Quota in MB')}
- />
- <Button type="submit" size="sm"><Plus size={14} /> {t('common.actions.create', 'Create')}</Button>
- </form>
-
- <DataTable
- columns={chrome.columns}
- data={filtered}
- keyField="id"
- sorts={sorts}
- onSortsChange={setSorts}
- {...chrome.tableProps}
- loading={loading}
- footer={<DataTableFooter shown={filtered.length} total={accounts.length} noun="account" />}
- emptyTitle={accounts.length === 0 ? 'No accounts in this domain.' : 'No accounts match this search.'}
- emptyMessage=""
- />
-
- <GridFilterDrawer {...chrome.drawerProps} />
- </section>
- );
-}
-
-// ---------- Relay (smarthost) ----------
-function RelayTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [relay, setRelay] = useState({ host: '', port: 587, username: '', password: '', enabled: false });
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- let alive = true;
- api.getEmailRelay()
- .then((res) => { if (alive) setRelay((r) => ({ ...r, ...(res?.relay || res || {}) })); })
- .catch(() => { /* defaults */ })
- .finally(() => { if (alive) setLoading(false); });
- return () => { alive = false; };
- }, []);
-
- const save = async (e) => {
- e.preventDefault();
- try {
- await api.updateEmailRelay(relay);
- toast.success(t('app.email.relaySaved', 'Relay saved'));
- } catch {
- toast.error(t('app.email.saveFailed', 'Save failed'));
- }
- };
-
- const test = async () => {
- try {
- await api.testEmailRelay(relay);
- toast.success(t('app.email.relayReachable', 'Relay reachable'));
- } catch {
- toast.error(t('app.email.relayTestFailed', 'Relay test failed'));
- }
- };
-
- const disable = async () => {
- try {
- await api.disableEmailRelay();
- setRelay((r) => ({ ...r, enabled: false }));
- toast.success(t('app.email.relayDisabled', 'Relay disabled'));
- } catch {
- toast.error(t('app.email.failedToDisableRelay', 'Failed to disable relay'));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Send size={16} /> {t('app.email.outboundRelaySmarthost', 'Outbound relay (smarthost)')}</h2>
- <form className="sk-email__form" onSubmit={save}>
- <label>{t('app.email.host', 'Host')}<Input value={relay.host || ''} onChange={(e) => setRelay({ ...relay, host: e.target.value })} placeholder="smtp.provider.com" /></label>
- <label>{t('common.labels.port', 'Port')}<Input type="number" value={relay.port || 587} onChange={(e) => setRelay({ ...relay, port: Number(e.target.value) })} /></label>
- <label>{t('common.labels.username', 'Username')}<Input value={relay.username || ''} onChange={(e) => setRelay({ ...relay, username: e.target.value })} /></label>
- <label>{t('common.labels.password', 'Password')}<Input type="password" value={relay.password || ''} onChange={(e) => setRelay({ ...relay, password: e.target.value })} /></label>
- <label className="sk-email__check">
- <input type="checkbox" checked={!!relay.enabled} onChange={(e) => setRelay({ ...relay, enabled: e.target.checked })} />
- {t('app.email.enableRelay', 'Enable relay')}
- </label>
- <div className="sk-email__actions">
- <Button type="submit" size="sm">{t('common.actions.save', 'Save')}</Button>
- <Button type="button" variant="outline" size="sm" onClick={test}>{t('common.actions.test', 'Test')}</Button>
- <Button type="button" variant="ghost" size="sm" onClick={disable}>{t('common.actions.disable', 'Disable')}</Button>
- </div>
- </form>
- </section>
- );
-}
-
-// ---------- Spam ----------
-function SpamTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [config, setConfig] = useState({ enabled: true, required_score: 5 });
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- let alive = true;
- api.getSpamConfig()
- .then((res) => { if (alive) setConfig((c) => ({ ...c, ...(res?.config || res || {}) })); })
- .catch(() => { /* defaults */ })
- .finally(() => { if (alive) setLoading(false); });
- return () => { alive = false; };
- }, []);
-
- const save = async (e) => {
- e.preventDefault();
- try {
- await api.updateSpamConfig(config);
- toast.success(t('app.email.spamConfigSaved', 'Spam config saved'));
- } catch {
- toast.error(t('app.email.saveFailed', 'Save failed'));
- }
- };
-
- const updateRules = async () => {
- try {
- await api.updateSpamRules();
- toast.success(t('app.email.ruleUpdateStarted', 'Rule update started'));
- } catch {
- toast.error(t('app.email.ruleUpdateFailed', 'Rule update failed'));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Filter size={16} /> {t('app.email.spamassassin', 'SpamAssassin')}</h2>
- <form className="sk-email__form" onSubmit={save}>
- <label className="sk-email__check">
- <input type="checkbox" checked={!!config.enabled} onChange={(e) => setConfig({ ...config, enabled: e.target.checked })} />
- {t('app.email.enableSpamFiltering', 'Enable spam filtering')}
- </label>
- <label>{t('app.email.requiredScore', 'Required score')}<Input type="number" step="0.1" value={config.required_score ?? 5} onChange={(e) => setConfig({ ...config, required_score: Number(e.target.value) })} /></label>
- <div className="sk-email__actions">
- <Button type="submit" size="sm">{t('common.actions.save', 'Save')}</Button>
- <Button type="button" variant="outline" size="sm" onClick={updateRules}>{t('app.email.updateRules', 'Update rules')}</Button>
- </div>
- </form>
- </section>
- );
-}
-
-// ---------- Webmail ----------
-function WebmailTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [state, setState] = useState(null);
- const [loading, setLoading] = useState(true);
-
- const load = useCallback(async () => {
- try {
- const res = await api.getWebmailStatus();
- setState(res?.status || res || null);
- } catch {
- setState(null);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => { load(); }, [load]);
-
- const install = async () => {
- try {
- await api.installWebmail();
- toast.success(t('app.email.webmailInstallStarted', 'Webmail install started'));
- load();
- } catch {
- toast.error(t('app.email.installFailed', 'Install failed'));
- }
- };
-
- const control = async (action) => {
- try {
- await api.controlWebmail(action);
- toast.success(t('app.email.webmail', 'Webmail: {{action}}', { action: action }));
- load();
- } catch {
- toast.error(t('app.email.failedToWebmail', 'Failed to {{action}} webmail', { action: action }));
- }
- };
-
- if (loading) return <div className="sk-email__empty">{t('common.loading', 'Loading…')}</div>;
-
- const installed = state?.installed ?? state?.is_installed;
- const running = state?.running;
-
- return (
- <section className="sk-email__section">
- <h2 className="sk-email__section-title"><Inbox size={16} /> {t('app.email.roundcubeWebmail', 'Roundcube webmail')}</h2>
- {!installed ? (
- <div className="sk-email__empty">
- <p>{t('app.email.webmailIsNotInstalled', 'Webmail is not installed.')}</p>
- <Button size="sm" onClick={install}><Plus size={14} /> {t('app.email.installWebmail', 'Install webmail')}</Button>
- </div>
- ) : (
- <div className="sk-email__actions">
- <Pill kind={running ? 'green' : 'red'}>{running ? 'Running' : 'Stopped'}</Pill>
- <Button variant="outline" size="sm" onClick={() => control(running ? 'restart' : 'start')}>
- {running ? 'Restart' : 'Start'}
- </Button>
- {running && <Button variant="ghost" size="sm" onClick={() => control('stop')}>{t('common.actions.stop', 'Stop')}</Button>}
- </div>
- )}
- </section>
- );
-}
-
-// ---------- Mail queue ----------
-
-// Built-in saved views for the queue.
-//
-// The queue payload is `mailq` output — a queue id, a byte size, a sender and
-// its recipients. There is no status field, so nothing here pretends there is
-// one: the only rule-based preset filters on `size`, which is a real integer on
-// every row (see PostfixService.get_queue).
-const QUEUE_VIEWS = [
- { name: 'Largest first', state: { search: '', sorts: [{ key: 'size', direction: 'desc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- { name: 'By sender', state: { search: '', sorts: [{ key: 'sender', direction: 'asc' }], hiddenKeys: [], columnFilters: NO_RULES } },
- {
- // What a backed-up queue is usually full of. 100 KB is the line between
- // a plain message (a few KB) and one carrying an attachment; Postfix's
- // own message_size_limit is 25 MB, so this is well inside real traffic.
- name: 'Large messages',
- state: {
- search: '', hiddenKeys: [],
- sorts: [{ key: 'size', direction: 'desc' }],
- columnFilters: {
- match: 'all',
- rules: [{ id: 'q1', field: 'size', op: 'gt', value: 102400 }],
- },
- },
- },
-];
-
-function QueueTab() {
- const { t } = useTranslation();
- const toast = useToast();
- const [queue, setQueue] = useState([]);
- const [loading, setLoading] = useState(true);
- const [search, setSearch] = useState('');
- const { sorts, setSorts } = useTableSort({ storageKey: 'serverkit-table-email-queue-sort' });
- const { hiddenKeys, setHiddenKeys } = useColumnVisibility({ storageKey: 'serverkit-table-email-queue-cols' });
-
- // Search is all this tab owns privately; the rest of the view state is the
- // shared envelope useTableChrome captures.
- const viewPageState = useMemo(() => ({ search }), [search]);
- const applyViewPageState = useCallback((saved) => {
- if (saved.search !== undefined) setSearch(saved.search);
- }, []);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const res = await api.getMailQueue();
- setQueue(res?.queue || res || []);
- } catch {
- setQueue([]);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => { load(); }, [load]);
-
- const flush = async () => {
- try {
- await api.flushMailQueue();
- toast.success(t('app.email.queueFlushed', 'Queue flushed'));
- load();
- } catch {
- toast.error(t('app.email.flushFailed', 'Flush failed'));
- }
- };
-
- const remove = async (id) => {
- try {
- await api.deleteMailQueueItem(id);
- load();
- } catch {
- toast.error(t('app.email.deleteFailed', 'Delete failed'));
- }
- };
-
- const filtered = queue.filter((item) => {
- const q = search.trim().toLowerCase();
- if (!q) return true;
- const id = String(item.id || item.queue_id || '').toLowerCase();
- const sender = String(item.sender || '').toLowerCase();
- const recipient = String(item.recipient || '').toLowerCase();
- return id.includes(q) || sender.includes(q) || recipient.includes(q);
- });
-
- const queueColumns = [
- {
- key: 'id',
- header: 'ID',
- sortable: true,
- hideable: false,
- sortValue: (item) => item.id || item.queue_id || '',
- render: (item) => <span className="sk-email__mono">{item.id || item.queue_id}</span>,
- },
- { key: 'sender', headerKey: 'app.email.sender', header: 'Sender', sortable: true, sortValue: (item) => item.sender || null, render: (item) => item.sender || '-' },
- { key: 'recipient', headerKey: 'app.email.recipient', header: 'Recipient', sortable: true, sortValue: (item) => item.recipient || null, render: (item) => item.recipient || '-' },
- {
- key: 'size',
- headerKey: 'common.labels.size', header: 'Size',
- sortable: true,
- // Bytes, straight off mailq. Typed explicitly because a preset
- // filters on it — inference would land on 'num' here anyway, but
- // only for as long as every loaded row happens to carry a size.
- type: 'num',
- unit: ' bytes',
- value: (item) => item.size ?? null,
- sortValue: (item) => item.size ?? null,
- render: (item) => item.size || '-',
- },
- {
- key: 'actions',
- header: '',
- hideable: false,
- className: 'sk-email__actions-col',
- cellClassName: 'sk-email__actions-cell',
- render: (item) => (
- <div className="sk-email__actions">
- <Button variant="ghost" size="sm" onClick={() => remove(item.id || item.queue_id)}>
- <Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
- </Button>
- </div>
- ),
- },
- ];
-
- const chrome = useTableChrome({
- columns: queueColumns,
- rows: filtered,
- viewPageKey: 'email-queue',
- builtinViews: QUEUE_VIEWS,
- noun: 'messages',
- sorts,
- setSorts,
- hiddenKeys,
- setHiddenKeys,
- pageState: viewPageState,
- applyPage: applyViewPageState,
- });
-
- return (
- <section className="sk-email__section">
- {/* Everything that acts on the queue rides the view line, in the
- same order the topbar pages use: action, search, filter, "⋮".
- Refresh is not repeated as a button — it is in the "⋮". */}
- <GridViewPicker
- views={chrome.views}
- label="messages"
- onCreate={chrome.createView}
- actions={(
- <>
- <Button variant="outline" size="sm" onClick={flush}>{t('app.email.flushQueue', 'Flush queue')}</Button>
- <SearchField
- value={search}
- onSearch={setSearch}
- placeholder={t('app.email.searchQueueBySenderRecipientOr', 'Search queue by sender, recipient, or ID…')}
- />
- <GridFilterButton
- count={chrome.filterCount}
- onClick={() => chrome.setDrawerOpen(true)}
- />
- <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
- </>
- )}
- />
-
- <GridChips {...chrome.chipProps} />
-
- <DataTable
- columns={chrome.columns}
- data={filtered}
- keyField={(item) => item.id || item.queue_id}
- sorts={sorts}
- onSortsChange={setSorts}
- {...chrome.tableProps}
- loading={loading}
- footer={<DataTableFooter shown={filtered.length} total={queue.length} noun="message" />}
- emptyTitle={queue.length === 0 ? 'The mail queue is empty.' : 'No messages match this search.'}
- emptyMessage=""
- />
-
- <GridFilterDrawer {...chrome.drawerProps} />
- </section>
- );
-}
diff --git a/frontend/src/plugins/serverkit-email/plugin.json b/frontend/src/plugins/serverkit-email/plugin.json
deleted file mode 100644
index 8db3c5f8..00000000
--- a/frontend/src/plugins/serverkit-email/plugin.json
+++ /dev/null
@@ -1,51 +0,0 @@
-{
- "name": "serverkit-email",
- "display_name": "Email Server",
- "version": "1.0.0",
- "description": "Full mail-server stack with Postfix/Dovecot, domains, mailboxes, aliases, DKIM/SPF/DMARC, SpamAssassin filtering, and Roundcube webmail. Most panels never run a mail server, so it ships as an opt-in extension.",
- "author": "ServerKit",
- "license": "MIT",
- "category": "integration",
- "homepage": "https://github.com/jhd3197/ServerKit",
- "permissions": [
- "shell",
- "filesystem",
- "network"
- ],
- "min_panel_version": "1.7.0",
- "entry_point": "email:email_bp",
- "url_prefix": "/api/v1/email",
- "icon": "<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\"/>",
- "contributions": {
- "nav": [
- {
- "id": "email",
- "label": "Email Server",
- "route": "/email",
- "category": "operations",
- "icon": "<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\"/>"
- }
- ],
- "routes": [
- {
- "path": "email",
- "component": "EmailPage"
- },
- {
- "path": "email/:tab",
- "component": "EmailPage"
- }
- ],
- "page_titles": {
- "/email": "Email Server"
- },
- "command_palette": [
- {
- "label": "Email",
- "path": "/email",
- "category": "Pages",
- "keywords": "smtp postfix dovecot mail imap dkim webmail"
- }
- ]
- }
-}
diff --git a/frontend/src/plugins/serverkit-email/services/email.js b/frontend/src/plugins/serverkit-email/services/email.js
deleted file mode 100644
index 78e811ab..00000000
--- a/frontend/src/plugins/serverkit-email/services/email.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// The extension's own /api/v1/email client, built on the panel's ApiClient
-// via the SDK singleton (JWT refresh, workspace headers, error normalization
-// included) — moved out of the host's services/api/system.js with the page.
-//
-// Two email surfaces deliberately STAY core and are not duplicated here:
-// the DNS-provider connections (/email/dns-providers — a core blueprint that
-// keeps its historical prefix) and the Settings → Connections relay tile's
-// calls. The relay methods below are this extension's own copies for the
-// Relay tab; the page and the Settings tile hit the same endpoints.
-import { api } from 'serverkit-sdk';
-
-const emailApi = {
- // Server
- getEmailStatus: () => api.request('/email/status'),
- installEmailServer: (data = {}) => api.request('/email/install', { method: 'POST', body: JSON.stringify(data) }),
- controlEmailService: (component, action) => api.request(`/email/service/${component}/${action}`, { method: 'POST' }),
-
- // Domains
- getEmailDomains: () => api.request('/email/domains'),
- addEmailDomain: (data) => api.request('/email/domains', { method: 'POST', body: JSON.stringify(data) }),
- getEmailDomain: (domainId) => api.request(`/email/domains/${domainId}`),
- deleteEmailDomain: (domainId) => api.request(`/email/domains/${domainId}`, { method: 'DELETE' }),
- verifyEmailDNS: (domainId) => api.request(`/email/domains/${domainId}/verify-dns`, { method: 'POST' }),
- deployEmailDNS: (domainId) => api.request(`/email/domains/${domainId}/deploy-dns`, { method: 'POST' }),
-
- // Accounts
- getEmailAccounts: (domainId) => api.request(`/email/domains/${domainId}/accounts`),
- createEmailAccount: (domainId, data) => api.request(`/email/domains/${domainId}/accounts`, { method: 'POST', body: JSON.stringify(data) }),
- getEmailAccount: (accountId) => api.request(`/email/accounts/${accountId}`),
- updateEmailAccount: (accountId, data) => api.request(`/email/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify(data) }),
- deleteEmailAccount: (accountId) => api.request(`/email/accounts/${accountId}`, { method: 'DELETE' }),
- changeEmailPassword: (accountId, password) => api.request(`/email/accounts/${accountId}/password`, { method: 'POST', body: JSON.stringify({ password }) }),
-
- // Aliases
- getEmailAliases: (domainId) => api.request(`/email/domains/${domainId}/aliases`),
- createEmailAlias: (domainId, data) => api.request(`/email/domains/${domainId}/aliases`, { method: 'POST', body: JSON.stringify(data) }),
- deleteEmailAlias: (aliasId) => api.request(`/email/aliases/${aliasId}`, { method: 'DELETE' }),
-
- // Forwarding
- getEmailForwarding: (accountId) => api.request(`/email/accounts/${accountId}/forwarding`),
- createEmailForwarding: (accountId, data) => api.request(`/email/accounts/${accountId}/forwarding`, { method: 'POST', body: JSON.stringify(data) }),
- updateEmailForwarding: (ruleId, data) => api.request(`/email/forwarding/${ruleId}`, { method: 'PUT', body: JSON.stringify(data) }),
- deleteEmailForwarding: (ruleId) => api.request(`/email/forwarding/${ruleId}`, { method: 'DELETE' }),
-
- // Outbound SMTP relay (smarthost)
- getEmailRelay: () => api.request('/email/relay'),
- updateEmailRelay: (data) => api.request('/email/relay', { method: 'PUT', body: JSON.stringify(data) }),
- testEmailRelay: (data) => api.request('/email/relay/test', { method: 'POST', body: JSON.stringify(data) }),
- disableEmailRelay: () => api.request('/email/relay', { method: 'DELETE' }),
-
- // SpamAssassin
- getSpamConfig: () => api.request('/email/spam/config'),
- updateSpamConfig: (data) => api.request('/email/spam/config', { method: 'PUT', body: JSON.stringify(data) }),
- updateSpamRules: () => api.request('/email/spam/update-rules', { method: 'POST' }),
-
- // Roundcube webmail
- getWebmailStatus: () => api.request('/email/webmail/status'),
- installWebmail: (data = {}) => api.request('/email/webmail/install', { method: 'POST', body: JSON.stringify(data) }),
- controlWebmail: (action) => api.request(`/email/webmail/service/${action}`, { method: 'POST' }),
- configureWebmailProxy: (domain) => api.request('/email/webmail/configure-proxy', { method: 'POST', body: JSON.stringify({ domain }) }),
-
- // Mail queue & logs
- getMailQueue: () => api.request('/email/queue'),
- flushMailQueue: () => api.request('/email/queue/flush', { method: 'POST' }),
- deleteMailQueueItem: (queueId) => api.request(`/email/queue/${queueId}`, { method: 'DELETE' }),
- getMailLogs: (lines = 100) => api.request(`/email/logs?lines=${lines}`),
-};
-
-export default emailApi;
diff --git a/frontend/src/plugins/serverkit-email/styles/email.scss b/frontend/src/plugins/serverkit-email/styles/email.scss
deleted file mode 100644
index 299ecb8c..00000000
--- a/frontend/src/plugins/serverkit-email/styles/email.scss
+++ /dev/null
@@ -1,277 +0,0 @@
-// Compiled through the extension's module graph (imported by index.jsx).
-// The host's design-token partial is imported via a sync-safe relative
-// path — the baked copy lives at frontend/src/plugins/serverkit-email/,
-// so this resolves to frontend/src/styles/_variables.scss.
-@import '../../../styles/variables';
-
-// ============================================
-// EMAIL SERVER PAGE (redesign — infra console look, REDESIGN_MAP #18):
-// status Pills on the Services list, MetricCard KPI strip (Overview),
-// dense .sk-dtable lists (services / accounts / queue), mono-uppercase
-// eyebrow section headers, token surfaces. Domains stay as a designed
-// card list. Class namespace = `sk-email` (the rebuilt Email.jsx emits it).
-//
-// Mail-volume chart, reputation/RBL ring, structured activity feed,
-// per-mailbox storage gauges and per-message retry are intentionally
-// absent — no backend yet (REDESIGN_MAP §5).
-// ============================================
-
-.sk-email {
- padding: $space-6;
-
- // ── Sections stack with breathing room ──────────────────
- &__section {
- display: flex;
- flex-direction: column;
- gap: $space-5;
- }
-
- // ── Mono-uppercase eyebrow section headers ──────────────
- &__section-title {
- display: flex;
- align-items: center;
- gap: $space-2;
- margin: 0;
- font-family: var(--mono);
- font-size: 10.5px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
-
- svg { color: var(--text-dim); }
- }
-
- // ── Empty / loading placeholders (shared look) ──────────
- &__empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: $space-2;
- padding: $space-6 $space-5;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- text-align: center;
- color: var(--text-dim);
- font-size: $font-size-sm;
-
- svg { color: var(--text-faint); }
-
- p { margin: 0; }
- }
-
- // ── Not-installed hero (EmptyState + preflight note) ─────
- &__hero {
- max-width: 560px;
- margin: $space-6 auto 0;
-
- .empty-state {
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- padding: $space-8 $space-6;
- }
- }
-
- &__hero-note {
- margin: $space-4 0 0;
- padding: $space-3 $space-4;
- background: var(--accent-bg);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 11.5px;
- line-height: 1.55;
- color: var(--text-dim);
- text-align: center;
- }
-
- // Inline install failure (component + stderr from the API) — same card
- // chrome as the hero note, in the danger tone. pre-line keeps one failing
- // component per line; anywhere stops a long unbroken stderr token from
- // widening the hero.
- &__hero-error {
- margin: $space-3 0 0;
- padding: $space-3 $space-4;
- background: var(--red-bg);
- border: 1px solid var(--red);
- border-radius: var(--radius);
- font-family: var(--mono);
- font-size: 11.5px;
- line-height: 1.55;
- color: var(--red);
- white-space: pre-line;
- overflow-wrap: anywhere;
- text-align: left;
- }
-
- // ── Action clusters (row actions, form buttons, toolbars) ─
- &__actions {
- display: flex;
- align-items: center;
- gap: $space-2;
- flex-wrap: wrap;
- }
-
- // Right-align the DataTable actions column
- &__actions-col { text-align: right; }
-
- &__actions-cell {
- text-align: right;
-
- .sk-email__actions { justify-content: flex-end; }
- }
-
- // ── Filters toolbar (domain select + search) ────────────
- // The row layout is the shared ListToolbar (.sk-listhead); this class
- // rides along on it to keep the eyebrow labels, select chrome and
- // search-box sizing below.
- &__filters {
- > label {
- display: flex;
- align-items: center;
- gap: $space-2;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
-
- select {
- padding: 6px 10px;
- background: var(--surface-2);
- border: 1px solid var(--border);
- border-radius: $radius-md;
- color: var(--text);
- font-family: $font-mono;
- font-size: $font-size-sm;
- cursor: pointer;
-
- &:focus {
- outline: none;
- border-color: var(--accent);
- }
- }
-
- // The global .search-box keeps its own chrome; just let it grow.
- .search-box {
- flex: 1;
- min-width: 220px;
- max-width: 360px;
- }
- }
-
- // ── Inline create/add forms (domain + account) ──────────
- &__add,
- &__form {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- gap: $space-3;
- padding: $space-4 $space-5;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
-
- label {
- display: flex;
- flex-direction: column;
- gap: $space-1;
- font-family: var(--mono);
- font-size: 10px;
- font-weight: $font-weight-semibold;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-faint);
- }
- }
-
- &__form { flex-direction: column; align-items: stretch; }
-
- // Checkbox rows keep sentence case (not eyebrow uppercase)
- &__check {
- flex-direction: row;
- align-items: center;
- gap: $space-2;
- font-family: inherit;
- font-size: $font-size-sm;
- font-weight: $font-weight-normal;
- letter-spacing: normal;
- text-transform: none;
- color: var(--text-dim);
- cursor: pointer;
-
- input[type='checkbox'] {
- width: 15px;
- height: 15px;
- accent-color: var(--accent);
- }
- }
-
- // ── Domains card list (kept as designed cards) ──────────
- &__domains {
- list-style: none;
- margin: 0;
- padding: 0;
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
- gap: $space-4;
- }
-
- &__domain {
- display: flex;
- flex-direction: column;
- gap: $space-3;
- padding: 15px 16px;
- background: var(--surface);
- border: 1px solid var(--border-soft);
- border-radius: var(--radius-lg);
- transition: border-color $transition-fast;
-
- &:hover { border-color: var(--border-strong); }
- }
-
- &__domain-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: $space-3;
- }
-
- &__domain-name {
- font-family: var(--mono);
- font-size: 13.5px;
- font-weight: $font-weight-semibold;
- color: var(--text);
- overflow-wrap: anywhere;
- }
-
- &__dns {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- }
-
- &__domain-meta {
- display: flex;
- flex-wrap: wrap;
- gap: $space-3;
- padding-top: $space-3;
- border-top: 1px solid var(--border-soft);
- font-family: var(--mono);
- font-size: 11.5px;
- color: var(--text-faint);
- }
-
- // ── Mono cell emphasis (queue ids, addresses) ───────────
- &__mono {
- font-family: var(--mono);
- font-size: 12.5px;
- color: var(--text);
- overflow-wrap: anywhere;
- }
-}