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(cloudflare): zone settings page (Phase 1)

Juan Denis125b1e45536c
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 89a5e7f8..4a76b558 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -303,6 +303,11 @@ def create_app(config_name=None):
from app.api.dns_zones import dns_zones_bp
app.register_blueprint(dns_zones_bp, url_prefix='/api/v1/dns')
+ # Register blueprints - Cloudflare operations (zone settings/cache/WAF on top
+ # of the existing Cloudflare DNS connection)
+ from app.api.cloudflare import cloudflare_bp
+ app.register_blueprint(cloudflare_bp, url_prefix='/api/v1/cloudflare')
+
# Register blueprints - Dynamic DNS
from app.api.ddns import ddns_bp
app.register_blueprint(ddns_bp, url_prefix='/api/v1/ddns')
diff --git a/backend/app/api/cloudflare.py b/backend/app/api/cloudflare.py
new file mode 100644
index 00000000..1c8b63a2
--- /dev/null
+++ b/backend/app/api/cloudflare.py
@@ -0,0 +1,81 @@
+"""Cloudflare operations API — zone settings (SSL/TLS, Speed, Caching, Security)
+and one-click hardening, on top of the existing Cloudflare DNS connection.
+
+Zones are addressed by their ServerKit ``DNSZone`` id (same as the ``/dns`` API);
+the service resolves the Cloudflare credential + zone id server-side. Reads are
+available to any authenticated user; writes require admin. Every mutating call is
+captured by the global audit fallback (method, route args, sanitized body).
+"""
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+
+from app.services.cloudflare_service import CloudflareService, CloudflareError
+
+cloudflare_bp = Blueprint('cloudflare', __name__)
+
+
+def _require_admin():
+ """Return the current user if admin, else ``None``."""
+ from app.models.user import User
+ user = User.query.get(get_jwt_identity())
+ return user if (user and user.is_admin) else None
+
+
+def _service_response(res):
+ """Map a service result dict to JSON. A failed *provider* call (reached
+ Cloudflare, got an error back) is a 502; resolution errors are raised as
+ CloudflareError upstream and handled separately as 400s."""
+ if not res.get('success'):
+ return jsonify({'error': res.get('error', 'Cloudflare request failed')}), 502
+ return jsonify(res)
+
+
+# ── Zone settings ────────────────────────────────────────────────────────────
+
+@cloudflare_bp.route('/zones/<int:zone_id>/settings', methods=['GET'])
+@jwt_required()
+def get_zone_settings(zone_id):
+ try:
+ res = CloudflareService.get_settings(zone_id)
+ except CloudflareError as e:
+ return jsonify({'error': str(e)}), 400
+ return _service_response(res)
+
+
+@cloudflare_bp.route('/zones/<int:zone_id>/settings/apply-preset', methods=['POST'])
+@jwt_required()
+def apply_preset(zone_id):
+ if not _require_admin():
+ return jsonify({'error': 'Admin access required'}), 403
+ try:
+ res = CloudflareService.apply_recommended(zone_id)
+ except CloudflareError as e:
+ return jsonify({'error': str(e)}), 400
+ # A preset is best-effort across many toggles; return 200 with the per-setting
+ # report even when the plan gated some (the UI surfaces partial success).
+ return jsonify(res)
+
+
+@cloudflare_bp.route('/zones/<int:zone_id>/settings/<setting_id>', methods=['GET'])
+@jwt_required()
+def get_zone_setting(zone_id, setting_id):
+ try:
+ res = CloudflareService.get_setting(zone_id, setting_id)
+ except CloudflareError as e:
+ return jsonify({'error': str(e)}), 400
+ return _service_response(res)
+
+
+@cloudflare_bp.route('/zones/<int:zone_id>/settings/<setting_id>', methods=['PATCH'])
+@jwt_required()
+def update_zone_setting(zone_id, setting_id):
+ if not _require_admin():
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json(silent=True) or {}
+ if 'value' not in data:
+ return jsonify({'error': 'A "value" field is required'}), 400
+ try:
+ res = CloudflareService.update_setting(zone_id, setting_id, data['value'])
+ except CloudflareError as e:
+ return jsonify({'error': str(e)}), 400
+ return _service_response(res)
diff --git a/backend/app/services/cloudflare_service.py b/backend/app/services/cloudflare_service.py
new file mode 100644
index 00000000..cc13d742
--- /dev/null
+++ b/backend/app/services/cloudflare_service.py
@@ -0,0 +1,220 @@
+"""Cloudflare zone operations beyond DNS records.
+
+ServerKit already connects Cloudflare as a DNS provider (``DNSProviderConfig`` +
+the shared :class:`~app.services.dns.cloudflare.CloudflareClient`). This service
+builds the *operations* surface on top of that same connection — starting with
+zone settings (SSL/TLS, Speed, Caching, Security) and a one-click hardening
+preset — so auth, encryption-at-rest, and credential resolution are reused, not
+re-implemented.
+
+A zone is addressed by its ServerKit ``DNSZone`` id (the same integer the rest of
+the ``/dns`` API uses); credential + Cloudflare zone id are resolved server-side
+via :meth:`DNSZoneService._resolve_credential`, the canonical resolver.
+"""
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class CloudflareError(Exception):
+ """A caller-facing problem resolving a zone (not found, not Cloudflare, no
+ connected credential). Mapped to a 400 by the API layer."""
+
+
+class CloudflareService:
+ """Zone settings + hardening on a connected Cloudflare zone."""
+
+ # Curated subset of Cloudflare zone settings ServerKit surfaces, grouped for
+ # the UI. Each setting: ``id`` (Cloudflare setting id), ``label``, ``type``
+ # (toggle | select | hsts) and, for selects, ``options`` ({value, label}).
+ # The page renders straight from this metadata; current values + the
+ # ``editable`` (plan-gating) flag come from the live settings response.
+ SETTING_GROUPS = [
+ {
+ 'key': 'ssl',
+ 'label': 'SSL/TLS',
+ 'settings': [
+ {'id': 'ssl', 'label': 'SSL/TLS encryption mode', 'type': 'select',
+ 'help': 'How Cloudflare connects to your origin. "Full (strict)" '
+ 'is the most secure and requires a valid origin certificate.',
+ 'options': [
+ {'value': 'off', 'label': 'Off (not secure)'},
+ {'value': 'flexible', 'label': 'Flexible'},
+ {'value': 'full', 'label': 'Full'},
+ {'value': 'strict', 'label': 'Full (strict)'},
+ ]},
+ {'id': 'always_use_https', 'label': 'Always use HTTPS', 'type': 'toggle',
+ 'help': 'Redirect every HTTP request to HTTPS.'},
+ {'id': 'automatic_https_rewrites', 'label': 'Automatic HTTPS rewrites',
+ 'type': 'toggle',
+ 'help': 'Rewrite insecure http:// links to https:// to avoid mixed content.'},
+ {'id': 'min_tls_version', 'label': 'Minimum TLS version', 'type': 'select',
+ 'options': [
+ {'value': '1.0', 'label': 'TLS 1.0'},
+ {'value': '1.1', 'label': 'TLS 1.1'},
+ {'value': '1.2', 'label': 'TLS 1.2 (recommended)'},
+ {'value': '1.3', 'label': 'TLS 1.3'},
+ ]},
+ {'id': 'tls_1_3', 'label': 'TLS 1.3', 'type': 'toggle',
+ 'help': 'Enable the latest, fastest TLS version.'},
+ {'id': 'security_header', 'label': 'HTTP Strict Transport Security (HSTS)',
+ 'type': 'hsts',
+ 'help': 'Tell browsers to only ever connect over HTTPS. Enable only once '
+ 'HTTPS works everywhere — it is hard to undo before max-age expires.'},
+ ],
+ },
+ {
+ 'key': 'speed',
+ 'label': 'Speed',
+ 'settings': [
+ {'id': 'brotli', 'label': 'Brotli compression', 'type': 'toggle',
+ 'help': 'Compress responses with Brotli for supporting browsers.'},
+ {'id': 'early_hints', 'label': 'Early Hints', 'type': 'toggle',
+ 'help': 'Send 103 Early Hints so browsers can preload assets sooner.'},
+ {'id': 'http3', 'label': 'HTTP/3 (with QUIC)', 'type': 'toggle'},
+ ],
+ },
+ {
+ 'key': 'caching',
+ 'label': 'Caching',
+ 'settings': [
+ {'id': 'cache_level', 'label': 'Caching level', 'type': 'select',
+ 'options': [
+ {'value': 'bypass', 'label': 'Bypass'},
+ {'value': 'basic', 'label': 'Basic'},
+ {'value': 'simplified', 'label': 'Simplified'},
+ {'value': 'aggressive', 'label': 'Aggressive (recommended)'},
+ {'value': 'cache_everything', 'label': 'Cache everything'},
+ ]},
+ {'id': 'browser_cache_ttl', 'label': 'Browser cache TTL', 'type': 'select',
+ 'options': [
+ {'value': 0, 'label': 'Respect existing headers'},
+ {'value': 1800, 'label': '30 minutes'},
+ {'value': 3600, 'label': '1 hour'},
+ {'value': 14400, 'label': '4 hours'},
+ {'value': 28800, 'label': '8 hours'},
+ {'value': 86400, 'label': '1 day'},
+ {'value': 604800, 'label': '1 week'},
+ ]},
+ {'id': 'development_mode', 'label': 'Development mode', 'type': 'toggle',
+ 'help': 'Temporarily bypass the cache while you work. Auto-expires after 3 hours.'},
+ {'id': 'always_online', 'label': 'Always Online', 'type': 'toggle',
+ 'help': 'Serve a cached copy of your site if your origin is unreachable.'},
+ ],
+ },
+ {
+ 'key': 'security',
+ 'label': 'Security',
+ 'settings': [
+ {'id': 'security_level', 'label': 'Security level', 'type': 'select',
+ 'options': [
+ {'value': 'off', 'label': 'Off'},
+ {'value': 'essentially_off', 'label': 'Essentially off'},
+ {'value': 'low', 'label': 'Low'},
+ {'value': 'medium', 'label': 'Medium'},
+ {'value': 'high', 'label': 'High'},
+ {'value': 'under_attack', 'label': "I'm under attack"},
+ ]},
+ {'id': 'browser_check', 'label': 'Browser integrity check', 'type': 'toggle',
+ 'help': 'Block requests from common malicious bots and crawlers.'},
+ {'id': 'challenge_ttl', 'label': 'Challenge passage', 'type': 'select',
+ 'help': 'How long a visitor stays verified after passing a challenge.',
+ 'options': [
+ {'value': 300, 'label': '5 minutes'},
+ {'value': 900, 'label': '15 minutes'},
+ {'value': 1800, 'label': '30 minutes'},
+ {'value': 3600, 'label': '1 hour'},
+ {'value': 7200, 'label': '2 hours'},
+ {'value': 10800, 'label': '3 hours'},
+ {'value': 14400, 'label': '4 hours'},
+ {'value': 28800, 'label': '8 hours'},
+ {'value': 86400, 'label': '1 day'},
+ ]},
+ ],
+ },
+ ]
+
+ # One-click hardening (plan §Phase 1 Actions): Full (strict), Always HTTPS,
+ # HSTS (6 months), TLS 1.2 floor + 1.3, Brotli, HTTP/3, 4h browser cache.
+ RECOMMENDED_PRESET = [
+ ('ssl', 'strict'),
+ ('always_use_https', 'on'),
+ ('automatic_https_rewrites', 'on'),
+ ('min_tls_version', '1.2'),
+ ('tls_1_3', 'on'),
+ ('brotli', 'on'),
+ ('http3', 'on'),
+ ('browser_cache_ttl', 14400),
+ ('security_header', {'strict_transport_security': {
+ 'enabled': True, 'max_age': 15552000,
+ 'include_subdomains': True, 'preload': False, 'nosniff': True}}),
+ ]
+
+ @staticmethod
+ def _zone_and_client(zone_id):
+ """Resolve ``(zone, CloudflareClient)`` for a ServerKit DNS zone id, or raise
+ :class:`CloudflareError` with a user-facing reason. Credential resolution
+ reuses the canonical resolver so the connection store is the single source
+ of truth."""
+ from app.services.dns_zone_service import DNSZoneService
+ from app.services.dns import CloudflareClient
+
+ zone = DNSZoneService.get_zone(zone_id)
+ if not zone:
+ raise CloudflareError('Zone not found')
+ if (zone.provider or '').lower() != 'cloudflare':
+ raise CloudflareError('This zone is not managed by Cloudflare')
+ credential = DNSZoneService._resolve_credential(zone)
+ if not credential:
+ raise CloudflareError('No connected Cloudflare credential resolves for this zone')
+ if not zone.provider_zone_id:
+ raise CloudflareError("Cloudflare hasn't been matched to this domain yet — "
+ 'open the DNS zone once to link it, then retry')
+ return zone, CloudflareClient(credential)
+
+ @staticmethod
+ def _zone_dict(zone):
+ return {'id': zone.id, 'domain': zone.domain,
+ 'provider_zone_id': zone.provider_zone_id}
+
+ @classmethod
+ def get_settings(cls, zone_id):
+ """Live zone settings, indexed by id, plus the UI grouping metadata."""
+ zone, client = cls._zone_and_client(zone_id)
+ res = client.get_zone_settings(zone.provider_zone_id)
+ if not res.get('success'):
+ return {'success': False, 'error': res.get('error', 'Failed to load zone settings')}
+ by_id = {s.get('id'): s for s in (res.get('result') or []) if isinstance(s, dict)}
+ return {'success': True, 'zone': cls._zone_dict(zone),
+ 'groups': cls.SETTING_GROUPS, 'settings': by_id}
+
+ @classmethod
+ def get_setting(cls, zone_id, setting_id):
+ zone, client = cls._zone_and_client(zone_id)
+ res = client.get_zone_setting(zone.provider_zone_id, setting_id)
+ if not res.get('success'):
+ return {'success': False, 'error': res.get('error', 'Failed to load setting')}
+ return {'success': True, 'setting': res.get('result')}
+
+ @classmethod
+ def update_setting(cls, zone_id, setting_id, value):
+ zone, client = cls._zone_and_client(zone_id)
+ res = client.update_zone_setting(zone.provider_zone_id, setting_id, value)
+ if not res.get('success'):
+ return {'success': False, 'error': res.get('error', 'Update failed')}
+ return {'success': True, 'setting': res.get('result')}
+
+ @classmethod
+ def apply_recommended(cls, zone_id):
+ """Apply the recommended hardening preset, returning a per-setting report so
+ the UI can show which toggles the plan allowed and which it gated."""
+ zone, client = cls._zone_and_client(zone_id)
+ results = []
+ for setting_id, value in cls.RECOMMENDED_PRESET:
+ res = client.update_zone_setting(zone.provider_zone_id, setting_id, value)
+ results.append({'setting': setting_id,
+ 'success': bool(res.get('success')),
+ 'error': None if res.get('success') else res.get('error')})
+ applied = sum(1 for r in results if r['success'])
+ return {'success': applied > 0, 'applied': applied,
+ 'total': len(results), 'results': results}
diff --git a/backend/app/services/dns/cloudflare.py b/backend/app/services/dns/cloudflare.py
index a6f55827..53a55c08 100644
--- a/backend/app/services/dns/cloudflare.py
+++ b/backend/app/services/dns/cloudflare.py
@@ -212,3 +212,47 @@ class CloudflareClient:
return {'success': True, 'message': 'Record deleted'}
except Exception as e:
return {'success': False, 'error': str(e)}
+
+ # ── generic v4 access (zone settings, cache, WAF, Workers, …) ─────────────
+ #
+ # The record methods above are the DNS-specific surface. Everything else in
+ # the Cloudflare operations roadmap (zone settings, cache purge, WAF rules,
+ # Workers, Tunnels, R2) is plain v4 REST, so it shares one thin ``request``
+ # helper rather than a bespoke method per call. It normalizes the envelope so
+ # every caller can rely on ``{success, error?, result?}``.
+ def request(self, method: str, path: str, json: dict = None,
+ params: dict = None, timeout: int = 20) -> dict:
+ """Make a Cloudflare v4 call. ``path`` is relative to the API base (a
+ leading slash is optional). Returns the parsed envelope dict (always with
+ a ``success`` key and, on failure, a human ``error``), or a normalized
+ ``{success: False, error}`` on a transport error."""
+ try:
+ url = f'{API_BASE}/{path.lstrip("/")}'
+ resp = requests.request(method.upper(), url, headers=self._headers(),
+ json=json, params=params, timeout=timeout)
+ try:
+ data = resp.json()
+ except ValueError:
+ return {'success': False,
+ 'error': f'HTTP {resp.status_code}: non-JSON response from Cloudflare'}
+ if not isinstance(data, dict):
+ return {'success': False, 'error': 'Unexpected Cloudflare response'}
+ if not data.get('success') and not data.get('error'):
+ data['error'] = _first_error(data)
+ return data
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ def get_zone_settings(self, zone_id: str) -> dict:
+ """All zone settings (``result`` is a list of ``{id, value, editable, …}``)."""
+ return self.request('GET', f'/zones/{zone_id}/settings')
+
+ def get_zone_setting(self, zone_id: str, setting_id: str) -> dict:
+ """A single zone setting by id."""
+ return self.request('GET', f'/zones/{zone_id}/settings/{setting_id}')
+
+ def update_zone_setting(self, zone_id: str, setting_id: str, value) -> dict:
+ """Patch a single zone setting. ``value`` is a scalar for most toggles or a
+ structured object for compound settings (e.g. HSTS ``security_header``)."""
+ return self.request('PATCH', f'/zones/{zone_id}/settings/{setting_id}',
+ json={'value': value})
diff --git a/backend/tests/test_cloudflare_zone_settings.py b/backend/tests/test_cloudflare_zone_settings.py
new file mode 100644
index 00000000..5e7288d8
--- /dev/null
+++ b/backend/tests/test_cloudflare_zone_settings.py
@@ -0,0 +1,160 @@
+"""Proving tests for Cloudflare zone settings (Phase 1 of the Cloudflare ops roadmap).
+
+Covers the generic v4 ``request`` helper on the shared client (envelope
+normalization), the zone-settings methods, and ``CloudflareService`` orchestration
+— credential/zone resolution guards, settings indexing, and the recommended
+hardening preset's per-setting reporting.
+
+Cloudflare HTTP is stubbed by monkeypatching ``requests.request`` on the client's
+imported ``requests`` module (the generic helper uses ``requests.request``).
+"""
+import pytest
+
+
+class _Resp:
+ def __init__(self, js, status=200):
+ self._js = js
+ self.status_code = status
+
+ def json(self):
+ return self._js
+
+
+def _client(token='tok'):
+ from app.services.dns import cloudflare as cf
+ from app.services.dns.base import DnsCredential
+ return cf.CloudflareClient(DnsCredential(provider='cloudflare', token=token))
+
+
+# ── generic request() envelope normalization ─────────────────────────────────
+
+def test_request_passes_success_through(monkeypatch):
+ from app.services.dns import cloudflare as cf
+ monkeypatch.setattr(cf.requests, 'request',
+ lambda *a, **k: _Resp({'success': True,
+ 'result': [{'id': 'ssl', 'value': 'full'}]}))
+ res = _client().get_zone_settings('zoneA')
+ assert res['success'] is True and res['result'][0]['id'] == 'ssl'
+
+
+def test_request_extracts_first_error(monkeypatch):
+ from app.services.dns import cloudflare as cf
+ monkeypatch.setattr(cf.requests, 'request',
+ lambda *a, **k: _Resp({'success': False,
+ 'errors': [{'message': 'Invalid zone'}]}))
+ res = _client().get_zone_setting('zoneA', 'ssl')
+ assert res['success'] is False and res['error'] == 'Invalid zone'
+
+
+def test_request_handles_transport_error(monkeypatch):
+ from app.services.dns import cloudflare as cf
+
+ def boom(*a, **k):
+ raise RuntimeError('network down')
+ monkeypatch.setattr(cf.requests, 'request', boom)
+ res = _client().get_zone_settings('zoneA')
+ assert res['success'] is False and 'network down' in res['error']
+
+
+def test_request_handles_non_json(monkeypatch):
+ from app.services.dns import cloudflare as cf
+
+ class _Bad(_Resp):
+ def json(self):
+ raise ValueError('no json')
+ monkeypatch.setattr(cf.requests, 'request', lambda *a, **k: _Bad({}, status=502))
+ res = _client().get_zone_settings('zoneA')
+ assert res['success'] is False and '502' in res['error']
+
+
+def test_update_zone_setting_patches_value(monkeypatch):
+ from app.services.dns import cloudflare as cf
+ seen = {}
+
+ def capture(method, url, headers=None, json=None, params=None, timeout=None):
+ seen.update(method=method, url=url, json=json)
+ return _Resp({'success': True, 'result': {'id': 'ssl', 'value': 'strict'}})
+ monkeypatch.setattr(cf.requests, 'request', capture)
+ res = _client().update_zone_setting('zoneA', 'ssl', 'strict')
+ assert res['success'] is True
+ assert seen['method'] == 'PATCH'
+ assert seen['url'].endswith('/zones/zoneA/settings/ssl')
+ assert seen['json'] == {'value': 'strict'}
+
+
+# ── service: zone resolution guards ──────────────────────────────────────────
+
+def _make_cf_zone(domain='example.com', provider='cloudflare', zid='zoneABC', token='tok'):
+ from app import db
+ from app.models.dns_zone import DNSZone
+ zone = DNSZone(domain=domain, provider=provider, provider_zone_id=zid)
+ if token:
+ zone.provider_config = {'api_token': token}
+ db.session.add(zone)
+ db.session.commit()
+ return zone
+
+
+def test_service_rejects_non_cloudflare_zone(app):
+ from app.services.cloudflare_service import CloudflareService, CloudflareError
+ zone = _make_cf_zone(provider='manual', token=None)
+ with pytest.raises(CloudflareError):
+ CloudflareService.get_settings(zone.id)
+
+
+def test_service_rejects_missing_zone(app):
+ from app.services.cloudflare_service import CloudflareService, CloudflareError
+ with pytest.raises(CloudflareError):
+ CloudflareService.get_settings(99999)
+
+
+def test_service_rejects_zone_without_provider_zone_id(app):
+ from app.services.cloudflare_service import CloudflareService, CloudflareError
+ zone = _make_cf_zone(zid=None)
+ with pytest.raises(CloudflareError):
+ CloudflareService.get_settings(zone.id)
+
+
+# ── service: settings + preset ───────────────────────────────────────────────
+
+def test_service_get_settings_indexes_by_id(app, monkeypatch):
+ from app.services.dns import cloudflare as cf
+ from app.services.cloudflare_service import CloudflareService
+ zone = _make_cf_zone()
+ monkeypatch.setattr(cf.requests, 'request',
+ lambda *a, **k: _Resp({'success': True, 'result': [
+ {'id': 'ssl', 'value': 'full', 'editable': True},
+ {'id': 'brotli', 'value': 'on', 'editable': True}]}))
+ res = CloudflareService.get_settings(zone.id)
+ assert res['success'] is True
+ assert res['settings']['ssl']['value'] == 'full'
+ assert res['zone']['domain'] == 'example.com'
+ assert any(g['key'] == 'ssl' for g in res['groups'])
+
+
+def test_service_update_setting_surfaces_provider_error(app, monkeypatch):
+ from app.services.dns import cloudflare as cf
+ from app.services.cloudflare_service import CloudflareService
+ zone = _make_cf_zone()
+ monkeypatch.setattr(cf.requests, 'request',
+ lambda *a, **k: _Resp({'success': False,
+ 'errors': [{'message': 'not editable on plan'}]}))
+ res = CloudflareService.update_setting(zone.id, 'http3', 'on')
+ assert res['success'] is False and 'not editable' in res['error']
+
+
+def test_service_apply_preset_reports_each(app, monkeypatch):
+ from app.services.dns import cloudflare as cf
+ from app.services.cloudflare_service import CloudflareService
+ zone = _make_cf_zone()
+
+ def capture(method, url, headers=None, json=None, params=None, timeout=None):
+ ok = not url.endswith('/http3') # fail one to prove partial reporting
+ return _Resp({'success': ok,
+ 'errors': [] if ok else [{'message': 'not on plan'}],
+ 'result': {}})
+ monkeypatch.setattr(cf.requests, 'request', capture)
+ res = CloudflareService.apply_recommended(zone.id)
+ assert res['total'] == len(CloudflareService.RECOMMENDED_PRESET)
+ assert res['applied'] == res['total'] - 1
+ assert any(r['setting'] == 'http3' and not r['success'] for r in res['results'])
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index df0d3434..be59cc79 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -59,6 +59,7 @@ import RemoteAccess from './pages/RemoteAccess';
import Workspaces from './pages/Workspaces';
import WorkspaceDetail from './pages/WorkspaceDetail';
import DNSZones from './pages/DNSZones';
+import CloudflareZoneSettings from './pages/CloudflareZoneSettings';
import StatusPages from './pages/StatusPages';
import PublicStatusPage from './pages/PublicStatusPage';
import CloudProvision from './pages/CloudProvision';
@@ -333,6 +334,9 @@ function AppRoutes() {
<Route path="ssl" element={<SSLCertificates />} />
<Route path="dynamic-dns" element={<DynamicDns />} />
</Route>
+ {/* Cloudflare zone settings — a detail page reached from a
+ Cloudflare-managed DNS zone (full-bleed, own top bar). */}
+ <Route path="cloudflare/zones/:zoneId" element={<CloudflareZoneSettings />} />
<Route path="databases" element={<Databases />} />
<Route path="databases/:tab" element={<Databases />} />
<Route path="docker" element={<Docker />} />
diff --git a/frontend/src/pages/CloudflareZoneSettings.jsx b/frontend/src/pages/CloudflareZoneSettings.jsx
new file mode 100644
index 00000000..6f3e4102
--- /dev/null
+++ b/frontend/src/pages/CloudflareZoneSettings.jsx
@@ -0,0 +1,345 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useParams, Link } from 'react-router-dom';
+import { Cloud, ShieldCheck, Lock, Gauge, Database, Wand2 } from 'lucide-react';
+import { PageTopbar } from '@/components/ds';
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
+import { Switch } from '@/components/ui/switch';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import {
+ Select, SelectTrigger, SelectContent, SelectItem, SelectValue,
+} from '@/components/ui/select';
+import PageLoader from '../components/PageLoader';
+import EmptyState from '../components/EmptyState';
+import { useToast } from '../contexts/ToastContext';
+import { useAuth } from '../contexts/AuthContext';
+import api from '../services/api';
+
+// HSTS max-age presets (seconds). 0 disables the max-age while keeping HSTS off.
+const HSTS_MAX_AGE = [
+ { value: 0, label: 'Off' },
+ { value: 86400, label: '1 day' },
+ { value: 604800, label: '1 week' },
+ { value: 2592000, label: '1 month' },
+ { value: 15552000, label: '6 months' },
+ { value: 31536000, label: '1 year' },
+ { value: 63072000, label: '2 years' },
+];
+
+const TAB_ICONS = {
+ ssl: <Lock size={15} />,
+ speed: <Gauge size={15} />,
+ caching: <Database size={15} />,
+ security: <ShieldCheck size={15} />,
+};
+
+const CloudflareZoneSettings = () => {
+ const { zoneId } = useParams();
+ const toast = useToast();
+ const { user } = useAuth();
+ const isAdmin = !!user?.is_admin;
+
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [zone, setZone] = useState(null);
+ const [groups, setGroups] = useState([]);
+ const [settings, setSettings] = useState({});
+ const [saving, setSaving] = useState(null); // setting id in flight
+ const [applying, setApplying] = useState(false);
+
+ const loadSettings = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await api.getCloudflareZoneSettings(zoneId);
+ setZone(data.zone || null);
+ setGroups(data.groups || []);
+ setSettings(data.settings || {});
+ } catch (err) {
+ setError(err.message || 'Failed to load Cloudflare settings');
+ } finally {
+ setLoading(false);
+ }
+ }, [zoneId]);
+
+ useEffect(() => { loadSettings(); }, [loadSettings]);
+
+ // Optimistically reflect the change, PATCH it, and reload truth on failure so
+ // the UI never drifts from Cloudflare.
+ const save = useCallback(async (settingId, value) => {
+ setSaving(settingId);
+ setSettings(prev => ({ ...prev, [settingId]: { ...(prev[settingId] || {}), value } }));
+ try {
+ await api.updateCloudflareZoneSetting(zoneId, settingId, value);
+ toast.success('Setting saved');
+ } catch (err) {
+ toast.error(err.message || 'Failed to save setting');
+ loadSettings();
+ } finally {
+ setSaving(null);
+ }
+ }, [zoneId, toast, loadSettings]);
+
+ const handleApplyPreset = async () => {
+ setApplying(true);
+ try {
+ const res = await api.applyCloudflareSettingsPreset(zoneId);
+ const failed = (res.results || []).filter(r => !r.success);
+ if (failed.length === 0) {
+ toast.success(`Applied recommended hardening (${res.applied} settings)`);
+ } else {
+ toast.info(`Applied ${res.applied}/${res.total}. ${failed.length} need a higher Cloudflare plan.`);
+ }
+ loadSettings();
+ } catch (err) {
+ toast.error(err.message || 'Failed to apply preset');
+ } finally {
+ setApplying(false);
+ }
+ };
+
+ if (loading) return <PageLoader />;
+
+ const crumbs = (
+ <span className="cf-crumbs">
+ <Link to="/dns">DNS Zones</Link>
+ <span className="cf-crumbs__sep">/</span>
+ <span className="cf-crumbs__cur">{zone?.domain || `Zone ${zoneId}`}</span>
+ <span className="cf-crumbs__sep">/</span>
+ <span className="cf-crumbs__cur">Cloudflare</span>
+ </span>
+ );
+
+ if (error) {
+ return (
+ <div className="app-detail-page app-detail-page--wide cf-zone">
+ <PageTopbar icon={<Cloud size={18} />} title={crumbs} />
+ <div className="cf-zone__body">
+ <EmptyState
+ icon={Cloud}
+ title="Cloudflare settings unavailable"
+ description={error}
+ />
+ <div className="cf-zone__error-actions">
+ <Button variant="outline" onClick={loadSettings}>Retry</Button>
+ <Link to="/dns"><Button variant="ghost">Back to DNS Zones</Button></Link>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const tabGroups = groups.filter(g => g.settings?.length);
+ const firstTab = tabGroups[0]?.key || 'actions';
+
+ return (
+ <div className="app-detail-page app-detail-page--wide cf-zone">
+ <PageTopbar
+ icon={<Cloud size={18} />}
+ title={crumbs}
+ meta={zone?.provider_zone_id ? `Zone ${zone.provider_zone_id}` : undefined}
+ />
+
+ <div className="cf-zone__body">
+ <Tabs defaultValue={firstTab} className="cf-zone__tabs">
+ <TabsList>
+ {tabGroups.map(g => (
+ <TabsTrigger key={g.key} value={g.key}>
+ {TAB_ICONS[g.key]}{g.label}
+ </TabsTrigger>
+ ))}
+ <TabsTrigger value="actions"><Wand2 size={15} />Actions</TabsTrigger>
+ </TabsList>
+
+ {tabGroups.map(g => (
+ <TabsContent key={g.key} value={g.key}>
+ <div className="cf-panel">
+ {g.settings.map(setting => (
+ <SettingRow
+ key={setting.id}
+ setting={setting}
+ state={settings[setting.id]}
+ saving={saving === setting.id}
+ disabled={!isAdmin}
+ onSave={save}
+ />
+ ))}
+ </div>
+ </TabsContent>
+ ))}
+
+ <TabsContent value="actions">
+ <div className="cf-panel cf-actions">
+ <div className="cf-action">
+ <div className="cf-action__text">
+ <h3>Apply recommended hardening</h3>
+ <p>
+ Sets Full (strict) SSL, Always Use HTTPS, HSTS (6 months),
+ a TLS 1.2 floor with TLS 1.3, Brotli, HTTP/3, and a 4-hour
+ browser cache. Settings your plan doesn&apos;t allow are skipped.
+ </p>
+ </div>
+ <Button onClick={handleApplyPreset} disabled={applying || !isAdmin}>
+ {applying ? 'Applying…' : 'Apply preset'}
+ </Button>
+ </div>
+ {!isAdmin && (
+ <p className="cf-actions__note">
+ Changing Cloudflare settings requires an admin account.
+ </p>
+ )}
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+ </div>
+ );
+};
+
+// A single setting row — label + help on the left, the control on the right.
+// Reads the current value/editability from the live settings state; renders the
+// control declaratively from the setting's `type`.
+function SettingRow({ setting, state, saving, disabled, onSave }) {
+ const present = state !== undefined && state !== null;
+ const editable = present ? state.editable !== false : false;
+ const locked = disabled || !editable || saving;
+
+ return (
+ <div className="cf-setting">
+ <div className="cf-setting__info">
+ <span className="cf-setting__label">{setting.label}</span>
+ {setting.help && <span className="cf-setting__help">{setting.help}</span>}
+ {!present && (
+ <Badge variant="secondary" className="cf-setting__badge">
+ Not available on this zone
+ </Badge>
+ )}
+ {present && !editable && (
+ <Badge variant="secondary" className="cf-setting__badge">
+ Locked by your Cloudflare plan
+ </Badge>
+ )}
+ </div>
+ <div className="cf-setting__control">
+ <SettingControl
+ setting={setting}
+ value={present ? state.value : undefined}
+ locked={locked || !present}
+ onSave={onSave}
+ />
+ </div>
+ </div>
+ );
+}
+
+function SettingControl({ setting, value, locked, onSave }) {
+ if (setting.type === 'toggle') {
+ return (
+ <Switch
+ checked={value === 'on'}
+ disabled={locked}
+ onCheckedChange={(checked) => onSave(setting.id, checked ? 'on' : 'off')}
+ />
+ );
+ }
+
+ if (setting.type === 'select') {
+ const current = value === undefined || value === null ? '' : String(value);
+ return (
+ <Select
+ value={current}
+ disabled={locked}
+ onValueChange={(v) => {
+ const opt = setting.options.find(o => String(o.value) === v);
+ onSave(setting.id, opt ? opt.value : v);
+ }}
+ >
+ <SelectTrigger className="cf-setting__select"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {setting.options.map(o => (
+ <SelectItem key={String(o.value)} value={String(o.value)}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+ }
+
+ if (setting.type === 'hsts') {
+ return <HstsControl value={value} locked={locked} onSave={onSave} settingId={setting.id} />;
+ }
+
+ return null;
+}
+
+// HSTS is a compound object setting; editing any field re-sends the whole
+// strict_transport_security object so the others are preserved.
+function HstsControl({ value, locked, onSave, settingId }) {
+ const sts = (value && value.strict_transport_security) || {};
+ const enabled = !!sts.enabled;
+
+ const patch = (changes) => {
+ const next = {
+ enabled: sts.enabled || false,
+ max_age: sts.max_age || 0,
+ include_subdomains: sts.include_subdomains || false,
+ preload: sts.preload || false,
+ nosniff: sts.nosniff !== undefined ? sts.nosniff : true,
+ ...changes,
+ };
+ onSave(settingId, { strict_transport_security: next });
+ };
+
+ return (
+ <div className="cf-hsts">
+ <div className="cf-hsts__row">
+ <span>Enabled</span>
+ <Switch
+ checked={enabled}
+ disabled={locked}
+ onCheckedChange={(checked) => patch({
+ enabled: checked,
+ // Give a sane max-age when first enabling.
+ max_age: checked && !sts.max_age ? 15552000 : sts.max_age || 0,
+ })}
+ />
+ </div>
+ {enabled && (
+ <>
+ <div className="cf-hsts__row">
+ <span>Max age</span>
+ <Select
+ value={String(sts.max_age || 0)}
+ disabled={locked}
+ onValueChange={(v) => patch({ max_age: Number(v) })}
+ >
+ <SelectTrigger className="cf-setting__select"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {HSTS_MAX_AGE.map(o => (
+ <SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="cf-hsts__row">
+ <span>Include subdomains</span>
+ <Switch
+ checked={!!sts.include_subdomains}
+ disabled={locked}
+ onCheckedChange={(checked) => patch({ include_subdomains: checked })}
+ />
+ </div>
+ <div className="cf-hsts__row">
+ <span>Preload</span>
+ <Switch
+ checked={!!sts.preload}
+ disabled={locked}
+ onCheckedChange={(checked) => patch({ preload: checked })}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+export default CloudflareZoneSettings;
diff --git a/frontend/src/pages/DNSZones.jsx b/frontend/src/pages/DNSZones.jsx
index 58bfc194..7a3851e7 100644
--- a/frontend/src/pages/DNSZones.jsx
+++ b/frontend/src/pages/DNSZones.jsx
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useCallback } from 'react';
-import { Globe, Layers } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { Globe, Layers, Cloud } from 'lucide-react';
import { useTopbarActions } from '@/hooks/useTopbarActions';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
@@ -23,6 +24,7 @@ import {
const DNSZones = () => {
const toast = useToast();
+ const navigate = useNavigate();
const { user } = useAuth();
const [zones, setZones] = useState([]);
const [loading, setLoading] = useState(true);
@@ -275,6 +277,12 @@ const DNSZones = () => {
<span className="text-muted">{zone.provider} &bull; {zone.record_count} records</span>
</div>
<div className="dns-zone-item__actions" onClick={e => e.stopPropagation()}>
+ {zone.provider === 'cloudflare' && (
+ <Button variant="outline" size="sm" title="Cloudflare zone settings"
+ onClick={() => navigate(`/cloudflare/zones/${zone.id}`)}>
+ <Cloud size={14} /> Cloudflare
+ </Button>
+ )}
<Button variant="outline" size="sm" onClick={() => handleCheckPropagation(zone.domain)}>Check</Button>
{user?.is_admin && (
<Button variant="destructive" size="sm" onClick={() => setDeleteConfirm(zone)}>Delete</Button>
diff --git a/frontend/src/services/api/cloudflare.js b/frontend/src/services/api/cloudflare.js
new file mode 100644
index 00000000..f21b3824
--- /dev/null
+++ b/frontend/src/services/api/cloudflare.js
@@ -0,0 +1,24 @@
+// Cloudflare operations — zone settings (SSL/TLS, Speed, Caching, Security) and
+// one-click hardening, layered on the existing Cloudflare DNS connection. Zones
+// are addressed by their ServerKit DNS zone id (same as the /dns API).
+
+export async function getCloudflareZoneSettings(zoneId) {
+ return this.request(`/cloudflare/zones/${zoneId}/settings`);
+}
+
+export async function getCloudflareZoneSetting(zoneId, settingId) {
+ return this.request(`/cloudflare/zones/${zoneId}/settings/${settingId}`);
+}
+
+export async function updateCloudflareZoneSetting(zoneId, settingId, value) {
+ return this.request(`/cloudflare/zones/${zoneId}/settings/${settingId}`, {
+ method: 'PATCH',
+ body: { value },
+ });
+}
+
+export async function applyCloudflareSettingsPreset(zoneId) {
+ return this.request(`/cloudflare/zones/${zoneId}/settings/apply-preset`, {
+ method: 'POST',
+ });
+}
diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.js
index 7c2d6ea3..94d310b4 100644
--- a/frontend/src/services/api/index.js
+++ b/frontend/src/services/api/index.js
@@ -9,6 +9,7 @@ import * as systemMethods from './system.js';
import * as securityMethods from './security.js';
import * as fileMethods from './files.js';
import * as dnsMethods from './dns.js';
+import * as cloudflareMethods from './cloudflare.js';
import * as pluginMethods from './plugins.js';
import * as deploymentJobMethods from './deploymentJobs.js';
import * as pairingMethods from './pairing.js';
@@ -39,6 +40,7 @@ class ApiService extends ApiClient {
securityMethods,
fileMethods,
dnsMethods,
+ cloudflareMethods,
pluginMethods,
deploymentJobMethods,
pairingMethods,
diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scss
index 78c0bd0e..731a4e33 100644
--- a/frontend/src/styles/main.scss
+++ b/frontend/src/styles/main.scss
@@ -111,6 +111,7 @@
@import 'pages/_remote-access';
@import 'pages/_workspaces';
@import 'pages/_dns-zones';
+@import 'pages/_cloudflare-zone';
@import 'pages/_status-pages';
@import 'pages/_cloud-provision';
@import 'pages/_marketplace';
diff --git a/frontend/src/styles/pages/_cloudflare-zone.scss b/frontend/src/styles/pages/_cloudflare-zone.scss
new file mode 100644
index 00000000..93c02462
--- /dev/null
+++ b/frontend/src/styles/pages/_cloudflare-zone.scss
@@ -0,0 +1,131 @@
+// Cloudflare zone settings — detail page reached from a Cloudflare-managed DNS
+// zone. Full-bleed top bar (PageTopbar) + tabbed setting groups.
+
+.cf-zone {
+ &__body {
+ padding: $spacing-lg;
+ max-width: 880px;
+ }
+
+ &__tabs {
+ margin-top: $spacing-sm;
+ }
+
+ &__error-actions {
+ display: flex;
+ justify-content: center;
+ gap: $spacing-sm;
+ margin-top: $spacing-md;
+ }
+}
+
+// Breadcrumb in the top-bar title slot (mirrors the service-detail crumbs).
+.cf-crumbs {
+ display: inline-flex;
+ align-items: center;
+ gap: $spacing-xs;
+ font-size: 0.95rem;
+
+ a {
+ color: $text-secondary;
+ text-decoration: none;
+
+ &:hover { color: $primary-color; }
+ }
+
+ &__sep { color: $text-tertiary; }
+ &__cur { color: $text-primary; font-weight: 600; }
+}
+
+.cf-panel {
+ background: $card-bg;
+ border: 1px solid $border-color;
+ border-radius: $radius-lg;
+ padding: $spacing-xs $spacing-lg;
+ margin-top: $spacing-md;
+}
+
+// One setting: label/help on the left, control hugging the right.
+.cf-setting {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: $spacing-lg;
+ padding: $spacing-md 0;
+ border-bottom: 1px solid $border-color;
+
+ &:last-child { border-bottom: none; }
+
+ &__info {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ }
+
+ &__label {
+ font-weight: 600;
+ color: $text-primary;
+ }
+
+ &__help {
+ font-size: 0.85rem;
+ color: $text-muted;
+ max-width: 52ch;
+ line-height: 1.4;
+ }
+
+ &__badge {
+ align-self: flex-start;
+ margin-top: 2px;
+ }
+
+ &__control {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ min-height: 32px;
+ }
+
+ &__select {
+ min-width: 200px;
+ }
+}
+
+// HSTS compound control — a small stack of rows.
+.cf-hsts {
+ display: flex;
+ flex-direction: column;
+ gap: $spacing-sm;
+ min-width: 240px;
+
+ &__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $spacing-md;
+ font-size: 0.88rem;
+ color: $text-secondary;
+ }
+}
+
+.cf-actions {
+ .cf-action {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $spacing-lg;
+ padding: $spacing-md 0;
+
+ &__text {
+ h3 { margin: 0 0 4px; font-size: 1rem; }
+ p { margin: 0; color: $text-muted; font-size: 0.88rem; max-width: 60ch; line-height: 1.5; }
+ }
+ }
+
+ &__note {
+ margin: $spacing-sm 0 0;
+ color: $text-muted;
+ font-size: 0.85rem;
+ }
+}