ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat: canonical domain + encryption key bootstrap
Juan Denis2b7a98c34891
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 3274dbd5..2c146e1a 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -45,9 +45,28 @@ def create_app(config_name=None):migrate.init_app(app, db)jwt.init_app(app)limiter.init_app(app)++ # Build CORS origins. Start with static config/env, then append the+ # persisted canonical domain from system settings so pointing an A record+ # at the panel works without restarting to edit .env.+ cors_origins = list(app.config['CORS_ORIGINS'])+ try:+ with app.app_context():+ from app.services.settings_service import SettingsService+ from app.utils.domain import canonical_origin+ canonical_domain = SettingsService.get('canonical_domain', '') or ''+ if canonical_domain:+ https_enabled = SettingsService.get('canonical_https_enabled', False) or False+ origin = canonical_origin(canonical_domain, https_enabled)+ if origin not in cors_origins:+ cors_origins.append(origin)+ except Exception:+ # Database may not exist yet during first install / migrations.+ pass+CORS(app,- origins=app.config['CORS_ORIGINS'],+ origins=cors_origins,supports_credentials=True,allow_headers=['Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key'],methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 143eeb2d..2d34fe02 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -9,6 +9,7 @@ from app.middleware.rbac import admin_required, get_current_userfrom app.services.audit_service import AuditServicefrom app.services.settings_service import SettingsServicefrom app.services.permission_service import PermissionService+from app.utils.domain import detect_request_domain, canonical_origin, is_valid_canonical_domainadmin_bp = Blueprint('admin', __name__)@@ -359,6 +360,58 @@ def update_setting(key):}), 200+@admin_bp.route('/settings/domain-detection', methods=['GET'])+@admin_required+def get_domain_detection():+ """Return the domain detected from the current request and current canonical setting."""+ detected_domain, is_https = detect_request_domain(request)+ current_domain = SettingsService.get('canonical_domain', '') or ''+ current_https = bool(SettingsService.get('canonical_https_enabled', False))+ return jsonify({+ 'detected_domain': detected_domain,+ 'is_https': is_https,+ 'current_canonical_domain': current_domain,+ 'current_canonical_https_enabled': current_https,+ 'current_canonical_origin': canonical_origin(current_domain, current_https) if current_domain else None,+ }), 200+++@admin_bp.route('/settings/canonical-domain', methods=['PUT'])+@admin_required+def set_canonical_domain():+ """Persist the canonical panel domain and HTTPS flag."""+ data = request.get_json() or {}+ domain = (data.get('domain') or '').strip().lower()+ https_enabled = bool(data.get('https_enabled', False))+ current_user_id = get_jwt_identity()++ if not domain:+ return jsonify({'error': 'domain is required'}), 400+ if not is_valid_canonical_domain(domain):+ return jsonify({'error': 'domain does not look like a valid canonical domain'}), 400++ old_domain = SettingsService.get('canonical_domain', '') or ''+ SettingsService.set('canonical_domain', domain, user_id=current_user_id)+ SettingsService.set('canonical_https_enabled', https_enabled, user_id=current_user_id)+ db.session.commit()++ AuditService.log_settings_change(+ user_id=current_user_id,+ key='canonical_domain',+ old_value=old_domain,+ new_value=domain+ )+ db.session.commit()++ return jsonify({+ 'message': 'Canonical domain updated',+ 'domain': domain,+ 'https_enabled': https_enabled,+ 'origin': canonical_origin(domain, https_enabled),+ 'restart_required': True,+ }), 200++# ============================================# Managed-sites domain & HTTPS (Phase 5)# ============================================diff --git a/backend/app/api/system.py b/backend/app/api/system.pyindex 668949b8..81e6e386 100644--- a/backend/app/api/system.py+++ b/backend/app/api/system.py@@ -197,9 +197,20 @@ def get_network_metrics():@system_bp.route('/health', methods=['GET'])def health_check():"""Health check endpoint - no auth required"""+ from app.utils.crypto import is_encryption_configured+ from app.services.settings_service import SettingsService+ from app.utils.domain import canonical_origin++ canonical_domain = SettingsService.get('canonical_domain', '') or ''+ https_enabled = bool(SettingsService.get('canonical_https_enabled', False))+return jsonify({'status': 'healthy',- 'service': 'serverkit-api'+ 'service': 'serverkit-api',+ 'encryption_configured': is_encryption_configured(),+ 'canonical_domain': canonical_domain,+ 'canonical_https_enabled': https_enabled,+ 'canonical_origin': canonical_origin(canonical_domain, https_enabled) if canonical_domain else None,}), 200diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex efb5553d..901c308d 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -62,6 +62,18 @@ class SettingsService:'type': 'boolean','description': 'Whether the wildcard certificate for the sites base domain is set up; managed subdomains serve HTTPS when true.'},+ # Canonical panel domain. When set, the panel uses this domain for+ # agent install commands, CORS origins, and optional IP redirects.+ 'canonical_domain': {+ 'value': '',+ 'type': 'string',+ 'description': 'Canonical domain for this ServerKit panel (e.g., serverkit.example.com). Used for agent URLs and CORS.'+ },+ 'canonical_https_enabled': {+ 'value': False,+ 'type': 'boolean',+ 'description': 'Whether the canonical domain is served over HTTPS. Controls CORS origins and agent install instructions.'+ },# SSO / OAuth settings'sso_google_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable Google OAuth login'},'sso_google_client_id': {'value': '', 'type': 'string', 'description': 'Google OAuth client ID'},diff --git a/backend/app/utils/crypto.py b/backend/app/utils/crypto.pyindex d3a6b2c4..98d2afa1 100644--- a/backend/app/utils/crypto.py+++ b/backend/app/utils/crypto.py@@ -6,8 +6,10 @@ Provides encryption/decryption for sensitive data like API secrets.import osimport base64+import reimport warningsimport logging+from pathlib import Pathfrom cryptography.fernet import Fernet, InvalidTokenfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC@@ -15,6 +17,104 @@ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAClogger = logging.getLogger(__name__)+def _find_env_file() -> Path:+ """Locate the ServerKit .env file on the host or in containers."""+ # Explicit override takes precedence even if the file does not yet exist,+ # so installers/tests can target a specific path.+ env_path = os.environ.get('SERVERKIT_ENV_FILE')+ if env_path:+ return Path(env_path)++ candidates = []++ # SERVERKIT_DIR is used by the CLI and install script+ serverkit_dir = os.environ.get('SERVERKIT_DIR')+ if serverkit_dir:+ candidates.append(Path(serverkit_dir) / '.env')++ # Project-root .env (works in dev and when installed to /opt/serverkit)+ # __file__ is backend/app/utils/crypto.py -> project root is 3 levels up+ candidates.append(Path(__file__).resolve().parents[2] / '.env')++ # Container layout fallback+ candidates.append(Path('/opt/serverkit/.env'))++ for candidate in candidates:+ if candidate.exists():+ return candidate++ # Default to project-root .env even if it doesn't exist, so callers can create it+ return candidates[0] if candidates else Path('/opt/serverkit/.env')+++def generate_encryption_key() -> str:+ """Generate a new Fernet encryption key."""+ return Fernet.generate_key().decode()+++def write_encryption_key_to_env(key: str, env_file: Path = None) -> Path:+ """Persist SERVERKIT_ENCRYPTION_KEY to the .env file, creating it if needed."""+ if env_file is None:+ env_file = _find_env_file()++ env_file = Path(env_file)+ env_file.parent.mkdir(parents=True, exist_ok=True)++ content = env_file.read_text() if env_file.exists() else ''++ # Replace existing key or append+ pattern = re.compile(r'^[ \t]*SERVERKIT_ENCRYPTION_KEY[ \t]*=.*$', re.MULTILINE)+ new_line = f'SERVERKIT_ENCRYPTION_KEY={key}'++ if pattern.search(content):+ content = pattern.sub(new_line, content)+ else:+ if content and not content.endswith('\n'):+ content += '\n'+ content += f'\n# Encryption key for agent pairing payloads and secrets at rest\n{new_line}\n'++ env_file.write_text(content)+ return env_file+++def ensure_encryption_key() -> bytes:+ """Ensure an encryption key exists in production.++ If SERVERKIT_ENCRYPTION_KEY is missing in production, auto-generate one and+ write it to the .env file. This prevents first-time pairing crashes while+ still keeping secrets encrypted at rest.++ Returns:+ bytes: The encryption key+ """+ key = os.environ.get('SERVERKIT_ENCRYPTION_KEY')+ if key:+ return key.encode()++ if os.environ.get('FLASK_ENV') != 'production':+ # Dev/test: fall through to the derived key below+ return None++ logger.warning(+ 'SERVERKIT_ENCRYPTION_KEY is not set in production. '+ 'Auto-generating one and writing it to .env. '+ 'This is normal for new installs.'+ )+ new_key = generate_encryption_key()+ try:+ env_file = write_encryption_key_to_env(new_key)+ os.environ['SERVERKIT_ENCRYPTION_KEY'] = new_key+ logger.info('SERVERKIT_ENCRYPTION_KEY written to %s', env_file)+ except Exception as exc:+ logger.error('Failed to persist SERVERKIT_ENCRYPTION_KEY: %s', exc)+ raise ValueError(+ 'SERVERKIT_ENCRYPTION_KEY must be set in production and could not be auto-generated. '+ 'Generate one with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"'+ ) from exc++ return new_key.encode()++def get_encryption_key() -> bytes:"""Get the encryption key from environment variable.@@ -26,18 +126,19 @@ def get_encryption_key() -> bytes:bytes: The encryption keyRaises:- ValueError: If SERVERKIT_ENCRYPTION_KEY is not set+ ValueError: If SERVERKIT_ENCRYPTION_KEY is not set and cannot be auto-generated"""key = os.environ.get('SERVERKIT_ENCRYPTION_KEY')if not key:- if os.environ.get('FLASK_ENV') == 'production':- raise ValueError('CRITICAL: SERVERKIT_ENCRYPTION_KEY must be set in production')+ # In production, try to auto-generate and persist the key+ auto_key = ensure_encryption_key()+ if auto_key is not None:+ return auto_key++ # Development / testing fallback (NOT for production!)logger.warning('SECURITY WARNING: Using derived development encryption key. Set SERVERKIT_ENCRYPTION_KEY for production.')warnings.warn('Using derived development encryption key - not suitable for production')- # In development, use a default key (NOT for production!)- # This allows the system to work without explicit configurationdefault_key = "DEV_ONLY_NOT_SECURE_CHANGE_IN_PRODUCTION_KEY"- # Derive a proper Fernet key from the defaultkdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,diff --git a/backend/app/utils/domain.py b/backend/app/utils/domain.pynew file mode 100644index 00000000..87ad5f2b--- /dev/null+++ b/backend/app/utils/domain.py@@ -0,0 +1,113 @@+"""Domain detection and canonical-domain helpers."""++import re+import ipaddress+from typing import Optional, Tuple+from flask import Request+++# Hosts that should never be treated as a canonical production domain.+_LOCAL_HOSTS = {+ 'localhost',+ '127.0.0.1',+ '::1',+ '0.0.0.0',+ 'lvh.me',+ '*.lvh.me',+}++_DOMAIN_RE = re.compile(+ r'^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*'+ r'[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$'+)+++def is_ip_address(host: str) -> bool:+ """Return True if ``host`` is an IPv4 or IPv6 address (with optional port)."""+ if not host:+ return False+ bare = host+ # Strip IPv6 brackets first, e.g. [::1]:8080 -> ::1+ if bare.startswith('['):+ bare = bare.split(']', 1)[0][1:]+ try:+ ipaddress.ip_address(bare)+ return True+ except ValueError:+ pass+ # Could be IPv4:port (e.g. 10.0.0.1:8080). Strip the port and retry.+ if ':' in bare:+ bare = bare.rsplit(':', 1)[0]+ try:+ ipaddress.ip_address(bare)+ return True+ except ValueError:+ pass+ return False+++def is_local_host(host: str) -> bool:+ """Return True if ``host`` is localhost or a local/dev wildcard."""+ if not host:+ return True+ host = host.lower().split(':', 1)[0]+ if host in _LOCAL_HOSTS:+ return True+ if host.endswith('.lvh.me') or host.endswith('.local'):+ return True+ return False+++def normalize_host(host: str) -> str:+ """Strip port and lower-case a Host header value."""+ if not host:+ return ''+ # IPv6 brackets may contain colons; strip the port outside the brackets.+ if host.startswith('['):+ host = host.split(']', 1)[0] + ']'+ else:+ host = host.split(':', 1)[0]+ return host.lower()+++def is_valid_canonical_domain(host: str) -> bool:+ """Return True if ``host`` looks like a real domain we can use as canonical."""+ host = normalize_host(host)+ if not host:+ return False+ if is_ip_address(host):+ return False+ if is_local_host(host):+ return False+ # Reject single-label hosts (e.g., just "serverkit")+ if '.' not in host:+ return False+ return bool(_DOMAIN_RE.match(host))+++def detect_request_domain(request: Request) -> Tuple[Optional[str], bool]:+ """Inspect a request and return the candidate canonical domain + HTTPS flag.++ Honors reverse-proxy headers (X-Forwarded-Host, X-Forwarded-Proto) and falls+ back to the request Host / scheme.++ Returns:+ (domain_or_none, is_https)+ """+ forwarded_host = request.headers.get('X-Forwarded-Host', '')+ host = forwarded_host.split(',')[0].strip() or request.host+ host = normalize_host(host)++ forwarded_proto = request.headers.get('X-Forwarded-Proto', '')+ proto = forwarded_proto.split(',')[0].strip() or request.scheme+ is_https = proto.lower() == 'https'++ if is_valid_canonical_domain(host):+ return host, is_https+ return None, is_https+++def canonical_origin(domain: str, https_enabled: bool) -> str:+ """Build an origin URL from a canonical domain setting."""+ scheme = 'https' if https_enabled else 'http'+ return f'{scheme}://{domain}'diff --git a/backend/tests/test_domain_and_encryption.py b/backend/tests/test_domain_and_encryption.pynew file mode 100644index 00000000..b96dcf4e--- /dev/null+++ b/backend/tests/test_domain_and_encryption.py@@ -0,0 +1,138 @@+"""Tests for canonical domain detection and encryption key bootstrap."""+import os+import re+import tempfile+from pathlib import Path++import pytest+from flask import Request+from werkzeug.test import EnvironBuilder++from app.utils.crypto import (+ generate_encryption_key,+ is_encryption_configured,+ get_encryption_key,+ ensure_encryption_key,+ write_encryption_key_to_env,+)+from app.utils.domain import (+ is_ip_address,+ is_valid_canonical_domain,+ detect_request_domain,+ canonical_origin,+)+++def _request(headers=None, **environ_kwargs):+ """Build a Flask Request for header-based tests without the full app."""+ builder = EnvironBuilder('/', headers=headers or {}, **environ_kwargs)+ return Request(builder.get_environ())+++class TestEncryptionKey:+ """Encryption key generation and bootstrap."""++ def test_generate_encryption_key_is_valid_fernet(self):+ key = generate_encryption_key()+ assert re.match(r'^[A-Za-z0-9_-]{43}=$', key)++ def test_is_encryption_configured_false_when_missing(self, monkeypatch):+ monkeypatch.delenv('SERVERKIT_ENCRYPTION_KEY', raising=False)+ assert is_encryption_configured() is False++ def test_is_encryption_configured_true_when_set(self, monkeypatch):+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', generate_encryption_key())+ assert is_encryption_configured() is True++ def test_get_encryption_key_uses_env_in_production(self, monkeypatch):+ key = generate_encryption_key()+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', key)+ monkeypatch.setenv('FLASK_ENV', 'production')+ assert get_encryption_key() == key.encode()++ def test_ensure_encryption_key_auto_generates_in_production(self, monkeypatch, tmp_path):+ monkeypatch.delenv('SERVERKIT_ENCRYPTION_KEY', raising=False)+ monkeypatch.setenv('FLASK_ENV', 'production')+ env_file = tmp_path / '.env'+ monkeypatch.setenv('SERVERKIT_ENV_FILE', str(env_file))++ key = ensure_encryption_key()+ assert key is not None+ assert is_encryption_configured() is True+ assert 'SERVERKIT_ENCRYPTION_KEY=' in env_file.read_text()++ def test_ensure_encryption_key_returns_none_in_testing(self, monkeypatch):+ monkeypatch.delenv('SERVERKIT_ENCRYPTION_KEY', raising=False)+ monkeypatch.setenv('FLASK_ENV', 'testing')+ assert ensure_encryption_key() is None++ def test_write_encryption_key_to_env_appends_and_updates(self, tmp_path):+ env_file = tmp_path / '.env'+ env_file.write_text('SECRET_KEY=abc\n')++ key = generate_encryption_key()+ write_encryption_key_to_env(key, env_file)+ content = env_file.read_text()+ assert f'SERVERKIT_ENCRYPTION_KEY={key}' in content+ assert content.count('SERVERKIT_ENCRYPTION_KEY') == 1++ key2 = generate_encryption_key()+ write_encryption_key_to_env(key2, env_file)+ content = env_file.read_text()+ assert f'SERVERKIT_ENCRYPTION_KEY={key2}' in content+ assert content.count('SERVERKIT_ENCRYPTION_KEY') == 1+++class TestDomainDetection:+ """Canonical domain detection helpers."""++ def test_is_ip_address_recognizes_ipv4(self):+ assert is_ip_address('192.168.1.1') is True+ assert is_ip_address('10.0.0.1:8080') is True++ def test_is_ip_address_recognizes_ipv6(self):+ assert is_ip_address('::1') is True+ assert is_ip_address('[::1]:8080') is True+ assert is_ip_address('2001:db8::1') is True++ def test_is_ip_address_rejects_domains(self):+ assert is_ip_address('serverkit.example.com') is False+ assert is_ip_address('localhost') is False++ def test_is_valid_canonical_domain_rejects_localhost_and_ips(self):+ assert is_valid_canonical_domain('localhost') is False+ assert is_valid_canonical_domain('127.0.0.1') is False+ assert is_valid_canonical_domain('192.168.1.1') is False+ assert is_valid_canonical_domain('::1') is False++ def test_is_valid_canonical_domain_rejects_single_label(self):+ assert is_valid_canonical_domain('serverkit') is False++ def test_is_valid_canonical_domain_accepts_real_domains(self):+ assert is_valid_canonical_domain('serverkit.example.com') is True+ assert is_valid_canonical_domain('panel.builditdesign.com') is True++ def test_canonical_origin_builds_url(self):+ assert canonical_origin('serverkit.example.com', True) == 'https://serverkit.example.com'+ assert canonical_origin('serverkit.example.com', False) == 'http://serverkit.example.com'++ def test_detect_request_domain_uses_host_header(self):+ req = _request(headers={'Host': 'serverkit.example.com'})+ domain, is_https = detect_request_domain(req)+ assert domain == 'serverkit.example.com'+ assert is_https is False++ def test_detect_request_domain_uses_x_forwarded_headers(self):+ req = _request(headers={+ 'Host': 'localhost',+ 'X-Forwarded-Host': 'panel.example.com',+ 'X-Forwarded-Proto': 'https',+ })+ domain, is_https = detect_request_domain(req)+ assert domain == 'panel.example.com'+ assert is_https is True++ def test_detect_request_domain_rejects_ip_hosts(self):+ req = _request(headers={'Host': '146.190.213.37'})+ domain, is_https = detect_request_domain(req)+ assert domain is Nonediff --git a/frontend/src/components/settings/SystemTab.jsx b/frontend/src/components/settings/SystemTab.jsxindex 8e804e93..9d13b987 100644--- a/frontend/src/components/settings/SystemTab.jsx+++ b/frontend/src/components/settings/SystemTab.jsx@@ -3,6 +3,8 @@ import { useAuth } from '../../contexts/AuthContext';import api from '../../services/api';import { InfoList, InfoItem } from '../InfoList';import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Switch } from '@/components/ui/switch';import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';function formatBytes(bytes) {@@ -39,10 +41,19 @@ const SystemTab = () => {const [savingTimezone, setSavingTimezone] = useState(false);const [timezoneMessage, setTimezoneMessage] = useState(null);+ const [domainLoading, setDomainLoading] = useState(false);+ const [detectedDomain, setDetectedDomain] = useState(null);+ const [canonicalDomain, setCanonicalDomain] = useState('');+ const [canonicalHttps, setCanonicalHttps] = useState(false);+ const [encryptionConfigured, setEncryptionConfigured] = useState(true);+ const [savingDomain, setSavingDomain] = useState(false);+ const [domainMessage, setDomainMessage] = useState(null);+useEffect(() => {if (isAdmin) {loadMetrics();loadTimezones();+ loadDomainInfo();}}, [isAdmin]);@@ -69,6 +80,48 @@ const SystemTab = () => {}}+ async function loadDomainInfo() {+ setDomainLoading(true);+ try {+ const [detection, health] = await Promise.all([+ api.getDomainDetection(),+ api.healthCheck()+ ]);+ setDetectedDomain(detection);+ setCanonicalDomain(detection.current_canonical_domain || '');+ setCanonicalHttps(detection.current_canonical_https_enabled || false);+ setEncryptionConfigured(health.encryption_configured !== false);+ } catch (err) {+ console.error('Failed to load domain info:', err);+ } finally {+ setDomainLoading(false);+ }+ }++ async function handleSaveCanonicalDomain() {+ setSavingDomain(true);+ setDomainMessage(null);+ try {+ const result = await api.setCanonicalDomain(canonicalDomain, canonicalHttps);+ setDomainMessage({+ type: 'success',+ text: `${result.message}. Restart the ServerKit backend service for CORS changes to take full effect.`+ });+ loadDomainInfo();+ } catch (err) {+ setDomainMessage({ type: 'error', text: err.message || 'Failed to save canonical domain' });+ } finally {+ setSavingDomain(false);+ setTimeout(() => setDomainMessage(null), 8000);+ }+ }++ async function handleUseDetectedDomain() {+ if (!detectedDomain?.detected_domain) return;+ setCanonicalDomain(detectedDomain.detected_domain);+ setCanonicalHttps(detectedDomain.is_https);+ }+async function handleTimezoneChange() {if (!selectedTimezone) return;@@ -210,6 +263,88 @@ const SystemTab = () => {</span></div></div>++ {/* Panel Domain */}+ <div className="settings-card">+ <h3>Panel Domain</h3>+ {!encryptionConfigured && (+ <div className="alert alert-warning" style={{ marginBottom: '1rem' }}>+ <strong>Encryption key not configured.</strong> Agent pairing and secret encryption+ will fail until SERVERKIT_ENCRYPTION_KEY is set in your .env file.+ </div>+ )}+ {domainLoading ? (+ <div className="loading">Loading domain settings...</div>+ ) : (+ <>+ {detectedDomain?.detected_domain && (+ <div className="form-group">+ <label>Detected Domain</label>+ <div className="form-row" style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>+ <code style={{ flex: 1 }}>+ {detectedDomain.is_https ? 'https' : 'http'}://{detectedDomain.detected_domain}+ </code>+ <Button+ variant="outline"+ size="sm"+ onClick={handleUseDetectedDomain}+ disabled={savingDomain}+ >+ Use this domain+ </Button>+ </div>+ <span className="form-help">+ Detected from the Host header of your current request+ </span>+ </div>+ )}+ {detectedDomain?.current_canonical_domain && (+ <div className="form-group">+ <label>Current Canonical Domain</label>+ <div>+ <code>{detectedDomain.current_canonical_origin || '-'}</code>+ </div>+ </div>+ )}+ <div className="form-group">+ <label htmlFor="canonical-domain">Canonical Domain</label>+ <Input+ id="canonical-domain"+ value={canonicalDomain}+ onChange={(e) => setCanonicalDomain(e.target.value)}+ placeholder="e.g. serverkit.example.com"+ disabled={savingDomain}+ />+ <span className="form-help">+ The domain you point at this ServerKit panel. Used for CORS and agent install commands.+ </span>+ </div>+ <div className="form-group" style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>+ <Switch+ id="canonical-https"+ checked={canonicalHttps}+ onCheckedChange={setCanonicalHttps}+ disabled={savingDomain}+ />+ <label htmlFor="canonical-https" style={{ margin: 0 }}>+ HTTPS enabled for canonical domain+ </label>+ </div>+ <Button+ variant="default"+ onClick={handleSaveCanonicalDomain}+ disabled={savingDomain || !canonicalDomain}+ >+ {savingDomain ? 'Saving...' : 'Save Canonical Domain'}+ </Button>+ {domainMessage && (+ <div className={`timezone-message ${domainMessage.type}`} style={{ marginTop: '0.75rem' }}>+ {domainMessage.text}+ </div>+ )}+ </>+ )}+ </div></div>);};diff --git a/frontend/src/services/api/system.js b/frontend/src/services/api/system.jsindex a53a697b..9c65644c 100644--- a/frontend/src/services/api/system.js+++ b/frontend/src/services/api/system.js@@ -31,6 +31,17 @@ export async function updateSystemSetting(key, value) {});}+export async function getDomainDetection() {+ return this.request('/admin/settings/domain-detection');+}++export async function setCanonicalDomain(domain, httpsEnabled) {+ return this.request('/admin/settings/canonical-domain', {+ method: 'PUT',+ body: { domain, https_enabled: httpsEnabled }+ });+}+export async function getAdminStats() {return this.request('/admin/stats');}diff --git a/nginx/sites-available/serverkit.conf b/nginx/sites-available/serverkit.confindex f645daf0..2e2af0a7 100644--- a/nginx/sites-available/serverkit.conf+++ b/nginx/sites-available/serverkit.conf@@ -3,6 +3,9 @@## This is the default server block for ServerKit.# Update server_name to your domain, or leave as _ for catch-all.+#+# Optional: place a canonical-domain redirect block in+# /etc/nginx/serverkit-canonical-domain.conf (managed by install.sh / settings UI).server {listen 80 default_server;@@ -51,3 +54,8 @@ server {# These are location-only snippets, NOT separate server blocks.include /etc/nginx/serverkit-locations/*.conf;}++# Optional canonical-domain redirect block. Generated by install.sh when a+# canonical domain is supplied; can also be created manually in+# /etc/nginx/serverkit-conf.d/*.conf.+include /etc/nginx/serverkit-conf.d/*.conf;diff --git a/serverkit b/serverkitindex 00453020..db00100b 100644--- a/serverkit+++ b/serverkit@@ -492,6 +492,16 @@ _update_source() {chmod +x "$INSTALL_DIR/serverkit"chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true+ # Ensure SERVERKIT_ENCRYPTION_KEY exists for installs that pre-date it+ if ! grep -q '^SERVERKIT_ENCRYPTION_KEY=' "$INSTALL_DIR/.env" 2>/dev/null; then+ print_info "Generating SERVERKIT_ENCRYPTION_KEY for existing install..."+ key=$(python3 -c 'import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')+ echo "" >> "$INSTALL_DIR/.env"+ echo "# Encryption key for agent pairing payloads and secrets at rest" >> "$INSTALL_DIR/.env"+ echo "SERVERKIT_ENCRYPTION_KEY=$key" >> "$INSTALL_DIR/.env"+ print_success "SERVERKIT_ENCRYPTION_KEY added to .env"+ fi+# Get new version from VERSION fileNEW_VERSION=$(get_local_version)NEW_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")@@ -769,8 +779,10 @@ cmd_generate_keys() {echo ""SECRET_KEY=$(openssl rand -hex 32)JWT_SECRET_KEY=$(openssl rand -hex 32)+ SERVERKIT_ENCRYPTION_KEY=$(python3 -c 'import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')echo "SECRET_KEY=$SECRET_KEY"echo "JWT_SECRET_KEY=$JWT_SECRET_KEY"+ echo "SERVERKIT_ENCRYPTION_KEY=$SERVERKIT_ENCRYPTION_KEY"echo ""}