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.

feat(sites): nudge admins when site-publishing config is half set up

Juan Denis9d49457dcd5f
diff --git a/backend/app/notifications/catalog.py b/backend/app/notifications/catalog.py
index 10afd30e..9bbcdc15 100644
--- a/backend/app/notifications/catalog.py
+++ b/backend/app/notifications/catalog.py
@@ -67,6 +67,26 @@ _CATALOG = {
'severity': 'warning',
'category': 'system',
},
+ # Managed-sites publishing readiness — nudged when a site is created but the
+ # base-domain / DNS / HTTPS config is only partly set up.
+ 'sites.publish.no_base_domain': {
+ 'title': 'Publish your sites at a real domain',
+ 'template': 'generic',
+ 'severity': 'warning',
+ 'category': 'system',
+ },
+ 'sites.publish.http_only': {
+ 'title': 'Managed sites are served over HTTP',
+ 'template': 'generic',
+ 'severity': 'info',
+ 'category': 'system',
+ },
+ 'sites.publish.no_server_ip': {
+ 'title': 'Set a server IP so site DNS can auto-create',
+ 'template': 'generic',
+ 'severity': 'warning',
+ 'category': 'system',
+ },
# Multi-alert monitoring digest (used by the legacy send_all path).
'monitoring.alert': {
'title': 'ServerKit alert',
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py
index 3f257a02..e384f7b8 100644
--- a/backend/app/services/site_domain_service.py
+++ b/backend/app/services/site_domain_service.py
@@ -139,6 +139,124 @@ class SiteDomainService:
except Exception as e:
return {'created': False, 'reason': 'error', 'error': str(e)}
+ @classmethod
+ def panel_host(cls):
+ """Hostname the ServerKit panel itself is served on (from the canonical
+ domain / panel origin), or ``None``. Used to tailor DNS guidance — an
+ install on a subdomain (``panel.example.com``) needs a different base
+ domain than one on the apex (``example.com``)."""
+ origin = cls.panel_origin()
+ if not origin:
+ return None
+ host = origin.split('://', 1)[-1].split('/', 1)[0].split(':', 1)[0]
+ return host.strip().lower().strip('.') or None
+
+ @classmethod
+ def suggested_base_domain(cls):
+ """A sensible ``sites_base_domain`` to suggest, derived from the panel's
+ own domain so the recommendation fits the install shape:
+
+ * apex install ``example.com`` → ``apps.example.com`` (keeps the apex for
+ the panel, scopes the site wildcard under a dedicated label), and
+ * subdomain install ``panel.example.com`` → ``apps.example.com`` (a
+ sibling label, so ``*.apps.example.com`` never collides with the
+ panel's own ``panel`` record).
+
+ Returns ``None`` when the panel domain is unknown (nothing to derive from).
+ """
+ host = cls.panel_host()
+ if not host or host in ('localhost',) or host.replace('.', '').isdigit():
+ return None
+ parts = host.split('.')
+ # A subdomain install (3+ labels) → sibling under the parent zone; an
+ # apex install (2 labels) → a dedicated label under the apex.
+ parent = '.'.join(parts[1:]) if len(parts) >= 3 else host
+ return f'apps.{parent}'
+
+ @classmethod
+ def publishing_gaps(cls):
+ """The managed-sites publishing config gaps that are open *right now*, as
+ a list of ``{code, event, message}`` (empty when publishing is fully set
+ up). Only surfaces gaps that are actionable given what IS configured — the
+ HTTPS and server-IP gaps are meaningless before a base domain exists, so a
+ missing base domain short-circuits the rest.
+ """
+ base = cls.base_domain()
+ if not base:
+ suggestion = cls.suggested_base_domain()
+ eg = f' (e.g. {suggestion})' if suggestion else ''
+ return [{
+ 'code': 'no_base_domain',
+ 'event': 'sites.publish.no_base_domain',
+ 'message': (
+ 'New sites are only reachable at localhost:<port>. Set a '
+ f'managed-sites base domain{eg} in Settings → Managed Sites and '
+ 'point a wildcard record (*.<domain>) at this server, so every '
+ 'site is published at <name>.<domain>.'),
+ }]
+
+ gaps = []
+ if not cls.https_enabled():
+ gaps.append({
+ 'code': 'http_only',
+ 'event': 'sites.publish.http_only',
+ 'message': (
+ f'Sites are published over HTTP at <name>.{base}. Enabling '
+ f'wildcard HTTPS (Settings → Managed Sites) serves them over TLS '
+ f'from a *.{base} certificate — optional, but recommended for a '
+ f'public site.'),
+ })
+ if cls.dns_mode() == 'per-site' and not cls.server_ip():
+ gaps.append({
+ 'code': 'no_server_ip',
+ 'event': 'sites.publish.no_server_ip',
+ 'message': (
+ f"DNS mode is per-site but no server public IP is set, so each "
+ f"site's A record under {base} can't be auto-created. Set the "
+ 'server public IP in Settings, or switch to wildcard DNS mode.'),
+ })
+ return gaps
+
+ @classmethod
+ def _has_open_gap_notice(cls, event_key):
+ """True when an admin already has an *unread* in-app nudge for this event,
+ so the same gap is nudged once — not on every site create."""
+ try:
+ from app import db
+ from app.notifications.models import Notification, NotificationDelivery
+ return db.session.query(NotificationDelivery.id).join(
+ Notification, NotificationDelivery.notification_id == Notification.id
+ ).filter(
+ Notification.event_key == event_key,
+ NotificationDelivery.channel == NotificationDelivery.CHANNEL_INAPP,
+ NotificationDelivery.read_at.is_(None),
+ ).first() is not None
+ except Exception:
+ return False
+
+ @classmethod
+ def notify_publishing_gaps(cls):
+ """Best-effort: drop an in-app nudge to admins for each open publishing
+ gap, deduped against an already-open unread nudge for the same gap. Never
+ raises — a nudge must never break the create flow that triggered it.
+ Returns ``{'sent': n}``."""
+ try:
+ gaps = cls.publishing_gaps()
+ except Exception:
+ return {'sent': 0}
+ sent = 0
+ for gap in gaps:
+ try:
+ if cls._has_open_gap_notice(gap['event']):
+ continue
+ from app.plugins_sdk import notify
+ notify.send(gap['event'], to='admins',
+ data={'message': gap['message'], 'summary': gap['message']})
+ sent += 1
+ except Exception:
+ continue
+ return {'sent': sent}
+
@classmethod
def _vhost_create_kwargs(cls, app, domains, ssl_cert, ssl_key, force_type=None):
"""Build ``NginxService.create_site(**kwargs)`` for ``app``, or
@@ -257,6 +375,10 @@ class SiteDomainService:
if dns and not dns.get('skipped') and not dns.get('created') and dns.get('message'):
warning = (warning + '; ' + dns['message']) if warning else dns['message']
+ # Nudge admins about any remaining publishing-config gaps (HTTP-only,
+ # per-site DNS without a server IP). Best-effort, deduped, never fatal.
+ cls.notify_publishing_gaps()
+
return {'success': True, 'host': host,
'url': cls.site_url(host, ssl=cls.https_enabled() and cls.covers(host)),
'dns': dns, 'nginx': nginx, 'warning': warning}
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 467f5ca0..1282ae03 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -2073,6 +2073,14 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
attach_err = attach_res.get('error') or 'Custom domain could not be attached'
wp_warning = (wp_warning + ' ' + attach_err) if wp_warning else attach_err
+ # Nudge admins (in-app) if the site landed on localhost or the
+ # base-domain/HTTPS/DNS config is only partly set up. Best-effort —
+ # never let a notification failure affect the create result.
+ try:
+ SiteDomainService.notify_publishing_gaps()
+ except Exception:
+ pass
+
result = {
'success': True,
'message': 'WordPress site created successfully',
diff --git a/backend/tests/test_sites_publishing_gaps.py b/backend/tests/test_sites_publishing_gaps.py
new file mode 100644
index 00000000..8c6a5728
--- /dev/null
+++ b/backend/tests/test_sites_publishing_gaps.py
@@ -0,0 +1,118 @@
+"""Proving tests for managed-sites publishing-readiness nudges.
+
+When a site is created but the base-domain / DNS / HTTPS config is only partly
+set up, admins get an in-app nudge to finish it — deduped so it fires once, not
+on every create. The suggested base domain is derived from the panel's own
+domain so it fits a subdomain vs apex install.
+"""
+
+
+def _set(key, value):
+ from app import db
+ from app.services.settings_service import SettingsService
+ SettingsService.set(key, value)
+ db.session.commit()
+
+
+def _mk_admin(username='pg-admin'):
+ from app import db
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ u = User(email=f'{username}@pg.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 _clear_base(app, monkeypatch):
+ # TestingConfig pins SITES_BASE_DOMAIN=lvh.me; clear both layers.
+ monkeypatch.setitem(app.config, 'SITES_BASE_DOMAIN', '')
+ _set('sites_base_domain', '')
+
+
+# ── publishing_gaps ──────────────────────────────────────────────────────────
+
+def test_gap_no_base_domain(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _clear_base(app, monkeypatch)
+ gaps = SiteDomainService.publishing_gaps()
+ assert [g['code'] for g in gaps] == ['no_base_domain']
+ # No other gaps are computed until a base domain exists.
+ assert gaps[0]['event'] == 'sites.publish.no_base_domain'
+
+
+def test_gap_http_only_when_base_set_no_https(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _set('sites_base_domain', 'apps.example.com') # default mode = wildcard
+ _set('sites_https_enabled', False)
+ gaps = SiteDomainService.publishing_gaps()
+ assert [g['code'] for g in gaps] == ['http_only']
+
+
+def test_gap_per_site_without_server_ip(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _set('sites_base_domain', 'apps.example.com')
+ _set('sites_https_enabled', False)
+ _set('sites_dns_mode', 'per-site')
+ _set('server_public_ip', '')
+ codes = [g['code'] for g in SiteDomainService.publishing_gaps()]
+ assert 'no_server_ip' in codes and 'http_only' in codes
+
+
+def test_no_gaps_when_fully_set_up(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _set('sites_base_domain', 'apps.example.com')
+ _set('sites_https_enabled', True) # wildcard mode, https on
+ assert SiteDomainService.publishing_gaps() == []
+
+
+# ── panel-domain-aware suggestion (subdomain vs apex install) ────────────────
+
+def test_suggested_base_domain_apex_install(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _set('canonical_domain', 'example.com') # panel on the apex
+ assert SiteDomainService.suggested_base_domain() == 'apps.example.com'
+
+
+def test_suggested_base_domain_subdomain_install(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _set('canonical_domain', 'panel.acme.co.uk') # panel on a subdomain
+ # Sibling label under the parent zone, so *.apps.* never collides with `panel`.
+ assert SiteDomainService.suggested_base_domain() == 'apps.acme.co.uk'
+
+
+def test_no_base_domain_message_includes_suggestion(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ _clear_base(app, monkeypatch)
+ _set('canonical_domain', 'panel.example.com')
+ msg = SiteDomainService.publishing_gaps()[0]['message']
+ assert 'apps.example.com' in msg
+
+
+# ── notify_publishing_gaps (in-app, deduped) ─────────────────────────────────
+
+def test_notify_sends_once_then_dedupes(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ from app.notifications.service import NotificationBusService
+ admin = _mk_admin()
+ _clear_base(app, monkeypatch)
+
+ first = SiteDomainService.notify_publishing_gaps()
+ assert first['sent'] == 1
+ assert NotificationBusService.unread_count(admin.id) == 1
+
+ # Second create with the same open gap must not stack another nudge.
+ second = SiteDomainService.notify_publishing_gaps()
+ assert second['sent'] == 0
+ assert NotificationBusService.unread_count(admin.id) == 1
+
+
+def test_notify_sends_nothing_when_ready(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ from app.notifications.service import NotificationBusService
+ admin = _mk_admin(username='pg-admin2')
+ _set('sites_base_domain', 'apps.example.com')
+ _set('sites_https_enabled', True)
+ assert SiteDomainService.notify_publishing_gaps() == {'sent': 0}
+ assert NotificationBusService.unread_count(admin.id) == 0