Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(wordpress): attach a custom domain with auto-DNS

Juan Denisad5c9b6bf0e1
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/<int:app_id>/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/<int:app_id>/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 (
+ <div className="modal-overlay" onClick={() => !attaching && onClose()}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2><Globe size={18} /> Add Custom Domain</h2>
+ <button className="modal-close" onClick={() => !attaching && onClose()}>&times;</button>
+ </div>
+
+ {!result ? (
+ <form onSubmit={handleAttach}>
+ <div className="wp-url-swap">
+ <div className="wp-url-swap__warning">
+ <AlertTriangle size={18} aria-hidden="true" />
+ <span>
+ Points a domain you own at this site. If a connected DNS provider
+ manages it, the A record is created automatically — otherwise
+ you&apos;ll get the exact record to add. The site URL is then
+ migrated to the domain (serialization-safe).
+ </span>
+ </div>
+
+ <div className="form-group">
+ <Label htmlFor="wp-domain">Domain</Label>
+ <Input
+ id="wp-domain"
+ type="text"
+ value={domain}
+ onChange={(e) => setDomain(e.target.value)}
+ placeholder="example.com"
+ disabled={attaching}
+ autoFocus
+ />
+ <span className="form-hint">A domain or subdomain you control, without http://</span>
+ </div>
+
+ <label className="wp-url-swap__keep">
+ <Switch checked={issueSsl} onCheckedChange={setIssueSsl} disabled={attaching} />
+ <span>
+ Set up HTTPS now
+ <small>Requests a Let&apos;s Encrypt certificate. Needs DNS to already resolve to this server.</small>
+ </span>
+ </label>
+ </div>
+
+ <div className="modal-actions">
+ <Button type="button" variant="outline" onClick={onClose} disabled={attaching}>Cancel</Button>
+ <Button type="submit" disabled={!valid || attaching}>
+ {attaching ? 'Attaching…' : 'Attach Domain'}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <>
+ <div className="wp-url-swap">
+ <div className="wp-url-swap__result">
+ <CheckCircle2 size={18} aria-hidden="true" />
+ <span>Site is now at <code>{result.url}</code></span>
+ </div>
+
+ {result.dns?.created ? (
+ <div className="form-hint">
+ DNS A record created automatically via {result.dns.provider}
+ {result.dns.zone ? ` (zone ${result.dns.zone})` : ''}.
+ </div>
+ ) : (
+ <div className="wp-url-swap__dns-manual">
+ <strong>Add this DNS record to finish:</strong>
+ {rec?.value ? (
+ <code className="wp-url-swap__record">
+ {rec.type}&nbsp;&nbsp;{rec.name}&nbsp;→&nbsp;{rec.value}
+ </code>
+ ) : (
+ <div className="form-hint">{result.dns?.message}</div>
+ )}
+ </div>
+ )}
+
+ {result.warning && (
+ <div className="wp-url-swap__preview-error">{result.warning}</div>
+ )}
+ </div>
+ <div className="modal-actions">
+ <Button type="button" onClick={onClose}>Done</Button>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
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 = () => {
</Button>
</>
)}
+ <Button
+ variant="ghost"
+ onClick={() => setShowAddDomain(true)}
+ title="Point a custom domain you own at this site (auto-DNS + migrate)"
+ >
+ <Plus size={16} />
+ Add Domain
+ </Button>
<Button
variant="ghost"
onClick={() => setShowChangeUrl(true)}
@@ -505,6 +515,14 @@ const WordPressDetail = () => {
/>
)}
+ {showAddDomain && (
+ <AttachDomainModal
+ site={site}
+ onClose={() => setShowAddDomain(false)}
+ onChanged={loadSite}
+ />
+ )}
+
{/* Clone Site Modal */}
{showCloneModal && (
<div className="modal-overlay" onClick={() => !cloning && setShowCloneModal(false)}>
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index d8fed824..705c68bf 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -41,6 +41,14 @@ const wordpressApi = {
body: { new_url: newUrl, keep_old_redirect: keepOldRedirect }
}),
+ // Attach a custom domain: auto-create DNS (or return the record to add) +
+ // optional HTTPS, then migrate the site to it.
+ attachDomain: (id, { domain, migrate = true, issueSsl = false, email } = {}) =>
+ api.request(`${BASE_PATH}/${id}/domain`, {
+ method: 'POST',
+ body: { domain, migrate, issue_ssl: issueSsl, email }
+ }),
+
// Replace the tag list for a site (agency organization labels)
setTags: (id, tags) => api.request(`${BASE_PATH}/${id}/tags`, {
method: 'PATCH',
diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scss
index aa5b2bdf..918f2206 100644
--- a/frontend/src/styles/pages/_wordpress.scss
+++ b/frontend/src/styles/pages/_wordpress.scss
@@ -2913,4 +2913,32 @@
font-size: 12.5px;
color: var(--red);
}
+
+ &__result {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ font-size: 13px;
+
+ svg { color: var(--green); flex-shrink: 0; }
+ code { font-family: var(--mono); color: var(--green); word-break: break-all; }
+ }
+
+ &__dns-manual {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 12.5px;
+ }
+
+ &__record {
+ font-family: var(--mono);
+ font-size: 12px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: var(--surface-2);
+ border: 1px solid var(--border-soft);
+ color: var(--text);
+ word-break: break-all;
+ }
}