From ad5c9b6bf0e152017eecfa074e9e00330fcb1e8b Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Mon, 15 Jun 2026 00:30:50 -0400 Subject: [PATCH] feat(wordpress): attach a custom domain with auto-DNS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turns "point myblog.com at this site" into one action that consumes the URL-swap tool. New DNSProviderService.find_zone_for_domain (longest zone-suffix match across connected providers) + ensure_a_record upsert the A record via Cloudflare/ Route53, or return the exact record to add when nothing manages the zone. WordPressService.attach_custom_domain orchestrates it: auto-create DNS (server IP from SiteDomainService), optionally obtain a Let's Encrypt cert (the host vhost is written first so certbot --nginx can validate), then migrate the site URL to the domain via change_site_url. External steps degrade to warnings; only a requested migration that errors aborts. POST /wordpress/sites//domain (admin). Frontend: "Add Domain" button + AttachDomainModal — enter a domain, optional HTTPS, and the result shows the auto-created record or the exact A record to add manually. Co-Authored-By: Claude Opus 4.8 --- backend/app/api/wordpress.py | 22 ++ backend/app/services/dns_provider_service.py | 45 ++++ backend/app/services/wordpress_service.py | 72 +++++++ backend/tests/test_attach_domain.py | 196 ++++++++++++++++++ .../wordpress/AttachDomainModal.jsx | 136 ++++++++++++ frontend/src/pages/WordPressDetail.jsx | 18 ++ frontend/src/services/wordpress.js | 8 + frontend/src/styles/pages/_wordpress.scss | 28 +++ 8 files changed, 525 insertions(+) create mode 100644 backend/tests/test_attach_domain.py create mode 100644 frontend/src/components/wordpress/AttachDomainModal.jsx diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py index 9399b971..a9915f0d 100644 --- a/backend/app/api/wordpress.py +++ b/backend/app/api/wordpress.py @@ -1121,6 +1121,28 @@ def change_site_url(app_id): return jsonify(result), 200 if result.get('success') else 400 +@wordpress_bp.route('/sites//domain', methods=['POST']) +@jwt_required() +@admin_required +def attach_custom_domain(app_id): + """Attach a user-owned custom domain: auto-create the DNS A record (or return + it to add manually), optional Let's Encrypt cert, then migrate the site URL.""" + app = _resolve_app(app_id) + if not app: + return jsonify({'error': 'Application not found'}), 404 + data = request.get_json() or {} + domain = data.get('domain') + if not domain: + return jsonify({'error': 'domain is required'}), 400 + result = WordPressService.attach_custom_domain( + app, domain, + migrate=data.get('migrate', True), + issue_ssl=data.get('issue_ssl', False), + email=data.get('email'), + ) + return jsonify(result), 200 if result.get('success') else 400 + + @wordpress_bp.route('/sites//optimize', methods=['POST']) @jwt_required() @admin_required diff --git a/backend/app/services/dns_provider_service.py b/backend/app/services/dns_provider_service.py index 5e51d7b6..7560b1a0 100644 --- a/backend/app/services/dns_provider_service.py +++ b/backend/app/services/dns_provider_service.py @@ -151,6 +151,51 @@ class DNSProviderService: 'message': 'All DNS records deployed' if all_ok else 'Some records failed', } + @classmethod + def find_zone_for_domain(cls, domain: str): + """Find a connected provider + zone that authoritatively covers ``domain``. + + Picks the longest matching zone suffix across every configured provider + (so ``blog.example.com`` matches a zone ``example.com``). Returns + ``(config, zone_dict)`` or ``(None, None)`` when nothing manages it. + """ + domain = (domain or '').strip().lower().rstrip('.') + best = None # (config, zone, zone_name_length) + for config in DNSProviderConfig.query.all(): + zres = cls.list_zones(config.id) + if not zres.get('success'): + continue + for zone in zres.get('zones', []): + zname = (zone.get('name') or '').strip().lower().rstrip('.') + if zname and (domain == zname or domain.endswith('.' + zname)): + if best is None or len(zname) > best[2]: + best = (config, zone, len(zname)) + return (best[0], best[1]) if best else (None, None) + + @classmethod + def ensure_a_record(cls, domain: str, ip: str) -> Dict: + """Upsert an ``A`` record ``domain -> ip`` via whichever connected provider + manages the zone. Degrades to manual instructions (``created: False`` with + the record to add) when there's no server IP, no provider, or an API error + — so the caller can always show the user what to do. + """ + domain = (domain or '').strip().lower().rstrip('.') + record = {'type': 'A', 'name': domain, 'value': ip} + if not domain: + return {'created': False, 'reason': 'no_domain', 'record': record} + if not ip: + return {'created': False, 'reason': 'no_server_ip', 'record': record, + 'message': 'Set the server public IP in Settings to auto-create DNS records.'} + config, zone = cls.find_zone_for_domain(domain) + if not config: + return {'created': False, 'reason': 'no_provider', 'record': record, + 'message': f'No connected DNS provider manages {domain} — add this record manually.'} + res = cls.set_record(config.id, zone['id'], 'A', domain, ip) + if res.get('success'): + return {'created': True, 'provider': config.name, 'zone': zone.get('name'), 'record': record} + return {'created': False, 'reason': 'api_error', 'error': res.get('error'), + 'provider': config.name, 'record': record} + # ── Cloudflare Implementation ── @classmethod diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py index d4461d4f..c46627ba 100644 --- a/backend/app/services/wordpress_service.py +++ b/backend/app/services/wordpress_service.py @@ -930,6 +930,78 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F] db.session.rollback() return f'could not update domain rows: {e}' + @classmethod + def attach_custom_domain(cls, app, domain: str, migrate: bool = True, + issue_ssl: bool = False, email: str = None) -> Dict: + """Point a user-owned domain at a site, end to end. + + Auto-creates the domain's A record via a connected DNS provider (or + returns the record to add manually), optionally obtains a Let's Encrypt + certificate, then migrates the site URL to the domain by reusing + ``change_site_url``. External steps (DNS, SSL) degrade to warnings rather + than failing the attach; only a requested migration that errors aborts. + """ + from app import db + from app.models.domain import Domain + from app.services.site_domain_service import SiteDomainService + from app.services.dns_provider_service import DNSProviderService + + if not app or not app.root_path: + return {'success': False, 'error': 'Site has no application/root path'} + + # Accept a bare host or a full URL; reduce to the host. + host = cls._host_of(cls._normalize_url(domain) or '') or (domain or '').strip().lower().rstrip('/') + if not host or '.' not in host: + return {'success': False, 'error': 'A valid custom domain (e.g. example.com) is required'} + + # 1) DNS: auto-create the A record, or report what to add manually. + dns = DNSProviderService.ensure_a_record(host, SiteDomainService.server_ip()) + + # 2) Optional HTTPS. certbot --nginx validates over the host's :80 vhost, + # so the host must already be served before the cert is requested. + ssl_result = None + use_https = False + if issue_ssl: + from app.services.ssl_service import SSLService + if not Domain.query.filter_by(name=host).first(): + db.session.add(Domain(name=host, is_primary=False, application_id=app.id)) + db.session.commit() + cls._write_app_vhost(app) + ssl_result = SSLService.obtain_certificate([host], email or f'admin@{host}') + use_https = bool(ssl_result and ssl_result.get('success')) + + # 3) Migrate the site URL to the domain (single rewrite to the final scheme). + scheme = 'https' if use_https else 'http' + migration = None + if migrate: + migration = cls.change_site_url(app, f'{scheme}://{host}', keep_old_redirect=True) + if not migration.get('success'): + return {'success': False, + 'error': f"DNS handled but moving the site to {host} failed: {migration.get('error')}", + 'dns': dns, 'ssl': ssl_result, 'migration': migration} + else: + # Attach the domain (primary + vhost) without rewriting WordPress. + cls._repoint_primary_domain(app, host, keep_old=True) + cls._write_app_vhost(app) + + warnings = [] + if not dns.get('created'): + warnings.append(dns.get('message') or 'Add the DNS record manually.') + if issue_ssl and not use_https: + warnings.append('HTTPS is not set up yet — enable SSL once DNS has propagated to this server.') + if migration and migration.get('warning'): + warnings.append(migration['warning']) + + return { + 'success': True, + 'domain': host, + 'url': (migration or {}).get('new_url') or f'{scheme}://{host}', + 'dns': dns, + 'ssl': ssl_result, + 'migration': migration, + 'warning': '; '.join(warnings) if warnings else None, + } + @classmethod def optimize_database(cls, path: str) -> Dict: """Optimize WordPress database.""" diff --git a/backend/tests/test_attach_domain.py b/backend/tests/test_attach_domain.py new file mode 100644 index 00000000..1f7ecfa4 --- /dev/null +++ b/backend/tests/test_attach_domain.py @@ -0,0 +1,196 @@ +"""Phase 3 proving tests — custom-domain attach + auto-DNS. + +Attaching a user-owned domain auto-creates its A record via a connected DNS +provider (or returns the record to add manually), then migrates the site to it +by reusing the URL-swap tool. +""" + + +def _mk_user(db, username='owner'): + from app.models import User + from werkzeug.security import generate_password_hash + u = User(email=f'{username}@test.local', username=username, + password_hash=generate_password_hash('x'), + role=User.ROLE_ADMIN, is_active=True) + db.session.add(u) + db.session.commit() + return u + + +def _mk_site_app(db, user_id, name='blog', port=8300, host='old.lvh.me'): + from app.models import Application + from app.models.domain import Domain + a = Application(name=name, app_type='docker', user_id=user_id, + root_path=f'/srv/{name}', port=port) + db.session.add(a) + db.session.commit() + db.session.add(Domain(name=host, is_primary=True, application_id=a.id)) + db.session.commit() + return a + + +def _mk_provider(db, name='cf', provider='cloudflare'): + from app.models.email import DNSProviderConfig + c = DNSProviderConfig(name=name, provider=provider, api_key='k') + db.session.add(c) + db.session.commit() + return c + + +# ── DNS zone matching + record upsert ─────────────────────────────────────── + +def test_find_zone_longest_suffix_match(app, monkeypatch): + from app import db + from app.services.dns_provider_service import DNSProviderService + + _mk_provider(db) + monkeypatch.setattr(DNSProviderService, 'list_zones', + classmethod(lambda cls, pid: {'success': True, 'zones': [ + {'id': 'z1', 'name': 'example.com'}, + {'id': 'z2', 'name': 'sub.example.com'}, + ]})) + + _, zone = DNSProviderService.find_zone_for_domain('blog.sub.example.com') + assert zone['id'] == 'z2' # longest suffix wins + _, zone = DNSProviderService.find_zone_for_domain('blog.example.com') + assert zone['id'] == 'z1' + cfg, zone = DNSProviderService.find_zone_for_domain('nope.org') + assert cfg is None and zone is None + + +def test_ensure_a_record_auto_creates(app, monkeypatch): + from app import db + from app.services.dns_provider_service import DNSProviderService + + _mk_provider(db) + monkeypatch.setattr(DNSProviderService, 'list_zones', + classmethod(lambda cls, pid: {'success': True, 'zones': [{'id': 'z1', 'name': 'example.com'}]})) + captured = {} + + def fake_set(cls, pid, zid, rtype, name, value, ttl=3600): + captured.update({'zid': zid, 'rtype': rtype, 'name': name, 'value': value}) + return {'success': True} + + monkeypatch.setattr(DNSProviderService, 'set_record', classmethod(fake_set)) + + res = DNSProviderService.ensure_a_record('blog.example.com', '203.0.113.5') + assert res['created'] is True + assert captured == {'zid': 'z1', 'rtype': 'A', 'name': 'blog.example.com', 'value': '203.0.113.5'} + + +def test_ensure_a_record_no_provider_returns_manual_record(app): + from app.services.dns_provider_service import DNSProviderService + res = DNSProviderService.ensure_a_record('blog.example.com', '1.2.3.4') + assert res['created'] is False + assert res['reason'] == 'no_provider' + assert res['record'] == {'type': 'A', 'name': 'blog.example.com', 'value': '1.2.3.4'} + + +def test_ensure_a_record_no_ip(app): + from app.services.dns_provider_service import DNSProviderService + res = DNSProviderService.ensure_a_record('blog.example.com', None) + assert res['created'] is False + assert res['reason'] == 'no_server_ip' + + +# ── attach orchestration ──────────────────────────────────────────────────── + +def test_attach_auto_dns_and_migrate(app, monkeypatch): + from app import db + from app.services.dns_provider_service import DNSProviderService + from app.services.wordpress_service import WordPressService + + user = _mk_user(db) + app_row = _mk_site_app(db, user.id, host='old.lvh.me') + + monkeypatch.setattr(DNSProviderService, 'ensure_a_record', + classmethod(lambda cls, host, ip: {'created': True, 'provider': 'cf', + 'zone': 'example.com', + 'record': {'type': 'A', 'name': host, 'value': ip}})) + captured = {} + + def fake_change(cls, a, new_url, keep_old_redirect=True): + captured['url'] = new_url + return {'success': True, 'new_url': new_url, 'old_url': 'http://old.lvh.me', 'replacements': 3} + + monkeypatch.setattr(WordPressService, 'change_site_url', classmethod(fake_change)) + + res = WordPressService.attach_custom_domain(app_row, 'blog.example.com') + assert res['success'] is True + assert res['domain'] == 'blog.example.com' + assert res['url'] == 'http://blog.example.com' + assert captured['url'] == 'http://blog.example.com' # migrated over http (no SSL) + assert res['dns']['created'] is True + assert res['warning'] is None + + +def test_attach_manual_dns_surfaces_record(app, monkeypatch): + from app import db + from app.services.dns_provider_service import DNSProviderService + from app.services.wordpress_service import WordPressService + + user = _mk_user(db, 'o2') + app_row = _mk_site_app(db, user.id, name='shop', host='old.lvh.me') + + monkeypatch.setattr(DNSProviderService, 'ensure_a_record', + classmethod(lambda cls, host, ip: {'created': False, 'reason': 'no_provider', + 'record': {'type': 'A', 'name': host, 'value': ip}, + 'message': 'add this record manually'})) + monkeypatch.setattr(WordPressService, 'change_site_url', + classmethod(lambda cls, a, new_url, keep_old_redirect=True: {'success': True, 'new_url': new_url})) + + res = WordPressService.attach_custom_domain(app_row, 'shop.example.org') + assert res['success'] is True + assert res['dns']['created'] is False + assert 'manually' in res['warning'].lower() + + +def test_attach_with_ssl_migrates_https(app, monkeypatch): + from app import db + import app.services.ssl_service as ssl_mod + import app.services.nginx_service as nginx_mod + from app.services.dns_provider_service import DNSProviderService + from app.services.wordpress_service import WordPressService + + user = _mk_user(db, 'o3') + app_row = _mk_site_app(db, user.id, name='sec', host='old.lvh.me') + + monkeypatch.setattr(DNSProviderService, 'ensure_a_record', + classmethod(lambda cls, host, ip: {'created': True, 'provider': 'cf', 'record': {}})) + monkeypatch.setattr(ssl_mod.SSLService, 'obtain_certificate', + classmethod(lambda cls, domains, email, **k: {'success': True, 'certificate_path': '/x'})) + monkeypatch.setattr(nginx_mod.NginxService, 'create_site', classmethod(lambda cls, **kw: {'success': True})) + monkeypatch.setattr(nginx_mod.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True})) + captured = {} + monkeypatch.setattr(WordPressService, 'change_site_url', + classmethod(lambda cls, a, new_url, keep_old_redirect=True: (captured.update({'url': new_url}), + {'success': True, 'new_url': new_url})[1])) + + res = WordPressService.attach_custom_domain(app_row, 'secure.example.com', issue_ssl=True) + assert res['success'] is True + assert res['ssl']['success'] is True + assert captured['url'] == 'https://secure.example.com' # https once the cert is obtained + + +def test_attach_without_migrate_sets_primary_domain(app, monkeypatch): + from app import db + import app.services.nginx_service as nginx_mod + from app.models.domain import Domain + from app.services.dns_provider_service import DNSProviderService + from app.services.wordpress_service import WordPressService + + user = _mk_user(db, 'o4') + app_row = _mk_site_app(db, user.id, name='nomig', host='old.lvh.me') + + monkeypatch.setattr(DNSProviderService, 'ensure_a_record', + classmethod(lambda cls, host, ip: {'created': True, 'record': {}})) + monkeypatch.setattr(nginx_mod.NginxService, 'create_site', classmethod(lambda cls, **kw: {'success': True})) + monkeypatch.setattr(nginx_mod.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True})) + called = {'change': False} + monkeypatch.setattr(WordPressService, 'change_site_url', + classmethod(lambda cls, *a, **k: called.update({'change': True}) or {'success': True})) + + res = WordPressService.attach_custom_domain(app_row, 'nomig.example.com', migrate=False) + assert res['success'] is True + assert called['change'] is False + assert Domain.query.filter_by(name='nomig.example.com', is_primary=True).first() is not None diff --git a/frontend/src/components/wordpress/AttachDomainModal.jsx b/frontend/src/components/wordpress/AttachDomainModal.jsx new file mode 100644 index 00000000..6345dc49 --- /dev/null +++ b/frontend/src/components/wordpress/AttachDomainModal.jsx @@ -0,0 +1,136 @@ +import { useState } from 'react'; +import { Globe, AlertTriangle, CheckCircle2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Switch } from '@/components/ui/switch'; +import wordpressApi from '../../services/wordpress'; +import { useToast } from '../../contexts/ToastContext'; + +// Attach a user-owned custom domain to a site: auto-create the DNS A record (or +// show the exact record to add manually), optional HTTPS, then migrate the site +// URL to it via the URL-swap tool. Shows the result inline so a manual DNS +// record can be read/copied. +export default function AttachDomainModal({ site, onClose, onChanged }) { + const toast = useToast(); + const [domain, setDomain] = useState(''); + const [issueSsl, setIssueSsl] = useState(false); + const [attaching, setAttaching] = useState(false); + const [result, setResult] = useState(null); + + const valid = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(domain.trim()); + + async function handleAttach(e) { + e?.preventDefault(); + if (!valid || attaching) return; + setAttaching(true); + toast.info('Attaching domain — creating DNS and moving the site…', { duration: 5000 }); + try { + const res = await wordpressApi.attachDomain(site.id, { domain: domain.trim(), issueSsl }); + if (res.success) { + setResult(res); + if (res.dns?.created) toast.success(`DNS A record created via ${res.dns.provider}`); + else toast.warning('Domain attached — add the DNS record shown to finish.', { duration: 7000 }); + onChanged?.(); + } else { + toast.error(res.error || 'Failed to attach domain'); + } + } catch (err) { + toast.error(err.message || 'Failed to attach domain'); + } finally { + setAttaching(false); + } + } + + const rec = result?.dns?.record; + + return ( +
!attaching && onClose()}> +
e.stopPropagation()}> +
+

Add Custom Domain

+ +
+ + {!result ? ( +
+
+
+
+ +
+ + setDomain(e.target.value)} + placeholder="example.com" + disabled={attaching} + autoFocus + /> + A domain or subdomain you control, without http:// +
+ + +
+ +
+ + +
+
+ ) : ( + <> +
+
+
+ + {result.dns?.created ? ( +
+ DNS A record created automatically via {result.dns.provider} + {result.dns.zone ? ` (zone ${result.dns.zone})` : ''}. +
+ ) : ( +
+ Add this DNS record to finish: + {rec?.value ? ( + + {rec.type}  {rec.name} → {rec.value} + + ) : ( +
{result.dns?.message}
+ )} +
+ )} + + {result.warning && ( +
{result.warning}
+ )} +
+
+ +
+ + )} +
+
+ ); +} diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx index d5c4c3bd..4c918362 100644 --- a/frontend/src/pages/WordPressDetail.jsx +++ b/frontend/src/pages/WordPressDetail.jsx @@ -9,6 +9,7 @@ import { useToast } from '../contexts/ToastContext'; import { useLogsDrawer } from '../contexts/LogsDrawerContext'; import { EnvironmentCard, SnapshotTable, GitConnectForm, CommitList, DiskUsageBar } from '../components/wordpress'; import ChangeUrlModal from '../components/wordpress/ChangeUrlModal'; +import AttachDomainModal from '../components/wordpress/AttachDomainModal'; import { HealthDot } from '../components/wordpress/HealthStatusPanel'; import { Pill, EnvTag, MetricCard, SegControl, ScoreGauge, ServiceTile } from '../components/ds'; import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary'; @@ -156,6 +157,7 @@ const WordPressDetail = () => { const [autoLoggingIn, setAutoLoggingIn] = useState(false); const [showCloneModal, setShowCloneModal] = useState(false); const [showChangeUrl, setShowChangeUrl] = useState(false); + const [showAddDomain, setShowAddDomain] = useState(false); const [cloning, setCloning] = useState(false); const [cloneName, setCloneName] = useState(''); const [clonedCreds, setClonedCreds] = useState(null); @@ -336,6 +338,14 @@ const WordPressDetail = () => { )} +