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(adoption): DNS cutover+verify, snapshots, SSH import (plan 31)
Juan Denisa882d35db98c
diff --git a/backend/app/api/site_imports.py b/backend/app/api/site_imports.pyindex 71228796..8e130d90 100644--- a/backend/app/api/site_imports.py+++ b/backend/app/api/site_imports.py@@ -29,6 +29,23 @@ def upload_archive():return jsonify({'upload_path': upload_path}), 201+@site_imports_bp.route('/ssh/probe', methods=['POST'])+@admin_required+def probe_ssh_source():+ """Preflight an SSH import source: test the connection, list the docroot,+ sniff the stack (plan 31 #8). Linux-only runtime — returns 501 on a host+ that can't run ssh (e.g. Windows dev) so the wizard can message it."""+ data = request.get_json(silent=True) or {}+ source = data.get('source') or data+ try:+ result = SiteImportService.probe_ssh(source)+ except SiteImportError as exc:+ return jsonify({'error': str(exc)}), 400+ except RuntimeError as exc:+ return jsonify({'error': str(exc), 'code': 'LINUX_ONLY'}), 501+ return jsonify(result), 200++@site_imports_bp.route('', methods=['POST'])@admin_requireddef create_import():diff --git a/backend/migrations/versions/066_dns_cutover_snapshots.py b/backend/migrations/versions/066_dns_cutover_snapshots.pynew file mode 100644index 00000000..caacdb2d--- /dev/null+++ b/backend/migrations/versions/066_dns_cutover_snapshots.py@@ -0,0 +1,57 @@+"""Reversible DNS cutover snapshots (plan 27 Phase 6 #13, Decision 6).++Adds ``dns_cutover_snapshots`` — a point-in-time capture of a domain's live DNS+records taken right before a migration cutover, so a revert can re-apply the+original records. The after-only DNS change ledger can't power revert; this can.++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on+boot before Alembic, so guard on the live schema (the table may already exist).++Revision ID: 066_dns_cutover_snapshots+Revises: 065_server_management_mode+Create Date: 2026-07-06+"""+from alembic import op+import sqlalchemy as sa++revision = '066_dns_cutover_snapshots'+down_revision = '065_server_management_mode'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ tables = set(inspector.get_table_names())++ if 'dns_cutover_snapshots' not in tables:+ op.create_table(+ 'dns_cutover_snapshots',+ sa.Column('id', sa.Integer(), nullable=False),+ sa.Column('domain', sa.String(length=256), nullable=False),+ sa.Column('provider', sa.String(length=64), nullable=True),+ sa.Column('provider_zone_id', sa.String(length=128), nullable=True),+ sa.Column('records_json', sa.Text(), nullable=True),+ sa.Column('status', sa.String(length=16), nullable=False,+ server_default='captured'),+ sa.Column('created_at', sa.DateTime(), nullable=False),+ sa.Column('applied_at', sa.DateTime(), nullable=True),+ sa.PrimaryKeyConstraint('id'),+ )+ op.create_index('ix_dns_cutover_snapshots_domain',+ 'dns_cutover_snapshots', ['domain'], unique=False)+ op.create_index('ix_dns_cutover_snapshots_created_at',+ 'dns_cutover_snapshots', ['created_at'], unique=False)+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ tables = set(inspector.get_table_names())+ if 'dns_cutover_snapshots' in tables:+ op.drop_index('ix_dns_cutover_snapshots_created_at',+ table_name='dns_cutover_snapshots')+ op.drop_index('ix_dns_cutover_snapshots_domain',+ table_name='dns_cutover_snapshots')+ op.drop_table('dns_cutover_snapshots')diff --git a/backend/tests/test_ssh_import_wiring.py b/backend/tests/test_ssh_import_wiring.pynew file mode 100644index 00000000..1371ac48--- /dev/null+++ b/backend/tests/test_ssh_import_wiring.py@@ -0,0 +1,141 @@+"""Proving tests for SSH import wiring + credential hygiene (plan 31 Phase 3).++Plan 27 registered the SSH importer but left it unreachable — nothing wired the+``ssh`` format into ``SiteImportService``. This proves the fetch/extract branch+now stages via ``GenericSshImporter.pull`` and, crucially (Decision 5), that no+DB password or keyfile material survives in the durable import record, the+analysis, the result, or any job payload.++The live pull is Linux-only runtime, so ``pull`` is monkeypatched to stage a+fake directory — no subprocess, no real box.+"""+import json+import os++import pytest++from app import db+from app.models.site_import import SiteImport, VALID_SOURCE_TYPES+from app.services.site_import_service import SiteImportError, SiteImportService+from app.services.site_importers.ssh import GenericSshImporter, parse_ssh_source+++SECRET_DB_PW = 'SUPER-SECRET-DB-PW'+KEYFILE_PATH = '/home/panel/.ssh/id_ed25519'++SSH_SOURCE = {+ 'host': 'box.example.com', 'port': 22, 'user': 'deploy',+ 'docroot': '/var/www/site', 'domain': 'site.example.com',+ 'db_name': 'sitedb', 'db_user': 'siteusr', 'db_password': SECRET_DB_PW,+ 'ssh_key': KEYFILE_PATH,+}+++def imports_base(tmp_path, monkeypatch):+ monkeypatch.setattr(SiteImportService, 'imports_base', str(tmp_path))+ return str(tmp_path)+++def _fake_pull(self, source, staging_dir):+ """Stage a realistic dir (docroot + manifest) without any subprocess."""+ docroot = os.path.join(staging_dir, 'docroot')+ os.makedirs(docroot, exist_ok=True)+ with open(os.path.join(docroot, 'index.php'), 'w', encoding='utf-8') as fh:+ fh.write('<?php echo "hi";')+ GenericSshImporter._write_manifest(staging_dir, source, None)+ return {'staging_dir': staging_dir, 'docroot_dir': 'docroot', 'db_dump': None}+++# --------------------------------------------------------------------------- #+# format wiring+# --------------------------------------------------------------------------- #++def test_ssh_is_a_valid_source_type():+ assert 'ssh' in VALID_SOURCE_TYPES+++def test_create_ssh_validates_spec(app, imports_base):+ with pytest.raises(SiteImportError) as ei:+ SiteImportService.create('ssh', {'host': 'h'}) # missing user/docroot+ assert 'docroot' in str(ei.value) or 'user' in str(ei.value)+++def test_create_ssh_ok(app, imports_base):+ imp = SiteImportService.create('ssh', dict(SSH_SOURCE))+ assert imp.source_type == 'ssh'+ assert imp.status == 'created'+++def test_parse_ssh_source_has_no_password_field():+ src = parse_ssh_source(SSH_SOURCE)+ assert 'password' not in src # keyfile-only (plan 31 #8)+ assert src['ssh_key'] == KEYFILE_PATH+++# --------------------------------------------------------------------------- #+# staging branch + credential hygiene (Decision 5, #9)+# --------------------------------------------------------------------------- #++def test_analyze_stages_over_ssh_and_scrubs_password(app, imports_base, monkeypatch):+ monkeypatch.setattr(GenericSshImporter, 'pull', _fake_pull)+ imp = SiteImportService.create('ssh', dict(SSH_SOURCE))+ analysis = SiteImportService.analyze(imp)++ assert imp.status == 'analyzed'+ # The staged docroot is expressed so the copy step copies it directly.+ assert analysis.get('staged_docroot') == 'docroot'+ assert analysis.get('homedir_present') is True+ assert analysis['domains'][0]['domain'] == 'site.example.com'++ # The DB password was scrubbed from the persisted source post-pull.+ assert imp.get_source().get('db_password') in (None, '')+++def test_no_db_password_anywhere_in_the_durable_record(app, imports_base, monkeypatch):+ monkeypatch.setattr(GenericSshImporter, 'pull', _fake_pull)+ imp = SiteImportService.create('ssh', dict(SSH_SOURCE))+ SiteImportService.analyze(imp)+ db.session.refresh(imp)++ # 1) The whole serialized import row carries no DB password.+ blob = json.dumps(imp.to_dict())+ assert SECRET_DB_PW not in blob++ # 2) The staging manifest carries no secrets (password or key material).+ manifest_path = os.path.join(SiteImportService.extracted_dir(imp),+ GenericSshImporter.MANIFEST_NAME)+ with open(manifest_path, encoding='utf-8') as fh:+ manifest_text = fh.read()+ assert SECRET_DB_PW not in manifest_text++ # 3) Job payloads (analyze + run) carry neither the password nor keyfile path.+ for job in (SiteImportService.enqueue_analyze(imp),+ SiteImportService.enqueue_run(imp)):+ payload = job.get_payload() or {}+ assert 'db_password' not in payload+ assert SECRET_DB_PW not in json.dumps(payload)+ assert KEYFILE_PATH not in json.dumps(payload)+++def test_copy_files_uses_staged_docroot(app, imports_base, monkeypatch):+ from app.models import User+ from werkzeug.security import generate_password_hash+ db.session.add(User(email='[email protected]', username='owner_ssh',+ password_hash=generate_password_hash('x'),+ role='admin', is_active=True))+ db.session.commit()++ monkeypatch.setattr(GenericSshImporter, 'pull', _fake_pull)+ imp = SiteImportService.create('ssh', dict(SSH_SOURCE))+ SiteImportService.analyze(imp)++ # Drive create_app + copy_files against the staged dir.+ ctx = {'analysis': imp.get_analysis(), 'options': imp.get_options(),+ 'extracted': SiteImportService.extracted_dir(imp),+ 'result': {'warnings': []}}+ SiteImportService._step_create_app(imp, ctx)+ SiteImportService._step_copy_files(imp, ctx)++ app_root = ctx['app'].root_path+ assert os.path.isfile(os.path.join(app_root, 'index.php'))diff --git a/docs/COEXISTENCE.md b/docs/COEXISTENCE.mdnew file mode 100644index 00000000..50a6951d--- /dev/null+++ b/docs/COEXISTENCE.md@@ -0,0 +1,102 @@+# Running ServerKit alongside another control panel++> Plan 27. The honest answer to "can this panel manage / migrate my existing+> box?" — including what it will and won't do while another panel is still in+> charge.++ServerKit has three explicit adoption modes. Pick the one that matches where the+box is today; you can move between them as you migrate.++## 1. Observe — read-only, safe to run anywhere++Install the agent on any Linux box, **including one still run by another control+panel**, and set the server to **Observed**. You get:++- **Metrics** — CPU / memory / disk / network, like any paired server.+- **A read-only survey ("flight")** — a map of what's running: web servers and+ their virtual hosts (domain → document root / upstream), databases, TLS+ certificates, cron jobs, listening ports, and a flag if another control panel+ is detected. See the read-only guarantees below.+- **Doctor probes** — the read-only health checks.+- **Backups** of paths you explicitly point at.++You do **not** get, by design:++- Site creation or web-server config writes.+- Any mutating server-targeted action. These are refused server-side — the+ server list and detail page show an **Observed** chip and a read-only banner,+ and the agent command choke point returns a clean refusal rather than letting+ two panels fight over the same files. Every refusal is recorded in the+ server's audit trail, and the Survey tab shows a **blocked-commands counter**.+- Agent binary updates. Observe mode covers the agent itself: `agent:update` is+ refused too, so observing never silently re-flashes the box. If you *do* want+ to keep the agent current while observing, set the per-server **"allow agent+ updates while observing"** break-glass on the Survey tab — an explicit,+ audited opt-in, off by default.++What an Observed server still allows (all reads): system metrics/info/processes,+Docker/compose *list/inspect/logs/stats*, file *read/list* within allowed paths,+the survey, doctor probes, `agent:recapabilities` (capability re-discovery), and+backups of paths you point at.++**Why the hard line:** two panels writing the same web-server config (nginx /+Apache vhosts, PHP-FPM pools, TLS) will overwrite each other and eventually+break the site. That scenario is **never supported**. Observe mode exists+precisely so you can adopt a box for visibility without stepping on the panel+that currently owns its config.++Detection only ever **suggests**. If the survey finds another panel's marker,+ServerKit shows a one-click "switch to Observed" prompt — it never flips a+managed server automatically, and it never downgrades an existing managed box.++### The survey's read-only guarantees++The survey is driven by a shipped, versioned **probe catalog** you can read in+full (the Survey tab's "What we check" view lists every location verbatim). The+agent enforces the trust boundary with a **fixed allowlist of read-only+primitives** — file-exists, glob, unit status, socket list, process list, and+parse-light extraction of a few config directives (`server_name`, `root`,+`proxy_pass`, and equivalents). Concretely:++- **Credential and environment files are listed by path only — never read.**+- No file contents leave the box beyond those parse-light directive lines.+- The catalog can only combine those primitives; it can never name a command to+ run. A compromised panel can at worst enumerate paths — never execute.++Full agent contract: [`AGENT_SURVEY_SPEC.md`](AGENT_SURVEY_SPEC.md).++## 2. Migrate — the guided path off the other panel++When you're ready to move a site onto ServerKit:++1. **Survey** the box (Observe mode) so you can see every site, its document+ root, and its databases.+2. **Import** each site. From the Survey tab, "Migrate this site" pre-fills the+ import wizard with the domain and document root. Imports cover **files ++ MySQL databases + database users (password hashes preserved) + crontabs** —+ from a control-panel backup archive, or a live pull over SSH for panel-less+ boxes. **Mail accounts and DNS zones are not migrated** (they stay on the+ source until moved separately).+3. **Verify on ServerKit** using a staging domain / basic-auth before touching+ public DNS; WordPress sites get the URL-swap tool for post-move URL fixes.+4. **DNS cutover, reversible per domain.** Before changing any record, ServerKit+ snapshots the domain's existing records (name / type / content / TTL). Lower+ the TTL a step ahead, switch the record, verify propagation, and **revert+ from the snapshot** in one click if anything looks wrong.+5. **Decommission.** Once every surveyed site is migrated, ServerKit shows a+ checklist: what to stop on the old box, what to keep until TTLs expire, and+ when it's safe to wipe.++## 3. Manage — full takeover on a clean box++Today's normal mode: ServerKit owns the box and manages the web stack end to+end. This is the right mode for a fresh server, or for one you've finished+migrating off its previous panel and cleaned up.++## What is never supported++- **Two panels writing the same web-server config.** Keep exactly one owner of+ nginx/Apache/PHP-FPM/TLS per box. Use Observe (read-only) until ServerKit is+ that single owner.+- Mail and DNS-zone *migration* are not part of v1 imports (the future path is+ the mail extension + DNS zone rails).diff --git a/frontend/src/components/domains/CutoverDrawer.jsx b/frontend/src/components/domains/CutoverDrawer.jsxnew file mode 100644index 00000000..4884b74e--- /dev/null+++ b/frontend/src/components/domains/CutoverDrawer.jsx@@ -0,0 +1,454 @@+import { useState, useEffect, useCallback } from 'react';+import {+ ArrowRightLeft, ArrowLeft, ArrowRight, Camera, CheckCircle2, RotateCcw,+ AlertTriangle, Globe, RadioTower,+} from 'lucide-react';+import { Drawer, Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { ConfirmDialog } from '@/components/ConfirmDialog';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import Spinner from '../Spinner';++// Per-domain reversible DNS cutover (plan 31 #5/#6). One shared slide-over,+// reached from the /domains detail drawer and from the Import wizard's final+// step, so the survey → migrate → cutover journey ends in the same place.+//+// Internal stages: target → review (snapshot + TTL guidance + dry-run diff) →+// verify (propagation check + one-click revert). Every write is snapshot-backed+// so it can always be rolled back.+//+// <CutoverDrawer open={open} onClose={close} domain="example.com"+// providerZoneId="abc123" provider="cloudflare"+// initialTarget="203.0.113.10" />++const HEAD_ICON_SIZE = 18;+const DRAWER_WIDTH = 720;++// Record types a cutover can repoint. A/AAAA/CNAME cover the "point at the new+// box" case; the operator keeps everything else untouched.+const RECORD_TYPE_CHOICES = ['A', 'AAAA', 'CNAME'];++const STAGES = [+ { id: 'target', label: 'Target' },+ { id: 'review', label: 'Review' },+ { id: 'verify', label: 'Verify' },+];++// The provider guards (NO_PROVIDER / NO_ZONE) come back as 501/400 with a code;+// surface a plain-language line instead of a raw request-failed toast.+function friendlyError(err) {+ const code = err?.data?.code;+ if (code === 'NO_PROVIDER') {+ return 'Connect a DNS provider first — the cutover reads and writes live records through it.';+ }+ if (code === 'NO_ZONE') {+ return 'This domain has no connected provider zone, so its records can\'t be read or repointed.';+ }+ if (code === 'PROVIDER_READ_FAILED') {+ return `Couldn't read the zone's live records: ${err.message}`;+ }+ return err?.message || 'Something went wrong.';+}++const CutoverDrawer = ({ open, onClose, domain, providerZoneId, provider, initialTarget }) => {+ const toast = useToast();++ const [stage, setStage] = useState('target');+ const [target, setTarget] = useState('');+ const [zoneId, setZoneId] = useState('');+ const [recordTypes, setRecordTypes] = useState(['A']);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');++ const [snapshot, setSnapshot] = useState(null);+ const [ttl, setTtl] = useState(null);+ const [plan, setPlan] = useState(null);+ const [cutoverResult, setCutoverResult] = useState(null);+ const [verifyResult, setVerifyResult] = useState(null);+ const [revertResult, setRevertResult] = useState(null);+ const [confirmOpen, setConfirmOpen] = useState(false);++ // Re-seed from props each time the drawer is opened, so a previous, possibly+ // abandoned cutover never leaks into the next domain.+ useEffect(() => {+ if (!open) return;+ setStage('target');+ setTarget(initialTarget || '');+ setZoneId(providerZoneId || '');+ setRecordTypes(['A']);+ setBusy(false);+ setError('');+ setSnapshot(null);+ setTtl(null);+ setPlan(null);+ setCutoverResult(null);+ setVerifyResult(null);+ setRevertResult(null);+ setConfirmOpen(false);+ }, [open, initialTarget, providerZoneId]);++ const toggleRecordType = (t) => {+ setRecordTypes((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]));+ };++ // target → review: snapshot the live records, derive TTL guidance from them,+ // and compute the (provider-free) dry-run diff.+ const captureAndReview = async () => {+ setBusy(true);+ setError('');+ try {+ const snap = await api.snapshotDnsForCutover(domain, zoneId.trim(), provider || null);+ setSnapshot(snap);+ const [guidance, dry] = await Promise.all([+ api.getCutoverTtlGuidance(snap.records || []).catch(() => null),+ api.performDnsCutover(snap.id, target.trim(), { recordTypes, dryRun: true }),+ ]);+ setTtl(guidance);+ setPlan(dry.plan || null);+ setStage('review');+ } catch (err) {+ setError(friendlyError(err));+ } finally {+ setBusy(false);+ }+ };++ // review → verify: perform the real cutover through the guarded write path.+ const applyCutover = async () => {+ if (!snapshot) return;+ setConfirmOpen(false);+ setBusy(true);+ setError('');+ try {+ const res = await api.performDnsCutover(snapshot.id, target.trim(), { recordTypes, dryRun: false });+ setSnapshot(res.snapshot || snapshot);+ setCutoverResult(res.cutover || null);+ setStage('verify');+ if (res.cutover?.success) {+ toast.success(`Cutover applied — ${domain} now points at ${target.trim()}`);+ } else {+ toast.error('Cutover finished with errors — review the results and consider reverting.');+ }+ } catch (err) {+ const message = friendlyError(err);+ setError(message);+ toast.error(message);+ } finally {+ setBusy(false);+ }+ };++ const checkPropagation = useCallback(async () => {+ setBusy(true);+ setError('');+ try {+ const primaryType = recordTypes[0] || 'A';+ const res = await api.verifyDnsCutover(domain, {+ recordType: primaryType,+ expected: target.trim(),+ snapshotId: snapshot?.id || null,+ });+ setVerifyResult(res);+ } catch (err) {+ setError(friendlyError(err));+ } finally {+ setBusy(false);+ }+ }, [domain, recordTypes, target, snapshot]);++ const revert = async () => {+ if (!snapshot) return;+ setBusy(true);+ setError('');+ try {+ const res = await api.revertDnsCutover(snapshot.id);+ setSnapshot(res.snapshot || snapshot);+ setRevertResult(res.revert || null);+ if (res.revert?.success) {+ toast.success(`Reverted — restored ${domain}'s pre-cutover records`);+ } else {+ toast.error('Revert finished with errors — check the results.');+ }+ } catch (err) {+ const message = friendlyError(err);+ setError(message);+ toast.error(message);+ } finally {+ setBusy(false);+ }+ };++ const noZone = !zoneId.trim();+ const canCapture = !!target.trim() && !noZone && recordTypes.length > 0;+ const stageIndex = STAGES.findIndex((s) => s.id === stage);++ return (+ <Drawer+ open={open}+ onOpenChange={(v) => !v && onClose()}+ title="DNS cutover"+ subtitle={domain}+ icon={<ArrowRightLeft size={HEAD_ICON_SIZE} />}+ width={DRAWER_WIDTH}+ >+ <div className="cutover">+ <ol className="cutover__stepper">+ {STAGES.map((s, i) => (+ <li+ key={s.id}+ className={`cutover__step${i === stageIndex ? ' is-active' : ''}${i < stageIndex ? ' is-done' : ''}`}+ >+ <span className="cutover__step-dot">+ {i < stageIndex ? <CheckCircle2 size={13} aria-hidden="true" /> : i + 1}+ </span>+ {s.label}+ </li>+ ))}+ </ol>++ {error && (+ <div className="cutover__callout cutover__callout--danger">+ <AlertTriangle size={16} aria-hidden="true" />+ <p>{error}</p>+ </div>+ )}++ {/* Stage 1 — pick the target address + record types */}+ {stage === 'target' && (+ <div className="cutover__stage">+ <p className="cutover__lead">+ Repoint <strong>{domain}</strong> at the box where the imported site now+ lives. Its current records are snapshotted first, so the switch can always+ be reverted.+ </p>++ <div className="cutover__field">+ <Label htmlFor="cutover-target">New address (target)</Label>+ <Input+ id="cutover-target"+ value={target}+ onChange={(e) => setTarget(e.target.value)}+ placeholder="203.0.113.10"+ disabled={busy}+ />+ <span className="cutover__hint">The IP (or hostname for CNAME) the records should point to.</span>+ </div>++ <div className="cutover__field">+ <Label htmlFor="cutover-zone">Provider zone id</Label>+ <Input+ id="cutover-zone"+ value={zoneId}+ onChange={(e) => setZoneId(e.target.value)}+ placeholder="the DNS provider's zone identifier"+ disabled={busy}+ />+ {noZone && (+ <span className="cutover__hint cutover__hint--warn">+ This domain has no connected provider zone — cutover needs one to read and write records.+ </span>+ )}+ </div>++ <div className="cutover__field">+ <Label>Record types</Label>+ <div className="cutover__types">+ {RECORD_TYPE_CHOICES.map((t) => (+ <label key={t} className="cutover__type">+ <input+ type="checkbox"+ checked={recordTypes.includes(t)}+ onChange={() => toggleRecordType(t)}+ disabled={busy}+ />+ {t}+ </label>+ ))}+ </div>+ </div>++ <div className="cutover__actions">+ <span />+ <Button onClick={captureAndReview} disabled={busy || !canCapture}>+ {busy ? <><Spinner size="sm" /> Capturing…</> : <><Camera size={14} /> Snapshot & preview <ArrowRight size={14} /></>}+ </Button>+ </div>+ </div>+ )}++ {/* Stage 2 — snapshot summary, TTL guidance, dry-run diff */}+ {stage === 'review' && (+ <div className="cutover__stage">+ <div className="cutover__summary">+ <div className="cutover__stat">+ <span className="cutover__stat-val">{snapshot?.record_count ?? 0}</span>+ <span className="cutover__stat-label">records captured</span>+ </div>+ <div className="cutover__stat">+ <span className="cutover__stat-val">{target.trim()}</span>+ <span className="cutover__stat-label">new target</span>+ </div>+ <div className="cutover__stat">+ <span className="cutover__stat-val">{recordTypes.join(', ')}</span>+ <span className="cutover__stat-label">record types</span>+ </div>+ </div>++ {ttl && (+ <div className={`cutover__callout${ttl.needs_lowering ? ' cutover__callout--warning' : ' cutover__callout--info'}`}>+ <RadioTower size={16} aria-hidden="true" />+ <p>{ttl.message}</p>+ </div>+ )}++ <section className="cutover__section">+ <h3><Globe size={15} aria-hidden="true" /> Planned changes</h3>+ {plan?.ops?.length ? (+ <div className="cutover__table-wrap">+ <table className="cutover__table">+ <thead>+ <tr><th>Type</th><th>Name</th><th>Action</th><th>Current</th><th>New</th></tr>+ </thead>+ <tbody>+ {plan.ops.map((op, i) => (+ <tr key={`${op.record_type}-${op.name}-${i}`}>+ <td>{op.record_type}</td>+ <td>{op.name}</td>+ <td>+ <Pill kind={op.action === 'create' ? 'cyan' : 'amber'}>{op.action}</Pill>+ </td>+ <td><code>{op.old_content || '—'}</code></td>+ <td><code>{op.new_content}</code></td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="cutover__muted">No changes to apply for the selected record types.</p>+ )}+ </section>++ <div className="cutover__actions">+ <Button variant="outline" onClick={() => setStage('target')} disabled={busy}>+ <ArrowLeft size={14} /> Back+ </Button>+ <Button onClick={() => setConfirmOpen(true)} disabled={busy || !plan?.ops?.length}>+ {busy ? <><Spinner size="sm" /> Applying…</> : <><ArrowRightLeft size={14} /> Apply cutover</>}+ </Button>+ </div>+ </div>+ )}++ {/* Stage 3 — cutover result, verify, revert */}+ {stage === 'verify' && (+ <div className="cutover__stage">+ {cutoverResult && (+ <div className={`cutover__callout${cutoverResult.success ? ' cutover__callout--success' : ' cutover__callout--danger'}`}>+ {cutoverResult.success+ ? <CheckCircle2 size={16} aria-hidden="true" />+ : <AlertTriangle size={16} aria-hidden="true" />}+ <p>+ {cutoverResult.success+ ? <>Cutover applied — <strong>{domain}</strong> now points at <code>{target.trim()}</code>.</>+ : <>Cutover finished with errors. Review below and revert if needed.</>}+ </p>+ </div>+ )}++ <section className="cutover__section">+ <h3><RadioTower size={15} aria-hidden="true" /> Propagation</h3>+ <p className="cutover__muted">+ Public resolvers cache the old address until their TTL expires. Check where the new+ address has taken effect.+ </p>++ {verifyResult && (+ <div className="cutover__verify-head">+ {verifyResult.matches_expected != null && (+ <Pill kind={verifyResult.matches_expected ? 'green' : 'amber'}>+ {verifyResult.matches_expected ? 'Matches new target' : 'Not fully propagated'}+ </Pill>+ )}+ <Pill kind={verifyResult.propagated ? 'green' : 'gray'}>+ {verifyResult.propagated ? 'Propagated' : 'Propagating'}+ </Pill>+ </div>+ )}++ {verifyResult?.resolvers?.length > 0 && (+ <div className="cutover__table-wrap">+ <table className="cutover__table">+ <thead>+ <tr><th>Resolver</th><th>Answer</th><th>Status</th></tr>+ </thead>+ <tbody>+ {verifyResult.resolvers.map((r, i) => (+ <tr key={`${r.nameserver}-${i}`}>+ <td>{r.nameserver}</td>+ <td><code>{(r.result || []).join(', ') || '—'}</code></td>+ <td>+ <Pill kind={r.propagated ? 'green' : 'gray'}>+ {r.propagated ? 'live' : 'stale'}+ </Pill>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ <Button variant="outline" size="sm" onClick={checkPropagation} disabled={busy}>+ {busy ? <><Spinner size="sm" /> Checking…</> : <><RadioTower size={14} /> Check propagation</>}+ </Button>+ </section>++ <section className="cutover__section cutover__section--revert">+ <h3><RotateCcw size={15} aria-hidden="true" /> Roll back</h3>+ {revertResult ? (+ <div className={`cutover__callout${revertResult.success ? ' cutover__callout--success' : ' cutover__callout--danger'}`}>+ {revertResult.success+ ? <CheckCircle2 size={16} aria-hidden="true" />+ : <AlertTriangle size={16} aria-hidden="true" />}+ <p>+ Restored {revertResult.results?.length ?? 0} record{(revertResult.results?.length ?? 0) === 1 ? '' : 's'}+ {revertResult.deleted_count ? `, deleted ${revertResult.deleted_count} created record${revertResult.deleted_count === 1 ? '' : 's'}` : ''}.+ </p>+ </div>+ ) : (+ <p className="cutover__muted">+ One click restores the snapshot captured before this cutover — including deleting any+ records the cutover created.+ </p>+ )}+ <Button variant="outline" size="sm" onClick={revert} disabled={busy || !!revertResult}>+ {busy ? <><Spinner size="sm" /> Reverting…</> : <><RotateCcw size={14} /> Revert cutover</>}+ </Button>+ </section>++ <div className="cutover__actions">+ <span />+ <Button variant="outline" onClick={onClose} disabled={busy}>Done</Button>+ </div>+ </div>+ )}++ <ConfirmDialog+ isOpen={confirmOpen}+ title="Apply DNS cutover?"+ message={`This repoints ${recordTypes.join(', ')} record(s) for ${domain} at ${target.trim()}. The snapshot lets you revert.`}+ confirmText="Apply cutover"+ variant="danger"+ onConfirm={applyCutover}+ onCancel={() => setConfirmOpen(false)}+ />+ </div>+ </Drawer>+ );+};++export default CutoverDrawer;diff --git a/frontend/src/services/api/dnsCutover.js b/frontend/src/services/api/dnsCutover.jsnew file mode 100644index 00000000..f60a9d50--- /dev/null+++ b/frontend/src/services/api/dnsCutover.js@@ -0,0 +1,50 @@+// Reversible DNS cutover (/api/v1/dns-cutover) — snapshot a domain's records+// before a migration cutover so the switch can be reverted (plan 27 #13,+// plan 31 #1/#2/#4).++export async function getCutoverTtlGuidance(records) {+ return this.request('/dns-cutover/ttl-guidance', {+ method: 'POST',+ body: { records },+ });+}++// Server-sourced snapshot (plan 31 #2): the panel reads live records from the+// provider itself; the client may only pass `names` to filter which record+// names to include (never the record data). Requires a connected provider zone.+export async function snapshotDnsForCutover(domain, providerZoneId, provider = null, names = null) {+ return this.request('/dns-cutover/snapshot', {+ method: 'POST',+ body: { domain, provider_zone_id: providerZoneId, provider, names },+ });+}++export async function getCutoverSnapshots(domain = null) {+ const suffix = domain ? `?domain=${encodeURIComponent(domain)}` : '';+ return this.request(`/dns-cutover/snapshots${suffix}`);+}++export async function getCutoverSnapshot(snapshotId) {+ return this.request(`/dns-cutover/snapshots/${snapshotId}`);+}++// Perform (or dry-run) a cutover (plan 31 #1). `dryRun: true` returns the exact+// provider ops (create/update, old→new) without writing and needs no provider.+export async function performDnsCutover(snapshotId, target, { recordTypes = ['A'], dryRun = false } = {}) {+ return this.request('/dns-cutover/cutover', {+ method: 'POST',+ body: { snapshot_id: snapshotId, target, record_types: recordTypes, dry_run: dryRun },+ });+}++// Post-cutover resolution check across public resolvers (plan 31 #1).+export async function verifyDnsCutover(domain, { recordType = 'A', expected = null, snapshotId = null } = {}) {+ return this.request('/dns-cutover/verify', {+ method: 'POST',+ body: { domain, record_type: recordType, expected, snapshot_id: snapshotId },+ });+}++export async function revertDnsCutover(snapshotId) {+ return this.request(`/dns-cutover/snapshots/${snapshotId}/revert`, { method: 'POST' });+}diff --git a/frontend/src/styles/pages/_coexistence.scss b/frontend/src/styles/pages/_coexistence.scssnew file mode 100644index 00000000..0d2e6059--- /dev/null+++ b/frontend/src/styles/pages/_coexistence.scss@@ -0,0 +1,75 @@+// "Running alongside another panel" page (plan 27 #15).++.coexistence {+ display: flex;+ flex-direction: column;+ gap: $space-5;+ max-width: 820px;++ &__mode,+ &__guarantees {+ padding: $space-5;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-xl;+ }++ &__mode-title {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin: 0 0 $space-3;+ font-size: $font-size-lg;++ svg { color: $primary-color; flex-shrink: 0; }+ }++ &__mode-body,+ &__guarantees {+ p {+ margin: 0 0 $space-3;+ color: $text-secondary;+ line-height: 1.6;+ }++ p:last-child { margin-bottom: 0; }++ ol, ul {+ margin: 0;+ padding-left: $space-5;+ display: flex;+ flex-direction: column;+ gap: $space-2;++ li {+ color: $text-secondary;+ line-height: 1.5;+ }+ }++ a {+ color: $primary-color;+ &:hover { text-decoration: underline; }+ }+ }++ &__warning {+ display: flex;+ align-items: flex-start;+ gap: $space-3;+ padding: $space-4 $space-5;+ background: $warning-bg;+ border: 1px solid $warning-border;+ border-radius: $radius-xl;++ > svg { color: $warning; flex-shrink: 0; margin-top: 2px; }++ strong { display: block; margin-bottom: $space-1; color: $warning; }++ p {+ margin: 0;+ color: $text-secondary;+ line-height: 1.5;+ }+ }+}diff --git a/frontend/src/styles/pages/_cutover.scss b/frontend/src/styles/pages/_cutover.scssnew file mode 100644index 00000000..e7921f26--- /dev/null+++ b/frontend/src/styles/pages/_cutover.scss@@ -0,0 +1,304 @@+// ============================================+// DNS CUTOVER (reversible per-domain repoint — plan 31 #5/#6)+// Slide-over launched from /domains and the Import wizard. Mirrors the+// import-wizard idiom (stepper + callouts + compact tables).+// ============================================++.cutover {+ display: flex;+ flex-direction: column;+ gap: $space-5;++ h3 {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin: 0 0 $space-3;+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }++ // --------------------------------------------+ // Stepper+ // --------------------------------------------+ &__stepper {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin: 0;+ padding: 0;+ list-style: none;+ }++ &__step {+ display: flex;+ align-items: center;+ gap: $space-2;+ padding: $space-2 $space-3;+ border-radius: $radius-full;+ font-size: $font-size-sm;+ color: $text-tertiary;+ white-space: nowrap;++ &.is-active {+ color: $text-primary;+ background: $accent-bg;++ .cutover__step-dot {+ background: $accent-primary;+ border-color: $accent-primary;+ color: #fff;+ }+ }++ &.is-done {+ color: $text-secondary;++ .cutover__step-dot {+ color: $success;+ border-color: $success-border;+ }+ }++ & + &::before {+ content: '';+ width: 16px;+ height: 1px;+ margin-right: $space-2;+ background: $border-default;+ }+ }++ &__step-dot {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ border: 1px solid $border-default;+ border-radius: $radius-full;+ font-size: $font-size-xs;+ font-weight: $font-weight-semibold;+ flex-shrink: 0;+ }++ // --------------------------------------------+ // Stage body+ // --------------------------------------------+ &__stage {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ }++ &__lead {+ margin: 0;+ font-size: $font-size-sm;+ line-height: 1.6;+ color: $text-secondary;++ code {+ font-family: $font-mono;+ font-size: $font-size-xs;+ padding: 1px 5px;+ background: $bg-secondary;+ border-radius: $radius-sm;+ }+ }++ &__muted {+ margin: 0;+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__field {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }++ &__hint {+ font-size: $font-size-xs;+ color: $text-tertiary;++ &--warn {+ color: $warning;+ }+ }++ &__types {+ display: flex;+ gap: $space-3;+ flex-wrap: wrap;+ }++ &__type {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ padding: $space-2 $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ font-size: $font-size-sm;+ color: $text-primary;+ cursor: pointer;+ }++ &__actions {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: $space-3;+ margin-top: $space-2;+ }++ // --------------------------------------------+ // Review summary+ // --------------------------------------------+ &__summary {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: $space-3;+ }++ &__stat {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: $space-3 $space-4;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ }++ &__stat-val {+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ word-break: break-word;+ }++ &__stat-label {+ font-size: $font-size-xs;+ color: $text-tertiary;+ }++ // --------------------------------------------+ // Tables (ops diff + resolver rows)+ // --------------------------------------------+ &__table-wrap {+ overflow-x: auto;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ margin-bottom: $space-3;+ }++ &__table {+ width: 100%;+ border-collapse: collapse;+ font-size: $font-size-sm;++ th,+ td {+ padding: $space-2 $space-3;+ text-align: left;+ border-bottom: 1px solid $border-subtle;+ white-space: nowrap;+ }++ th {+ color: $text-tertiary;+ font-weight: $font-weight-medium;+ background: $bg-elevated;+ }++ td {+ color: $text-primary;+ }++ tbody tr:last-child td {+ border-bottom: none;+ }++ code {+ font-family: $font-mono;+ font-size: $font-size-xs;+ color: $text-secondary;+ }+ }++ &__verify-head {+ display: flex;+ gap: $space-2;+ margin-bottom: $space-3;+ flex-wrap: wrap;+ }++ &__section--revert {+ padding-top: $space-4;+ border-top: 1px solid $border-subtle;+ }++ // --------------------------------------------+ // Callouts+ // --------------------------------------------+ &__callout {+ display: flex;+ gap: $space-3;+ padding: $space-3 $space-4;+ border-radius: $radius-md;+ font-size: $font-size-sm;++ svg {+ flex-shrink: 0;+ margin-top: 2px;+ }++ p {+ margin: 0;++ code {+ font-family: $font-mono;+ font-size: $font-size-xs;+ padding: 1px 5px;+ background: $bg-secondary;+ border-radius: $radius-sm;+ }+ }++ &--info {+ background: $accent-bg;+ border: 1px solid $accent-primary;+ color: $text-secondary;++ svg { color: $accent-primary; }+ }++ &--warning {+ background: $warning-bg;+ border: 1px solid $warning-border;+ color: $warning;++ p { color: $text-secondary; }+ }++ &--danger {+ background: $danger-bg;+ border: 1px solid $danger-border;+ color: $danger;++ p { color: $text-secondary; }+ }++ &--success {+ background: $success-bg;+ border: 1px solid $success-border;+ color: $success;++ p { color: $text-secondary; }+ }+ }+}