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(domains): unify domains & DNS into one surface + admin-only Connections
Juan Denisd344302ac13b
diff --git a/backend/app/api/connections.py b/backend/app/api/connections.pyindex c64e4133..dee0e95e 100644--- a/backend/app/api/connections.py+++ b/backend/app/api/connections.py@@ -5,8 +5,8 @@ is the single source of truth for "what's connected"."""from flask import Blueprint, jsonify-from flask_jwt_extended import jwt_required, get_jwt_identity+from app.middleware.rbac import admin_required, get_current_userfrom app.services.connection_registry import ConnectionRegistryconnections_bp = Blueprint('connections', __name__)@@ -14,12 +14,11 @@ connections_bp = Blueprint('connections', __name__)@connections_bp.route('', methods=['GET'])@connections_bp.route('/', methods=['GET'])-@jwt_required()+@admin_requireddef list_connections():- """List every connected external account (secret-free)."""- raw = get_jwt_identity()- try:- user_id = int(raw)- except (TypeError, ValueError):- user_id = raw- return jsonify({'connections': ConnectionRegistry.list_all(user_id=user_id)})+ """List every connected external account (secret-free). Admin-only — these are+ server-wide credentials (Cloudflare tokens, cloud keys, …), not personal+ settings, so the whole Connections surface lives under Administration."""+ user = get_current_user()+ return jsonify({'connections': ConnectionRegistry.list_all(+ user_id=user.id if user else None)})diff --git a/backend/app/api/dns_zones.py b/backend/app/api/dns_zones.pyindex 5475ebb4..c1961d99 100644--- a/backend/app/api/dns_zones.py+++ b/backend/app/api/dns_zones.py@@ -18,6 +18,51 @@ def list_zones():return jsonify({'zones': [z.to_dict() for z in zones]})+@dns_zones_bp.route('/portfolio', methods=['GET'])+@jwt_required()+def dns_portfolio():+ """Every domain visible across connected DNS providers, merged with adopted+ zones — powers the Domains-page portfolio. Read-only: viewing the inventory is+ open to any authenticated user; adopting/managing a zone is admin-gated."""+ return jsonify(DNSZoneService.list_portfolio())+++@dns_zones_bp.route('/adopt', methods=['POST'])+@jwt_required()+def adopt_zone():+ """Materialize a local zone row for a provider domain so it can be managed.+ Idempotent — returns the existing zone if already adopted."""+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403+ data = request.get_json() or {}+ try:+ zone = DNSZoneService.adopt_zone(+ data.get('domain'), data.get('dns_provider_config_id'))+ return jsonify(zone.to_dict())+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++@dns_zones_bp.route('/registration', methods=['GET'])+@jwt_required()+def domain_registration():+ """Registration expiry / registrar for a domain via RDAP — the lazy fallback+ when a connected provider has no registration data."""+ domain = request.args.get('domain', '')+ return jsonify(DNSZoneService.lookup_domain_registration(domain))+++@dns_zones_bp.route('/provider-records', methods=['GET'])+@jwt_required()+def provider_records():+ """Live DNS records for a provider zone addressed by ?config_id= and ?zone=+ (the provider's zone id) — powers the Domains drawer without adopting first."""+ config_id = request.args.get('config_id', type=int)+ zone = request.args.get('zone')+ return jsonify(DNSZoneService.list_provider_records_by_ref(config_id, zone))++@dns_zones_bp.route('/<int:zone_id>', methods=['GET'])@jwt_required()def get_zone(zone_id):diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex c0ef00e9..50ddf5f8 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -52,6 +52,7 @@ from app.queue_bus.models import QueueGroup, Queue, QueueMessagefrom app.notifications.models import Notification, NotificationDeliveryfrom app.models.email_provider import EmailProviderConnectionfrom app.models.system_event import SystemEvent+from app.models.domain_registration import DomainRegistration__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -86,4 +87,5 @@ __all__ = ['Notification', 'NotificationDelivery','EmailProviderConnection','SystemEvent',+ 'DomainRegistration',]diff --git a/backend/app/models/domain_registration.py b/backend/app/models/domain_registration.pynew file mode 100644index 00000000..12805597--- /dev/null+++ b/backend/app/models/domain_registration.py@@ -0,0 +1,28 @@+from datetime import datetime+from app import db+++class DomainRegistration(db.Model):+ """Cached domain registration facts (expiry, registrar) looked up lazily via+ RDAP/WHOIS. Persisted so the Domains list can show expiry without re-querying on+ every page load — keyed by bare domain so it works whether or not the domain is+ adopted as a DNS zone or attached to an app."""+ __tablename__ = 'domain_registrations'++ id = db.Column(db.Integer, primary_key=True)+ domain = db.Column(db.String(256), nullable=False, unique=True, index=True)+ expires_at = db.Column(db.DateTime, nullable=True)+ registrar = db.Column(db.String(255), nullable=True)+ auto_renew = db.Column(db.Boolean, nullable=True)+ source = db.Column(db.String(32), nullable=True) # rdap | provider+ checked_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ return {+ 'domain': self.domain,+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,+ 'registrar': self.registrar,+ 'auto_renew': self.auto_renew,+ 'source': self.source,+ 'checked_at': self.checked_at.isoformat() if self.checked_at else None,+ }diff --git a/backend/app/services/dns/cloudflare.py b/backend/app/services/dns/cloudflare.pyindex 5f75384b..3213367d 100644--- a/backend/app/services/dns/cloudflare.py+++ b/backend/app/services/dns/cloudflare.py@@ -76,19 +76,49 @@ class CloudflareClient:return {'success': False, 'error': str(e)}def list_zones(self) -> dict:- """List the zones this credential can manage."""+ """List the zones this credential can manage. Each zone carries its+ ``account_id`` so account-scoped lookups (e.g. registrar expiry) need no+ second discovery call."""try:- resp = requests.get(f'{API_BASE}/zones?per_page=50',+ resp = requests.get(f'{API_BASE}/zones?per_page=100',headers=self._headers(), timeout=15)data = resp.json()if not data.get('success'):return {'success': False, 'error': _first_error(data) or 'Failed to list zones'}- zones = [{'id': z['id'], 'name': z['name'], 'status': z['status']}+ zones = [{'id': z['id'], 'name': z['name'], 'status': z['status'],+ 'account_id': (z.get('account') or {}).get('id')}for z in data.get('result', [])]return {'success': True, 'zones': zones}except Exception as e:return {'success': False, 'error': str(e)}+ def list_registrar_domains(self, account_id: str) -> dict:+ """Domains registered through Cloudflare Registrar for ``account_id``, with+ their registration expiry and auto-renew flag.++ Best-effort by design: a DNS-scoped token without *Domain (Registrar): Read*+ returns an error the caller is expected to ignore (the domain simply shows no+ expiry), and only domains actually registered at Cloudflare appear — a zone+ whose domain is registered elsewhere won't be listed here."""+ if not account_id:+ return {'success': False, 'error': 'No account id'}+ try:+ resp = requests.get(+ f'{API_BASE}/accounts/{account_id}/registrar/domains?per_page=100',+ headers=self._headers(), timeout=15)+ data = resp.json()+ if not data.get('success'):+ return {'success': False, 'error': _first_error(data)}+ domains = [{+ 'name': (d.get('name') or '').lower().rstrip('.'),+ 'expires_at': d.get('expires_at'),+ 'auto_renew': d.get('auto_renew'),+ 'registrar': d.get('current_registrar') or 'Cloudflare',+ } for d in (data.get('result') or [])]+ return {'success': True, 'domains': domains}+ except Exception as e:+ return {'success': False, 'error': str(e)}+def list_records(self, zone_id: str) -> dict:"""List every record in a zone (paginated) — the live state the mirrorclassifies into ServerKit-owned vs the user's own records."""diff --git a/backend/app/services/dns_zone_service.py b/backend/app/services/dns_zone_service.pyindex fbf2d8f4..352d800d 100644--- a/backend/app/services/dns_zone_service.py+++ b/backend/app/services/dns_zone_service.py@@ -38,6 +38,105 @@ class DNSZoneService:def list_zones():return DNSZone.query.order_by(DNSZone.domain).all()+ @staticmethod+ def list_portfolio():+ """Every domain visible across connected DNS providers, merged with the+ locally-adopted zones — the data behind the Domains-page portfolio.++ For each connected ``DNSProviderConfig`` we read its account's zones live and+ tag each with whether ServerKit has already adopted it (so the UI can deep+ link straight to records / Cloudflare ops). A provider whose token can't+ enumerate zones (e.g. a single-zone scoped token) is reported under+ ``errors`` instead of silently showing nothing, so the UI can prompt for+ broader access.++ Returns ``{domains, providers, errors}``. Note: the underlying Cloudflare+ client lists the first page only, so accounts with very many zones may be+ partial — adoption still works for any domain typed in elsewhere.+ """+ from app.models.email import DNSProviderConfig+ from app.services.dns_provider_service import DNSProviderService++ # Adopted zones, keyed by bare domain, so a provider zone resolves its row.+ local_by_domain = {}+ for z in DNSZone.query.all():+ local_by_domain.setdefault((z.domain or '').lower().rstrip('.'), z)++ domains, errors, providers_out = [], [], []+ seen = set() # (provider, domain) — dedupe a domain shared across configs+ for cfg in DNSProviderConfig.query.order_by(DNSProviderConfig.name).all():+ providers_out.append({'id': cfg.id, 'name': cfg.name, 'provider': cfg.provider})+ zres = DNSProviderService.list_zones(cfg.id)+ if not zres.get('success'):+ errors.append({+ 'config_id': cfg.id, 'config_name': cfg.name,+ 'provider': cfg.provider, 'error': zres.get('error', 'unknown error'),+ })+ continue+ zones = zres.get('zones', [])+ registrar = DNSZoneService._cf_registrar_map(cfg, zones)+ for z in zones:+ name = (z.get('name') or '').strip().lower().rstrip('.')+ if not name or (cfg.provider, name) in seen:+ continue+ seen.add((cfg.provider, name))+ local = local_by_domain.get(name)+ reg = registrar.get(name) or {}+ domains.append({+ 'domain': name,+ 'provider': cfg.provider,+ 'provider_zone_id': z.get('id'),+ 'status': z.get('status'),+ 'config_id': cfg.id,+ 'config_name': cfg.name,+ 'adopted': local is not None,+ 'zone_id': local.id if local else None,+ 'record_count': local.records.count() if local else None,+ # Registration expiry / auto-renew — present only when the domain is+ # registered at Cloudflare and the token can read Registrar.+ 'expires_at': reg.get('expires_at'),+ 'auto_renew': reg.get('auto_renew'),+ 'registrar': reg.get('registrar'),+ })++ # Fill expiry/registrar from the persisted RDAP cache for any domain a+ # provider didn't supply (most domains are registered outside their DNS+ # provider) — so a lookup done in the drawer shows up in the list after.+ from app.models.domain_registration import DomainRegistration+ cache = {r.domain: r for r in DomainRegistration.query.all()}+ for d in domains:+ if not d.get('expires_at'):+ cached = cache.get(d['domain'])+ if cached and cached.expires_at:+ d['expires_at'] = cached.expires_at.isoformat()+ if not d.get('registrar'):+ d['registrar'] = cached.registrar++ domains.sort(key=lambda d: d['domain'])+ return {'domains': domains, 'providers': providers_out, 'errors': errors}++ @staticmethod+ def _cf_registrar_map(config, zones):+ """Map ``domain -> {expires_at, auto_renew, registrar}`` from Cloudflare+ Registrar for the accounts that own ``zones``. Best-effort: returns ``{}`` for+ non-Cloudflare providers, or when the token can't read Registrar (a DNS-only+ scope) — the portfolio then simply shows no expiry for those domains."""+ if config.provider != 'cloudflare':+ return {}+ try:+ from app.services.dns import CloudflareClient+ from app.services.dns.base import DnsCredential+ client = CloudflareClient(DnsCredential.from_provider_config(config))+ out = {}+ for account_id in {z.get('account_id') for z in zones if z.get('account_id')}:+ res = client.list_registrar_domains(account_id)+ if res.get('success'):+ for d in res.get('domains', []):+ out[d['name']] = d+ return out+ except Exception:+ return {}+@staticmethoddef get_zone(zone_id):return DNSZone.query.get(zone_id)@@ -86,6 +185,30 @@ class DNSZoneService:db.session.commit()return zone+ @staticmethod+ def adopt_zone(domain, config_id=None):+ """Idempotently materialize a local zone row for a provider domain so it can+ be managed (records, Cloudflare ops). Returns the existing row when the zone+ is already adopted — safe to call on every "Manage" click. Backfills the+ connection link on a pre-existing manual row when a ``config_id`` is given.+ """+ domain = (domain or '').strip().lower().rstrip('.')+ if not domain:+ raise ValueError('Domain required')+ existing = DNSZone.query.filter_by(domain=domain).first()+ if existing:+ if config_id and not existing.dns_provider_config_id:+ from app.models.email import DNSProviderConfig+ config = DNSProviderConfig.query.get(int(config_id))+ if config:+ existing.provider = config.provider+ existing.dns_provider_config_id = config.id+ db.session.commit()+ return existing+ return DNSZoneService.create_zone({+ 'domain': domain, 'dns_provider_config_id': config_id,+ })+@classmethoddef link_legacy_zones(cls):"""One-time, idempotent: migrate Cloudflare zones that still carry an inline@@ -181,6 +304,146 @@ class DNSZoneService:},}+ @staticmethod+ def list_provider_records_by_ref(config_id, provider_zone_id):+ """Live records for a Cloudflare zone addressed directly by connection ++ provider zone id — so the Domains drawer can show a domain's real DNS without+ first adopting it into a local zone row. Each record is tagged ``serverkit``+ (owned) or ``external`` like the zone mirror."""+ from app.models.email import DNSProviderConfig+ config = DNSProviderConfig.query.get(int(config_id)) if config_id else None+ if not config:+ return {'success': False, 'error': 'Connection not found'}+ if config.provider != 'cloudflare':+ return {'success': False, 'error': 'Live records are only available for Cloudflare'}+ if not provider_zone_id:+ return {'success': False, 'error': 'No provider zone id for this domain'}++ from app.services.dns import CloudflareClient+ from app.services.dns.base import DnsCredential+ from app.services.dns_ownership_service import DnsOwnershipService++ res = CloudflareClient(DnsCredential.from_provider_config(config)).list_records(provider_zone_id)+ if not res.get('success'):+ return res+ owned_ids, owned_keys = DnsOwnershipService.owned_keys(provider_zone_id)+ records = []+ for r in res['records']:+ owned = (r['id'] in owned_ids) or \+ ((r['type'], (r['name'] or '').lower().rstrip('.')) in owned_keys)+ records.append({**r, 'managed_by': 'serverkit' if owned else 'external'})+ return {+ 'success': True,+ 'records': records,+ 'counts': {+ 'serverkit': sum(1 for x in records if x['managed_by'] == 'serverkit'),+ 'external': sum(1 for x in records if x['managed_by'] == 'external'),+ },+ }++ @staticmethod+ def _rdap_entity_name(entity):+ """Pull a display name out of an RDAP entity's jCard (vcardArray)."""+ try:+ for item in entity.get('vcardArray', [])[1]:+ if item[0] == 'fn':+ return item[3]+ except Exception:+ pass+ return None++ @staticmethod+ def _parse_rdap_date(s):+ """Parse an RDAP eventDate (ISO 8601, often Zulu) into a naive-UTC datetime."""+ if not s:+ return None+ try:+ from datetime import timezone+ s = s.strip()+ if s.endswith('Z'):+ s = s[:-1] + '+00:00'+ dt = datetime.fromisoformat(s)+ if dt.tzinfo:+ dt = dt.astimezone(timezone.utc).replace(tzinfo=None)+ return dt+ except Exception:+ return None++ @staticmethod+ def _registration_is_fresh(row):+ if not row.checked_at:+ return False+ age = (datetime.utcnow() - row.checked_at).total_seconds()+ # Expiry dates change rarely → cache 30d; negative results re-checked in 3d.+ ttl = 30 * 86400 if row.expires_at else 3 * 86400+ return age < ttl++ @staticmethod+ def _rdap_query(domain):+ """One RDAP HTTP lookup. Returns {success, expires_at(iso str), registrar}."""+ import requests+ try:+ resp = requests.get(+ f'https://rdap.org/domain/{domain}',+ headers={'Accept': 'application/rdap+json'}, timeout=8)+ if resp.status_code == 404:+ return {'success': False, 'error': 'Domain not found in RDAP'}+ if resp.status_code != 200:+ return {'success': False, 'error': f'RDAP returned {resp.status_code}'}+ data = resp.json()+ except Exception as e:+ return {'success': False, 'error': str(e)}+ expires_at = None+ for ev in data.get('events') or []:+ if ev.get('eventAction') in ('expiration', 'expiry'):+ expires_at = ev.get('eventDate')+ break+ registrar = None+ for ent in data.get('entities') or []:+ if 'registrar' in (ent.get('roles') or []):+ registrar = DNSZoneService._rdap_entity_name(ent)+ break+ return {'success': True, 'expires_at': expires_at, 'registrar': registrar}++ @staticmethod+ def lookup_domain_registration(domain, force=False):+ """Registration expiry + registrar for a domain, **cached** in the+ ``domain_registrations`` table. Looks up via RDAP (the JSON-over-HTTPS WHOIS+ successor; rdap.org bootstraps the right registry — no `whois` binary) only+ when there's no fresh cached row, then persists the result so the Domains+ list shows it without re-querying on every load. ``force`` bypasses the cache.+ """+ from app.models.domain_registration import DomainRegistration+ domain = (domain or '').strip().lower().rstrip('.')+ if not domain or '.' not in domain:+ return {'success': False, 'error': 'Invalid domain'}++ row = DomainRegistration.query.filter_by(domain=domain).first()+ if row and not force and DNSZoneService._registration_is_fresh(row):+ return {'success': True, 'cached': True, **row.to_dict()}++ result = DNSZoneService._rdap_query(domain)++ if row is None:+ row = DomainRegistration(domain=domain)+ db.session.add(row)+ if result.get('success'):+ row.expires_at = DNSZoneService._parse_rdap_date(result.get('expires_at'))+ row.registrar = result.get('registrar')+ row.source = 'rdap'+ row.checked_at = datetime.utcnow()+ try:+ db.session.commit()+ except Exception:+ db.session.rollback()++ if result.get('success'):+ return {'success': True, **row.to_dict()}+ # Transient failure — surface previously cached data if we have it.+ if row.expires_at:+ return {'success': True, 'stale': True, **row.to_dict()}+ return {'success': False, 'error': result.get('error', 'lookup failed')}+@staticmethoddef create_record(zone_id, data):zone = DNSZone.query.get(zone_id)diff --git a/backend/tests/test_dns_portfolio.py b/backend/tests/test_dns_portfolio.pynew file mode 100644index 00000000..18f2dd59--- /dev/null+++ b/backend/tests/test_dns_portfolio.py@@ -0,0 +1,250 @@+"""Proving tests for the DNS domain portfolio (Domains-page "see all my domains").++Before this, a connected Cloudflare account's zones never surfaced anywhere — the+Domains page only listed app-linked rows and DNS Zones only listed hand-added+zones. ``DNSZoneService.list_portfolio`` reads each connected provider's account+live and merges it with the locally-adopted zones, and ``adopt_zone`` lazily+materializes a managed zone row on demand (idempotently). These tests prove:++* provider zones surface as un-adopted portfolio rows,+* an already-adopted domain is flagged with its local zone id + record count,+* a token that can't enumerate zones is reported under ``errors`` (not swallowed),+* adopt is idempotent — clicking "Manage" twice never duplicates a zone, and+* the HTTP endpoint returns the portfolio to an authenticated caller.+"""++from app.services.dns_provider_service import DNSProviderService+from app.services.dns_zone_service import DNSZoneService+++def _add_connection(name='cf', token='tok'):+ from app.models.email import DNSProviderConfig+ DNSProviderService.add_provider(name=name, provider='cloudflare', api_key=token)+ return DNSProviderConfig.query.filter_by(name=name).first()+++def _stub_zones(monkeypatch, result):+ """Make every DNSProviderService.list_zones(config_id) return ``result``."""+ monkeypatch.setattr(DNSProviderService, 'list_zones',+ classmethod(lambda cls, cid: result))+++def test_portfolio_lists_provider_zones_unadopted(app, monkeypatch):+ conn = _add_connection()+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'example.com', 'status': 'active'},+ {'id': 'z2', 'name': 'shop.example.com', 'status': 'pending'},+ ]})++ out = DNSZoneService.list_portfolio()+ by_domain = {d['domain']: d for d in out['domains']}++ assert set(by_domain) == {'example.com', 'shop.example.com'}+ apex = by_domain['example.com']+ assert apex['provider'] == 'cloudflare'+ assert apex['provider_zone_id'] == 'z1'+ assert apex['config_id'] == conn.id+ assert apex['adopted'] is False and apex['zone_id'] is None+ assert out['errors'] == []+ assert any(p['id'] == conn.id for p in out['providers'])+++def test_portfolio_marks_adopted_zone(app, monkeypatch):+ from app import db+ from app.models.dns_zone import DNSZone++ conn = _add_connection()+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'example.com', 'status': 'active'},+ ]})++ zone = DNSZone(domain='example.com', provider='cloudflare',+ provider_zone_id='z1', dns_provider_config_id=conn.id)+ db.session.add(zone)+ db.session.commit()++ apex = next(d for d in DNSZoneService.list_portfolio()['domains']+ if d['domain'] == 'example.com')+ assert apex['adopted'] is True+ assert apex['zone_id'] == zone.id+ assert apex['record_count'] == 0+++def test_portfolio_surfaces_scoped_token_error(app, monkeypatch):+ """A single-zone scoped token can't list zones — surface it, don't show nothing."""+ conn = _add_connection()+ _stub_zones(monkeypatch, {'success': False, 'error': 'token lacks Zone:Read'})++ out = DNSZoneService.list_portfolio()+ assert out['domains'] == []+ assert len(out['errors']) == 1+ assert out['errors'][0]['config_id'] == conn.id+ assert 'Zone:Read' in out['errors'][0]['error']+++def test_adopt_zone_is_idempotent(app, monkeypatch):+ from app.models.dns_zone import DNSZone++ conn = _add_connection()+ # create_zone matches the typed domain to a provider zone via list_zones.+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'example.com'},+ ]})++ z1 = DNSZoneService.adopt_zone('example.com', conn.id)+ assert z1.provider == 'cloudflare'+ assert z1.provider_zone_id == 'z1'+ assert z1.dns_provider_config_id == conn.id++ z2 = DNSZoneService.adopt_zone('EXAMPLE.com', conn.id) # case-insensitive, again+ assert z2.id == z1.id+ assert DNSZone.query.filter_by(domain='example.com').count() == 1+++def test_portfolio_enriches_cloudflare_registrar_expiry(app, monkeypatch):+ """A Cloudflare-registered domain gets its expiry + auto-renew from the Registrar+ API; a zone registered elsewhere (no registrar entry) shows none."""+ from app.services.dns import CloudflareClient++ _add_connection()+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'example.com', 'status': 'active', 'account_id': 'acct1'},+ {'id': 'z2', 'name': 'elsewhere.com', 'status': 'active', 'account_id': 'acct1'},+ ]})+ monkeypatch.setattr(CloudflareClient, 'list_registrar_domains',+ lambda self, acct: {'success': True, 'domains': [+ {'name': 'example.com', 'expires_at': '2027-01-01T00:00:00Z',+ 'auto_renew': True, 'registrar': 'Cloudflare'},+ ]})++ by_domain = {d['domain']: d for d in DNSZoneService.list_portfolio()['domains']}+ assert by_domain['example.com']['expires_at'] == '2027-01-01T00:00:00Z'+ assert by_domain['example.com']['auto_renew'] is True+ # A zone not registered at Cloudflare has no registrar row → no expiry.+ assert by_domain['elsewhere.com']['expires_at'] is None+ assert by_domain['elsewhere.com']['auto_renew'] is None+++def test_provider_records_by_ref_lists_live_records(app, monkeypatch):+ """The drawer reads a domain's live records by connection + provider zone id,+ without adopting first; each record is tagged owned vs external."""+ from app.services.dns import CloudflareClient++ conn = _add_connection()+ monkeypatch.setattr(CloudflareClient, 'list_records',+ lambda self, zid: {'success': True, 'records': [+ {'id': 'r1', 'type': 'A', 'name': 'example.com',+ 'content': '1.2.3.4', 'ttl': 1, 'proxied': True, 'priority': None},+ ]})++ res = DNSZoneService.list_provider_records_by_ref(conn.id, 'zoneX')+ assert res['success'] is True+ assert res['records'][0]['type'] == 'A'+ assert res['records'][0]['proxied'] is True+ # Nothing in the ownership ledger → classified as the user's own record.+ assert res['records'][0]['managed_by'] == 'external'+ assert res['counts'] == {'serverkit': 0, 'external': 1}+++def test_provider_records_by_ref_requires_cloudflare(app):+ res = DNSZoneService.list_provider_records_by_ref(999999, 'zoneX')+ assert res['success'] is False+++def test_portfolio_endpoint_returns_domains(app, client, auth_headers, monkeypatch):+ _add_connection()+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'example.com', 'status': 'active'},+ ]})++ resp = client.get('/api/v1/dns/portfolio', headers=auth_headers)+ assert resp.status_code == 200+ body = resp.get_json()+ assert [d['domain'] for d in body['domains']] == ['example.com']+ assert body['domains'][0]['adopted'] is False+++def test_lookup_domain_registration_rdap(app, monkeypatch):+ """RDAP fallback parses the expiration event + registrar name from the response."""+ import requests++ class _Resp:+ status_code = 200++ def json(self):+ return {+ 'events': [+ {'eventAction': 'registration', 'eventDate': '2020-01-01T00:00:00Z'},+ {'eventAction': 'expiration', 'eventDate': '2027-03-04T00:00:00Z'},+ ],+ 'entities': [{+ 'roles': ['registrar'],+ 'vcardArray': ['vcard', [['version', {}, 'text', '4.0'],+ ['fn', {}, 'text', 'MarkMonitor Inc.']]],+ }],+ }++ monkeypatch.setattr(requests, 'get', lambda url, headers=None, timeout=None: _Resp())+ res = DNSZoneService.lookup_domain_registration('example.com')+ assert res['success'] is True+ # Round-trips through the cache as a parsed datetime (Zulu normalized away).+ assert res['expires_at'].startswith('2027-03-04')+ assert res['registrar'] == 'MarkMonitor Inc.'+++def test_lookup_domain_registration_not_found(app, monkeypatch):+ import requests++ class _Resp:+ status_code = 404++ def json(self):+ return {}++ monkeypatch.setattr(requests, 'get', lambda url, headers=None, timeout=None: _Resp())+ assert DNSZoneService.lookup_domain_registration('nope.invalid')['success'] is False+++def test_registration_persists_and_caches(app, monkeypatch):+ """A lookup is saved to the cache table and a second call is served from it+ without re-querying RDAP — so the data survives a page refresh."""+ from app.models.domain_registration import DomainRegistration++ calls = {'n': 0}++ def fake_rdap(domain):+ calls['n'] += 1+ return {'success': True, 'expires_at': '2027-03-04T00:00:00Z', 'registrar': 'GoDaddy.com, LLC'}++ monkeypatch.setattr(DNSZoneService, '_rdap_query', staticmethod(fake_rdap))++ r1 = DNSZoneService.lookup_domain_registration('builditdesign.com')+ assert r1['success'] and r1['registrar'] == 'GoDaddy.com, LLC'+ row = DomainRegistration.query.filter_by(domain='builditdesign.com').first()+ assert row is not None and row.expires_at is not None++ r2 = DNSZoneService.lookup_domain_registration('builditdesign.com')+ assert r2.get('cached') is True+ assert calls['n'] == 1 # second call hit the cache, not the network+++def test_portfolio_merges_cached_registration(app, monkeypatch):+ """Expiry looked up earlier (and cached) shows up in the portfolio/table even+ though the provider supplies none."""+ from app import db+ from datetime import datetime+ from app.models.domain_registration import DomainRegistration++ _add_connection()+ _stub_zones(monkeypatch, {'success': True, 'zones': [+ {'id': 'z1', 'name': 'builditdesign.com', 'status': 'active'}, # no account_id → no registrar call+ ]})+ db.session.add(DomainRegistration(+ domain='builditdesign.com', expires_at=datetime(2027, 3, 4),+ registrar='GoDaddy.com, LLC', source='rdap'))+ db.session.commit()++ apex = next(d for d in DNSZoneService.list_portfolio()['domains']+ if d['domain'] == 'builditdesign.com')+ assert apex['expires_at'] is not None+ assert apex['registrar'] == 'GoDaddy.com, LLC'diff --git a/frontend/src/components/domains/DomainDnsPanel.jsx b/frontend/src/components/domains/DomainDnsPanel.jsxnew file mode 100644index 00000000..1a7ce71c--- /dev/null+++ b/frontend/src/components/domains/DomainDnsPanel.jsx@@ -0,0 +1,253 @@+// The DNS records section shown inside the Domains drawer — the same inline+// experience for an app-created domain and a Cloudflare zone, so the two no longer+// feel like different products. For a Cloudflare domain it shows the *live* zone+// records (tagged ServerKit-managed vs your own), so you can see the real DNS+// without leaving the drawer; for a ServerKit/manual zone it shows the managed+// records. Admins can add a record inline (the zone is adopted on demand), and+// deeper management links out to the Cloudflare ops surface / full DNS page.+import { useState, useEffect, useCallback } from 'react';+import { useNavigate } from 'react-router-dom';+import { Network, Plus, RefreshCw, ExternalLink, Cloud, ShieldCheck } from 'lucide-react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { ProviderBrandIcon } from '../icons/ProviderBrands';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { FormField, FormRow } from '../FormField';+import {+ Select, SelectTrigger, SelectContent, SelectItem, SelectValue,+} from '@/components/ui/select';++const RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'SRV', 'CAA', 'NS'];+const PROXYABLE = ['A', 'AAAA', 'CNAME'];+const EMPTY_FORM = { record_type: 'A', name: '@', content: '', ttl: 3600, priority: '', proxied: false };++const normalizeLive = (r) => ({+ id: r.id, type: r.type, name: r.name, content: r.content,+ ttl: r.ttl, proxied: r.proxied, priority: r.priority, source: r.managed_by,+});+const normalizeManaged = (r) => ({+ id: r.id, type: r.record_type, name: r.name, content: r.content,+ ttl: r.ttl, proxied: r.proxied, priority: r.priority, source: 'serverkit',+});++export default function DomainDnsPanel({ domain, isAdmin }) {+ const navigate = useNavigate();+ const toast = useToast();+ const isCloudflare = domain?.provider === 'cloudflare';+ const canLive = isCloudflare && !!domain?.provider_zone_id && !!domain?.config_id;++ const [records, setRecords] = useState([]);+ const [state, setState] = useState('loading'); // loading | ready | none | error+ const [error, setError] = useState('');+ const [zoneId, setZoneId] = useState(domain?.zone_id || null); // local DNSZone id, once known+ const [showAdd, setShowAdd] = useState(false);+ const [form, setForm] = useState(EMPTY_FORM);+ const [saving, setSaving] = useState(false);++ const load = useCallback(async () => {+ if (!domain) return;+ setState('loading');+ setError('');+ setZoneId(domain.zone_id || null); // reset so a prior domain's id can't leak in+ try {+ if (canLive) {+ const res = await api.getProviderRecords(domain.config_id, domain.provider_zone_id);+ if (!res.success) { setError(res.error || 'Could not load records'); setState('error'); return; }+ setRecords((res.records || []).map(normalizeLive));+ setZoneId(domain.zone_id || null);+ } else if (domain.zone_id) {+ const res = await api.getDNSRecords(domain.zone_id);+ setRecords((res.records || []).map(normalizeManaged));+ setZoneId(domain.zone_id);+ } else {+ // App/manual domain without a provider zone — match a local zone by name.+ const zones = (await api.getDNSZones()).zones || [];+ const zone = zones.find((z) => z.domain === domain.name);+ if (!zone) { setState('none'); return; }+ const res = await api.getDNSRecords(zone.id);+ setRecords((res.records || []).map(normalizeManaged));+ setZoneId(zone.id);+ }+ setState('ready');+ } catch (e) {+ setError(e.message || 'Could not load records');+ setState('error');+ }+ }, [domain, canLive]);++ useEffect(() => { setShowAdd(false); setForm(EMPTY_FORM); load(); }, [load]);++ // Materialize the local zone row on demand (writes / Cloudflare ops need it).+ async function ensureZone() {+ if (zoneId) return zoneId;+ const zone = await api.adoptDnsZone(domain.name, domain.config_id);+ setZoneId(zone.id);+ return zone.id;+ }++ async function handleAdd() {+ setSaving(true);+ try {+ const zid = await ensureZone();+ await api.createDNSRecord(zid, {+ record_type: form.record_type,+ name: form.name || '@',+ content: form.content,+ ttl: Number(form.ttl) || 3600,+ priority: form.priority !== '' && form.priority != null ? Number(form.priority) : null,+ proxied: isCloudflare && PROXYABLE.includes(form.record_type) ? !!form.proxied : false,+ });+ toast.success('Record added');+ setShowAdd(false);+ setForm(EMPTY_FORM);+ await load();+ } catch (e) {+ toast.error(e.message || 'Failed to add record');+ } finally {+ setSaving(false);+ }+ }++ async function openCloudflareOps() {+ try {+ const zid = await ensureZone();+ navigate(`/cloudflare/zones/${zid}`);+ } catch (e) {+ toast.error(e.message || 'Could not open Cloudflare');+ }+ }++ // A proxied A/AAAA/CNAME means Cloudflare terminates TLS at its edge — i.e. the+ // site is served over HTTPS with no separate certificate to manage here.+ const hasProxiedSSL = isCloudflare && records.some((r) => r.proxied && PROXYABLE.includes(r.type));++ return (+ <div className="ddp">+ <div className="ddp__head">+ <h3 className="ddp__title">+ DNS records{state === 'ready' && <span className="ddp__count"> · {records.length}</span>}+ </h3>+ <div className="ddp__head-actions">+ <Button variant="ghost" size="sm" onClick={load} title="Refresh records">+ <RefreshCw size={14} />+ </Button>+ {isAdmin && (state === 'ready' || state === 'none') && (+ <Button size="sm" onClick={() => setShowAdd((v) => !v)}>+ <Plus size={14} /> Add record+ </Button>+ )}+ </div>+ </div>++ {canLive && (+ <p className="ddp__hint">+ Live from Cloudflare — records ServerKit manages are tagged; the rest are your own and shown read-only.+ </p>+ )}++ {state === 'ready' && hasProxiedSSL && (+ <p className="ddp__ssl">+ <ShieldCheck size={13} /> HTTPS is served by Cloudflare on proxied records — no separate certificate needed.+ </p>+ )}++ {showAdd && isAdmin && (+ <div className="ddp__form">+ <FormRow>+ <FormField label="Type">+ <Select value={form.record_type} onValueChange={(v) => setForm({ ...form, record_type: v })}>+ <SelectTrigger><SelectValue /></SelectTrigger>+ <SelectContent>{RECORD_TYPES.map((t) => <SelectItem key={t} value={t}>{t}</SelectItem>)}</SelectContent>+ </Select>+ </FormField>+ <FormField label="Name">+ <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="@ or subdomain" />+ </FormField>+ </FormRow>+ <FormField label="Content">+ <Input value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} placeholder="IP address or target" />+ </FormField>+ <FormRow>+ <FormField label="TTL">+ <Input type="number" value={form.ttl} onChange={(e) => setForm({ ...form, ttl: e.target.value })} />+ </FormField>+ {(form.record_type === 'MX' || form.record_type === 'SRV') && (+ <FormField label="Priority">+ <Input type="number" value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })} />+ </FormField>+ )}+ </FormRow>+ {isCloudflare && PROXYABLE.includes(form.record_type) && (+ <label className="ddp__proxy-toggle">+ <input type="checkbox" checked={!!form.proxied} onChange={(e) => setForm({ ...form, proxied: e.target.checked })} />+ Proxy through Cloudflare (orange cloud)+ </label>+ )}+ <div className="ddp__form-actions">+ <Button variant="outline" size="sm" onClick={() => setShowAdd(false)}>Cancel</Button>+ <Button size="sm" disabled={!form.content || saving} onClick={handleAdd}>+ {saving ? 'Adding…' : 'Add record'}+ </Button>+ </div>+ </div>+ )}++ {state === 'loading' && <p className="ddp__msg">Loading records…</p>}+ {state === 'error' && <p className="ddp__msg ddp__msg--error">{error}</p>}+ {state === 'none' && <p className="ddp__msg">This domain isn't set up for DNS in ServerKit yet.</p>}++ {state === 'ready' && (+ records.length === 0 ? (+ <p className="ddp__msg">No DNS records yet.</p>+ ) : (+ <div className="ddp__table-wrap">+ <table className="sk-dtable ddp__table">+ <thead>+ <tr>+ <th className="ddp__c-type">Type</th>+ <th className="ddp__c-name">Name</th>+ <th>Content</th>+ <th className="ddp__c-ttl">TTL</th>+ {isCloudflare && <th className="ddp__c-proxy">Proxy</th>}+ {canLive && <th className="ddp__c-src">Source</th>}+ </tr>+ </thead>+ <tbody>+ {records.map((r) => (+ <tr key={r.id}>+ <td><span className={`dns-rtype dns-rtype--${(r.type || '').toLowerCase()}`}>{r.type}</span></td>+ <td className="sk-cell-mono ddp__c-name" title={r.name}>{r.name}</td>+ <td className="sk-cell-mono ddp__content" title={r.content}>{r.priority ? `${r.priority} ` : ''}{r.content}</td>+ <td className="sk-cell-mono">{r.ttl === 1 ? 'Auto' : r.ttl}</td>+ {isCloudflare && (+ <td>{r.proxied+ ? <span className="ddp__proxy ddp__proxy--on"><Cloud size={12} /> Proxied</span>+ : <span className="ddp__proxy">DNS only</span>}</td>+ )}+ {canLive && (+ <td>{r.source === 'serverkit'+ ? <span className="ddp__src ddp__src--sk">ServerKit</span>+ : <span className="ddp__src">External</span>}</td>+ )}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )+ )}++ <div className="ddp__foot">+ {isCloudflare && (+ <Button variant="outline" size="sm" onClick={openCloudflareOps}>+ <ProviderBrandIcon provider="cloudflare" size={14} /> Open in Cloudflare+ </Button>+ )}+ <Button variant="ghost" size="sm" onClick={() => navigate('/dns')}>+ <Network size={14} /> Full DNS page <ExternalLink size={12} />+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/settings/connections/ConnectionsHub.jsx b/frontend/src/components/settings/connections/ConnectionsHub.jsxindex c2a10a82..d97dfa6a 100644--- a/frontend/src/components/settings/connections/ConnectionsHub.jsx+++ b/frontend/src/components/settings/connections/ConnectionsHub.jsx@@ -318,6 +318,7 @@ export default function ConnectionsHub() {connected: true, statusLabel: list.length === 1 ? 'Connected' : `${list.length} connected`, statusTone: 'ok',subtitle: list.map((p) => p.name).join(', '),scopes: dedupeScopes(list.map(deriveScope).filter(Boolean)),+ manageHref: '/domains', manageLabel: 'Domains',}: { connected: false, statusLabel: 'Not connected', statusTone: 'neutral', scopes: [] };} else if (provider.kind === 'registrar') {@@ -365,6 +366,19 @@ export default function ConnectionsHub() {const unencryptedCount = allConnections.filter((c) => c && c.encrypted === false).length;+ // Defense in depth: Settings only mounts this for admins and the registry API is+ // admin-gated, but guard here too so the hub never half-renders for a non-admin.+ if (!isAdmin) {+ return (+ <div className="connections-hub">+ <div className="connections-hub__warning">+ <ShieldAlert size={16} />+ <span>Connections are managed by administrators.</span>+ </div>+ </div>+ );+ }+return (<div className="connections-hub">{!loading && unencryptedCount > 0 && (diff --git a/frontend/src/pages/Domains.jsx b/frontend/src/pages/Domains.jsxindex b3d2fdee..98cdf0f0 100644--- a/frontend/src/pages/Domains.jsx+++ b/frontend/src/pages/Domains.jsx@@ -1,11 +1,11 @@import { useState, useEffect } from 'react';-import { useNavigate } from 'react-router-dom';import {Globe, Plus, ShieldCheck, RefreshCw, Trash2, ExternalLink,- AlertTriangle, Clock, Lock, Search, ChevronRight, Network as NetworkIcon,+ AlertTriangle, Clock, Lock, Search, ChevronRight,} from 'lucide-react';import api from '../services/api';import { useToast } from '../contexts/ToastContext';+import { useAuth } from '../contexts/AuthContext';import EmptyState from '../components/EmptyState';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';@@ -17,22 +17,22 @@ import {import { MetricCard, SegControl, Pill, Drawer, DataTable } from '@/components/ds';import { useTopbarActions } from '@/hooks/useTopbarActions';import RegistrarPortfolio from '../components/domains/RegistrarPortfolio';+import { ProviderBrandIcon } from '../components/icons/ProviderBrands';+import DomainDnsPanel from '../components/domains/DomainDnsPanel';+import { formatExpiry } from '../utils/expiry';const Domains = () => {const toast = useToast();- const navigate = useNavigate();+ const { isAdmin } = useAuth();const [domains, setDomains] = useState([]);const [apps, setApps] = useState([]);+ const [portfolio, setPortfolio] = useState([]); // zones across connected DNS providers+ const [portfolioErrors, setPortfolioErrors] = useState([]);const [loading, setLoading] = useState(true);const [error, setError] = useState('');const [filter, setFilter] = useState('all');const [drawerDomain, setDrawerDomain] = useState(null);-- // Inline DNS records for the open drawer domain- const [dnsRecords, setDnsRecords] = useState([]);- const [dnsLoading, setDnsLoading] = useState(false);- const [dnsError, setDnsError] = useState('');- const [dnsHasZone, setDnsHasZone] = useState(true);+ const [regInfo, setRegInfo] = useState(null); // lazy registration lookup for the open drawer// Modal statesconst [showAddModal, setShowAddModal] = useState(false);@@ -50,38 +50,29 @@ const Domains = () => {loadData();}, []);- // Load DNS records for the domain shown in the drawer. A domain has no zone- // reference, so we match it to a DNS zone by name; unmanaged domains have no- // zone and fall back to the empty/hint state rather than erroring.+ // Lazily resolve registration (expiry/registrar) for the open provider domain:+ // use the provider value if present, else fall back to a one-off RDAP lookup.useEffect(() => {- if (!drawerDomain) return;+ if (!drawerDomain || drawerDomain.source === 'app') { setRegInfo(null); return; }+ if (drawerDomain.expires_at) {+ setRegInfo({+ expires_at: drawerDomain.expires_at,+ auto_renew: drawerDomain.auto_renew,+ registrar: drawerDomain.registrar,+ source: drawerDomain.registrar ? 'cache' : 'provider',+ });+ return;+ }let cancelled = false;- const domainName = drawerDomain.name;-- async function loadDnsRecords() {- setDnsLoading(true);- setDnsError('');- setDnsRecords([]);- setDnsHasZone(true);- try {- const zonesData = await api.getDNSZones();- const zone = (zonesData.zones || []).find(z => z.domain === domainName);+ setRegInfo({ loading: true });+ api.getDomainRegistration(drawerDomain.name)+ .then((r) => {if (cancelled) return;- if (!zone) {- setDnsHasZone(false);- return;- }- const recordsData = await api.getDNSRecords(zone.id);- if (cancelled) return;- setDnsRecords(recordsData.records || []);- } catch {- if (!cancelled) setDnsError('Failed to load DNS records');- } finally {- if (!cancelled) setDnsLoading(false);- }- }-- loadDnsRecords();+ setRegInfo(r && r.success+ ? { expires_at: r.expires_at, registrar: r.registrar, source: 'rdap' }+ : { error: (r && r.error) || 'not found' });+ })+ .catch(() => { if (!cancelled) setRegInfo({ error: 'lookup failed' }); });return () => { cancelled = true; };}, [drawerDomain]);@@ -92,12 +83,15 @@ const Domains = () => {promise,new Promise((_, reject) => setTimeout(() => reject(new Error('Request timeout')), ms)),]);- const [domainsData, appsData] = await Promise.all([+ const [domainsData, appsData, portfolioData] = await Promise.all([timeout(api.getDomains(), 10000).catch(() => ({ domains: [] })),timeout(api.getApps(), 10000).catch(() => ({ apps: [] })),+ timeout(api.getDnsPortfolio(), 15000).catch(() => ({ domains: [], errors: [] })),]);setDomains(domainsData.domains || []);setApps(appsData.apps || []);+ setPortfolio(portfolioData.domains || []);+ setPortfolioErrors(portfolioData.errors || []);} catch (err) {setError('Failed to load data');console.error(err);@@ -215,14 +209,60 @@ const Domains = () => {return <Pill kind="gray">No SSL</Pill>;}+ // One unified list: ServerKit's app-linked domains + every zone in a connected+ // DNS provider. A domain that is both keeps its app row and gains the provider+ // badge, expiry, and quick actions; provider-only zones become their own rows.+ const norm = (s) => (s || '').toLowerCase().replace(/\.$/, '');+ const providerByDomain = new Map(portfolio.map((z) => [norm(z.domain), z]));+ const appNames = new Set(domains.map((d) => norm(d.name)));+ const mergedRows = [+ ...domains.map((d) => {+ const p = providerByDomain.get(norm(d.name));+ return {+ ...d,+ key: `app:${d.id}`,+ source: 'app',+ provider: p?.provider || null,+ config_id: p?.config_id ?? null,+ config_name: p?.config_name ?? null,+ provider_zone_id: p?.provider_zone_id ?? null,+ adopted: p?.adopted ?? false,+ zone_id: p?.zone_id ?? null,+ expires_at: p?.expires_at ?? null,+ auto_renew: p?.auto_renew ?? null,+ registrar: p?.registrar ?? null,+ };+ }),+ ...portfolio+ .filter((z) => !appNames.has(norm(z.domain)))+ .map((z) => ({+ key: `prov:${z.provider}:${z.domain}`,+ source: 'provider',+ name: z.domain,+ provider: z.provider,+ config_id: z.config_id,+ config_name: z.config_name,+ provider_zone_id: z.provider_zone_id,+ adopted: z.adopted,+ zone_id: z.zone_id,+ cfStatus: z.status,+ expires_at: z.expires_at,+ auto_renew: z.auto_renew,+ registrar: z.registrar,+ application_id: null,+ ssl_enabled: false,+ is_primary: false,+ })),+ ].sort((a, b) => a.name.localeCompare(b.name));+const sslActiveCount = domains.filter(d => d.ssl_enabled).length;const expiringCount = domains.filter(d => sslState(d) === 'expiring').length;const attentionCount = domains.filter(d => !d.ssl_enabled).length;- const shown = domains.filter(d => (+ const shown = mergedRows.filter(d => (filter === 'all' ? true: filter === 'ssl' ? sslState(d) === 'expiring'- : filter === 'issues' ? !d.ssl_enabled : true+ : filter === 'issues' ? (d.source !== 'provider' && !d.ssl_enabled) : true));useTopbarActions(() =>@@ -250,17 +290,17 @@ const Domains = () => {{loading ? (<EmptyState loading title="Loading domains..." />- ) : domains.length === 0 ? (+ ) : mergedRows.length === 0 ? (<EmptyStateicon={Globe}- title="No domains configured"- description="Add a domain to your application to get started."+ title="No domains yet"+ description="Attach a domain to an application, or connect a DNS provider to see its zones here."action={<Button onClick={() => setShowAddModal(true)}><Plus size={16} /> Add Domain</Button>}/>) : (<div className="domains-body"><div className="dom-kpis">- <MetricCard tone="accent" icon={<Globe size={16} />} value={domains.length} label="Domains" />+ <MetricCard tone="accent" icon={<Globe size={16} />} value={mergedRows.length} label="Domains" /><MetricCard tone="green" icon={<Lock size={16} />} value={sslActiveCount} label="SSL active" /><MetricCard tone="amber" icon={<Clock size={16} />} value={expiringCount} label="Expiring ≤30d" /><MetricCard tone="red" icon={<AlertTriangle size={16} />} value={attentionCount} label="Needs attention" />@@ -279,6 +319,18 @@ const Domains = () => {/></div>+ {portfolioErrors.length > 0 && (+ <div className="dom-portfolio-note">+ <AlertTriangle size={14} />+ <span>+ {portfolioErrors.length === 1+ ? `${portfolioErrors[0].config_name}: ${portfolioErrors[0].error}`+ : `${portfolioErrors.length} DNS connections couldn't list their zones`}+ {' — '}a Cloudflare token needs <strong>Zone:Read</strong> on all zones to list the whole account.+ </span>+ </div>+ )}+{shown.length === 0 ? (<div className="dom-empty">No domains match this filter.</div>) : (@@ -287,7 +339,7 @@ const Domains = () => {tableClassName="sk-dtable"sortable={false}data={shown}- keyField="id"+ keyField="key"onRowClick={setDrawerDomain}columns={[{@@ -295,10 +347,15 @@ const Domains = () => {header: 'Domain',render: (d) => (<div className="sk-cell-name">- <span className="dom-fav"><Globe size={15} /></span>+ <span className="dom-fav">+ {d.provider+ ? <ProviderBrandIcon provider={d.provider} size={15} />+ : <Globe size={15} />}+ </span><span>{d.name}{d.is_primary && <span className="dom-primary">Primary</span>}+ {d.source === 'provider' && d.adopted && <span className="dom-managed">Managed</span>}</span></div>),@@ -312,21 +369,33 @@ const Domains = () => {: <span className="dom-dash">—</span>),},- { key: 'ssl', header: 'SSL', render: sslPill },+ {+ key: 'expiry',+ header: 'Expires',+ render: (d) => {+ const exp = formatExpiry(d.expires_at);+ if (!exp) return <span className="dom-dash">—</span>;+ return (+ <span className={`dom-expiry dom-expiry--${exp.tone}`} title={exp.relative}>+ {exp.absolute}+ </span>+ );+ },+ },+ {+ key: 'ssl',+ header: 'SSL',+ render: (d) => d.source === 'provider' ? <span className="dom-dash">—</span> : sslPill(d),+ },{key: 'autoRenew',header: 'Auto-renew',render: (d) => (- d.ssl_enabled- ? (d.ssl_auto_renew ? <Pill kind="green">on</Pill> : <Pill kind="gray">off</Pill>)- : <span className="dom-dash">—</span>+ d.auto_renew == null+ ? <span className="dom-dash">—</span>+ : d.auto_renew ? <Pill kind="green">on</Pill> : <Pill kind="gray">off</Pill>),},- {- key: 'status',- header: 'Status',- render: (d) => <Pill kind={d.ssl_enabled ? 'green' : 'amber'}>{d.ssl_enabled ? 'active' : 'unconfigured'}</Pill>,- },{key: 'chevron',header: '',@@ -344,122 +413,115 @@ const Domains = () => {<Draweropen={!!drawerDomain}onOpenChange={(open) => { if (!open) setDrawerDomain(null); }}- icon={<Globe size={18} />}+ icon={drawerDomain?.provider ? <ProviderBrandIcon provider={drawerDomain.provider} size={18} /> : <Globe size={18} />}iconColor="var(--accent-bright)"title={drawerDomain?.name || ''}subtitle={drawerDomain- ? `${drawerDomain.application_id ? getAppName(drawerDomain.application_id) : 'unlinked'} · ${sslState(drawerDomain)}`+ ? (drawerDomain.source === 'app'+ ? `${drawerDomain.application_id ? getAppName(drawerDomain.application_id) : 'unlinked'} · ${sslState(drawerDomain)}`+ : `${drawerDomain.config_name || drawerDomain.provider || 'DNS'} zone${drawerDomain.cfStatus ? ` · ${drawerDomain.cfStatus}` : ''}`): ''}- width={640}+ width={1100}+ headerExtra={drawerDomain && (+ <div className="dom-drawer__headeractions">+ <Button variant="outline" size="sm" asChild>+ <a href={`${drawerDomain.ssl_enabled ? 'https' : 'http'}://${drawerDomain.name}`} target="_blank" rel="noopener noreferrer">+ <ExternalLink size={14} /> Visit+ </a>+ </Button>+ {drawerDomain.source === 'app' && (+ <>+ <Button variant="outline" size="sm" onClick={() => handleVerifyDomain(drawerDomain)}>+ <Search size={14} /> Verify DNS+ </Button>+ {drawerDomain.ssl_enabled ? (+ <>+ <Button variant="outline" size="sm" disabled={actionLoading} onClick={() => handleRenewSsl(drawerDomain)}>+ <RefreshCw size={14} /> Renew SSL+ </Button>+ <Button variant="outline" size="sm" onClick={() => handleDisableSsl(drawerDomain)}>+ <Lock size={14} /> Disable SSL+ </Button>+ </>+ ) : (+ <Button size="sm" onClick={() => { setSelectedDomain(drawerDomain); setShowSslModal(true); setDrawerDomain(null); }}>+ <Lock size={14} /> Enable SSL+ </Button>+ )}+ </>+ )}+ </div>+ )}>{drawerDomain && (<div className="dom-drawer">- <div className="dom-drawer__actions">- <Button variant="outline" size="sm" asChild>- <a href={`${drawerDomain.ssl_enabled ? 'https' : 'http'}://${drawerDomain.name}`} target="_blank" rel="noopener noreferrer">- <ExternalLink size={14} /> Visit- </a>- </Button>- <Button variant="outline" size="sm" onClick={() => handleVerifyDomain(drawerDomain)}>- <Search size={14} /> Verify DNS- </Button>- {drawerDomain.ssl_enabled ? (+ <div className="dom-specs">+ {drawerDomain.source === 'app' ? (<>- <Button variant="outline" size="sm" disabled={actionLoading} onClick={() => handleRenewSsl(drawerDomain)}>- <RefreshCw size={14} /> Renew SSL- </Button>- <Button variant="outline" size="sm" onClick={() => handleDisableSsl(drawerDomain)}>- <Lock size={14} /> Disable SSL- </Button>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">SSL certificate</div>+ <div style={{ marginTop: 8 }}>{sslPill(drawerDomain)}</div>+ <div className="sk-spec-card__sub">+ {drawerDomain.ssl_enabled+ ? (drawerDomain.ssl_expires_at ? `Expires ${new Date(drawerDomain.ssl_expires_at).toLocaleDateString()}` : "Let's Encrypt")+ : 'Not issued'}+ </div>+ </div>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">Linked site</div>+ <div className="sk-spec-card__value">{drawerDomain.application_id ? getAppName(drawerDomain.application_id) : 'Unlinked'}</div>+ <div className="sk-spec-card__sub">{drawerDomain.is_primary ? 'Primary domain' : 'Alias'}</div>+ </div>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">Status</div>+ <div style={{ marginTop: 8 }}>+ <Pill kind={drawerDomain.ssl_enabled ? 'green' : 'amber'}>{drawerDomain.ssl_enabled ? 'active' : 'unconfigured'}</Pill>+ </div>+ <div className="sk-spec-card__sub">Auto-renew {drawerDomain.ssl_auto_renew ? 'on' : 'off'}</div>+ </div></>) : (- <Button size="sm" onClick={() => { setSelectedDomain(drawerDomain); setShowSslModal(true); setDrawerDomain(null); }}>- <Lock size={14} /> Enable SSL- </Button>+ <>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">DNS provider</div>+ <div className="sk-spec-card__value">{drawerDomain.config_name || drawerDomain.provider}</div>+ <div className="sk-spec-card__sub">{drawerDomain.adopted ? 'Managed in ServerKit' : 'Read-only'}</div>+ </div>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">Zone status</div>+ <div style={{ marginTop: 8 }}>+ <Pill kind={drawerDomain.cfStatus === 'active' ? 'green' : 'amber'}>{drawerDomain.cfStatus || 'active'}</Pill>+ </div>+ <div className="sk-spec-card__sub">{drawerDomain.provider}</div>+ </div>+ <div className="sk-spec-card">+ <div className="sk-spec-card__label">Registration</div>+ <div className="sk-spec-card__value">+ {regInfo?.loading ? 'Looking up…' : (formatExpiry(regInfo?.expires_at)?.relative || '—')}+ </div>+ <div className="sk-spec-card__sub">+ {regInfo?.loading ? 'WHOIS / RDAP lookup' : (() => {+ const exp = formatExpiry(regInfo?.expires_at);+ if (!exp) return regInfo?.error ? 'Lookup unavailable' : '—';+ return [exp.absolute, regInfo?.registrar].filter(Boolean).join(' · ');+ })()}+ </div>+ </div>+ </>)}</div>- <div className="dom-specs">- <div className="sk-spec-card">- <div className="sk-spec-card__label">SSL certificate</div>- <div style={{ marginTop: 8 }}>{sslPill(drawerDomain)}</div>- <div className="sk-spec-card__sub">- {drawerDomain.ssl_enabled- ? (drawerDomain.ssl_expires_at ? `Expires ${new Date(drawerDomain.ssl_expires_at).toLocaleDateString()}` : "Let's Encrypt")- : 'Not issued'}- </div>- </div>- <div className="sk-spec-card">- <div className="sk-spec-card__label">Linked site</div>- <div className="sk-spec-card__value">{drawerDomain.application_id ? getAppName(drawerDomain.application_id) : 'Unlinked'}</div>- <div className="sk-spec-card__sub">{drawerDomain.is_primary ? 'Primary domain' : 'Alias'}</div>- </div>- <div className="sk-spec-card">- <div className="sk-spec-card__label">Status</div>- <div style={{ marginTop: 8 }}>- <Pill kind={drawerDomain.ssl_enabled ? 'green' : 'amber'}>{drawerDomain.ssl_enabled ? 'active' : 'unconfigured'}</Pill>- </div>- <div className="sk-spec-card__sub">Auto-renew {drawerDomain.ssl_auto_renew ? 'on' : 'off'}</div>- </div>- </div>-- <div className="dom-drawer__section dom-dns">- <h3 className="dom-drawer__sectiontitle">- DNS records- {dnsHasZone && !dnsLoading && !dnsError && (- <span className="dom-dns__count">· {dnsRecords.length}</span>- )}- </h3>-- {dnsLoading ? (- <p className="dom-drawer__hint">Loading DNS records…</p>- ) : dnsError ? (- <p className="dom-drawer__hint dom-dns__error">{dnsError}</p>- ) : !dnsHasZone ? (- <p className="dom-drawer__hint">No DNS records — this domain isn't managed in DNS Zones.</p>- ) : dnsRecords.length === 0 ? (- <p className="dom-drawer__hint">No DNS records.</p>- ) : (- <div className="dom-dns__table">- <table className="sk-dtable">- <thead>- <tr>- <th className="dom-dns__col-type">Type</th>- <th>Name</th>- <th>Value</th>- <th className="dom-dns__col-ttl">TTL</th>- </tr>- </thead>- <tbody>- {dnsRecords.map(rec => (- <tr key={rec.id}>- <td>- <span className={`dns-rtype dns-rtype--${(rec.record_type || '').toLowerCase()}`}>- {rec.record_type}- </span>- </td>- <td className="sk-cell-mono">{rec.name}</td>- <td className="sk-cell-mono dom-dns__value">- {rec.priority ? `${rec.priority} ` : ''}{rec.content}- </td>- <td className="sk-cell-mono">{rec.ttl}</td>- </tr>- ))}- </tbody>- </table>- </div>- )}-- <Button variant="outline" size="sm" onClick={() => navigate('/dns')}>- <NetworkIcon size={14} /> Manage DNS records- </Button>+ <div className="dom-drawer__section">+ <DomainDnsPanel domain={drawerDomain} isAdmin={isAdmin} /></div>- <div className="dom-drawer__danger">- <Button variant="outline" size="sm" className="dom-delete-btn" onClick={() => { handleDeleteDomain(drawerDomain); setDrawerDomain(null); }}>- <Trash2 size={14} /> Delete domain- </Button>- </div>+ {drawerDomain.source === 'app' && (+ <div className="dom-drawer__danger">+ <Button variant="outline" size="sm" className="dom-delete-btn" onClick={() => { handleDeleteDomain(drawerDomain); setDrawerDomain(null); }}>+ <Trash2 size={14} /> Delete domain+ </Button>+ </div>+ )}</div>)}</Drawer>diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 96b72bd0..39ced436 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -29,7 +29,7 @@ const VALID_TABS = ['profile', 'security', 'connections', 'appearance', 'sidebar// Tabs that belong to the server-wide "Administration" group (admin-only); the// rest are personal "My Account" settings. Drives the two-way section switch so// personal prefs aren't interleaved with destructive system controls.-const ADMIN_TABS = ['users', 'activity', 'site', 'sso', 'api', 'ai', 'migrations', 'system', 'developer'];+const ADMIN_TABS = ['users', 'activity', 'site', 'connections', 'sso', 'api', 'ai', 'migrations', 'system', 'developer'];const Settings = () => {const [activeTab, setActiveTab] = useTabParam('/settings', VALID_TABS);@@ -113,14 +113,6 @@ const Settings = () => {</svg>Notifications</Button>- <Button- variant="ghost"- className={`settings-nav-item ${activeTab === 'connections' ? 'active' : ''}`}- onClick={() => setActiveTab('connections')}- >- <Link2 size={18} />- Connections- </Button><div className="settings-nav-divider">Preferences</div><Buttonvariant="ghost"@@ -221,6 +213,14 @@ const Settings = () => {</svg>Site Settings</Button>+ <Button+ variant="ghost"+ className={`settings-nav-item ${activeTab === 'connections' ? 'active' : ''}`}+ onClick={() => setActiveTab('connections')}+ >+ <Link2 size={18} />+ Connections+ </Button><Buttonvariant="ghost"className={`settings-nav-item ${activeTab === 'sso' ? 'active' : ''}`}@@ -299,7 +299,7 @@ const Settings = () => {<div className="settings-content">{activeTab === 'profile' && <ProfileTab />}{activeTab === 'security' && <SecuritySettingsTab />}- {activeTab === 'connections' && <ConnectionsHub />}+ {activeTab === 'connections' && isAdmin && <ConnectionsHub />}{activeTab === 'appearance' && <AppearanceTab />}{activeTab === 'sidebar' && <SidebarSettings />}{activeTab === 'whitelabel' && <WhiteLabelTab />}diff --git a/frontend/src/services/api/dns.js b/frontend/src/services/api/dns.jsindex 2a580b7a..3d179823 100644--- a/frontend/src/services/api/dns.js+++ b/frontend/src/services/api/dns.js@@ -12,6 +12,34 @@ export async function createDNSZone(data) {return this.request('/dns/', { method: 'POST', body: data });}+// Domains-page portfolio: every domain across connected DNS providers, merged with+// adopted zones (read-only; viewing is open to any authenticated user).+export async function getDnsPortfolio() {+ return this.request('/dns/portfolio');+}++// Idempotently adopt a provider domain into a managed zone so it can be edited /+// reached in the Cloudflare ops surface. Returns the (existing-or-new) zone.+export async function adoptDnsZone(domain, dnsProviderConfigId) {+ return this.request('/dns/adopt', {+ method: 'POST',+ body: { domain, dns_provider_config_id: dnsProviderConfigId },+ });+}++// Live records for a provider zone addressed by connection + provider zone id —+// lets the Domains drawer show a domain's real DNS without adopting it first.+export async function getProviderRecords(configId, providerZoneId) {+ const params = new URLSearchParams({ config_id: configId, zone: providerZoneId });+ return this.request(`/dns/provider-records?${params.toString()}`);+}++// Registration expiry / registrar via RDAP (WHOIS successor) — lazy fallback when+// no connected provider has the data. One domain per call.+export async function getDomainRegistration(domain) {+ return this.request(`/dns/registration?domain=${encodeURIComponent(domain)}`);+}+export async function deleteDNSZone(zoneId) {return this.request(`/dns/${zoneId}`, { method: 'DELETE' });}diff --git a/frontend/src/styles/pages/_domains.scss b/frontend/src/styles/pages/_domains.scssindex 69ae2f68..5af54e14 100644--- a/frontend/src/styles/pages/_domains.scss+++ b/frontend/src/styles/pages/_domains.scss@@ -92,7 +92,197 @@.dom-chev { color: var(--text-ghost); }+// "Managed" chip — a provider zone ServerKit has adopted for record/ops management.+.dom-managed {+ margin-left: $space-2;+ padding: 1px 6px;+ border-radius: $radius-sm;+ background: $success-bg;+ color: $success;+ font-size: 10px;+ font-weight: $font-weight-semibold;+}++// Registration expiry, coloured by urgency.+.dom-expiry {+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;++ &--green { color: $success; }+ &--amber { color: $warning; }+ &--red { color: $danger; }+}++// Inline per-row actions (DNS records / Cloudflare) for provider domains.+.dom-row-actions {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: $space-2;+}++// Notice when a connected token couldn't enumerate its zones (e.g. scoped token).+.dom-portfolio-note {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin-bottom: $space-3;+ padding: $space-2 $space-3;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ background: fade($warning, 8%);+ font-size: $font-size-xs;+ color: $text-secondary;++ svg { color: $warning; flex-shrink: 0; }+ strong { color: $text-primary; }+}++// DNS records panel inside the Domains drawer (DomainDnsPanel) — the unified+// inline DNS experience for both app domains and provider zones.+.ddp {+ display: flex;+ flex-direction: column;+ gap: $space-3;++ &__head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ }++ &__title {+ margin: 0;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }++ &__count { color: $text-tertiary; }++ &__head-actions { display: flex; align-items: center; gap: $space-2; }++ &__hint {+ margin: 0;+ font-size: $font-size-xs;+ color: $text-tertiary;+ }++ &__msg {+ margin: 0;+ padding: $space-4;+ text-align: center;+ font-size: $font-size-sm;+ color: $text-tertiary;+ background: var(--surface-2);+ border-radius: $radius-md;++ &--error { color: $danger; }+ }++ &__form {+ display: flex;+ flex-direction: column;+ gap: $space-3;+ padding: $space-3;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ background: var(--surface-2);+ }++ &__form-actions {+ display: flex;+ justify-content: flex-end;+ gap: $space-2;+ }++ &__proxy-toggle {+ display: flex;+ align-items: center;+ gap: $space-2;+ font-size: $font-size-sm;+ color: $text-secondary;+ cursor: pointer;+ }++ &__table-wrap { width: 100%; }++ // Fixed layout so the table never overflows the drawer — narrow columns get a+ // set width, Name + Content share the rest and ellipsis-truncate (full value+ // on hover via title), so there's no horizontal scroll.+ &__table {+ width: 100%;+ table-layout: fixed;++ td, th { white-space: nowrap; }+ }++ &__c-type { width: 58px; }+ &__c-ttl { width: 76px; }+ &__c-proxy { width: 116px; }+ &__c-src { width: 100px; }++ &__c-name,+ &__content {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__ssl {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0;+ font-size: $font-size-xs;+ color: $success;++ svg { flex-shrink: 0; }+ }++ &__proxy {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: $font-size-xs;+ color: $text-tertiary;++ &--on { color: #f6821f; font-weight: $font-weight-medium; }+ }++ &__src {+ font-size: 11px;+ font-weight: $font-weight-medium;+ color: $text-tertiary;+ padding: 1px 6px;+ border-radius: $radius-full;+ background: var(--surface-2);++ &--sk { color: $success; background: $success-bg; }+ }++ &__foot {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-wrap: wrap;+ padding-top: $space-2;+ border-top: 1px solid $border-subtle;+ }+}+// ── Detail drawer body ──────────────────────────────────────+// Header actions live in the drawer head (top-right); pad past the close "×".+.dom-drawer__headeractions {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: $space-2;+ padding-right: 32px;+}+.dom-drawer {padding: $space-5 $space-5 $space-8;display: flex;diff --git a/frontend/src/utils/expiry.js b/frontend/src/utils/expiry.jsnew file mode 100644index 00000000..6d14173a--- /dev/null+++ b/frontend/src/utils/expiry.js@@ -0,0 +1,28 @@+// Human-friendly expiry formatting for registration / certificate dates. Returns+// null for a missing or unparseable date, otherwise both an exact date and a+// relative phrase plus an urgency tone, so callers can show e.g. "439 days left"+// with the real date ("Mar 4, 2027") on a second line or in a tooltip.+export function formatExpiry(iso) {+ if (!iso) return null;+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return null;++ const days = Math.round((date.getTime() - Date.now()) / 86400000);+ const absolute = date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });++ let relative;+ if (days < 0) relative = `Expired ${Math.abs(days)}d ago`;+ else if (days === 0) relative = 'Expires today';+ else if (days < 60) relative = `${days} days left`;+ else if (days < 365) relative = `${Math.round(days / 30)} months left`;+ else {+ const years = Math.floor(days / 365);+ const months = Math.round((days % 365) / 30);+ relative = months ? `${years}y ${months}mo left` : `${years} year${years > 1 ? 's' : ''} left`;+ }++ const tone = days < 0 ? 'red' : days <= 30 ? 'amber' : 'green';+ return { days, absolute, relative, tone };+}++export default formatExpiry;