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(wordpress): publish new sites at a real subdomain, not localhost:port
Juan Denis1a0214f11deb
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.pynew file mode 100644index 00000000..02075d6b--- /dev/null+++ b/backend/app/services/site_domain_service.py@@ -0,0 +1,65 @@+"""Resolve the public address of a managed site.++A bare published port (``127.0.0.1:8300``) is reachable on the box but is+useless as a public website URL. Instead every managed site is given a real+hostname ``<slug>.<base_domain>`` and the operator points a single wildcard DNS+record (``*.<base_domain>``) at the server — so a new site is reachable the+moment it is created, with no per-site DNS work.++The base domain is a one-time operator setting (``system_settings`` key+``sites_base_domain``), falling back to ``SITES_BASE_DOMAIN`` in config. In+development that defaults to ``lvh.me``, a public resolver that maps+``*.lvh.me -> 127.0.0.1``, so subdomain routing can be exercised locally with+zero DNS setup. When no base domain is configured the helpers return ``None``+and callers fall back to the legacy ``localhost:<port>`` behaviour.+"""+import re++from flask import current_app++from app.models.system_settings import SystemSettings+++class SiteDomainService:+ DEFAULT_BASE_DOMAIN = 'lvh.me'++ @classmethod+ def base_domain(cls):+ """The configured base domain, or '' when site routing is not set up.++ Prefers the runtime setting (editable in-app) over the config default so+ an operator can change it without redeploying.+ """+ val = SystemSettings.get('sites_base_domain')+ if val:+ return str(val).strip().lstrip('.').lower()+ return (current_app.config.get('SITES_BASE_DOMAIN') or '').strip().lstrip('.').lower()++ @classmethod+ def server_ip(cls):+ """Public IP that wildcard/custom A-records should point at (Phase 3)."""+ return SystemSettings.get('server_public_ip') or current_app.config.get('SERVER_PUBLIC_IP') or None++ @staticmethod+ def slugify(name):+ """Turn a site name into a DNS-safe label (a-z, 0-9, single dashes)."""+ s = (name or '').strip().lower()+ s = re.sub(r'[^a-z0-9-]', '-', s)+ s = re.sub(r'-+', '-', s).strip('-')+ return s or 'site'++ @classmethod+ def subdomain_for(cls, name):+ """``<slug>.<base_domain>`` for a site name, or ``None`` when no base+ domain is configured (site routing disabled)."""+ base = cls.base_domain()+ if not base:+ return None+ return f'{cls.slugify(name)}.{base}'++ @classmethod+ def site_url(cls, host, ssl=False):+ """Canonical URL for a host. HTTP for now; the wildcard-cert phase flips+ managed subdomains to HTTPS."""+ scheme = 'https' if ssl else 'http'+ return f'{scheme}://{host}'diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex 7b76c635..1a08ca4f 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -1441,6 +1441,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]from app import dbfrom app.models import Application, WordPressSitefrom app.services.template_service import TemplateService+ from app.services.site_domain_service import SiteDomainService# Sanitize name for Dockersafe_name = name.lower().replace(' ', '-')@@ -1482,7 +1483,16 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]# run the install, so no admin user exists. Do it via the Docker-aware# wp_cli bridge (host-filesystem hardening does not apply to volumes).admin_password = cls._generate_password()- site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'+ # Publish at a real hostname (<slug>.<base_domain>) instead of+ # localhost:<port>. WordPress bakes whatever --url we pass in as its+ # 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)+ if site_host:+ site_url = SiteDomainService.site_url(site_host)+ else:+ site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'wp_warning = Noneharden_actions = []cache_actions = []@@ -1536,6 +1546,14 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]# only meaningful if the automated install finalized).multisite = cls.is_multisite(app.root_path) if admin_password else False+ # Publish the site at its hostname: a Domain row + nginx reverse-proxy+ # vhost so <slug>.<base_domain> reaches the container. Best-effort — a+ # box without nginx (local dev) degrades to a warning, never failing+ # the create.+ routing = cls._provision_routing(app, site_host)+ if routing.get('warning'):+ wp_warning = (wp_warning + ' ' + routing['warning']) if wp_warning else routing['warning']+# Surface any best-effort cache failures without failing the create.if cache_warnings:note = 'Site created, but some caches could not be enabled — ' + '; '.join(cache_warnings) + '.'@@ -1568,6 +1586,8 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]'message': 'WordPress site created successfully','site': wp_site.to_dict(),'http_port': http_port,+ 'url': site_url,+ 'domain': site_host,'admin_user': admin_user if admin_password else None,'admin_password': admin_password,'hardening': harden_actions,@@ -1581,6 +1601,66 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]db.session.rollback()return {'success': False, 'error': str(e)}+ @classmethod+ def _provision_routing(cls, app, site_host) -> Dict:+ """Publish a managed site at ``site_host`` via a primary Domain row + an+ nginx reverse-proxy vhost to the container's published port.++ Best-effort and never raises: a box without nginx (e.g. local Windows+ dev) records the Domain and returns a warning rather than failing site+ creation. Returns ``{'domain', 'nginx', 'warning'}``.+ """+ from app import db+ from app.models.domain import Domain+ from app.services.nginx_service import NginxService++ if not site_host:+ return {'domain': None, 'nginx': None, 'warning': None}++ warning = None+ try:+ if not Domain.query.filter_by(name=site_host).first():+ Domain.query.filter_by(application_id=app.id, is_primary=True).update({'is_primary': False})+ db.session.add(Domain(name=site_host, is_primary=True, application_id=app.id))+ db.session.commit()+ except Exception as e:+ db.session.rollback()+ warning = f'could not record domain {site_host}: {e}'++ nginx_result = None+ if app.port:+ try:+ domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()] or [site_host]+ nginx_result = NginxService.create_site(+ name=app.name, app_type='docker', domains=domains,+ root_path=app.root_path or '', port=app.port,+ )+ if nginx_result.get('success'):+ en = NginxService.enable_site(app.name)+ if not en.get('success'):+ nginx_result['warning'] = f"vhost written but not enabled: {en.get('error')}"+ else:+ msg = f"nginx vhost not created: {nginx_result.get('error')}"+ warning = (warning + '; ' + msg) if warning else msg+ except Exception as e:+ msg = f'nginx vhost error: {e}'+ warning = (warning + '; ' + msg) if warning else msg+ return {'domain': site_host, 'nginx': nginx_result, 'warning': warning}++ @classmethod+ def _canonical_site_url(cls, app) -> str:+ """The URL WordPress serves under — its primary domain if one exists,+ else the legacy localhost:<port> address. Used to build correct+ search-replace pairs when cloning."""+ from app.models.domain import Domain+ d = (Domain.query.filter_by(application_id=app.id, is_primary=True).first()+ or Domain.query.filter_by(application_id=app.id).first())+ if d:+ return f'http://{d.name}'+ if app.port:+ return f'http://localhost:{app.port}'+ return None+@classmethoddef clone_site(cls, source_site_id: int, new_name: str, user_id: int) -> Dict:"""Clone an existing Docker WordPress site into a NEW independent top-level@@ -1615,11 +1695,10 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]new_root = new_site.application.root_pathnew_compose = os.path.join(new_root, 'docker-compose.yml')http_port = create_res.get('http_port')- new_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'+ new_url = create_res.get('url') or (f'http://localhost:{http_port}' if http_port else 'http://localhost')try:- src_port = source.application.port- source_url = f'http://localhost:{src_port}' if src_port else None+ source_url = cls._canonical_site_url(source.application)# 2) Clone the source DB into the new stack (root user for a clean overwrite;# both stacks use db name 'wordpress'; root pw lives in each .env DB_PASSWORD).@@ -1629,10 +1708,14 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]'truncate_tables': ['actionscheduler_actions', 'actionscheduler_logs'],}if source_url and new_url and source_url != new_url:- clone_options['search_replace'] = {- source_url: new_url,- f'localhost:{src_port}': f'localhost:{http_port}',- }+ # Rewrite the source's URL to the clone's, both with and without+ # scheme so host-only and serialized references are covered.+ sr = {source_url: new_url}+ src_host = source_url.split('://', 1)[-1]+ new_host = new_url.split('://', 1)[-1]+ if src_host != new_host:+ sr[src_host] = new_host+ clone_options['search_replace'] = srclone_res = DatabaseSyncService.clone_between_containers(source_compose_path=source_compose,target_compose_path=new_compose,@@ -1923,6 +2006,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]"""Tear down Docker stack and delete records for a WordPressSite."""from app import dbfrom app.services.docker_service import DockerService+ from app.services.nginx_service import NginxServiceif wp_site.application and wp_site.application.root_path:root_path = wp_site.application.root_path@@ -1931,6 +2015,13 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]shutil.rmtree(root_path, ignore_errors=True)if wp_site.application:+ # Remove the reverse-proxy vhost we provisioned so a deleted site+ # doesn't leave dangling nginx config. The Domain rows cascade-delete+ # with the Application (Application.domains is delete-orphan).+ try:+ NginxService.delete_site(wp_site.application.name)+ except Exception:+ passdb.session.delete(wp_site.application)db.session.delete(wp_site)diff --git a/backend/config.py b/backend/config.pyindex 00c5c7a3..deb464ce 100644--- a/backend/config.py+++ b/backend/config.py@@ -46,9 +46,24 @@ class Config:if _public_url and _public_url not in CORS_ORIGINS:CORS_ORIGINS.append(_public_url)+ # ── Managed-site routing ────────────────────────────────────────────+ # Each managed site is published at <slug>.<SITES_BASE_DOMAIN>; the+ # operator points a wildcard DNS record (*.<SITES_BASE_DOMAIN>) at the+ # server so new sites are reachable with no per-site DNS work. Empty by+ # default so production must opt in explicitly — when empty, site+ # provisioning falls back to the legacy localhost:<port> URL. The runtime+ # 'sites_base_domain' setting overrides this (see SiteDomainService).+ SITES_BASE_DOMAIN = os.environ.get('SITES_BASE_DOMAIN', '')+ # Public IP the wildcard/custom A-records should point at when auto-creating+ # DNS records via a connected provider.+ SERVER_PUBLIC_IP = os.environ.get('SERVER_PUBLIC_IP', '')+class DevelopmentConfig(Config):DEBUG = True+ # lvh.me resolves *.lvh.me -> 127.0.0.1, so subdomain routing works locally+ # with zero DNS setup.+ SITES_BASE_DOMAIN = os.environ.get('SITES_BASE_DOMAIN', 'lvh.me')@classmethoddef init_app(cls, app):@@ -65,6 +80,9 @@ class TestingConfig(Config):SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'sqlite:///:memory:')# Reduce noise during testsJWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=5)+ # Deterministic base domain so subdomain-provisioning tests don't depend on+ # the developer's shell environment.+ SITES_BASE_DOMAIN = 'lvh.me'class ProductionConfig(Config):diff --git a/backend/tests/test_site_routing.py b/backend/tests/test_site_routing.pynew file mode 100644index 00000000..5f1bed4d--- /dev/null+++ b/backend/tests/test_site_routing.py@@ -0,0 +1,123 @@+"""Phase 1 proving tests.++Managed sites are published at a real hostname (<slug>.<base_domain>) instead+of localhost:<port>: SiteDomainService resolves the host, and WordPressService+provisions a primary Domain row + nginx reverse-proxy vhost.+"""+++def _mk_user(db, username='owner'):+ from app.models import User+ from werkzeug.security import generate_password_hash+ u = User(email=f'{username}@test.local', username=username,+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(u)+ db.session.commit()+ return u+++def _mk_app(db, user_id, name='blog', port=8300):+ from app.models import Application+ a = Application(name=name, app_type='docker', user_id=user_id,+ root_path=f'/srv/{name}', port=port)+ db.session.add(a)+ db.session.commit()+ return a+++# ── site domain resolution ──────────────────────────────────────────────────++def test_subdomain_for_uses_testing_base_domain(app):+ from app.services.site_domain_service import SiteDomainService+ # TestingConfig pins SITES_BASE_DOMAIN = lvh.me.+ assert SiteDomainService.base_domain() == 'lvh.me'+ assert SiteDomainService.subdomain_for('My Blog!') == 'my-blog.lvh.me'+ assert SiteDomainService.site_url('my-blog.lvh.me') == 'http://my-blog.lvh.me'+++def test_subdomain_none_when_base_domain_unset(app, monkeypatch):+ from app.services.site_domain_service import SiteDomainService+ monkeypatch.setitem(app.config, 'SITES_BASE_DOMAIN', '')+ assert SiteDomainService.base_domain() == ''+ # No base domain -> provisioning falls back to the legacy localhost URL.+ assert SiteDomainService.subdomain_for('blog') is None+++def test_runtime_setting_overrides_config(app):+ from app import db+ from app.models.system_settings import SystemSettings+ from app.services.site_domain_service import SiteDomainService+ SystemSettings.set('sites_base_domain', 'apps.example.com')+ db.session.commit()+ assert SiteDomainService.base_domain() == 'apps.example.com'+ assert SiteDomainService.subdomain_for('Shop') == 'shop.apps.example.com'+++# ── routing provisioning ────────────────────────────────────────────────────++def test_provision_routing_creates_primary_domain_and_docker_vhost(app, monkeypatch):+ from app import db+ from app.models.domain import Domain+ from app.services import nginx_service+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db)+ app_row = _mk_app(db, user.id, name='blog', port=8300)++ captured = {}++ def fake_create_site(cls, **kw):+ captured.update(kw)+ return {'success': True}++ monkeypatch.setattr(nginx_service.NginxService, 'create_site', classmethod(fake_create_site))+ monkeypatch.setattr(nginx_service.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))++ res = WordPressService._provision_routing(app_row, 'blog.lvh.me')+ assert res['warning'] is None+ assert res['domain'] == 'blog.lvh.me'++ d = Domain.query.filter_by(application_id=app_row.id).first()+ assert d is not None+ assert d.name == 'blog.lvh.me'+ assert d.is_primary is True++ # Reverse-proxy vhost, not php-fpm: docker app_type + the container's port.+ assert captured['app_type'] == 'docker'+ assert captured['port'] == 8300+ assert 'blog.lvh.me' in captured['domains']+++def test_provision_routing_warns_when_nginx_unavailable(app, monkeypatch):+ from app import db+ from app.models.domain import Domain+ from app.services import nginx_service+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'owner2')+ app_row = _mk_app(db, user.id, name='shop', port=8400)++ monkeypatch.setattr(nginx_service.NginxService, 'create_site',+ classmethod(lambda cls, **kw: {'success': False, 'error': 'nginx not installed'}))++ res = WordPressService._provision_routing(app_row, 'shop.lvh.me')+ # Domain still recorded; the nginx failure is a warning, never an exception.+ assert Domain.query.filter_by(name='shop.lvh.me').first() is not None+ assert res['warning'] and 'nginx' in res['warning']+++def test_canonical_site_url_prefers_primary_domain(app):+ from app import db+ from app.models.domain import Domain+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'owner3')+ app_row = _mk_app(db, user.id, name='acme', port=8500)++ # No domain yet -> legacy localhost URL.+ assert WordPressService._canonical_site_url(app_row) == 'http://localhost:8500'++ db.session.add(Domain(name='acme.lvh.me', is_primary=True, application_id=app_row.id))+ db.session.commit()+ assert WordPressService._canonical_site_url(app_row) == 'http://acme.lvh.me'