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): pull-import a live site over SSH

Juan Denis64658cf91de5
diff --git a/backend/tests/test_wp_ssh_import.py b/backend/tests/test_wp_ssh_import.py
new file mode 100644
index 00000000..042e8fd5
--- /dev/null
+++ b/backend/tests/test_wp_ssh_import.py
@@ -0,0 +1,369 @@
+"""Tests for the WordPress-over-SSH pull importer (Panel Improvements #3).
+
+Covers: wp-config probe parsing, host-key fingerprint pinning (mismatch
+rejection), the SSRF host guard (metadata/loopback), tar traversal guards, the
+full job step sequence with every remote exec stubbed, and the admin API
+(auth + happy path with the enqueue stubbed).
+"""
+import io
+import os
+import tarfile
+
+import pytest
+
+from app.services import wordpress_bridge
+
+
+def _svc():
+ return wordpress_bridge.get('wp_ssh_import_service', 'WpSshImportService')
+
+
+def _err():
+ return wordpress_bridge.get('wp_ssh_import_service', 'WpSshImportError')
+
+
+WP_CONFIG_FIXTURE = """<?php
+define( 'DB_NAME', 'legacy_wp' );
+define('DB_USER', 'legacy_user');
+define("DB_PASSWORD", "s3cr3t-pw");
+define( 'DB_HOST', 'localhost' );
+define( 'WP_HOME', 'https://old.example.com' );
+$table_prefix = 'lw_';
+require_once ABSPATH . 'wp-settings.php';
+"""
+
+
+# ---- probe parsing ---------------------------------------------------------
+
+def test_parse_wp_config_extracts_db_facts():
+ svc = _svc()
+ cfg = svc.parse_wp_config(WP_CONFIG_FIXTURE)
+ assert cfg['db_name'] == 'legacy_wp'
+ assert cfg['db_user'] == 'legacy_user'
+ assert cfg['db_password'] == 's3cr3t-pw'
+ assert cfg['db_host'] == 'localhost'
+ assert cfg['wp_home'] == 'https://old.example.com'
+ assert cfg['table_prefix'] == 'lw_'
+
+
+def test_parse_wp_config_defaults_prefix():
+ svc = _svc()
+ cfg = svc.parse_wp_config("define('DB_NAME','x');")
+ assert cfg['table_prefix'] == 'wp_'
+ assert 'db_password' not in cfg
+
+
+def test_fingerprint_of_is_openssh_sha256():
+ import base64
+ import hashlib
+ svc = _svc()
+ blob = b'\x00\x00\x00\x0bssh-ed25519' + b'\x00' * 32
+ b64 = base64.b64encode(blob).decode()
+ expected = 'SHA256:' + base64.b64encode(
+ hashlib.sha256(blob).digest()).decode().rstrip('=')
+ assert svc.fingerprint_of(b64) == expected
+
+
+# ---- SSRF host guard -------------------------------------------------------
+
+ 'localhost', '127.0.0.1', '::1', '169.254.169.254', '0.0.0.0', '',
+ '-oProxyCommand=evil', 'bad host name',
+])
+def test_validate_host_rejects_dangerous_targets(host):
+ svc, err = _svc(), _err()
+ with pytest.raises(err):
+ svc.validate_host(host)
+
+
+def test_validate_host_allows_explicit_private_ip():
+ # LAN migrations are legitimate: RFC1918 typed by the operator is allowed.
+ svc = _svc()
+ assert svc.validate_host('10.11.12.13') == '10.11.12.13'
+ assert svc.validate_host('192.168.1.50') == '192.168.1.50'
+
+
+# ---- host-key pinning ------------------------------------------------------
+
+_KEYSCAN = [{'type': 'ssh-ed25519', 'key': 'QUJDREVGRw==',
+ 'line': 'h ssh-ed25519 QUJDREVGRw=='}]
+
+
+def test_assert_pinned_rejects_mismatch(monkeypatch):
+ svc, err = _svc(), _err()
+ monkeypatch.setattr(svc, '_keyscan', lambda host, port: list(_KEYSCAN))
+ good = svc.fingerprint_of(_KEYSCAN[0]['key'])
+ scan = svc.assert_pinned('10.0.0.9', 22, good)
+ assert scan['fingerprint'] == good and 'known_hosts' in scan
+ with pytest.raises(err, match='mismatch'):
+ svc.assert_pinned('10.0.0.9', 22, 'SHA256:not-the-pinned-key')
+
+
+# ---- tar traversal guards --------------------------------------------------
+
+def _make_tar(path, entries, link=None):
+ with tarfile.open(path, 'w:gz') as tf:
+ for name, content in entries.items():
+ data = content.encode()
+ info = tarfile.TarInfo(name=name)
+ info.size = len(data)
+ tf.addfile(info, io.BytesIO(data))
+ if link:
+ info = tarfile.TarInfo(name=link[0])
+ info.type = tarfile.SYMTYPE
+ info.linkname = link[1]
+ tf.addfile(info)
+
+
+def test_safe_extract_tar_rejects_parent_traversal(tmp_path):
+ svc = _svc()
+ t = tmp_path / 'evil.tar.gz'
+ _make_tar(str(t), {'../escape.txt': 'x', 'ok.txt': 'y'})
+ dest = tmp_path / 'out'
+ dest.mkdir()
+ res = svc.safe_extract_tar(str(t), str(dest))
+ assert res['success'] is False and 'Unsafe path' in res['error']
+ assert not (tmp_path / 'escape.txt').exists()
+
+
+def test_safe_extract_tar_rejects_absolute_paths(tmp_path):
+ svc = _svc()
+ t = tmp_path / 'abs.tar.gz'
+ _make_tar(str(t), {'/etc/evil.txt': 'x'})
+ dest = tmp_path / 'out2'
+ dest.mkdir()
+ res = svc.safe_extract_tar(str(t), str(dest))
+ assert res['success'] is False
+
+
+def test_safe_extract_tar_drops_escaping_symlink_and_extracts_rest(tmp_path):
+ svc = _svc()
+ t = tmp_path / 'link.tar.gz'
+ _make_tar(str(t), {'wp-content/ok.txt': 'y'}, link=('evil-link', '/etc/passwd'))
+ dest = tmp_path / 'out3'
+ dest.mkdir()
+ res = svc.safe_extract_tar(str(t), str(dest))
+ assert res['success'] is True
+ assert (dest / 'wp-content' / 'ok.txt').read_text() == 'y'
+ assert not (dest / 'evil-link').exists()
+
+
+def test_safe_extract_tar_rejects_garbage(tmp_path):
+ svc = _svc()
+ bad = tmp_path / 'not.tar.gz'
+ bad.write_text('nope')
+ dest = tmp_path / 'out4'
+ dest.mkdir()
+ res = svc.safe_extract_tar(str(bad), str(dest))
+ assert res['success'] is False
+
+
+# ---- job step sequence (remote exec fully stubbed) --------------------------
+
+class FakeJob:
+ id = 77
+
+ def __init__(self, payload):
+ self.payload = payload
+ self.result = None
+
+ def get_payload(self):
+ return self.payload
+
+ def set_payload(self, p):
+ self.payload = p
+
+ def set_result(self, r):
+ self.result = r
+
+ def get_result(self):
+ return self.result
+
+
+def _job_payload():
+ return {
+ 'connection': {'host': '10.20.30.40', 'port': 22, 'username': 'root',
+ 'auth': {'private_key': 'FAKE-KEY'}},
+ 'fingerprint': 'SHA256:pinned',
+ 'target': {'site_name': 'migrated-site', 'admin_email': '[email protected]'},
+ 'options': {'wp_path': '/var/www/html', 'old_url': None},
+ 'user_id': 1,
+ }
+
+
+def _stub_remote(svc, monkeypatch, tmp_path, has_wp_cli=True):
+ """Stub every SSH touchpoint; returns the list of remote commands run."""
+ calls = []
+ monkeypatch.setattr(svc, 'assert_pinned',
+ lambda host, port, fp: {'fingerprint': fp, 'key_type': 'ssh-ed25519',
+ 'known_hosts': 'h ssh-ed25519 AAAA\n'})
+
+ def fake_ssh(conn, kh, cmd, input_bytes=None, timeout=None, stdout_path=None):
+ calls.append(cmd)
+ if 'wp-config.php' in cmd:
+ return {'code': 0, 'stdout': WP_CONFIG_FIXTURE.encode(), 'stderr': b''}
+ if 'command -v wp' in cmd:
+ out = b'yes' if has_wp_cli else b'no'
+ return {'code': 0, 'stdout': out, 'stderr': b''}
+ if 'option get siteurl' in cmd:
+ return {'code': 0, 'stdout': b'https://old.example.com\n', 'stderr': b''}
+ if cmd.startswith('tar czf'):
+ src = tmp_path / 'srcroot'
+ (src / 'wp-content' / 'plugins').mkdir(parents=True, exist_ok=True)
+ (src / 'wp-content' / 'plugins' / 'p.php').write_text('<?php')
+ (src / 'index.php').write_text('<?php')
+ with tarfile.open(stdout_path, 'w:gz') as tf:
+ tf.add(str(src), arcname='.')
+ return {'code': 0, 'stdout': b'', 'stderr': b''}
+ if 'db export' in cmd or 'mysqldump' in cmd:
+ with open(stdout_path, 'wb') as fh:
+ fh.write(b'-- dump\nCREATE TABLE lw_options (x int);\n')
+ return {'code': 0, 'stdout': b'', 'stderr': b''}
+ return {'code': 0, 'stdout': b'', 'stderr': b''}
+
+ monkeypatch.setattr(svc, '_ssh_exec', fake_ssh)
+ return calls
+
+
+def test_run_import_step_sequence(app, monkeypatch, tmp_path):
+ svc = _svc()
+ calls = _stub_remote(svc, monkeypatch, tmp_path)
+
+ captured = {}
+
+ def fake_import(**kwargs):
+ captured.update(kwargs)
+ return {'success': True, 'site': {'id': 5, 'name': 'migrated-site'},
+ 'http_port': 8123, 'new_url': 'http://localhost:8123',
+ 'wp_content_imported': True}
+
+ monkeypatch.setattr(svc, '_import_into_panel', fake_import)
+ monkeypatch.setattr(svc, '_check_homepage', lambda port: True)
+
+ job = FakeJob(_job_payload())
+ result = svc.run_import(job)
+
+ steps = [s['step'] for s in result['steps']]
+ assert steps == ['pin_check', 'read_config', 'pull_docroot', 'dump_db',
+ 'rebuild_site', 'validate', 'done']
+ assert result['success'] is True
+ assert result['old_url'] == 'https://old.example.com'
+ assert result['new_url'] == 'http://localhost:8123'
+ assert result['homepage_ok'] is True
+
+ # The rebuild reused the extension's import path with the pulled artifacts.
+ assert captured['name'] == 'migrated-site'
+ assert captured['old_url'] == 'https://old.example.com'
+ assert captured['sql_path'] and os.path.basename(captured['sql_path']) == 'source.sql'
+ assert captured['wp_content_zip_path'].endswith('wp-content.zip')
+
+ # Secrets scrubbed from the persisted payload once the job ended.
+ assert job.payload['connection']['auth'] == {'scrubbed': True}
+ # No secrets in the step log.
+ flat = str(result['steps'])
+ assert 's3cr3t-pw' not in flat and 'FAKE-KEY' not in flat
+ assert any('tar czf' in c for c in calls)
+
+
+def test_run_import_pin_mismatch_aborts_before_any_pull(app, monkeypatch, tmp_path):
+ svc, err = _svc(), _err()
+ pulled = []
+ monkeypatch.setattr(svc, 'assert_pinned',
+ lambda host, port, fp: (_ for _ in ()).throw(
+ err('Host key mismatch: nope')))
+ monkeypatch.setattr(svc, '_ssh_exec',
+ lambda *a, **k: pulled.append(a) or {'code': 0, 'stdout': b'', 'stderr': b''})
+
+ job = FakeJob(_job_payload())
+ with pytest.raises(err, match='mismatch'):
+ svc.run_import(job)
+ assert pulled == [] # nothing touched the remote after the failed pin check
+ assert (job.result or {}).get('steps') and job.result['steps'][-1]['step'] == 'failed'
+
+
+# ---- API -------------------------------------------------------------------
+
+def test_probe_requires_auth(client):
+ r = client.post('/api/v1/wordpress/ssh-import/probe', json={'host': 'x'})
+ assert r.status_code == 401
+
+
+def test_probe_happy_path(client, auth_headers, monkeypatch):
+ svc = _svc()
+ monkeypatch.setattr(svc, 'probe',
+ lambda **kw: {'host_key_fingerprint': 'SHA256:abc',
+ 'db_name': 'legacy_wp', 'wp_version': '6.4',
+ 'site_url': 'https://old.example.com'})
+ r = client.post('/api/v1/wordpress/ssh-import/probe', headers=auth_headers,
+ json={'host': '10.0.0.5', 'username': 'root',
+ 'auth': {'password': 'x'}, 'wp_path': '/var/www/html'})
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['host_key_fingerprint'] == 'SHA256:abc'
+ assert 'db_password' not in body
+
+
+def test_probe_rejects_metadata_host(client, auth_headers):
+ r = client.post('/api/v1/wordpress/ssh-import/probe', headers=auth_headers,
+ json={'host': '169.254.169.254', 'username': 'root',
+ 'auth': {'password': 'x'}, 'wp_path': '/var/www/html'})
+ assert r.status_code == 400
+ assert 'error' in r.get_json()
+
+
+def test_start_import_enqueues_job(client, auth_headers, monkeypatch):
+ svc = _svc()
+
+ class J:
+ id = 321
+ monkeypatch.setattr(svc, 'enqueue_import',
+ lambda **kw: J() if kw['fingerprint'] == 'SHA256:abc' else None)
+ r = client.post('/api/v1/wordpress/ssh-import', headers=auth_headers,
+ json={'connection': {'host': '10.0.0.5', 'username': 'root',
+ 'auth': {'password': 'x'}},
+ 'fingerprint': 'SHA256:abc',
+ 'target': {'site_name': 'migrated'},
+ 'options': {'wp_path': '/var/www/html'}})
+ assert r.status_code == 202
+ assert r.get_json() == {'success': True, 'job_id': 321}
+
+
+def test_start_import_requires_fingerprint(client, auth_headers):
+ r = client.post('/api/v1/wordpress/ssh-import', headers=auth_headers,
+ json={'connection': {'host': '10.0.0.5', 'username': 'root',
+ 'auth': {'password': 'x'}},
+ 'target': {'site_name': 'migrated'},
+ 'options': {'wp_path': '/var/www/html'}})
+ assert r.status_code == 400
+ assert 'fingerprint' in r.get_json()['error']
+
+
+def test_status_endpoint_reads_job(client, auth_headers, app):
+ from app import db
+ from app.jobs.models import Job
+ mod = wordpress_bridge.load('wp_ssh_import_service')
+
+ job = Job(kind=mod.JOB_KIND, status='running')
+ job.set_payload({'connection': {'auth': {'password': 'never-echoed'}}})
+ job.set_result({'steps': [{'step': 'pin_check', 'message': 'ok'}]})
+ db.session.add(job)
+ other = Job(kind='backup.policy.run', status='running')
+ db.session.add(other)
+ db.session.commit()
+
+ r = client.get(f'/api/v1/wordpress/ssh-import/{job.id}', headers=auth_headers)
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['status'] == 'running'
+ assert body['steps'][0]['step'] == 'pin_check'
+ assert 'never-echoed' not in r.get_data(as_text=True) # payload never echoed
+
+ r = client.get(f'/api/v1/wordpress/ssh-import/{other.id}', headers=auth_headers)
+ assert r.status_code == 404
+
+
+def test_job_kind_registered():
+ from app.jobs import registry
+ mod = wordpress_bridge.load('wp_ssh_import_service')
+ mod.WpSshImportService.register_jobs()
+ assert registry.is_registered(mod.JOB_KIND)
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py
new file mode 100644
index 00000000..937fa7f8
--- /dev/null
+++ b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import.py
@@ -0,0 +1,76 @@
+"""WordPress-over-SSH pull importer API (Panel Improvements #3).
+
+Admin-only surface:
+
+* ``POST /api/v1/wordpress/ssh-import/probe`` — connect to the source box,
+ return the host-key fingerprint + site facts for operator confirmation.
+* ``POST /api/v1/wordpress/ssh-import`` — enqueue the import job (requires the
+ probed fingerprint back: that confirmation IS the host-key trust decision).
+* ``GET /api/v1/wordpress/ssh-import/<job_id>`` — poll job status + step log.
+
+Mounted via ``plugin.json`` ``extra_blueprints`` at ``/api/v1/wordpress``.
+"""
+from flask import Blueprint, request, jsonify
+
+from app.middleware.rbac import admin_required, get_current_user
+
+from .wp_ssh_import_service import (
+ JOB_KIND, WpSshImportError, WpSshImportService,
+)
+
+wp_ssh_import_bp = Blueprint('wp_ssh_import', __name__)
+
+# Belt-and-braces: the manifest declares the job handler too, but registering on
+# blueprint import guarantees the kind exists as soon as the API is mounted.
+WpSshImportService.register_jobs()
+
+
+@wp_ssh_import_bp.route('/ssh-import/probe', methods=['POST'])
+@admin_required
+def ssh_import_probe():
+ """Probe a remote WordPress over SSH: host-key fingerprint + site facts."""
+ data = request.get_json() or {}
+ try:
+ result = WpSshImportService.probe(
+ host=data.get('host'),
+ port=data.get('port') or 22,
+ username=data.get('username'),
+ auth=data.get('auth') or {},
+ wp_path=data.get('wp_path'),
+ )
+ except WpSshImportError as e:
+ return jsonify({'error': str(e)}), 400
+ return jsonify(result)
+
+
+@wp_ssh_import_bp.route('/ssh-import', methods=['POST'])
+@admin_required
+def ssh_import_start():
+ """Enqueue the pull-import job. Body: {connection, fingerprint, target, options}."""
+ data = request.get_json() or {}
+ user = get_current_user()
+ try:
+ job = WpSshImportService.enqueue_import(
+ connection=data.get('connection') or {},
+ fingerprint=(data.get('fingerprint') or '').strip(),
+ target=data.get('target') or {},
+ options=data.get('options') or {},
+ user_id=user.id,
+ )
+ except WpSshImportError as e:
+ return jsonify({'error': str(e)}), 400
+ return jsonify({'success': True, 'job_id': job.id}), 202
+
+
+@wp_ssh_import_bp.route('/ssh-import/<job_id>', methods=['GET'])
+@admin_required
+def ssh_import_status(job_id):
+ """Job status + step log for a running/finished SSH import."""
+ from app.jobs.models import Job
+ job = Job.query.get(job_id)
+ if not job or job.kind != JOB_KIND:
+ return jsonify({'error': 'Import job not found'}), 404
+ out = job.to_dict() # payload excluded by default — never echo credentials
+ result = job.get_result() or {}
+ out['steps'] = result.get('steps') or []
+ return jsonify(out)
diff --git a/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py
new file mode 100644
index 00000000..3f66624b
--- /dev/null
+++ b/builtin-extensions/serverkit-wordpress/backend/wp_ssh_import_service.py
@@ -0,0 +1,657 @@
+"""WordPress-over-SSH pull importer (Panel Improvements #3).
+
+Point the panel at any live WordPress site reachable over SSH and rebuild it as
+a managed site: probe the box (host-key fingerprint + wp-config facts), then a
+background job pulls the docroot with ``tar`` streamed over SSH, dumps the DB
+through the same tunnel, and hands everything to the extension's existing
+``WordPressService.import_site`` flow (fresh Docker stack + DB overwrite +
+URL search-replace + wp-content copy).
+
+Security posture:
+
+* **Host-key pinning** — the SHA256 fingerprint captured at probe time must be
+ re-presented for the import; every later SSH connection re-scans the host and
+ refuses to proceed on any mismatch (StrictHostKeyChecking=yes against a
+ known_hosts file we write from the verified scan — never the user's).
+* **SSRF guard** — the target host is resolved before any connection and
+ rejected when it lands on loopback, link-local (incl. the 169.254.169.254
+ cloud metadata endpoint), unspecified or multicast space. Explicit private
+ RFC1918/ULA addresses are ALLOWED on purpose: LAN-to-panel migrations are a
+ legitimate use; only metadata/loopback tricks are blocked (assumption logged).
+* **No secrets on command lines or in logs** — the SSH key goes through a
+ 0600 temp file, passwords through ``sshpass -e`` (env), the remote MySQL
+ password through the remote process' stdin. Job step logs carry no secrets,
+ and the job payload is scrubbed of credentials when the job finishes.
+* **Traversal-guarded extraction** — the pulled docroot tarball is unpacked
+ with an explicit member filter (no absolute paths, no ``..``, no links that
+ escape the destination, no device nodes).
+
+All process execution funnels through ``_run`` / ``_ssh_exec`` choke-points so
+the test suite can stub the remote side entirely.
+"""
+import base64
+import hashlib
+import ipaddress
+import logging
+import os
+import re
+import shutil
+import socket
+import subprocess
+import tarfile
+import tempfile
+import zipfile
+from typing import Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+JOB_KIND = 'wordpress.ssh_import.run'
+
+# Preferred host-key algorithms for the pinned fingerprint, best first.
+_KEY_PREFERENCE = ['ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384',
+ 'ecdsa-sha2-nistp521', 'rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']
+
+_HOST_RE = re.compile(r'^[A-Za-z0-9._:\-\[\]]+$')
+_USER_RE = re.compile(r'^[A-Za-z0-9._\-]+$')
+
+
+class WpSshImportError(Exception):
+ """Operator-facing failure (message is safe to surface)."""
+
+
+class WpSshImportService:
+ """Probe + pull-import a remote WordPress site over SSH."""
+
+ CONNECT_TIMEOUT = 15
+ EXEC_TIMEOUT = 60
+ TRANSFER_TIMEOUT = 3600
+
+ # ------------------------------------------------------------------ #
+ # Choke-points (stubbed in tests)
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def _run(cls, cmd: List[str], input_bytes: bytes = None, timeout: int = None,
+ env: Dict = None, stdout_path: str = None) -> Dict:
+ """Run a local process. Returns {'code', 'stdout', 'stderr'} (bytes-safe).
+
+ When ``stdout_path`` is given, stdout is streamed to that file instead
+ of being buffered (used for docroot/DB pulls).
+ """
+ full_env = dict(os.environ)
+ if env:
+ full_env.update(env)
+ try:
+ if stdout_path:
+ with open(stdout_path, 'wb') as out:
+ proc = subprocess.run(
+ cmd, input=input_bytes, stdout=out,
+ stderr=subprocess.PIPE, timeout=timeout or cls.EXEC_TIMEOUT,
+ env=full_env,
+ )
+ return {'code': proc.returncode, 'stdout': b'',
+ 'stderr': proc.stderr or b''}
+ proc = subprocess.run(
+ cmd, input=input_bytes, capture_output=True,
+ timeout=timeout or cls.EXEC_TIMEOUT, env=full_env,
+ )
+ return {'code': proc.returncode, 'stdout': proc.stdout or b'',
+ 'stderr': proc.stderr or b''}
+ except subprocess.TimeoutExpired:
+ return {'code': -1, 'stdout': b'', 'stderr': b'timed out'}
+ except FileNotFoundError as e:
+ return {'code': -1, 'stdout': b'', 'stderr': str(e).encode()}
+
+ # ------------------------------------------------------------------ #
+ # Host validation (SSRF guard)
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def validate_host(cls, host: str) -> str:
+ """Return the cleaned host or raise WpSshImportError.
+
+ Blocks loopback, link-local (incl. 169.254.169.254 metadata),
+ unspecified and multicast targets. Private RFC1918/ULA addresses are
+ allowed by design — LAN migrations are legitimate (logged).
+ """
+ host = (host or '').strip().strip('[]')
+ if not host or host.startswith('-') or not _HOST_RE.match(host):
+ raise WpSshImportError('Invalid host')
+ if host.lower() in ('localhost', 'localhost.localdomain'):
+ raise WpSshImportError('Refusing to import from loopback')
+ try:
+ infos = socket.getaddrinfo(host, 22, proto=socket.IPPROTO_TCP)
+ except socket.gaierror:
+ raise WpSshImportError(f'Host does not resolve: {host}')
+ private_seen = False
+ for info in infos:
+ try:
+ ip = ipaddress.ip_address(info[4][0])
+ except ValueError:
+ continue
+ if ip.is_loopback or ip.is_unspecified or ip.is_multicast or ip.is_link_local:
+ raise WpSshImportError(
+ f'Refusing to import from {ip} (loopback/link-local/metadata range)')
+ if ip.is_private:
+ private_seen = True
+ if private_seen:
+ logger.info('wp ssh-import: %s resolves to a private address; '
+ 'allowing (LAN migration assumed)', host)
+ return host
+
+ @classmethod
+ def _validate_conn(cls, conn: Dict) -> Dict:
+ host = cls.validate_host(conn.get('host'))
+ username = (conn.get('username') or '').strip()
+ if not username or not _USER_RE.match(username):
+ raise WpSshImportError('Invalid username')
+ try:
+ port = int(conn.get('port') or 22)
+ except (TypeError, ValueError):
+ raise WpSshImportError('Invalid port')
+ if not 1 <= port <= 65535:
+ raise WpSshImportError('Invalid port')
+ auth = conn.get('auth') or {}
+ if not (auth.get('password') or auth.get('private_key')):
+ raise WpSshImportError('A password or private key is required')
+ return {'host': host, 'port': port, 'username': username, 'auth': auth}
+
+ # ------------------------------------------------------------------ #
+ # Host-key scan + pinning
+ # ------------------------------------------------------------------ #
+
+ @staticmethod
+ def fingerprint_of(key_b64: str) -> str:
+ """OpenSSH-style SHA256 fingerprint of a base64 host key blob."""
+ digest = hashlib.sha256(base64.b64decode(key_b64)).digest()
+ return 'SHA256:' + base64.b64encode(digest).decode().rstrip('=')
+
+ @classmethod
+ def _keyscan(cls, host: str, port: int) -> List[Dict]:
+ """ssh-keyscan the host. Returns [{'type','key','line'}], best-first."""
+ res = cls._run(['ssh-keyscan', '-T', str(cls.CONNECT_TIMEOUT),
+ '-p', str(port), '--', host], timeout=cls.CONNECT_TIMEOUT + 10)
+ keys = []
+ for raw in (res.get('stdout') or b'').decode('utf-8', 'replace').splitlines():
+ raw = raw.strip()
+ if not raw or raw.startswith('#'):
+ continue
+ parts = raw.split()
+ if len(parts) >= 3:
+ keys.append({'type': parts[1], 'key': parts[2], 'line': raw})
+ if not keys:
+ raise WpSshImportError(f'Could not read an SSH host key from {host}:{port}')
+
+ def rank(k):
+ try:
+ return _KEY_PREFERENCE.index(k['type'])
+ except ValueError:
+ return len(_KEY_PREFERENCE)
+ keys.sort(key=rank)
+ return keys
+
+ @classmethod
+ def scan_fingerprint(cls, host: str, port: int) -> Dict:
+ """Scan and return {'fingerprint', 'key_type', 'known_hosts'} (all keys)."""
+ keys = cls._keyscan(host, port)
+ return {
+ 'fingerprint': cls.fingerprint_of(keys[0]['key']),
+ 'key_type': keys[0]['type'],
+ 'known_hosts': '\n'.join(k['line'] for k in keys) + '\n',
+ }
+
+ @classmethod
+ def assert_pinned(cls, host: str, port: int, expected_fingerprint: str) -> Dict:
+ """Re-scan the host and require the pinned fingerprint.
+
+ The pin is satisfied if ANY of the host's current keys matches (a box
+ legitimately offers several algorithms; what matters is that the key
+ the operator confirmed is still presented). Returns
+ {'fingerprint','key_type','known_hosts'} built from this fresh scan."""
+ keys = cls._keyscan(host, port)
+ fps = [cls.fingerprint_of(k['key']) for k in keys]
+ if expected_fingerprint not in fps:
+ raise WpSshImportError(
+ 'Host key mismatch: the server no longer presents the pinned '
+ f'fingerprint {expected_fingerprint}. Refusing to connect.')
+ return {
+ 'fingerprint': fps[0],
+ 'key_type': keys[0]['type'],
+ 'known_hosts': '\n'.join(k['line'] for k in keys) + '\n',
+ }
+
+ # ------------------------------------------------------------------ #
+ # SSH exec
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def _ssh_exec(cls, conn: Dict, known_hosts: str, remote_cmd: str,
+ input_bytes: bytes = None, timeout: int = None,
+ stdout_path: str = None) -> Dict:
+ """Run ``remote_cmd`` on the pinned host. All SSH goes through here."""
+ tmpdir = tempfile.mkdtemp(prefix='wpsshimp_')
+ try:
+ kh_path = os.path.join(tmpdir, 'known_hosts')
+ with open(kh_path, 'w') as fh:
+ fh.write(known_hosts)
+ auth = conn.get('auth') or {}
+ cmd = ['ssh',
+ '-p', str(conn['port']),
+ '-o', 'StrictHostKeyChecking=yes',
+ '-o', f'UserKnownHostsFile={kh_path}',
+ '-o', f'ConnectTimeout={cls.CONNECT_TIMEOUT}',
+ '-o', 'NumberOfPasswordPrompts=1']
+ env = None
+ key_path = None
+ if auth.get('private_key'):
+ key_path = os.path.join(tmpdir, 'id_key')
+ with open(key_path, 'w') as fh:
+ fh.write(auth['private_key'].rstrip() + '\n')
+ if os.name != 'nt':
+ os.chmod(key_path, 0o600)
+ cmd += ['-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
+ '-i', key_path]
+ elif auth.get('password'):
+ if not shutil.which('sshpass'):
+ raise WpSshImportError(
+ 'Password authentication needs the "sshpass" package on '
+ 'the panel host — install it, or use an SSH private key.')
+ env = {'SSHPASS': auth['password']}
+ cmd = ['sshpass', '-e'] + cmd + ['-o', 'PubkeyAuthentication=no']
+ cmd += ['--', f"{conn['username']}@{conn['host']}", remote_cmd]
+ return cls._run(cmd, input_bytes=input_bytes,
+ timeout=timeout or cls.EXEC_TIMEOUT,
+ env=env, stdout_path=stdout_path)
+ finally:
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ # ------------------------------------------------------------------ #
+ # wp-config parsing
+ # ------------------------------------------------------------------ #
+
+ _DEFINE_RE = r"define\s*\(\s*['\"]{name}['\"]\s*,\s*['\"](?P<val>[^'\"]*)['\"]\s*\)"
+
+ @classmethod
+ def parse_wp_config(cls, text: str) -> Dict:
+ """Extract DB facts + table prefix from wp-config.php source."""
+ out = {}
+ for name, key in (('DB_NAME', 'db_name'), ('DB_USER', 'db_user'),
+ ('DB_PASSWORD', 'db_password'), ('DB_HOST', 'db_host'),
+ ('WP_HOME', 'wp_home'), ('WP_SITEURL', 'wp_siteurl')):
+ m = re.search(cls._DEFINE_RE.format(name=name), text or '')
+ if m:
+ out[key] = m.group('val')
+ m = re.search(r"\$table_prefix\s*=\s*['\"]([^'\"]+)['\"]", text or '')
+ out['table_prefix'] = m.group(1) if m else 'wp_'
+ return out
+
+ # ------------------------------------------------------------------ #
+ # Probe
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def probe(cls, host: str, port: int, username: str, auth: Dict,
+ wp_path: str) -> Dict:
+ """Connect, capture the host-key fingerprint and read site facts.
+
+ Returns facts only — the remote DB password is intentionally NOT
+ included (the import job re-reads wp-config itself)."""
+ conn = cls._validate_conn({'host': host, 'port': port,
+ 'username': username, 'auth': auth})
+ wp_path = cls._clean_remote_path(wp_path)
+ scan = cls.scan_fingerprint(conn['host'], conn['port'])
+ kh = scan['known_hosts']
+ q = cls._shq(wp_path)
+
+ cfg_res = cls._ssh_exec(conn, kh, f'cat {q}/wp-config.php')
+ if cfg_res['code'] != 0:
+ err = (cfg_res['stderr'] or b'').decode('utf-8', 'replace').strip()
+ raise WpSshImportError(
+ f'Could not read {wp_path}/wp-config.php over SSH'
+ + (f': {err.splitlines()[-1]}' if err else ''))
+ cfg = cls.parse_wp_config(cfg_res['stdout'].decode('utf-8', 'replace'))
+ if not cfg.get('db_name'):
+ raise WpSshImportError('wp-config.php found but DB_NAME could not be parsed')
+
+ # wp-cli availability + version + siteurl (fallbacks: version.php / config).
+ wp_cli = cls._ssh_exec(conn, kh, 'command -v wp >/dev/null 2>&1 && echo yes || echo no')
+ has_wp_cli = b'yes' in (wp_cli.get('stdout') or b'')
+
+ wp_version = None
+ site_url = cfg.get('wp_home') or cfg.get('wp_siteurl')
+ if has_wp_cli:
+ r = cls._ssh_exec(conn, kh, f'wp core version --path={q} 2>/dev/null')
+ if r['code'] == 0:
+ wp_version = r['stdout'].decode('utf-8', 'replace').strip() or None
+ r = cls._ssh_exec(conn, kh, f'wp option get siteurl --path={q} 2>/dev/null')
+ if r['code'] == 0:
+ site_url = r['stdout'].decode('utf-8', 'replace').strip() or site_url
+ if not wp_version:
+ r = cls._ssh_exec(conn, kh,
+ f"grep -oE \"wp_version = '[^']+'\" {q}/wp-includes/version.php 2>/dev/null")
+ m = re.search(r"wp_version = '([^']+)'",
+ (r.get('stdout') or b'').decode('utf-8', 'replace'))
+ if m:
+ wp_version = m.group(1)
+
+ size_kb = None
+ r = cls._ssh_exec(conn, kh, f'du -sk {q} 2>/dev/null')
+ m = re.match(r'^(\d+)', (r.get('stdout') or b'').decode('utf-8', 'replace').strip())
+ if m:
+ size_kb = int(m.group(1))
+
+ return {
+ 'host_key_fingerprint': scan['fingerprint'],
+ 'host_key_type': scan['key_type'],
+ 'wp_version': wp_version,
+ 'site_url': site_url,
+ 'db_name': cfg['db_name'],
+ 'db_user': cfg.get('db_user'),
+ 'db_host': cfg.get('db_host') or 'localhost',
+ 'table_prefix': cfg.get('table_prefix', 'wp_'),
+ 'docroot_size_kb': size_kb,
+ 'has_wp_cli': has_wp_cli,
+ }
+
+ # ------------------------------------------------------------------ #
+ # Safe tar extraction
+ # ------------------------------------------------------------------ #
+
+ @staticmethod
+ def safe_extract_tar(tar_path: str, dest: str) -> Dict:
+ """Extract a tarball rejecting traversal, links out of dest, devices."""
+ dest_real = os.path.realpath(dest)
+ try:
+ with tarfile.open(tar_path, 'r:*') as tf:
+ for member in tf:
+ name = member.name
+ if name.startswith(('/', '\\')) or os.path.isabs(name) \
+ or '..' in name.replace('\\', '/').split('/'):
+ return {'success': False,
+ 'error': f'Unsafe path in archive: {name}'}
+ target = os.path.realpath(os.path.join(dest_real, name))
+ if target != dest_real and not target.startswith(dest_real + os.sep):
+ return {'success': False,
+ 'error': f'Unsafe path in archive: {name}'}
+ if member.isdev():
+ continue # never extract device/fifo nodes
+ if member.issym() or member.islnk():
+ link = member.linkname
+ base = os.path.dirname(os.path.join(dest_real, name))
+ link_target = os.path.realpath(
+ link if os.path.isabs(link) else os.path.join(base, link))
+ if not link_target.startswith(dest_real):
+ continue # drop links escaping the destination
+ tf.extract(member, dest_real)
+ return {'success': True}
+ except (tarfile.TarError, EOFError, OSError) as e:
+ return {'success': False, 'error': f'Not a valid tar archive: {e}'}
+
+ # ------------------------------------------------------------------ #
+ # Import job
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def enqueue_import(cls, connection: Dict, fingerprint: str, target: Dict,
+ options: Dict, user_id: int):
+ """Validate inputs and enqueue the import job. Returns the Job row."""
+ from app.jobs.service import JobService
+ conn = cls._validate_conn(connection or {})
+ if not fingerprint:
+ raise WpSshImportError('The probed host_key_fingerprint is required '
+ '(probe first, then confirm the host key)')
+ target = target or {}
+ if not (target.get('site_name') or '').strip():
+ raise WpSshImportError('target.site_name is required')
+ payload = {
+ 'connection': conn,
+ 'fingerprint': fingerprint,
+ 'target': {
+ 'site_name': target['site_name'].strip(),
+ 'admin_email': (target.get('admin_email') or '').strip(),
+ },
+ 'options': {
+ 'wp_path': cls._clean_remote_path((options or {}).get('wp_path')),
+ 'old_url': ((options or {}).get('old_url') or '').strip() or None,
+ },
+ 'user_id': user_id,
+ }
+ return JobService.enqueue(JOB_KIND, payload=payload, max_attempts=1,
+ owner_type='wordpress_ssh_import', owner_id=user_id)
+
+ @classmethod
+ def run_import(cls, job) -> Dict:
+ """Job handler for ``wordpress.ssh_import.run``. Steps are appended to
+ the job result as it goes so the UI can poll progress."""
+ payload = job.get_payload() or {}
+ state = {'steps': []}
+ workdir = tempfile.mkdtemp(prefix='wpsshimport_')
+ try:
+ result = cls._run_import_steps(job, payload, state, workdir)
+ state.update(result)
+ state['success'] = True
+ return state
+ except WpSshImportError as e:
+ cls._step(job, state, 'failed', str(e))
+ state['success'] = False
+ state['error'] = str(e)
+ raise
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
+ cls._scrub_job_secrets(job)
+
+ @classmethod
+ def _run_import_steps(cls, job, payload: Dict, state: Dict, workdir: str) -> Dict:
+ conn = cls._validate_conn(payload.get('connection') or {})
+ fingerprint = payload.get('fingerprint')
+ target = payload.get('target') or {}
+ options = payload.get('options') or {}
+ wp_path = cls._clean_remote_path(options.get('wp_path'))
+ user_id = payload.get('user_id')
+ q = cls._shq(wp_path)
+
+ # 1) Host-key pin check.
+ cls._step(job, state, 'pin_check', f'Verifying pinned host key for {conn["host"]}')
+ scan = cls.assert_pinned(conn['host'], conn['port'], fingerprint)
+ kh = scan['known_hosts']
+
+ # 2) Read remote facts (creds never leave this process).
+ cls._step(job, state, 'read_config', 'Reading remote wp-config.php')
+ cfg_res = cls._ssh_exec(conn, kh, f'cat {q}/wp-config.php')
+ if cfg_res['code'] != 0:
+ raise WpSshImportError('Could not read wp-config.php on the source host')
+ cfg = cls.parse_wp_config(cfg_res['stdout'].decode('utf-8', 'replace'))
+ if not cfg.get('db_name'):
+ raise WpSshImportError('DB_NAME could not be parsed from wp-config.php')
+ has_wp_cli = b'yes' in (cls._ssh_exec(
+ conn, kh, 'command -v wp >/dev/null 2>&1 && echo yes || echo no'
+ ).get('stdout') or b'')
+
+ old_url = options.get('old_url')
+ if not old_url and has_wp_cli:
+ r = cls._ssh_exec(conn, kh, f'wp option get siteurl --path={q} 2>/dev/null')
+ if r['code'] == 0:
+ old_url = r['stdout'].decode('utf-8', 'replace').strip() or None
+ if not old_url:
+ old_url = cfg.get('wp_home') or cfg.get('wp_siteurl')
+ if not old_url:
+ raise WpSshImportError(
+ 'Could not determine the source site URL — pass options.old_url')
+
+ # 3) Pull the docroot as a tar stream (no rsync dependency).
+ cls._step(job, state, 'pull_docroot', 'Pulling the docroot over SSH (tar stream)')
+ tar_path = os.path.join(workdir, 'docroot.tar.gz')
+ pull = cls._ssh_exec(conn, kh, f'tar czf - -C {q} .',
+ timeout=cls.TRANSFER_TIMEOUT, stdout_path=tar_path)
+ if pull['code'] != 0 or not os.path.getsize(tar_path):
+ err = (pull.get('stderr') or b'').decode('utf-8', 'replace').strip()
+ raise WpSshImportError('Docroot pull failed'
+ + (f': {err.splitlines()[-1]}' if err else ''))
+ extract_dir = os.path.join(workdir, 'docroot')
+ os.makedirs(extract_dir, exist_ok=True)
+ ext = cls.safe_extract_tar(tar_path, extract_dir)
+ if not ext.get('success'):
+ raise WpSshImportError(ext.get('error') or 'Docroot extraction failed')
+
+ # Repack wp-content only: core files come from the managed image, and
+ # the source wp-config must never override the managed stack's.
+ wp_content_src = os.path.join(extract_dir, 'wp-content')
+ wp_content_zip = None
+ if os.path.isdir(wp_content_src):
+ wp_content_zip = os.path.join(workdir, 'wp-content.zip')
+ cls._zip_dir(wp_content_src, wp_content_zip, arc_root='wp-content')
+ else:
+ cls._step(job, state, 'pull_docroot',
+ 'No wp-content directory found in the pulled docroot; '
+ 'importing database only')
+
+ # 4) Dump the DB through the tunnel (no remote temp files, no creds on argv).
+ cls._step(job, state, 'dump_db', 'Dumping the source database over SSH')
+ sql_path = os.path.join(workdir, 'source.sql')
+ if has_wp_cli:
+ dump = cls._ssh_exec(conn, kh, f'wp db export - --path={q} --single-transaction',
+ timeout=cls.TRANSFER_TIMEOUT, stdout_path=sql_path)
+ else:
+ db_host = cfg.get('db_host') or 'localhost'
+ host_part = db_host.split(':')[0] or 'localhost'
+ remote = ('read -r MYSQL_PWD; export MYSQL_PWD; '
+ f'exec mysqldump --single-transaction -h {cls._shq(host_part)} '
+ f'-u {cls._shq(cfg.get("db_user") or "root")} '
+ f'{cls._shq(cfg["db_name"])}')
+ dump = cls._ssh_exec(conn, kh, remote,
+ input_bytes=(cfg.get('db_password') or '').encode() + b'\n',
+ timeout=cls.TRANSFER_TIMEOUT, stdout_path=sql_path)
+ if dump['code'] != 0 or not os.path.getsize(sql_path):
+ err = (dump.get('stderr') or b'').decode('utf-8', 'replace').strip()
+ raise WpSshImportError('Database dump failed'
+ + (f': {err.splitlines()[-1]}' if err else ''))
+
+ # 5-7) Rebuild as a managed site: create stack, import DB, search-replace
+ # old URL -> new URL, copy wp-content, flush caches — all via the
+ # extension's existing import path.
+ cls._step(job, state, 'rebuild_site',
+ f'Creating managed site "{target.get("site_name")}" and importing')
+ site_result = cls._import_into_panel(
+ name=target.get('site_name'),
+ admin_email=target.get('admin_email') or '',
+ user_id=user_id,
+ sql_path=sql_path,
+ old_url=old_url,
+ wp_content_zip_path=wp_content_zip,
+ )
+ if not site_result.get('success'):
+ raise WpSshImportError(site_result.get('error') or 'Site rebuild failed')
+
+ # 8) Validate: fetch the homepage via the local port (best-effort).
+ cls._step(job, state, 'validate', 'Validating the imported site')
+ http_port = site_result.get('http_port')
+ homepage_ok = cls._check_homepage(http_port) if http_port else None
+
+ cls._step(job, state, 'done', 'Import finished')
+ out = {
+ 'site': site_result.get('site'),
+ 'http_port': http_port,
+ 'old_url': old_url,
+ 'new_url': site_result.get('new_url'),
+ 'wp_content_imported': bool(site_result.get('wp_content_imported')),
+ 'homepage_ok': homepage_ok,
+ }
+ if site_result.get('warning'):
+ out['warning'] = site_result['warning']
+ return out
+
+ # ------------------------------------------------------------------ #
+ # Helpers
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def _import_into_panel(cls, **kwargs) -> Dict:
+ """Indirection over WordPressService.import_site (stubbed in tests)."""
+ from .wordpress_service import WordPressService
+ return WordPressService.import_site(**kwargs)
+
+ @classmethod
+ def _check_homepage(cls, http_port) -> Optional[bool]:
+ import urllib.request
+ try:
+ req = urllib.request.Request(f'http://localhost:{http_port}/',
+ method='GET')
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ return 200 <= resp.status < 500
+ except Exception:
+ return False
+
+ @staticmethod
+ def _zip_dir(src_dir: str, zip_path: str, arc_root: str = ''):
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
+ for root, _dirs, files in os.walk(src_dir):
+ for fname in files:
+ full = os.path.join(root, fname)
+ rel = os.path.relpath(full, src_dir)
+ arc = os.path.join(arc_root, rel) if arc_root else rel
+ zf.write(full, arc.replace(os.sep, '/'))
+
+ @staticmethod
+ def _shq(value: str) -> str:
+ """Single-quote a value for the remote POSIX shell."""
+ return "'" + str(value or '').replace("'", "'\\''") + "'"
+
+ @staticmethod
+ def _clean_remote_path(path: str) -> str:
+ path = (path or '').strip()
+ if not path:
+ raise WpSshImportError('The remote WordPress path (wp_path) is required')
+ if not path.startswith('/'):
+ raise WpSshImportError('wp_path must be an absolute path')
+ if '\n' in path or '\r' in path:
+ raise WpSshImportError('Invalid wp_path')
+ return path.rstrip('/') or '/'
+
+ @classmethod
+ def _step(cls, job, state: Dict, name: str, message: str):
+ """Append a progress step to the job result and persist (best-effort)."""
+ from datetime import datetime
+ entry = {'step': name, 'message': message,
+ 'at': datetime.utcnow().isoformat() + 'Z'}
+ state['steps'].append(entry)
+ logger.info('wp ssh-import job %s: [%s] %s',
+ getattr(job, 'id', '?'), name, message)
+ try:
+ from app import db
+ job.set_result(state)
+ db.session.commit()
+ except Exception: # never let progress bookkeeping kill the import
+ pass
+
+ @classmethod
+ def _scrub_job_secrets(cls, job):
+ """Drop credentials from the persisted job payload once the job ends."""
+ try:
+ from app import db
+ payload = job.get_payload() or {}
+ conn = payload.get('connection') or {}
+ if conn.get('auth'):
+ conn['auth'] = {'scrubbed': True}
+ payload['connection'] = conn
+ job.set_payload(payload)
+ db.session.commit()
+ except Exception:
+ pass
+
+ # ------------------------------------------------------------------ #
+ # Registration
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def register_jobs(cls):
+ from app.jobs import registry
+ registry.register(JOB_KIND, cls.run_import, replace=True)
+
+
+def run_wp_ssh_import_job(job):
+ """Module-level handler target for the manifest ``jobs`` declaration."""
+ return WpSshImportService.run_import(job)
+
+
+def register_jobs():
+ WpSshImportService.register_jobs()
diff --git a/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx b/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx
new file mode 100644
index 00000000..16518a69
--- /dev/null
+++ b/builtin-extensions/serverkit-wordpress/frontend/WordPressSshImport.jsx
@@ -0,0 +1,304 @@
+// Import a live WordPress site over SSH (Panel Improvements #3).
+//
+// Three-step surface rendered inside the WordPress tab group:
+// 1. Connection — host/port/user + password-or-key + remote WP path.
+// 2. Probe — the backend captures the SSH host-key fingerprint and reads
+// site facts (wp-config, version, size). The operator explicitly trusts
+// the fingerprint before anything else touches the box.
+// 3. Import — enqueues the pull-import job and polls its step log.
+//
+// After sync this file lives at frontend/src/plugins/serverkit-wordpress/, so
+// shared pieces are imported through the host's `@/` alias like core pages do.
+import { useEffect, useRef, useState } from 'react';
+import { Link } from 'react-router-dom';
+import api from '@/services/api';
+import Spinner from '@/components/Spinner';
+import { useToast } from '@/contexts/ToastContext';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+
+const POLL_MS = 2500;
+
+export default function WordPressSshImport() {
+ const toast = useToast();
+ const [conn, setConn] = useState({
+ host: '', port: '22', username: 'root',
+ authMethod: 'key', password: '', privateKey: '',
+ wpPath: '/var/www/html',
+ });
+ const [probing, setProbing] = useState(false);
+ const [probe, setProbe] = useState(null); // probe result (incl. fingerprint)
+ const [trusted, setTrusted] = useState(false); // operator confirmed the host key
+ const [target, setTarget] = useState({ siteName: '', adminEmail: '', oldUrl: '' });
+ const [starting, setStarting] = useState(false);
+ const [job, setJob] = useState(null); // { id, status, steps, result, error }
+ const pollRef = useRef(null);
+
+ useEffect(() => () => clearInterval(pollRef.current), []);
+
+ const authPayload = () => (conn.authMethod === 'password'
+ ? { password: conn.password }
+ : { private_key: conn.privateKey });
+
+ const handleProbe = async () => {
+ setProbing(true);
+ setProbe(null);
+ setTrusted(false);
+ try {
+ const result = await api.request('/wordpress/ssh-import/probe', {
+ method: 'POST',
+ body: {
+ host: conn.host.trim(),
+ port: parseInt(conn.port, 10) || 22,
+ username: conn.username.trim(),
+ auth: authPayload(),
+ wp_path: conn.wpPath.trim(),
+ },
+ });
+ setProbe(result);
+ setTarget(t => ({ ...t, oldUrl: t.oldUrl || result.site_url || '' }));
+ } catch (error) {
+ toast.error(error.message || 'Probe failed');
+ } finally {
+ setProbing(false);
+ }
+ };
+
+ const pollJob = async (jobId) => {
+ try {
+ const status = await api.request(`/wordpress/ssh-import/${jobId}`);
+ setJob(status);
+ if (['completed', 'failed', 'dead'].includes(status.status)) {
+ clearInterval(pollRef.current);
+ pollRef.current = null;
+ if (status.status === 'completed') {
+ toast.success('WordPress site imported successfully');
+ } else {
+ toast.error(status.error || 'Import failed — see the step log');
+ }
+ }
+ } catch {
+ /* transient poll error — keep polling */
+ }
+ };
+
+ const handleStart = async () => {
+ if (!trusted) { toast.error('Confirm the host-key fingerprint first'); return; }
+ if (!target.siteName.trim()) { toast.error('New site name is required'); return; }
+ setStarting(true);
+ try {
+ const res = await api.request('/wordpress/ssh-import', {
+ method: 'POST',
+ body: {
+ connection: {
+ host: conn.host.trim(),
+ port: parseInt(conn.port, 10) || 22,
+ username: conn.username.trim(),
+ auth: authPayload(),
+ },
+ fingerprint: probe.host_key_fingerprint,
+ target: {
+ site_name: target.siteName.trim(),
+ admin_email: target.adminEmail.trim(),
+ },
+ options: {
+ wp_path: conn.wpPath.trim(),
+ old_url: target.oldUrl.trim() || undefined,
+ },
+ },
+ });
+ setJob({ id: res.job_id, status: 'pending', steps: [] });
+ pollRef.current = setInterval(() => pollJob(res.job_id), POLL_MS);
+ pollJob(res.job_id);
+ } catch (error) {
+ toast.error(error.message || 'Failed to start the import');
+ } finally {
+ setStarting(false);
+ }
+ };
+
+ const running = job && !['completed', 'failed', 'dead'].includes(job.status);
+ const canProbe = conn.host.trim() && conn.username.trim() && conn.wpPath.trim()
+ && (conn.authMethod === 'password' ? conn.password : conn.privateKey);
+ const facts = probe && [
+ ['WordPress version', probe.wp_version || 'unknown'],
+ ['Site URL', probe.site_url || 'unknown'],
+ ['Database', probe.db_name],
+ ['Table prefix', probe.table_prefix],
+ ['Docroot size', probe.docroot_size_kb != null
+ ? `${(probe.docroot_size_kb / 1024).toFixed(1)} MB` : 'unknown'],
+ ['WP-CLI on source', probe.has_wp_cli ? 'yes' : 'no (fallbacks used)'],
+ ];
+
+ return (
+ <div className="sk-tabgroup__inner wp-ssh-import">
+ <div className="page-section">
+ <h2 className="text-lg font-semibold">Import a live site over SSH</h2>
+ <p className="text-sm text-muted-foreground">
+ Point at any WordPress install you can reach over SSH. The panel pulls the
+ files and database through the tunnel and rebuilds it as a managed site —
+ nothing is installed on the source server.
+ </p>
+ </div>
+
+ {/* Step 1 — connection */}
+ <div className="card p-4 mb-4">
+ <h3 className="font-medium mb-3">1. Source server</h3>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="form-group">
+ <Label>Host <span className="required">*</span></Label>
+ <Input value={conn.host} disabled={running}
+ onChange={e => setConn({ ...conn, host: e.target.value })}
+ placeholder="203.0.113.10 or wp.example.com" />
+ </div>
+ <div className="form-group">
+ <Label>Port</Label>
+ <Input value={conn.port} disabled={running}
+ onChange={e => setConn({ ...conn, port: e.target.value })}
+ placeholder="22" />
+ </div>
+ <div className="form-group">
+ <Label>Username <span className="required">*</span></Label>
+ <Input value={conn.username} disabled={running}
+ onChange={e => setConn({ ...conn, username: e.target.value })}
+ placeholder="root" />
+ </div>
+ <div className="form-group">
+ <Label>WordPress path <span className="required">*</span></Label>
+ <Input value={conn.wpPath} disabled={running}
+ onChange={e => setConn({ ...conn, wpPath: e.target.value })}
+ placeholder="/var/www/html" />
+ <span className="form-hint">Absolute path of the directory containing wp-config.php.</span>
+ </div>
+ </div>
+ <div className="form-group">
+ <Label>Authentication</Label>
+ <div className="flex gap-4 mb-2">
+ <label className="flex items-center gap-2 text-sm">
+ <input type="radio" checked={conn.authMethod === 'key'} disabled={running}
+ onChange={() => setConn({ ...conn, authMethod: 'key' })} />
+ Private key
+ </label>
+ <label className="flex items-center gap-2 text-sm">
+ <input type="radio" checked={conn.authMethod === 'password'} disabled={running}
+ onChange={() => setConn({ ...conn, authMethod: 'password' })} />
+ Password
+ </label>
+ </div>
+ {conn.authMethod === 'key' ? (
+ <>
+ <textarea
+ className="w-full font-mono text-xs"
+ rows={5}
+ value={conn.privateKey}
+ disabled={running}
+ onChange={e => setConn({ ...conn, privateKey: e.target.value })}
+ placeholder={'-----BEGIN OPENSSH PRIVATE KEY-----\n…'}
+ />
+ <span className="form-hint">Used for this import only — never stored.</span>
+ </>
+ ) : (
+ <>
+ <Input type="password" value={conn.password} disabled={running}
+ onChange={e => setConn({ ...conn, password: e.target.value })}
+ placeholder="SSH password" />
+ <span className="form-hint">Used for this import only — never stored. Password auth requires the sshpass package on the panel host.</span>
+ </>
+ )}
+ </div>
+ <Button onClick={handleProbe} disabled={!canProbe || probing || running}>
+ {probing ? <><Spinner size="sm" /> Probing…</> : 'Probe server'}
+ </Button>
+ </div>
+
+ {/* Step 2 — facts + host-key trust */}
+ {probe && (
+ <div className="card p-4 mb-4">
+ <h3 className="font-medium mb-3">2. Confirm the host</h3>
+ <div className="form-group">
+ <Label>SSH host-key fingerprint ({probe.host_key_type})</Label>
+ <code className="block font-mono text-xs break-all">{probe.host_key_fingerprint}</code>
+ <span className="form-hint">
+ Compare against the server you expect (ssh-keygen -lf on the source).
+ Every step of the import is pinned to this exact key.
+ </span>
+ </div>
+ <table className="text-sm">
+ <tbody>
+ {facts.map(([k, v]) => (
+ <tr key={k}>
+ <td className="pr-4 text-muted-foreground">{k}</td>
+ <td className="font-mono">{String(v)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ <label className="flex items-center gap-2 text-sm mt-3">
+ <input type="checkbox" checked={trusted} disabled={running}
+ onChange={e => setTrusted(e.target.checked)} />
+ I recognize this fingerprint — trust this host for the import
+ </label>
+ </div>
+ )}
+
+ {/* Step 3 — target + run */}
+ {probe && (
+ <div className="card p-4 mb-4">
+ <h3 className="font-medium mb-3">3. New managed site</h3>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="form-group">
+ <Label>Site name <span className="required">*</span></Label>
+ <Input value={target.siteName} disabled={running}
+ onChange={e => setTarget({ ...target, siteName: e.target.value })}
+ placeholder="my-migrated-site" />
+ <span className="form-hint">Letters, numbers, and hyphens only.</span>
+ </div>
+ <div className="form-group">
+ <Label>Admin email</Label>
+ <Input type="email" value={target.adminEmail} disabled={running}
+ onChange={e => setTarget({ ...target, adminEmail: e.target.value })}
+ placeholder="[email protected]" />
+ </div>
+ <div className="form-group">
+ <Label>Original site URL</Label>
+ <Input value={target.oldUrl} disabled={running}
+ onChange={e => setTarget({ ...target, oldUrl: e.target.value })}
+ placeholder="https://old-site.com" />
+ <span className="form-hint">Rewritten to the new local address after import (detected automatically when possible).</span>
+ </div>
+ </div>
+ <Button onClick={handleStart} disabled={!trusted || starting || running}>
+ {starting ? <><Spinner size="sm" /> Starting…</> : 'Pull and import'}
+ </Button>
+ </div>
+ )}
+
+ {/* Job progress */}
+ {job && (
+ <div className="card p-4 mb-4">
+ <h3 className="font-medium mb-3">
+ Import job #{job.id} — {job.status}
+ {running && <Spinner size="sm" />}
+ </h3>
+ <ul className="text-sm font-mono space-y-1">
+ {(job.steps || []).map((s, i) => (
+ <li key={i}>
+ <span className="text-muted-foreground">[{s.step}]</span> {s.message}
+ </li>
+ ))}
+ </ul>
+ {job.status === 'failed' && job.error && (
+ <p className="text-sm text-destructive mt-2">{job.error}</p>
+ )}
+ {job.status === 'completed' && (
+ <p className="text-sm mt-2">
+ Done. <Link to="/wordpress" className="underline">Open the WordPress sites list</Link>
+ {job.result?.new_url && <> — new address: <code>{job.result.new_url}</code></>}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-wordpress/frontend/index.jsx b/builtin-extensions/serverkit-wordpress/frontend/index.jsx
index 567ea288..b6defac9 100644
--- a/builtin-extensions/serverkit-wordpress/frontend/index.jsx
+++ b/builtin-extensions/serverkit-wordpress/frontend/index.jsx
@@ -23,6 +23,7 @@ import WordPressPluginLibrary from '../../pages/WordPressPluginLibrary';
import WordPressProjects from '../../pages/WordPressProjects';
import WordPressProject from '../../pages/WordPressProject';
import WordPressDetail from '../../pages/WordPressDetail';
+import WordPressSshImport from './WordPressSshImport';
// "WordPress Projects" was renamed to "Pipelines" (§2 unification). Forward old
// deep links to the new space.
@@ -40,6 +41,9 @@ export function WordPressExtension() {
<Route index element={<WordPress />} />
<Route path="plugins/library" element={<WordPressPluginLibrary />} />
<Route path="pipelines" element={<WordPressProjects />} />
+ {/* SSH pull-import (Panel Improvements #3) — shares the group
+ chrome; reached via the command palette / direct link. */}
+ <Route path="ssh-import" element={<WordPressSshImport />} />
</Route>
{/* Full-bleed pipeline detail (own chrome, outside the tab group). */}
<Route path="pipelines/:id" element={<WordPressProject />} />
diff --git a/builtin-extensions/serverkit-wordpress/plugin.json b/builtin-extensions/serverkit-wordpress/plugin.json
index 97888f65..cac630a0 100644
--- a/builtin-extensions/serverkit-wordpress/plugin.json
+++ b/builtin-extensions/serverkit-wordpress/plugin.json
@@ -27,6 +27,17 @@
"attr": "environment_pipeline_bp",
"url_prefix": "/api/v1/wordpress/pipelines",
"name": "environment_pipeline_pipelines"
+ },
+ {
+ "module": "wp_ssh_import",
+ "attr": "wp_ssh_import_bp",
+ "url_prefix": "/api/v1/wordpress"
+ }
+ ],
+ "jobs": [
+ {
+ "kind": "wordpress.ssh_import.run",
+ "handler": "wp_ssh_import_service:run_wp_ssh_import_job"
}
],
"icon": "<path d=\"M12 2a10 10 0 100 20 10 10 0 000-20zm-8 10a8 8 0 011.4-4.5l4.7 12.9A8 8 0 014 12zm8 8c-.8 0-1.6-.1-2.3-.3l2.4-7 2.5 6.8.1.1A8 8 0 0112 20zm1.1-11.8c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1-.8 0-2.2-.1-2.2-.1-.5 0-.6.6-.1.6 0 0 .4.1.9.1l1.3 3.6-1.9 5.6L6.6 8.2c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1h-.4A8 8 0 0112 4a8 8 0 016.5 3.3h-.3c-.8 0-1.4.7-1.4 1.5 0 .7.4 1.3.8 2 .3.6.7 1.3.7 2.3 0 .7-.3 1.6-.6 2.7l-.8 2.7-2.9-8.8z\"/>",
@@ -46,10 +57,12 @@
"page_titles": {
"/wordpress": "WordPress Sites",
"/wordpress/plugins/library": "WordPress Plugin Library",
- "/wordpress/pipelines": "WordPress Pipelines"
+ "/wordpress/pipelines": "WordPress Pipelines",
+ "/wordpress/ssh-import": "Import WordPress over SSH"
},
"command_palette": [
{ "label": "WordPress", "path": "/wordpress", "category": "Pages", "keywords": "wp sites" },
+ { "label": "Import WordPress over SSH", "path": "/wordpress/ssh-import", "category": "Pages", "keywords": "wp migrate pull import ssh" },
{ "label": "WordPress Pipelines", "path": "/wordpress/pipelines", "category": "Pages", "keywords": "wp environments projects pipeline" }
]
}