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(cloudflare): Cloudflare Tunnels (Phase 5)
Juan Denis2f1999018dc8
diff --git a/backend/app/api/cloudflare.py b/backend/app/api/cloudflare.pyindex 9ddf09a0..d16925ea 100644--- a/backend/app/api/cloudflare.py+++ b/backend/app/api/cloudflare.py@@ -237,3 +237,89 @@ def delete_worker(zone_id, name):except CloudflareError as e:return jsonify({'error': str(e)}), 400return _service_response(res)+++# ── Tunnels (cloudflared) ────────────────────────────────────────────────────++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels', methods=['GET'])+@jwt_required()+def list_tunnels(zone_id):+ try:+ res = CloudflareService.list_tunnels(zone_id)+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels', methods=['POST'])+@jwt_required()+def create_tunnel(zone_id):+ if not _require_admin():+ return jsonify({'error': 'Admin access required'}), 403+ data = request.get_json(silent=True) or {}+ try:+ res = CloudflareService.create_tunnel(zone_id, data.get('name'))+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels/<tunnel_id>/install', methods=['GET'])+@jwt_required()+def tunnel_install(zone_id, tunnel_id):+ if not _require_admin():+ return jsonify({'error': 'Admin access required'}), 403+ try:+ res = CloudflareService.get_tunnel_install(zone_id, tunnel_id)+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels/<tunnel_id>/hostnames', methods=['GET'])+@jwt_required()+def tunnel_hostnames(zone_id, tunnel_id):+ try:+ res = CloudflareService.get_tunnel_hostnames(zone_id, tunnel_id)+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels/<tunnel_id>/hostnames', methods=['POST'])+@jwt_required()+def add_tunnel_hostname(zone_id, tunnel_id):+ if not _require_admin():+ return jsonify({'error': 'Admin access required'}), 403+ data = request.get_json(silent=True) or {}+ try:+ res = CloudflareService.add_tunnel_hostname(+ zone_id, tunnel_id, data.get('hostname'), data.get('service'))+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels/<tunnel_id>/hostnames', methods=['DELETE'])+@jwt_required()+def remove_tunnel_hostname(zone_id, tunnel_id):+ if not _require_admin():+ return jsonify({'error': 'Admin access required'}), 403+ data = request.get_json(silent=True) or {}+ try:+ res = CloudflareService.remove_tunnel_hostname(zone_id, tunnel_id, data.get('hostname'))+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)+++@cloudflare_bp.route('/zones/<int:zone_id>/tunnels/<tunnel_id>', methods=['DELETE'])+@jwt_required()+def delete_tunnel(zone_id, tunnel_id):+ if not _require_admin():+ return jsonify({'error': 'Admin access required'}), 403+ try:+ res = CloudflareService.delete_tunnel(zone_id, tunnel_id)+ except CloudflareError as e:+ return jsonify({'error': str(e)}), 400+ return _service_response(res)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex d4a27a27..c0ef00e9 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -45,6 +45,7 @@ from app.models.secret_vault import SecretVault, Secretfrom app.models.webhook_gateway import WebhookEndpoint, WebhookDeliveryfrom app.models.waf_policy import WafPolicyfrom app.models.cloudflare_worker import CloudflareWorker+from app.models.cloudflare_tunnel import CloudflareTunnelfrom app.models.backup_policy import BackupPolicyfrom app.models.backup_run import BackupRunfrom app.queue_bus.models import QueueGroup, Queue, QueueMessage@@ -79,7 +80,7 @@ __all__ = ['SecretVault', 'Secret','WebhookEndpoint', 'WebhookDelivery','WafPolicy',- 'CloudflareWorker',+ 'CloudflareWorker', 'CloudflareTunnel','BackupPolicy', 'BackupRun','QueueGroup', 'Queue', 'QueueMessage','Notification', 'NotificationDelivery',diff --git a/backend/app/models/cloudflare_tunnel.py b/backend/app/models/cloudflare_tunnel.pynew file mode 100644index 00000000..68517306--- /dev/null+++ b/backend/app/models/cloudflare_tunnel.py@@ -0,0 +1,39 @@+from datetime import datetime+from app import db+++class CloudflareTunnel(db.Model):+ """A Cloudflare Tunnel (cloudflared / cfd_tunnel) ServerKit created.++ Distinct from the WireGuard remote-access ``Tunnel`` model — this is a+ Cloudflare-managed tunnel that exposes a local service through Cloudflare's+ edge. Records the connector token (encrypted at rest) so the install command+ can be shown without re-fetching, and which connection owns it.+ """+ __tablename__ = 'cloudflare_tunnels'+ __table_args__ = (+ db.UniqueConstraint('account_id', 'tunnel_id', name='uq_cf_tunnel_account_id'),+ )++ id = db.Column(db.Integer, primary_key=True)+ tunnel_id = db.Column(db.String(64), nullable=False, index=True) # Cloudflare tunnel id+ name = db.Column(db.String(128), nullable=False)+ account_id = db.Column(db.String(64), nullable=False)+ dns_provider_config_id = db.Column(+ db.Integer, db.ForeignKey('dns_provider_configs.id'), nullable=True)+ token_encrypted = db.Column(db.Text) # cloudflared connector token (encrypted)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ # Never serialize the token here — it's revealed only at creation time and+ # re-fetched on demand via the install endpoint.+ return {+ 'id': self.id,+ 'tunnel_id': self.tunnel_id,+ 'name': self.name,+ 'account_id': self.account_id,+ 'dns_provider_config_id': self.dns_provider_config_id,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }diff --git a/backend/app/services/cloudflare_service.py b/backend/app/services/cloudflare_service.pyindex 2bc33c33..70d52200 100644--- a/backend/app/services/cloudflare_service.py+++ b/backend/app/services/cloudflare_service.py@@ -538,3 +538,167 @@ class CloudflareService:if not res.get('success'):return {'success': False, 'error': res.get('error', 'Failed to delete route')}return {'success': True}++ # ── Tunnels (cloudflared) ────────────────────────────────────────────────+ # Cloudflare Tunnels expose a local/private service through Cloudflare's edge+ # without a public IP. Distinct from ServerKit's WireGuard remote-access+ # tunnels. Account-scoped; account resolved from the zone.++ @staticmethod+ def _install_command(token):+ """The one-liner an operator runs on the target host to attach a connector."""+ if not token:+ return None+ return f'cloudflared service install {token}'++ @classmethod+ def list_tunnels(cls, zone_id):+ from app.models.cloudflare_tunnel import CloudflareTunnel+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ res = client.list_tunnels(account_id)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to list tunnels')}+ managed = {t.tunnel_id for t in+ CloudflareTunnel.query.filter_by(account_id=account_id).all()}+ tunnels = [{'id': t.get('id'), 'name': t.get('name'), 'status': t.get('status'),+ 'created_at': t.get('created_at'),+ 'connections': len(t.get('connections') or []),+ 'managed': t.get('id') in managed}+ for t in (res.get('result') or [])]+ return {'success': True, 'account_id': account_id, 'tunnels': tunnels}++ @classmethod+ def create_tunnel(cls, zone_id, name):+ """Create a tunnel and return the connector token + install command (the+ token is revealed once here and stored encrypted for later)."""+ from app import db+ from app.models.cloudflare_tunnel import CloudflareTunnel+ from app.utils.crypto import encrypt_secret++ name = (name or '').strip()+ if not name:+ raise CloudflareError('A tunnel name is required')+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ res = client.create_tunnel(account_id, name)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to create tunnel')}+ result = res.get('result') or {}+ tunnel_id = result.get('id')+ token = result.get('token')+ if not token and tunnel_id:+ tres = client.get_tunnel_token(account_id, tunnel_id)+ token = tres.get('result') if tres.get('success') else None++ rec = CloudflareTunnel(+ tunnel_id=tunnel_id, name=name, account_id=account_id,+ dns_provider_config_id=zone.dns_provider_config_id,+ token_encrypted=encrypt_secret(token) if token else None)+ db.session.add(rec)+ db.session.commit()+ return {'success': True, 'tunnel': rec.to_dict(),+ 'token': token, 'install': cls._install_command(token)}++ @classmethod+ def get_tunnel_install(cls, zone_id, tunnel_id):+ """Re-fetch the connector token + install command for a tunnel."""+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ tres = client.get_tunnel_token(account_id, tunnel_id)+ if not tres.get('success'):+ return {'success': False, 'error': tres.get('error', 'Failed to fetch token')}+ token = tres.get('result')+ return {'success': True, 'token': token, 'install': cls._install_command(token)}++ @classmethod+ def delete_tunnel(cls, zone_id, tunnel_id):+ from app import db+ from app.models.cloudflare_tunnel import CloudflareTunnel+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ res = client.delete_tunnel(account_id, tunnel_id)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to delete tunnel')}+ rec = CloudflareTunnel.query.filter_by(account_id=account_id, tunnel_id=tunnel_id).first()+ if rec:+ db.session.delete(rec)+ db.session.commit()+ return {'success': True}++ @classmethod+ def get_tunnel_hostnames(cls, zone_id, tunnel_id):+ """The public-hostname ingress rules configured on a tunnel."""+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ res = client.get_tunnel_configuration(account_id, tunnel_id)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to load tunnel config')}+ ingress = ((res.get('result') or {}).get('config') or {}).get('ingress') or []+ hostnames = [{'hostname': r.get('hostname'), 'service': r.get('service')}+ for r in ingress if r.get('hostname')]+ return {'success': True, 'hostnames': hostnames}++ @classmethod+ def add_tunnel_hostname(cls, zone_id, tunnel_id, hostname, service):+ """Route a public hostname to a local service through the tunnel, and+ best-effort create the proxied CNAME that points it at the tunnel."""+ hostname = (hostname or '').strip().lower().rstrip('.')+ service = (service or '').strip()+ if not hostname or not service:+ raise CloudflareError('Both a hostname and a service '+ '(e.g. http://localhost:8080) are required')+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)++ cur = client.get_tunnel_configuration(account_id, tunnel_id)+ config = ((cur.get('result') or {}).get('config') or {}) if cur.get('success') else {}+ # Keep only real hostname rules, replace/insert this one, re-add catch-all.+ ingress = [r for r in (config.get('ingress') or [])+ if r.get('hostname') and r.get('hostname') != hostname]+ ingress.append({'hostname': hostname, 'service': service})+ ingress.append({'service': 'http_status:404'})+ config['ingress'] = ingress++ res = client.put_tunnel_configuration(account_id, tunnel_id, config)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to set tunnel route')}+ dns = cls._ensure_tunnel_cname(zone, client, hostname, tunnel_id)+ return {'success': True, 'dns': dns}++ @classmethod+ def remove_tunnel_hostname(cls, zone_id, tunnel_id, hostname):+ hostname = (hostname or '').strip().lower().rstrip('.')+ if not hostname:+ raise CloudflareError('A hostname is required')+ zone, client = cls._zone_and_client(zone_id)+ account_id = cls._account_id(zone, client)+ cur = client.get_tunnel_configuration(account_id, tunnel_id)+ config = ((cur.get('result') or {}).get('config') or {}) if cur.get('success') else {}+ ingress = [r for r in (config.get('ingress') or [])+ if r.get('hostname') and r.get('hostname') != hostname]+ ingress.append({'service': 'http_status:404'})+ config['ingress'] = ingress+ res = client.put_tunnel_configuration(account_id, tunnel_id, config)+ if not res.get('success'):+ return {'success': False, 'error': res.get('error', 'Failed to remove tunnel route')}+ return {'success': True}++ @staticmethod+ def _ensure_tunnel_cname(zone, client, hostname, tunnel_id):+ """Best-effort: upsert the proxied CNAME ``hostname → <id>.cfargotunnel.com``+ that publishes the tunnel. Reported, never fatal — the route is already set."""+ try:+ from app.services.dns.base import DnsRecordSpec+ from app.services.dns_ownership_service import DnsOwnershipService+ target = f'{tunnel_id}.cfargotunnel.com'+ spec = DnsRecordSpec(record_type='CNAME', name=hostname, content=target,+ ttl=1, proxied=True)+ res = DnsOwnershipService.guarded_upsert(+ client, provider='cloudflare', provider_zone_id=zone.provider_zone_id,+ spec=spec, source='cf-tunnel', config_id=zone.dns_provider_config_id,+ allow_foreign=True)+ return {'created': bool(res.get('success')),+ 'error': None if res.get('success') else res.get('error')}+ except Exception as e:+ return {'created': False, 'error': str(e)}diff --git a/backend/app/services/dns/cloudflare.py b/backend/app/services/dns/cloudflare.pyindex 20f0b866..81415c62 100644--- a/backend/app/services/dns/cloudflare.py+++ b/backend/app/services/dns/cloudflare.py@@ -350,3 +350,34 @@ class CloudflareClient:def delete_worker_route(self, zone_id: str, route_id: str) -> dict:return self.request('DELETE', f'/zones/{zone_id}/workers/routes/{route_id}')++ # ── Tunnels (cloudflared / cfd_tunnel) ────────────────────────────────────+ # Account-scoped. As of Dec 2025 the list endpoint defaults to active-only;+ # we pass is_deleted=false explicitly to be unambiguous.+ def list_tunnels(self, account_id: str) -> dict:+ return self.request('GET', f'/accounts/{account_id}/cfd_tunnel',+ params={'is_deleted': 'false'})++ def create_tunnel(self, account_id: str, name: str) -> dict:+ """Create a remotely-managed tunnel (config stored at Cloudflare)."""+ return self.request('POST', f'/accounts/{account_id}/cfd_tunnel',+ json={'name': name, 'config_src': 'cloudflare'})++ def delete_tunnel(self, account_id: str, tunnel_id: str) -> dict:+ return self.request('DELETE', f'/accounts/{account_id}/cfd_tunnel/{tunnel_id}')++ def get_tunnel_token(self, account_id: str, tunnel_id: str) -> dict:+ """The connector token (``result`` is the token string for ``cloudflared``)."""+ return self.request('GET', f'/accounts/{account_id}/cfd_tunnel/{tunnel_id}/token')++ def get_tunnel_connections(self, account_id: str, tunnel_id: str) -> dict:+ return self.request('GET', f'/accounts/{account_id}/cfd_tunnel/{tunnel_id}/connections')++ def get_tunnel_configuration(self, account_id: str, tunnel_id: str) -> dict:+ return self.request('GET', f'/accounts/{account_id}/cfd_tunnel/{tunnel_id}/configurations')++ def put_tunnel_configuration(self, account_id: str, tunnel_id: str, config: dict) -> dict:+ """Set the tunnel's ingress rules (public hostname → local service)."""+ return self.request('PUT',+ f'/accounts/{account_id}/cfd_tunnel/{tunnel_id}/configurations',+ json={'config': config})diff --git a/backend/tests/test_cloudflare_zone_settings.py b/backend/tests/test_cloudflare_zone_settings.pyindex 924676c1..bf9307a3 100644--- a/backend/tests/test_cloudflare_zone_settings.py+++ b/backend/tests/test_cloudflare_zone_settings.py@@ -469,3 +469,138 @@ def test_delete_worker_removes_local_row(app, monkeypatch):res = CloudflareService.delete_worker(zone.id, 'gone')assert res['success'] is Trueassert CloudflareWorker.query.filter_by(account_id='acct1', name='gone').first() is None+++# ── Tunnels (Phase 5) ────────────────────────────────────────────────────────++def test_client_list_tunnels_passes_is_deleted_false(monkeypatch):+ from app.services.dns import cloudflare as cf+ seen = {}++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ seen.update(params=params, url=url)+ return _Resp({'success': True, 'result': []})+ monkeypatch.setattr(cf.requests, 'request', req)+ _client().list_tunnels('acct1')+ assert seen['params'] == {'is_deleted': 'false'}+ assert seen['url'].endswith('/accounts/acct1/cfd_tunnel')+++def test_client_create_tunnel_uses_cloudflare_config_src(monkeypatch):+ from app.services.dns import cloudflare as cf+ seen = {}++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ seen.update(json=json)+ return _Resp({'success': True, 'result': {'id': 't'}})+ monkeypatch.setattr(cf.requests, 'request', req)+ _client().create_tunnel('acct1', 'home')+ assert seen['json'] == {'name': 'home', 'config_src': 'cloudflare'}+++def test_create_tunnel_requires_name(app):+ from app.services.cloudflare_service import CloudflareService, CloudflareError+ zone = _make_cf_zone()+ with pytest.raises(CloudflareError):+ CloudflareService.create_tunnel(zone.id, ' ')+++def test_create_tunnel_stores_token_and_returns_install(app, monkeypatch):+ from app.services.dns import cloudflare as cf+ from app.services.cloudflare_service import CloudflareService+ from app.models.cloudflare_tunnel import CloudflareTunnel+ from app.utils.crypto import decrypt_secret_safe+ zone = _make_cf_zone()++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ if method == 'GET' and url.endswith('/zones/zoneABC'):+ return _Resp({'success': True, 'result': {'account': {'id': 'acct1'}}})+ if method == 'POST' and url.endswith('/accounts/acct1/cfd_tunnel'):+ return _Resp({'success': True, 'result': {'id': 'tun1', 'token': 'TOKEN123'}})+ return _Resp({'success': False})+ monkeypatch.setattr(cf.requests, 'request', req)++ res = CloudflareService.create_tunnel(zone.id, 'home')+ assert res['success'] is True and res['token'] == 'TOKEN123'+ assert res['install'] == 'cloudflared service install TOKEN123'+ rec = CloudflareTunnel.query.filter_by(account_id='acct1', tunnel_id='tun1').first()+ assert rec is not None+ # Token stored encrypted at rest, recoverable via the safe decrypt.+ assert rec.token_encrypted != 'TOKEN123'+ assert decrypt_secret_safe(rec.token_encrypted) == 'TOKEN123'+++def test_list_tunnels_flags_managed(app, monkeypatch):+ from app import db+ from app.services.dns import cloudflare as cf+ from app.services.cloudflare_service import CloudflareService+ from app.models.cloudflare_tunnel import CloudflareTunnel+ zone = _make_cf_zone()+ db.session.add(CloudflareTunnel(tunnel_id='tun1', name='mine', account_id='acct1'))+ db.session.commit()++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ if url.endswith('/zones/zoneABC'):+ return _Resp({'success': True, 'result': {'account': {'id': 'acct1'}}})+ if url.endswith('/accounts/acct1/cfd_tunnel'):+ return _Resp({'success': True, 'result': [+ {'id': 'tun1', 'name': 'mine', 'status': 'healthy', 'connections': [{}]},+ {'id': 'tun2', 'name': 'other', 'status': 'down'}]})+ return _Resp({'success': False})+ monkeypatch.setattr(cf.requests, 'request', req)++ res = CloudflareService.list_tunnels(zone.id)+ by_id = {t['id']: t for t in res['tunnels']}+ assert by_id['tun1']['managed'] is True and by_id['tun1']['connections'] == 1+ assert by_id['tun2']['managed'] is False+++def test_delete_tunnel_removes_local_row(app, monkeypatch):+ from app import db+ from app.services.dns import cloudflare as cf+ from app.services.cloudflare_service import CloudflareService+ from app.models.cloudflare_tunnel import CloudflareTunnel+ zone = _make_cf_zone()+ db.session.add(CloudflareTunnel(tunnel_id='tun1', name='mine', account_id='acct1'))+ db.session.commit()++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ if url.endswith('/zones/zoneABC'):+ return _Resp({'success': True, 'result': {'account': {'id': 'acct1'}}})+ if method == 'DELETE' and url.endswith('/accounts/acct1/cfd_tunnel/tun1'):+ return _Resp({'success': True})+ return _Resp({'success': False})+ monkeypatch.setattr(cf.requests, 'request', req)++ res = CloudflareService.delete_tunnel(zone.id, 'tun1')+ assert res['success'] is True+ assert CloudflareTunnel.query.filter_by(account_id='acct1', tunnel_id='tun1').first() is None+++def test_add_tunnel_hostname_sets_ingress_with_catchall(app, monkeypatch):+ from app.services.dns import cloudflare as cf+ from app.services.cloudflare_service import CloudflareService+ zone = _make_cf_zone()+ put_body = {}++ def req(method, url, headers=None, json=None, params=None, timeout=None):+ if method == 'GET' and url.endswith('/zones/zoneABC'):+ return _Resp({'success': True, 'result': {'account': {'id': 'acct1'}}})+ if method == 'GET' and url.endswith('/cfd_tunnel/tun1/configurations'):+ return _Resp({'success': True, 'result': {'config': {'ingress': [+ {'service': 'http_status:404'}]}}})+ if method == 'PUT' and url.endswith('/cfd_tunnel/tun1/configurations'):+ put_body.update(json or {})+ return _Resp({'success': True, 'result': {}})+ return _Resp({'success': False})+ monkeypatch.setattr(cf.requests, 'request', req)+ # Isolate the ingress logic from the best-effort CNAME upsert.+ monkeypatch.setattr(CloudflareService, '_ensure_tunnel_cname',+ lambda zone, client, hostname, tunnel_id: {'created': True, 'error': None})++ res = CloudflareService.add_tunnel_hostname(+ zone.id, 'tun1', 'App.Example.com', 'http://localhost:8080')+ assert res['success'] is True and res['dns']['created'] is True+ ingress = put_body['config']['ingress']+ assert ingress[0] == {'hostname': 'app.example.com', 'service': 'http://localhost:8080'}+ assert ingress[-1] == {'service': 'http_status:404'} # required catch-all is lastdiff --git a/frontend/src/components/cloudflare/TunnelsPanel.jsx b/frontend/src/components/cloudflare/TunnelsPanel.jsxnew file mode 100644index 00000000..d7765a12--- /dev/null+++ b/frontend/src/components/cloudflare/TunnelsPanel.jsx@@ -0,0 +1,369 @@+import { useState, useEffect, useCallback } from 'react';+import { Network } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Badge } from '@/components/ui/badge';+import EmptyState from '../EmptyState';+import { useToast } from '../../contexts/ToastContext';+import api from '../../services/api';++function InstallBox({ command }) {+ const toast = useToast();++ if (!command) {+ return <p className="cf-tunnels__hint">No install command available.</p>;+ }++ const handleCopy = async () => {+ try {+ await navigator.clipboard?.writeText(command);+ toast.success('Copied');+ } catch (err) {+ toast.error(err.message);+ }+ };++ return (+ <div className="cf-tunnels__install">+ <code className="cf-tunnels__cmd">{command}</code>+ <Button size="sm" variant="outline" onClick={handleCopy}>+ Copy+ </Button>+ </div>+ );+}++function TunnelRow({ zoneId, tunnel, isAdmin, onChanged }) {+ const toast = useToast();++ const [install, setInstall] = useState(null);+ const [expanded, setExpanded] = useState(false);+ const [hostnames, setHostnames] = useState([]);+ const [hostname, setHostname] = useState('');+ const [service, setService] = useState('');+ const [working, setWorking] = useState(false);++ const loadHostnames = useCallback(async () => {+ try {+ const res = await api.getCloudflareTunnelHostnames(zoneId, tunnel.id);+ setHostnames(res.hostnames || []);+ } catch (err) {+ toast.error(err.message);+ }+ }, [zoneId, tunnel.id, toast]);++ const handleToggleInstall = async () => {+ if (install) {+ setInstall(null);+ return;+ }+ setWorking(true);+ try {+ const res = await api.getCloudflareTunnelInstall(zoneId, tunnel.id);+ setInstall(res.install || null);+ } catch (err) {+ toast.error(err.message);+ } finally {+ setWorking(false);+ }+ };++ const handleToggleHostnames = async () => {+ const next = !expanded;+ setExpanded(next);+ if (next && hostnames.length === 0) {+ await loadHostnames();+ }+ };++ const handleDelete = async () => {+ setWorking(true);+ try {+ await api.deleteCloudflareTunnel(zoneId, tunnel.id);+ toast.success(`Deleted Cloudflare Tunnel "${tunnel.name}"`);+ onChanged();+ } catch (err) {+ toast.error(err.message);+ } finally {+ setWorking(false);+ }+ };++ const handleRemoveHostname = async (h) => {+ setWorking(true);+ try {+ await api.removeCloudflareTunnelHostname(zoneId, tunnel.id, h.hostname);+ toast.success('Hostname removed');+ await loadHostnames();+ } catch (err) {+ toast.error(err.message);+ } finally {+ setWorking(false);+ }+ };++ const handleAddHostname = async () => {+ setWorking(true);+ try {+ const res = await api.addCloudflareTunnelHostname(+ zoneId,+ tunnel.id,+ hostname,+ service,+ );+ toast.success('Hostname routed');+ if (res.dns && !res.dns.created) {+ toast.error('Route set, but the DNS record failed: ' + res.dns.error);+ }+ setHostname('');+ setService('');+ await loadHostnames();+ } catch (err) {+ toast.error(err.message);+ } finally {+ setWorking(false);+ }+ };++ const writeDisabled = !isAdmin || working;++ return (+ <li className="cf-tunnels__item">+ <div className="cf-tunnels__item-head">+ <span className="cf-tunnels__name">{tunnel.name}</span>+ <code className="cf-tunnels__meta">{tunnel.id.slice(0, 12)}…</code>+ {tunnel.status && (+ <span className="cf-tunnels__meta">{tunnel.status}</span>+ )}+ {tunnel.connections != null && (+ <span className="cf-tunnels__meta">{tunnel.connections}</span>+ )}+ {tunnel.managed && <Badge variant="secondary">ServerKit</Badge>}+ </div>++ <div className="cf-tunnels__item-actions">+ <Button+ size="sm"+ variant="outline"+ onClick={handleToggleInstall}+ disabled={!isAdmin || working}+ >+ Install command+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={handleToggleHostnames}+ disabled={working}+ >+ Hostnames+ </Button>+ <Button+ variant="destructive"+ size="sm"+ onClick={handleDelete}+ disabled={writeDisabled}+ >+ Delete+ </Button>+ </div>++ {install && <InstallBox command={install} />}++ {expanded && (+ <div className="cf-tunnels__hostnames">+ {hostnames.length === 0 ? (+ <p className="cf-tunnels__hint">No public hostnames routed yet.</p>+ ) : (+ hostnames.map((h) => (+ <div className="cf-tunnels__host" key={h.hostname}>+ <span>+ <code>{h.hostname}</code> → <code>{h.service}</code>+ </span>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => handleRemoveHostname(h)}+ disabled={writeDisabled}+ >+ Remove+ </Button>+ </div>+ ))+ )}++ <div className="cf-tunnels__host-add">+ <Input+ value={hostname}+ placeholder="app.example.com"+ onChange={(e) => setHostname(e.target.value)}+ disabled={writeDisabled}+ />+ <Input+ value={service}+ placeholder="http://localhost:8080"+ onChange={(e) => setService(e.target.value)}+ disabled={writeDisabled}+ />+ <Button+ size="sm"+ onClick={handleAddHostname}+ disabled={writeDisabled || !hostname.trim() || !service.trim()}+ >+ Add+ </Button>+ </div>+ <p className="cf-tunnels__hint">+ The hostname should be inside this zone's domain; a proxied DNS+ record is created automatically.+ </p>+ </div>+ )}+ </li>+ );+}++export default function TunnelsPanel({ zoneId, isAdmin }) {+ const toast = useToast();++ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [tunnels, setTunnels] = useState([]);++ // Create form state+ const [name, setName] = useState('');+ const [creating, setCreating] = useState(false);+ const [lastInstall, setLastInstall] = useState(null);++ const loadData = useCallback(async () => {+ try {+ const data = await api.getCloudflareTunnels(zoneId);+ setTunnels(data.tunnels || []);+ setError(null);+ } catch (err) {+ setError(err.message);+ }+ }, [zoneId]);++ useEffect(() => {+ let active = true;+ setLoading(true);+ (async () => {+ try {+ const data = await api.getCloudflareTunnels(zoneId);+ if (!active) return;+ setTunnels(data.tunnels || []);+ setError(null);+ } catch (err) {+ if (active) setError(err.message);+ } finally {+ if (active) setLoading(false);+ }+ })();+ return () => {+ active = false;+ };+ }, [zoneId]);++ const handleCreate = async () => {+ setCreating(true);+ try {+ const res = await api.createCloudflareTunnel(zoneId, name);+ toast.success(`Created tunnel "${name}"`);+ setLastInstall({ name, install: res.install, token: res.token });+ setName('');+ await loadData();+ } catch (err) {+ toast.error(err.message);+ } finally {+ setCreating(false);+ }+ };++ if (loading) {+ return <div className="cf-tunnels__loading">Loading Cloudflare Tunnels…</div>;+ }++ if (error) {+ return (+ <EmptyState+ icon={Network}+ title="Cloudflare Tunnels unavailable"+ description={error}+ />+ );+ }++ const createDisabled = !isAdmin || creating || !name.trim();++ return (+ <div className="cf-tunnels">+ {/* Create a Cloudflare Tunnel */}+ <section className="cf-tunnels__section">+ <h3 className="cf-tunnels__heading">Create a Cloudflare Tunnel</h3>+ <p className="cf-tunnels__hint">+ A Cloudflare Tunnel exposes a local or private service through+ Cloudflare's edge — no public IP or open ports required.+ </p>++ <div className="cf-tunnels__field">+ <label className="cf-tunnels__label">Name</label>+ <Input+ value={name}+ placeholder="home-jellyfin"+ onChange={(e) => setName(e.target.value)}+ disabled={!isAdmin || creating}+ />+ </div>++ <div className="cf-tunnels__actions">+ <Button onClick={handleCreate} disabled={createDisabled}>+ Create+ </Button>+ </div>++ {lastInstall && (+ <div className="cf-tunnels__install">+ <p className="cf-tunnels__hint">+ Run this once on the machine hosting your local service. The+ connector token is shown only now.+ </p>+ <InstallBox command={lastInstall.install} />+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setLastInstall(null)}+ >+ Dismiss+ </Button>+ </div>+ )}+ </section>++ {/* Cloudflare Tunnels list */}+ <section className="cf-tunnels__section">+ <h3 className="cf-tunnels__heading">Cloudflare Tunnels ({tunnels.length})</h3>++ {tunnels.length === 0 ? (+ <EmptyState+ icon={Network}+ title="No Cloudflare Tunnels"+ description="Create one above to expose a local service without a public IP."+ />+ ) : (+ <ul className="cf-tunnels__list">+ {tunnels.map((tunnel) => (+ <TunnelRow+ key={tunnel.id}+ zoneId={zoneId}+ tunnel={tunnel}+ isAdmin={isAdmin}+ onChanged={loadData}+ />+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}diff --git a/frontend/src/pages/CloudflareZoneSettings.jsx b/frontend/src/pages/CloudflareZoneSettings.jsxindex c57e5249..947ae9be 100644--- a/frontend/src/pages/CloudflareZoneSettings.jsx+++ b/frontend/src/pages/CloudflareZoneSettings.jsx@@ -1,9 +1,10 @@import { useState, useEffect, useCallback } from 'react';import { useParams, Link } from 'react-router-dom';-import { Cloud, ShieldCheck, Lock, Gauge, Database, Wand2, Eraser, Flame, Zap } from 'lucide-react';+import { Cloud, ShieldCheck, Lock, Gauge, Database, Wand2, Eraser, Flame, Zap, Network } from 'lucide-react';import { PageTopbar } from '@/components/ds';import WafPanel from '../components/cloudflare/WafPanel';import WorkersPanel from '../components/cloudflare/WorkersPanel';+import TunnelsPanel from '../components/cloudflare/TunnelsPanel';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';import { Switch } from '@/components/ui/switch';import { Button } from '@/components/ui/button';@@ -189,6 +190,7 @@ const CloudflareZoneSettings = () => {))}<TabsTrigger value="waf"><Flame size={15} />WAF</TabsTrigger><TabsTrigger value="workers"><Zap size={15} />Workers</TabsTrigger>+ <TabsTrigger value="tunnels"><Network size={15} />Tunnels</TabsTrigger><TabsTrigger value="actions"><Wand2 size={15} />Actions</TabsTrigger></TabsList>@@ -221,6 +223,12 @@ const CloudflareZoneSettings = () => {</div></TabsContent>+ <TabsContent value="tunnels">+ <div className="cf-panel">+ <TunnelsPanel zoneId={zoneId} isAdmin={isAdmin} />+ </div>+ </TabsContent>+<TabsContent value="actions"><div className="cf-panel cf-actions"><div className="cf-action">diff --git a/frontend/src/services/api/cloudflare.js b/frontend/src/services/api/cloudflare.jsindex 45850ede..bfc5db4d 100644--- a/frontend/src/services/api/cloudflare.js+++ b/frontend/src/services/api/cloudflare.js@@ -94,3 +94,43 @@ export async function deleteCloudflareWorkerRoute(zoneId, routeId) {method: 'DELETE',});}++// Cloudflare Tunnels (cloudflared) — expose a local service through the edge.+export async function getCloudflareTunnels(zoneId) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels`);+}++export async function createCloudflareTunnel(zoneId, name) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels`, {+ method: 'POST',+ body: { name },+ });+}++export async function deleteCloudflareTunnel(zoneId, tunnelId) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels/${tunnelId}`, {+ method: 'DELETE',+ });+}++export async function getCloudflareTunnelInstall(zoneId, tunnelId) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels/${tunnelId}/install`);+}++export async function getCloudflareTunnelHostnames(zoneId, tunnelId) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels/${tunnelId}/hostnames`);+}++export async function addCloudflareTunnelHostname(zoneId, tunnelId, hostname, service) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels/${tunnelId}/hostnames`, {+ method: 'POST',+ body: { hostname, service },+ });+}++export async function removeCloudflareTunnelHostname(zoneId, tunnelId, hostname) {+ return this.request(`/cloudflare/zones/${zoneId}/tunnels/${tunnelId}/hostnames`, {+ method: 'DELETE',+ body: { hostname },+ });+}diff --git a/frontend/src/styles/pages/_cloudflare-zone.scss b/frontend/src/styles/pages/_cloudflare-zone.scssindex 848d0c01..11a259d1 100644--- a/frontend/src/styles/pages/_cloudflare-zone.scss+++ b/frontend/src/styles/pages/_cloudflare-zone.scss@@ -362,3 +362,138 @@flex-shrink: 0;}}++// Tunnels tab — create form, install command box, tunnel list with hostnames.+.cf-tunnels {+ &__loading {+ padding: $spacing-lg;+ color: $text-muted;+ }++ &__section {+ padding: $spacing-md 0;+ border-bottom: 1px solid $border-color;++ &:last-child { border-bottom: none; }+ }++ &__heading {+ margin: 0 0 $spacing-sm;+ font-size: 0.95rem;+ }++ &__hint {+ margin: $spacing-xs 0 0;+ color: $text-muted;+ font-size: 0.82rem;+ }++ &__field {+ margin-bottom: $spacing-sm;+ max-width: 420px;+ }++ &__label {+ display: block;+ font-size: 0.82rem;+ color: $text-secondary;+ margin-bottom: 4px;+ }++ &__actions {+ display: flex;+ justify-content: flex-start;+ }++ &__install {+ margin-top: $spacing-md;+ padding: $spacing-md;+ background: $bg-code;+ border: 1px solid $border-color;+ border-radius: $radius-md;+ display: flex;+ flex-direction: column;+ gap: $spacing-sm;+ align-items: flex-start;+ }++ &__cmd {+ display: block;+ width: 100%;+ font-family: $font-mono;+ font-size: 0.8rem;+ color: $text-primary;+ white-space: pre-wrap;+ word-break: break-all;+ }++ &__list {+ list-style: none;+ margin: $spacing-sm 0 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: $spacing-sm;+ }++ &__item {+ padding: $spacing-md;+ background: $bg-elevated;+ border: 1px solid $border-color;+ border-radius: $radius-md;+ }++ &__item-head {+ display: flex;+ align-items: center;+ gap: $spacing-sm;+ flex-wrap: wrap;+ }++ &__name {+ font-weight: 600;+ color: $text-primary;+ }++ &__meta {+ color: $text-muted;+ font-size: 0.8rem;+ font-family: $font-mono;+ }++ &__item-actions {+ display: flex;+ gap: $spacing-sm;+ margin-top: $spacing-sm;+ flex-wrap: wrap;+ }++ &__hostnames {+ margin-top: $spacing-md;+ padding-top: $spacing-md;+ border-top: 1px solid $border-color;+ display: flex;+ flex-direction: column;+ gap: $spacing-sm;+ }++ &__host {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $spacing-md;++ code {+ font-family: $font-mono;+ font-size: 0.82rem;+ color: $text-secondary;+ }+ }++ &__host-add {+ display: flex;+ gap: $spacing-sm;+ flex-wrap: wrap;+ align-items: center;+ }+}