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(wordpress): per-site plugin/theme/core vulnerability scanning (#28)
Juan Denis2b5db90f89a3
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex a7e3693b..eb74325f 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -515,6 +515,39 @@ def get_site_analytics(app_id):return jsonify(result), 200+@wordpress_bp.route('/sites/<int:app_id>/vulnerabilities', methods=['GET'])+@jwt_required()+def get_site_vulnerabilities(app_id):+ """Return persisted vulnerability findings + live scan status for a site."""+ from app.services.wp_vulnerability_service import WpVulnerabilityService+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ return jsonify(WpVulnerabilityService.get_results(wp_site)), 200+++@wordpress_bp.route('/sites/<int:app_id>/vulnerabilities/scan', methods=['POST'])+@jwt_required()+@admin_required+def scan_site_vulnerabilities(app_id):+ """Start a background vulnerability scan (cross-references the WPVulnerability feed)."""+ from app.services.wp_vulnerability_service import WpVulnerabilityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ return jsonify(WpVulnerabilityService.start_scan(wp_site)), 200++@wordpress_bp.route('/sites/<int:app_id>/info', methods=['GET'])@jwt_required()def get_wordpress_info(app_id):diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 76410709..c074ef07 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -12,7 +12,7 @@ from app.models.workflow import Workflow, WorkflowExecution, WorkflowLogfrom app.models.webhook import GitWebhook, WebhookLog, GitDeploymentfrom app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession, AgentVersion, AgentRolloutfrom app.models.security_alert import SecurityAlert-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob, WordPressVulnerabilityfrom app.models.environment_activity import EnvironmentActivityfrom app.models.promotion_job import PromotionJobfrom app.models.sanitization_profile import SanitizationProfile@@ -39,7 +39,7 @@ __all__ = ['NotificationPreferences', 'Deployment', 'DeploymentDiff', 'DeploymentJob', 'DeploymentJobLog', 'SystemSettings', 'AuditLog','MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'SecurityAlert',- 'WordPressSite', 'DatabaseSnapshot', 'SyncJob',+ 'WordPressSite', 'DatabaseSnapshot', 'SyncJob', 'WordPressVulnerability','EnvironmentActivity', 'PromotionJob', 'SanitizationProfile','EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig','OAuthIdentity', 'SourceConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.pyindex 6f827abf..366fe4fd 100644--- a/backend/app/models/wordpress_site.py+++ b/backend/app/models/wordpress_site.py@@ -78,6 +78,9 @@ class WordPressSite(db.Model):disk_usage_bytes = db.Column(db.BigInteger, default=0)disk_usage_updated_at = db.Column(db.DateTime)+ # Vulnerability scan (#28)+ last_vuln_scan_at = db.Column(db.DateTime)+# Auto-syncauto_sync_schedule = db.Column(db.String(100)) # cron expressionauto_sync_enabled = db.Column(db.Boolean, default=False)@@ -94,6 +97,7 @@ class WordPressSite(db.Model):foreign_keys=[production_site_id])snapshots = db.relationship('DatabaseSnapshot', backref='site', lazy='dynamic', cascade='all, delete-orphan')+ vulnerabilities = db.relationship('WordPressVulnerability', backref='site', lazy='dynamic', cascade='all, delete-orphan')sync_jobs_as_source = db.relationship('SyncJob',foreign_keys='SyncJob.source_site_id',@@ -145,6 +149,7 @@ class WordPressSite(db.Model):'disk_usage_bytes': self.disk_usage_bytes,'disk_usage_human': DatabaseSnapshot._format_size(self.disk_usage_bytes) if self.disk_usage_bytes else None,'disk_usage_updated_at': self.disk_usage_updated_at.isoformat() if self.disk_usage_updated_at else None,+ 'last_vuln_scan_at': self.last_vuln_scan_at.isoformat() if self.last_vuln_scan_at else None,'auto_sync_schedule': self.auto_sync_schedule,'auto_sync_enabled': self.auto_sync_enabled,'created_at': self.created_at.isoformat() if self.created_at else None,@@ -299,3 +304,48 @@ class SyncJob(db.Model):def __repr__(self):return f'<SyncJob {self.id} {self.source_site_id}->{self.target_site_id}>'+++class WordPressVulnerability(db.Model):+ """A known vulnerability found in a WordPress site's plugin, theme, or core."""++ __tablename__ = 'wordpress_vulnerabilities'++ id = db.Column(db.Integer, primary_key=True)+ site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False, index=True)++ # What is affected+ source = db.Column(db.String(20), nullable=False) # 'core' | 'plugin' | 'theme'+ slug = db.Column(db.String(200)) # directory slug ('' for core)+ name = db.Column(db.String(255)) # display name+ installed_version = db.Column(db.String(50))++ # The advisory+ advisory_id = db.Column(db.String(100)) # CVE id / WPVulnerability uuid+ title = db.Column(db.Text)+ severity = db.Column(db.String(20), default='unknown') # critical|high|medium|low|unknown+ cvss_score = db.Column(db.String(10))+ fixed_in = db.Column(db.String(50)) # version the fix landed in (None if unfixed)+ reference_url = db.Column(db.String(500))++ detected_at = db.Column(db.DateTime, default=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'site_id': self.site_id,+ 'source': self.source,+ 'slug': self.slug,+ 'name': self.name,+ 'installed_version': self.installed_version,+ 'advisory_id': self.advisory_id,+ 'title': self.title,+ 'severity': self.severity,+ 'cvss_score': self.cvss_score,+ 'fixed_in': self.fixed_in,+ 'reference_url': self.reference_url,+ 'detected_at': self.detected_at.isoformat() if self.detected_at else None,+ }++ def __repr__(self):+ return f'<WordPressVulnerability {self.id} {self.source}:{self.slug} {self.severity}>'diff --git a/backend/app/services/wp_vulnerability_service.py b/backend/app/services/wp_vulnerability_service.pynew file mode 100644index 00000000..5f03339c--- /dev/null+++ b/backend/app/services/wp_vulnerability_service.py@@ -0,0 +1,318 @@+"""Per-site WordPress vulnerability scanning (#28).++Cross-references a site's installed plugin/theme/core slug+version against the+keyless community WPVulnerability API (https://www.wpvulnerability.net) and+persists findings as WordPressVulnerability rows.++Docker-correct: installed versions are read via the Docker-aware WP-CLI bridge+(WordPressService.get_plugins/get_themes/get_wordpress_info). The scan runs in a+background thread (like the Lynis scan) so the single worker never blocks on the+WP-CLI + external-HTTP work; the UI polls get_results() for status.++Feed notes (see WPVulnerability docs):+- endpoints: /plugin/<slug>/ , /theme/<slug>/ , /core/<version>/ (trailing slash).+- 404 is NOT used for "no known vulns": a clean slug returns HTTP 200 with+ error=0 and data.vulnerability null/empty. Never treat HTTP 200 as vulnerable.+- plugin/theme vulns carry an `operator` version-bounds object; core vulns do not+ (querying by exact version means every returned core vuln applies).+- numeric-ish fields come back as strings; prefer cvss3.severity (full words).+"""++import logging+import threading+import time+from datetime import datetime+from urllib.parse import quote++import requests++logger = logging.getLogger(__name__)++API_BASE = 'https://www.wpvulnerability.net'+USER_AGENT = 'ServerKit-VulnScan/1.0 (+https://serverkit.ai)'+HTTP_TIMEOUT = 8+CACHE_TTL = 3600 # 1h, matching the feed's CDN cache+++class WpVulnerabilityService:+ # Feed cache: {(kind, key): (fetched_at_epoch, data_dict|None)}+ _feed_cache = {}+ _cache_lock = threading.Lock()++ # Per-site scan state: {site_id: {'status': 'running'|'completed'|'error', 'error': str|None}}+ _scans = {}+ _scan_lock = threading.Lock()++ _SEV_ORDER = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3, 'unknown': 4}++ # ---------- public API ----------++ @classmethod+ def get_results(cls, site):+ """Return persisted findings + live scan status for a site."""+ from app.models import WordPressVulnerability+ rows = WordPressVulnerability.query.filter_by(site_id=site.id).all()+ findings = [r.to_dict() for r in rows]+ findings.sort(key=lambda f: cls._SEV_ORDER.get(f.get('severity'), 9))+ summary = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'unknown': 0, 'total': len(findings)}+ for f in findings:+ sev = f.get('severity') if f.get('severity') in summary else 'unknown'+ summary[sev] += 1+ with cls._scan_lock:+ state = dict(cls._scans.get(site.id, {}))+ return {+ 'success': True,+ 'vulnerabilities': findings,+ 'scanned_at': site.last_vuln_scan_at.isoformat() if site.last_vuln_scan_at else None,+ 'scan_status': state.get('status', 'idle'),+ 'scan_error': state.get('error'),+ 'summary': summary,+ }++ @classmethod+ def start_scan(cls, site):+ """Kick off a background scan for the site; returns immediately."""+ from flask import current_app+ with cls._scan_lock:+ if cls._scans.get(site.id, {}).get('status') == 'running':+ return {'success': True, 'status': 'running', 'message': 'A scan is already running.'}+ cls._scans[site.id] = {'status': 'running', 'error': None}+ app = current_app._get_current_object()+ threading.Thread(+ target=cls._run_scan, args=(app, site.id), daemon=True, name=f'wp-vuln-{site.id}'+ ).start()+ return {'success': True, 'status': 'running'}++ # ---------- scan worker ----------++ @classmethod+ def _run_scan(cls, app, site_id):+ with app.app_context():+ from app import db+ from app.models import WordPressSite, WordPressVulnerability+ try:+ site = WordPressSite.query.get(site_id)+ if not site or not site.application:+ raise RuntimeError('Site not found')+ findings = cls._scan_site(site.application.root_path)+ if findings is None:+ raise RuntimeError('Could not read WordPress (is the site running?)')+ # Replace the site's findings with the fresh set.+ WordPressVulnerability.query.filter_by(site_id=site_id).delete(synchronize_session=False)+ for f in findings:+ db.session.add(WordPressVulnerability(site_id=site_id, **f))+ site.last_vuln_scan_at = datetime.utcnow()+ db.session.commit()+ with cls._scan_lock:+ cls._scans[site_id] = {'status': 'completed', 'error': None}+ except Exception as e:+ logger.error(f'Vulnerability scan failed for site {site_id}: {e}')+ try:+ db.session.rollback()+ except Exception:+ pass+ with cls._scan_lock:+ cls._scans[site_id] = {'status': 'error', 'error': str(e)}++ @classmethod+ def _scan_site(cls, path):+ """Return a list of finding-dicts, or None if the install can't be read at+ all (container down / not WordPress).++ Reads core/plugins/themes via the Docker-aware WP-CLI bridge directly —+ NOT get_wordpress_info, whose host-filesystem wp-config.php check fails for+ volume-backed Docker sites (the primary managed model). Core is optional;+ we only bail when WP-CLI answers nothing at all."""+ from app.services.wordpress_service import WordPressService+ core_res = WordPressService.wp_cli(path, ['core', 'version'])+ core_version = (core_res.get('output') or '').strip() if core_res.get('success') else None+ plugins = WordPressService.get_plugins(path) or []+ themes = WordPressService.get_themes(path) or []+ if not core_version and not plugins and not themes:+ return None+ findings = []+ if core_version:+ findings += cls._check_core(core_version)+ for p in plugins:+ slug, version = p.get('name'), p.get('version')+ if slug and version:+ findings += cls._check_component('plugin', slug, version)+ for t in themes:+ slug, version = t.get('name'), t.get('version')+ if slug and version:+ findings += cls._check_component('theme', slug, version)+ return findings++ # ---------- feed lookups ----------++ @classmethod+ def _fetch(cls, kind, key):+ """GET the feed for a plugin/theme slug or core version (cached).+ Returns the parsed 'data' dict, or None on miss/error/no-data."""+ ck = (kind, key)+ now = time.time()+ with cls._cache_lock:+ cached = cls._feed_cache.get(ck)+ if cached and (now - cached[0]) < CACHE_TTL:+ return cached[1]+ data = None+ try:+ resp = requests.get(+ f'{API_BASE}/{kind}/{quote(str(key), safe="")}/',+ headers={'User-Agent': USER_AGENT, 'Accept': 'application/json'},+ timeout=HTTP_TIMEOUT,+ )+ if resp.status_code == 200:+ body = resp.json()+ if isinstance(body, dict) and body.get('error') in (0, '0'):+ data = body.get('data') or None+ except Exception as e:+ logger.debug(f'Vuln feed fetch failed ({kind}/{key}): {e}')+ data = None+ with cls._cache_lock:+ cls._feed_cache[ck] = (now, data)+ return data++ @classmethod+ def _check_core(cls, version):+ data = cls._fetch('core', version)+ return [cls._finding('core', '', 'WordPress core', version, v, fixed_in=None)+ for v in ((data or {}).get('vulnerability') or [])]++ @classmethod+ def _check_component(cls, source, slug, version):+ data = cls._fetch(source, slug)+ if not data:+ return []+ name = data.get('name') or slug+ out = []+ for v in (data.get('vulnerability') or []):+ op = v.get('operator') or {}+ if cls._version_in_range(version, op):+ out.append(cls._finding(source, slug, name, version, v, fixed_in=cls._fixed_in(op)))+ return out++ # ---------- finding builder ----------++ # CVSS v2 short severity codes -> our scale.+ _CVSS_SHORT = {'c': 'critical', 'h': 'high', 'm': 'medium', 'l': 'low'}++ @classmethod+ def _severity_from_impact(cls, impact):+ """Best-effort (severity, score). Prefer cvss3.severity (full words), fall+ back to cvss.severity (short codes) or a numeric score, else 'unknown'.+ Guards against impact being null or a list (the feed is heterogeneous)."""+ if not isinstance(impact, dict):+ return 'unknown', None+ cvss3 = impact.get('cvss3') or {}+ sev = cvss3.get('severity')+ if sev in cls._SEV_ORDER:+ return sev, cvss3.get('score')+ cvss = impact.get('cvss') or {}+ mapped = cls._CVSS_SHORT.get(str(cvss.get('severity') or '').lower())+ if mapped in cls._SEV_ORDER:+ return mapped, cvss.get('score') or cvss3.get('score')+ score = cvss3.get('score') or cvss.get('score')+ try:+ s = float(score)+ if s >= 9.0:+ return 'critical', score+ if s >= 7.0:+ return 'high', score+ if s >= 4.0:+ return 'medium', score+ if s > 0:+ return 'low', score+ except (TypeError, ValueError):+ pass+ return 'unknown', score++ @classmethod+ def _finding(cls, source, slug, name, version, vuln, fixed_in):+ severity, score = cls._severity_from_impact(vuln.get('impact'))++ # Prefer a real CVE id + its reference; else fall back to the feed uuid.+ advisory_id = vuln.get('uuid')+ ref_url = None+ for src in (vuln.get('source') or []):+ sid = src.get('id') or ''+ if isinstance(sid, str) and sid.upper().startswith('CVE-'):+ advisory_id = sid+ ref_url = src.get('link') or ref_url+ break+ ref_url = ref_url or src.get('link')++ # Only keep http(s) references — the feed is third-party and the URL is+ # rendered as an href, so block javascript:/data: schemes.+ if ref_url and not str(ref_url).lower().startswith(('http://', 'https://')):+ ref_url = None++ return {+ 'source': source,+ 'slug': slug,+ 'name': (name or slug or '')[:255],+ 'installed_version': str(version)[:50],+ 'advisory_id': str(advisory_id)[:100] if advisory_id else None,+ 'title': vuln.get('name'),+ 'severity': severity,+ 'cvss_score': str(score)[:10] if score not in (None, '') else None,+ 'fixed_in': str(fixed_in)[:50] if fixed_in else None,+ 'reference_url': str(ref_url)[:500] if ref_url else None,+ }++ @staticmethod+ def _fixed_in(op):+ # With max_operator 'lt' the fix landed exactly at max_version.+ if op.get('max_operator') == 'lt' and op.get('max_version'):+ return op.get('max_version')+ return None++ # ---------- version matching ----------++ @staticmethod+ def _vtuple(v):+ parts = []+ for chunk in str(v).split('.'):+ num = ''+ for ch in chunk:+ if ch.isdigit():+ num += ch+ else:+ break+ parts.append(int(num) if num else 0)+ return tuple(parts)++ @classmethod+ def _vcmp(cls, a, b):+ ta, tb = cls._vtuple(a), cls._vtuple(b)+ n = max(len(ta), len(tb))+ ta += (0,) * (n - len(ta))+ tb += (0,) * (n - len(tb))+ return (ta > tb) - (ta < tb)++ @classmethod+ def _version_in_range(cls, installed, op):+ """True if the installed version satisfies the operator bounds (vulnerable).+ A null bound is unbounded on that side; an empty operator is treated as+ not-determinable (skip) to avoid false positives across all versions."""+ if not op:+ return False+ minv, mino = op.get('min_version'), op.get('min_operator')+ maxv, maxo = op.get('max_version'), op.get('max_operator')+ if minv:+ if mino not in ('ge', 'gt'):+ return False # unrecognized bound — skip rather than over-flag+ c = cls._vcmp(installed, minv)+ if mino == 'ge' and c < 0:+ return False+ if mino == 'gt' and c <= 0:+ return False+ if maxv:+ if maxo not in ('lt', 'le'):+ return False+ c = cls._vcmp(installed, maxv)+ if maxo == 'lt' and c >= 0:+ return False+ if maxo == 'le' and c > 0:+ return False+ return Truediff --git a/backend/migrations/versions/011_wordpress_vulnerabilities.py b/backend/migrations/versions/011_wordpress_vulnerabilities.pynew file mode 100644index 00000000..dd3dfd01--- /dev/null+++ b/backend/migrations/versions/011_wordpress_vulnerabilities.py@@ -0,0 +1,67 @@+"""Per-site WordPress vulnerability findings (#28).++Adds:+- table wordpress_vulnerabilities (findings cross-referenced against the+ WPVulnerability feed, FK site_id -> wordpress_sites.id)+- wordpress_sites.last_vuln_scan_at (nullable DateTime) so a "scanned & clean"+ site is distinguishable from a never-scanned one.++Idempotent: MigrationService._fix_missing_columns runs db.create_all() (creating+the new table) and ALTER-adds the new column on boot before Alembic runs, so+guard on the live schema — exactly like 009/010.++Revision ID: 011_wordpress_vulnerabilities+Revises: 010_wordpress_status_monitoring+Create Date: 2026-06-01+"""+from alembic import op+import sqlalchemy as sa++revision = '011_wordpress_vulnerabilities'+down_revision = '010_wordpress_status_monitoring'+branch_labels = None+depends_on = None+++def _has_col(inspector, table, col):+ if table not in inspector.get_table_names():+ return False+ return col in {c['name'] for c in inspector.get_columns(table)}+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)++ if 'wordpress_vulnerabilities' not in inspector.get_table_names():+ op.create_table(+ 'wordpress_vulnerabilities',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False, index=True),+ sa.Column('source', sa.String(length=20), nullable=False),+ sa.Column('slug', sa.String(length=200)),+ sa.Column('name', sa.String(length=255)),+ sa.Column('installed_version', sa.String(length=50)),+ sa.Column('advisory_id', sa.String(length=100)),+ sa.Column('title', sa.Text()),+ sa.Column('severity', sa.String(length=20)),+ sa.Column('cvss_score', sa.String(length=10)),+ sa.Column('fixed_in', sa.String(length=50)),+ sa.Column('reference_url', sa.String(length=500)),+ sa.Column('detected_at', sa.DateTime()),+ )++ if 'wordpress_sites' in inspector.get_table_names() and \+ not _has_col(inspector, 'wordpress_sites', 'last_vuln_scan_at'):+ with op.batch_alter_table('wordpress_sites') as batch_op:+ batch_op.add_column(sa.Column('last_vuln_scan_at', sa.DateTime(), nullable=True))+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if _has_col(inspector, 'wordpress_sites', 'last_vuln_scan_at'):+ with op.batch_alter_table('wordpress_sites') as batch_op:+ batch_op.drop_column('last_vuln_scan_at')+ if 'wordpress_vulnerabilities' in inspector.get_table_names():+ op.drop_table('wordpress_vulnerabilities')diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex bdaafefc..f8e03544 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -256,11 +256,12 @@ The headline value of a managed platform, and the most net-new — but it leansHighest-effort, broadest surface — but by now the `WordPressSite` is a first-class object with health, SSL, backups, cache, and an API-key-reachable REST surface, so these bind cleanly. **Estimated cluster: 1–2 weeks, parallelizable.**-### #28 — Plugin/theme/core vulnerability scanning `[L]` ❌+### #28 — Plugin/theme/core vulnerability scanning `[L]` ❌ — ✅ Done (keyless WPVulnerability feed; per-site findings with severity)- **Today:** `get_plugins`/`get_themes` return slug + version; the VulnerabilityTab is OS-only (Lynis). No WP vuln feed.- **Do:** Cross-reference slug+version against a public WordPress vulnerability API (e.g. a WPScan/Patchstack-style feed), persist findings per `WordPressSite`, surface in the VulnerabilityTab.- **Reuse:** `get_plugins`/`get_themes`, the existing vuln UI shell.- **Done when:** Vulnerable plugins/themes are flagged per site with severity.+- **Landed:** New `WpVulnerabilityService` reads installed plugin/theme/core slug+version via the **Docker-aware WP-CLI** bridge (`wp core version` + `get_plugins`/`get_themes` directly — *not* the host-filesystem-gated `get_wordpress_info`, which fails for volume-backed sites) and cross-references the **keyless community WPVulnerability API** (`https://www.wpvulnerability.net/{plugin,theme,core}/…`, no signup, 1h in-memory cache, descriptive UA, 8s timeout). It matches the installed version against each advisory's `operator` bounds (plugins/themes; core advisories all apply since the feed is version-scoped), extracts CVE id / severity (`cvss3` → `cvss` short-code → score fallback) / fixed-in / reference, and persists results as a new **`WordPressVulnerability`** child model (FK → `wordpress_sites.id`) + a `last_vuln_scan_at` column (Alembic **011**, idempotent). The scan runs in a **background thread** (Lynis-style, so the single worker never blocks on the WP-CLI + external HTTP), and a new **Vulnerabilities tab** on the site detail polls for status and renders findings with severity badges, CVE links, installed/fixed versions, and a summary. On-demand only (no scheduled external calls). Security hardening (3-lens review): `reference_url` is restricted to http(s) (blocks `javascript:` hrefs), the feed slug is percent-encoded, and an unrecognized version operator skips rather than over-flags. *(Deferred follow-ups: a scheduled periodic re-scan, and an optional "bring-your-own WPScan API key" for manually-verified data.)* Verified: backend `py_compile`, frontend lint-clean + production build, 3-lens adversarial review (major fixed: the Docker volume-backed core-read gating). Not runtime-exercised on a real host.### #29 — Safe update manager `[L]` 🟡- **Today:** Update primitives exist (#7); no history, scheduling, exclusions, staging-first, and pre-update backup is DB-only/core-only.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex d9bbf0c1..9a215a0b 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -18,6 +18,7 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { Textarea } from '@/components/ui/textarea';+import { Badge } from '@/components/ui/badge';// Detail Page Skeleton for initial loadingconst DetailPageSkeleton = () => (@@ -72,7 +73,7 @@ const DetailPageSkeleton = () => (</div>);-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics'];+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities'];const WordPressDetail = () => {const { id } = useParams();@@ -355,6 +356,12 @@ const WordPressDetail = () => {><BarChart3 size={14} /> Analytics</div>+ <div+ className={`app-detail-tab ${activeTab === 'vulnerabilities' ? 'active' : ''}`}+ onClick={() => setActiveTab('vulnerabilities')}+ >+ <ShieldCheck size={14} /> Vulnerabilities+ </div></div>{/* Clone Site Modal */}@@ -400,6 +407,7 @@ const WordPressDetail = () => {{activeTab === 'backups' && <BackupsTab siteId={site.id} />}{activeTab === 'uptime' && <UptimeTab siteId={site.id} />}{activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}+ {activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}</ErrorBoundary></div></div>@@ -632,6 +640,116 @@ const UptimeTab = ({ siteId }) => {);};+// Vulnerabilities Tab — cross-references plugin/theme/core versions against the+// keyless WPVulnerability community feed (#28). On-demand background scan + poll.+const VulnerabilitiesTab = ({ siteId }) => {+ const toast = useToast();+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);+ const [scanning, setScanning] = useState(false);++ const load = React.useCallback(async () => {+ try {+ const res = await wordpressApi.getVulnerabilities(siteId);+ setData(res);+ } catch (err) {+ toast.error(err.message || 'Failed to load vulnerabilities');+ } finally {+ setLoading(false);+ }+ }, [siteId, toast]);++ useEffect(() => { load(); }, [load]);+ useEffect(() => {+ if (data?.scan_status !== 'running') return undefined;+ const t = setTimeout(() => { load(); }, 2500);+ return () => clearTimeout(t);+ }, [data, load]);++ async function handleScan() {+ setScanning(true);+ try {+ await wordpressApi.scanVulnerabilities(siteId);+ toast.info('Vulnerability scan started…');+ await load();+ } catch (err) {+ toast.error(err.message || 'Failed to start scan');+ } finally {+ setScanning(false);+ }+ }++ if (loading) return <div className="tab-loading"><p className="hint">Loading vulnerabilities...</p></div>;++ const running = data?.scan_status === 'running';+ const summary = data?.summary || {};+ const vulns = data?.vulnerabilities || [];+ const sevVariant = (s) => ({ critical: 'destructive', high: 'destructive', medium: 'warning', low: 'info' }[s] || 'secondary');++ return (+ <div className="app-overview-grid">+ <div className="app-overview-left">+ <div className="app-panel">+ <div className="app-panel-header">Vulnerability scan</div>+ <div className="app-panel-body">+ <div className="app-detail-actions">+ <Button size="sm" onClick={handleScan} disabled={scanning || running}>+ {running ? 'Scanning…' : 'Run scan'}+ </Button>+ </div>+ <div className="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">Last scan</span><span className="app-info-value">{data?.scanned_at ? new Date(data.scanned_at).toLocaleString() : 'Never'}</span></div>+ <div className="app-info-item"><span className="app-info-label">Findings</span><span className="app-info-value">{summary.total ?? 0}</span></div>+ </div>+ {summary.total > 0 && (+ <div className="app-detail-actions">+ {summary.critical > 0 && <Badge variant="destructive">{summary.critical} critical</Badge>}+ {summary.high > 0 && <Badge variant="destructive">{summary.high} high</Badge>}+ {summary.medium > 0 && <Badge variant="warning">{summary.medium} medium</Badge>}+ {summary.low > 0 && <Badge variant="info">{summary.low} low</Badge>}+ {summary.unknown > 0 && <Badge variant="secondary">{summary.unknown} unrated</Badge>}+ </div>+ )}+ {data?.scan_error && <p className="hint">Last scan error: {data.scan_error}</p>}+ <p className="hint">Cross-references installed plugin, theme, and core versions against the WPVulnerability community database. Re-run after updating.</p>+ </div>+ </div>++ {vulns.length === 0 ? (+ <div className="app-panel">+ <div className="app-panel-body">+ <p className="hint">{data?.scanned_at ? 'No known vulnerabilities found.' : 'No scan has run yet — click Run scan to check this site.'}</p>+ </div>+ </div>+ ) : (+ <div className="app-panel">+ <div className="app-panel-header">Findings</div>+ <div className="app-panel-body">+ {vulns.map(v => (+ <div className="form-group" key={v.id}>+ <div>+ <Badge variant={sevVariant(v.severity)}>{v.severity}</Badge>{' '}+ <strong>{v.name}</strong>+ </div>+ {v.title && <span className="form-hint">{v.title}</span>}+ <span className="form-hint">+ {v.source}{v.slug ? ` · ${v.slug}` : ''} · installed {v.installed_version}+ {v.fixed_in ? ` · fixed in ${v.fixed_in}` : ' · no fix yet'}+ {v.advisory_id ? ` · ${v.advisory_id}` : ''}+ </span>+ {v.reference_url && (+ <a href={v.reference_url} target="_blank" rel="noopener noreferrer" className="form-hint">View advisory ↗</a>+ )}+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>+ );+};+// Analytics Tab — per-site traffic + error analytics (#25), parsed on-demand from// the apache container access log. PHP fatals, response time, and cache hit ratio// are not in the default access log (deferred to #30 / #22-#23).diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 771d23e4..976357ec 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -185,6 +185,10 @@ const wordpressApi = {// Traffic + error analytics (#25) — parsed on-demand from the apache access log.getSiteAnalytics: (siteId, hours = 24) => api.request(`${BASE_PATH}/${siteId}/analytics?hours=${hours}`),+ // Vulnerability scanning (#28) — plugin/theme/core vs the WPVulnerability feed.+ getVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities`),+ scanVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities/scan`, { method: 'POST' }),+// Mint a one-time passwordless wp-admin login URL for the current operator.autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {method: 'POST'