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(sites): per-base wildcard HTTPS + base-domain registry API
Juan Denise718a95f4322
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex f520d10e..fcdb2d08 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -429,13 +429,48 @@ def sites_https_status():@admin_bp.route('/sites-https/setup', methods=['POST'])@admin_requireddef sites_https_setup():- """Create the wildcard DNS record + issue the wildcard cert for the base domain."""+ """Create the wildcard DNS record + issue the wildcard cert for a base domain+ (the default base when ``base`` is omitted)."""from app.services.sites_https_service import SitesHttpsServicedata = request.get_json() or {}- result = SitesHttpsService.setup(data.get('provider_id'), email=data.get('email'))+ result = SitesHttpsService.setup(data.get('provider_id'), email=data.get('email'),+ base=data.get('base') or data.get('domain'))return jsonify(result), 200 if result.get('success') else 400+@admin_bp.route('/sites-https/base-domains', methods=['POST'])+@admin_required+def sites_base_domain_add():+ """Register a base domain managed sites can publish under."""+ from app.services.site_base_domain_service import SiteBaseDomainService+ data = request.get_json() or {}+ result = SiteBaseDomainService.add(+ data.get('domain'),+ dns_provider_config_id=data.get('provider_id') or data.get('dns_provider_config_id'),+ dns_mode=data.get('dns_mode') or 'wildcard',+ make_default=bool(data.get('make_default')),+ )+ return jsonify(result), 201 if result.get('success') else 400+++@admin_bp.route('/sites-https/base-domains/<path:domain>', methods=['DELETE'])+@admin_required+def sites_base_domain_remove(domain):+ """Unregister a base domain (promotes another to default if it was default)."""+ from app.services.site_base_domain_service import SiteBaseDomainService+ result = SiteBaseDomainService.remove(domain)+ return jsonify(result), 200 if result.get('success') else 404+++@admin_bp.route('/sites-https/base-domains/<path:domain>/default', methods=['POST'])+@admin_required+def sites_base_domain_set_default(domain):+ """Make a registered base domain the default for new sites."""+ from app.services.site_base_domain_service import SiteBaseDomainService+ result = SiteBaseDomainService.set_default(domain)+ return jsonify(result), 200 if result.get('success') else 404++# ============================================# Admin Statistics Endpoints# ============================================diff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex 2f476aaa..1ceec8e9 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -216,28 +216,50 @@ def create_domain():return jsonify(response), 201+@domains_bp.route('/base-domains', methods=['GET'])+@jwt_required()+def list_base_domains():+ """The base domains a new site can be published under, for the create-flow+ picker. Returns the registry (default first) or, on a legacy single-base+ install, the one configured base. ``default`` names the pre-selected base."""+ from app.services.site_domain_service import SiteDomainService+ from app.services.site_base_domain_service import SiteBaseDomainService+ rows = SiteBaseDomainService.list_rows()+ if rows:+ bases = [{'domain': r.domain, 'is_default': r.is_default,+ 'https_enabled': r.https_enabled, 'dns_mode': r.dns_mode} for r in rows]+ else:+ base = SiteDomainService.base_domain()+ bases = ([{'domain': base, 'is_default': True,+ 'https_enabled': SiteDomainService.https_enabled(),+ 'dns_mode': SiteDomainService.dns_mode()}] if base else [])+ default = next((b['domain'] for b in bases if b['is_default']), None)+ return jsonify({'base_domains': bases, 'default': default}), 200++@domains_bp.route('/suggest-subdomain', methods=['GET'])@jwt_required()def suggest_subdomain():"""Suggest a managed-sites subdomain (<slug>.<base>) for an app, so the UI can- prefill the 'give this a subdomain' action."""+ prefill the 'give this a subdomain' action. Honours an optional ``base``."""from app.services.site_domain_service import SiteDomainServiceapp_id = request.args.get('application_id', type=int)app = Application.query.get(app_id) if app_id else None- base = SiteDomainService.base_domain()+ base = SiteDomainService.resolve_base(request.args.get('base'))if not base:return jsonify({'base_domain': None, 'suggestion': None,'dns_mode': SiteDomainService.dns_mode()}), 200slug = SiteDomainService.slugify(app.name) if app else 'site'return jsonify({'base_domain': base, 'suggestion': f'{slug}.{base}',- 'dns_mode': SiteDomainService.dns_mode()}), 200+ 'dns_mode': SiteDomainService.dns_mode(base)}), 200@domains_bp.route('/give-subdomain', methods=['POST'])@jwt_required()def give_subdomain():- """Publish an app at <label>.<base_domain> in one click — Domain row + nginx- vhost + (per-site mode) an auto-created A record."""+ """Publish an app at <label>.<base> in one click — Domain row + nginx vhost ++ (per-site mode) an auto-created A record. Accepts an optional ``base`` to+ publish under a specific registered base domain."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)data = request.get_json() or {}@@ -248,7 +270,7 @@ def give_subdomain():return jsonify({'error': 'Access denied'}), 403from app.services.site_domain_service import SiteDomainService- result = SiteDomainService.give_subdomain(app, label=data.get('label'))+ result = SiteDomainService.give_subdomain(app, label=data.get('label'), base=data.get('base'))return jsonify(result), 200 if result.get('success') else 400diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 4b270616..176b1db3 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -57,6 +57,7 @@ def create_site():enable_page_cache = bool(data.get('enablePageCache'))enable_object_cache = bool(data.get('enableObjectCache'))domain = (data.get('domain') or '').strip()+ base_domain = (data.get('baseDomain') or data.get('base_domain') or '').strip()if not name:return jsonify({'error': 'Site name is required'}), 400@@ -71,6 +72,7 @@ def create_site():enable_page_cache=enable_page_cache,enable_object_cache=enable_object_cache,domain=domain or None,+ base_domain=base_domain or None,)if result.get('success'):diff --git a/backend/app/services/sites_https_service.py b/backend/app/services/sites_https_service.pyindex bf15320c..434a30fd 100644--- a/backend/app/services/sites_https_service.py+++ b/backend/app/services/sites_https_service.py@@ -17,25 +17,35 @@ class SitesHttpsService:@classmethoddef status(cls):- """Current managed-sites routing/HTTPS configuration."""+ """Current managed-sites routing/HTTPS configuration, including the full+ base-domain registry (``bases``). The top-level fields reflect the default+ base for back-compat."""+ from app.services.site_base_domain_service import SiteBaseDomainServicereturn {'base_domain': SiteDomainService.base_domain(),'server_ip': SiteDomainService.server_ip(),'https_enabled': SiteDomainService.https_enabled(),'dns_mode': SiteDomainService.dns_mode(),'providers': DNSProviderService.list_providers(),+ 'bases': [r.to_dict() for r in SiteBaseDomainService.list_rows()],}@classmethod- def setup(cls, provider_id, email=None):- """Create ``*.<base>`` + ``<base>`` A records and issue the wildcard cert.+ def setup(cls, provider_id, email=None, base=None):+ """Create ``*.<base>`` + ``<base>`` A records and issue the wildcard cert+ for one base domain (the default base when ``base`` is None).Requires a configured base domain and a connected DNS provider. Theserver IP is needed to create the A records; without it the cert canstill be issued (DNS-01 doesn't need them) but traffic won't route untilthe records exist — surfaced as a warning rather than a failure.++ On success the base's HTTPS state is persisted: to its registry row when+ it has one (also recording the provider used), else to the legacy+ ``sites_https_enabled`` / ``sites_dns_mode`` settings for the default base."""- base = SiteDomainService.base_domain()+ from app.services.site_base_domain_service import SiteBaseDomainService+ base = SiteDomainService._norm(base) if base else SiteDomainService.base_domain()if not base:return {'success': False, 'error': 'Set the sites base domain first (Settings).'}@@ -63,9 +73,14 @@ class SitesHttpsService:return {'success': False, 'error': f"Wildcard certificate failed: {cert.get('error')}",'dns': dns, 'ssl': cert, 'warning': '; '.join(warnings) if warnings else None}- SettingsService.set('sites_https_enabled', True)# The wildcard record now covers every subdomain, so wildcard is the mode.- SettingsService.set('sites_dns_mode', 'wildcard')+ row = SiteBaseDomainService.get(base)+ if row:+ SiteBaseDomainService.update(base, https_enabled=True, dns_mode='wildcard',+ dns_provider_config_id=config.id)+ else:+ SettingsService.set('sites_https_enabled', True)+ SettingsService.set('sites_dns_mode', 'wildcard')return {'success': True, 'base_domain': base, 'https_enabled': True,'dns': dns, 'ssl': cert, 'cert_path': cert.get('certificate_path'),diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex 1282ae03..5c3aca2e 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -1907,7 +1907,8 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]@classmethoddef create_site(cls, name: str, admin_email: str, user_id: int, admin_user: str = 'admin',php_version: str = None, enable_page_cache: bool = False,- enable_object_cache: bool = False, domain: str = None) -> Dict:+ enable_object_cache: bool = False, domain: str = None,+ base_domain: str = None) -> Dict:"""Create a new WordPress site via Docker.One-click orchestration: provision the Docker stack on a chosen PHP version,@@ -1965,9 +1966,11 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]# canonical home/siteurl, so this is what makes the site usable as an# actual website. Falls back to localhost when no base domain is set# (e.g. an unconfigured production install).- site_host = SiteDomainService.subdomain_for(safe_name)+ site_host = SiteDomainService.subdomain_for(safe_name, base=base_domain)if site_host:- site_url = SiteDomainService.site_url(site_host, ssl=SiteDomainService.https_enabled())+ base_used = SiteDomainService.covering_base(site_host)+ site_url = SiteDomainService.site_url(+ site_host, ssl=SiteDomainService.https_enabled(base_used))else:site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'wp_warning = Nonediff --git a/backend/tests/test_site_base_domains.py b/backend/tests/test_site_base_domains.pyindex f1f9639d..fa9732c1 100644--- a/backend/tests/test_site_base_domains.py+++ b/backend/tests/test_site_base_domains.py@@ -110,6 +110,69 @@ def test_https_and_dns_mode_are_per_base(app, monkeypatch):assert fc.endswith('/toto.com/fullchain.pem')+# ── API: registry list + admin management ────────────────────────────────────++def test_base_domains_list_endpoint(app, client, auth_headers):+ from app.services.site_base_domain_service import SiteBaseDomainService+ _set('sites_base_domain', 'example.com')+ SiteBaseDomainService.add('toto.com')+ resp = client.get('/api/v1/domains/base-domains', headers=auth_headers)+ assert resp.status_code == 200+ data = resp.get_json()+ assert data['default'] == 'example.com'+ assert {b['domain'] for b in data['base_domains']} == {'example.com', 'toto.com'}+++def test_base_domains_list_legacy_single(app, client, auth_headers):+ # No registry rows: falls back to the single configured base.+ _set('sites_base_domain', 'solo.example.com')+ resp = client.get('/api/v1/domains/base-domains', headers=auth_headers)+ data = resp.get_json()+ assert data['default'] == 'solo.example.com'+ assert data['base_domains'][0]['is_default'] is True+++def test_admin_add_and_set_default_and_remove(app, client, auth_headers):+ _set('sites_base_domain', 'example.com')+ add = client.post('/api/v1/admin/sites-https/base-domains',+ json={'domain': 'toto.com'}, headers=auth_headers)+ assert add.status_code == 201+ mk = client.post('/api/v1/admin/sites-https/base-domains/toto.com/default', headers=auth_headers)+ assert mk.status_code == 200 and mk.get_json()['base']['is_default'] is True+ rm = client.delete('/api/v1/admin/sites-https/base-domains/example.com', headers=auth_headers)+ assert rm.status_code == 200+++def test_per_base_https_setup_persists_to_row(app, monkeypatch):+ from app import db+ from app.models.email import DNSProviderConfig+ from app.services.dns_provider_service import DNSProviderService+ from app.services.advanced_ssl_service import AdvancedSSLService+ from app.services.sites_https_service import SitesHttpsService+ from app.services.site_base_domain_service import SiteBaseDomainService+ from app.services.site_domain_service import SiteDomainService++ _set('sites_base_domain', 'example.com')+ SiteBaseDomainService.add('toto.com') # a second base, https off+ provider = DNSProviderConfig(name='cf', provider='cloudflare', api_key='tok', api_secret='sec')+ db.session.add(provider)+ _set('server_public_ip', '203.0.113.9')++ monkeypatch.setattr(DNSProviderService, 'ensure_a_record',+ classmethod(lambda cls, host, ip: {'created': True, 'record': {}}))+ monkeypatch.setattr(AdvancedSSLService, 'issue_wildcard_cert', staticmethod(+ lambda domain, prov, creds, email=None: {'success': True,+ 'certificate_path': f'/etc/letsencrypt/live/{domain}/fullchain.pem'}))++ res = SitesHttpsService.setup(provider.id, base='toto.com')+ assert res['success'] and res['base_domain'] == 'toto.com'+ # Persisted to toto.com's row only — example.com stays HTTP.+ assert SiteBaseDomainService.get('toto.com').https_enabled is True+ assert SiteBaseDomainService.get('toto.com').dns_provider_config_id == provider.id+ assert SiteDomainService.https_enabled('toto.com') is True+ assert SiteDomainService.https_enabled('example.com') is False++def test_give_subdomain_under_chosen_base(app, monkeypatch):from app.services.site_base_domain_service import SiteBaseDomainServicefrom app.services.site_domain_service import SiteDomainService