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(analytics): WordPress + nginx tracker wiring (Phase 5)
Juan Denisd6e8c737dc46
diff --git a/backend/tests/test_analytics_extension.py b/backend/tests/test_analytics_extension.pyindex 8725a18b..1c95e62c 100644--- a/backend/tests/test_analytics_extension.py+++ b/backend/tests/test_analytics_extension.py@@ -31,8 +31,8 @@ def _load_ext():f'builtin extension backend not importable from {EXT_DIR}')mods = {}for name in ('config', 'models', 'ingest_service', 'rollup_service',- 'report_service', 'site_service', 'lifecycle', 'jobs',- 'analytics'):+ 'report_service', 'site_service', 'wp_integration',+ 'nginx_integration', 'lifecycle', 'jobs', 'analytics'):mods[name] = importlib.import_module(f'app.plugins.{SLUG}.{name}')return mods@@ -44,6 +44,8 @@ ingest_mod = _M['ingest_service']rollup_mod = _M['rollup_service']report_mod = _M['report_service']site_mod = _M['site_service']+wp_mod = _M['wp_integration']+nginx_mod = _M['nginx_integration']lifecycle_mod = _M['lifecycle']jobs_mod = _M['jobs']bp_mod = _M['analytics']@@ -737,3 +739,189 @@ def test_snippet_missing_site_404(app, analytics_client):viewer = _auth(_mk_viewer())r = analytics_client.get('/api/v1/analytics/sites/9999/snippet', headers=viewer)assert r.status_code == 404+++# --------------------------------------------------------------------------- #+# Phase 5: WordPress mu-plugin injection+# --------------------------------------------------------------------------- #+def test_mu_plugin_php_content():+ php = wp_mod.build_mu_plugin_php('KEY123', 'https://panel.test/api/v1/analytics/tracker.js')+ assert php.startswith('<?php')+ assert "add_action('wp_head'" in php+ assert 'KEY123' in php and 'https://panel.test/api/v1/analytics/tracker.js' in php+ assert 'esc_url' in php and 'esc_attr' in php+++def test_wp_inject_writes_and_is_idempotent(app, tmp_path, monkeypatch):+ from types import SimpleNamespace+ site = _mk_site(app_id=42)+ target = SimpleNamespace(container='wp1', is_docker=False, root=str(tmp_path))+ monkeypatch.setattr(wp_mod, '_resolve_target', lambda s: target)++ res = wp_mod.inject(site, 'https://panel.test/api/v1/analytics/tracker.js')+ assert res.get('success')+ mu = tmp_path / 'wp-content' / 'mu-plugins' / 'serverkit-analytics.php'+ assert mu.exists()+ body = mu.read_text(encoding='utf-8')+ assert site.site_key in body+ assert site.get_settings().get('wp_injected') is True++ # Re-run overwrites, stays single file, flag persists.+ wp_mod.inject(site, 'https://panel.test/api/v1/analytics/tracker.js')+ assert mu.exists()+ assert site.get_settings().get('wp_injected') is True+++def test_wp_inject_docker_uses_exec(app, monkeypatch):+ from types import SimpleNamespace+ calls = []+ site = _mk_site(app_id=7)+ target = SimpleNamespace(container='wpc', is_docker=True, root=None)+ monkeypatch.setattr(wp_mod, '_resolve_target', lambda s: target)+ monkeypatch.setattr(wp_mod, '_docker_exec',+ lambda c, argv, input_text=None: calls.append((c, argv, input_text)) or {'success': True})+ res = wp_mod.inject(site, 'https://p.test/api/v1/analytics/tracker.js')+ assert res.get('success')+ # mkdir then tee-with-content+ assert any(a[1][0] == 'tee' and a[2] and site.site_key in a[2] for a in calls)+++def test_wp_remove_deletes_and_clears_flag(app, tmp_path, monkeypatch):+ from types import SimpleNamespace+ site = _mk_site(app_id=42)+ target = SimpleNamespace(container='wp1', is_docker=False, root=str(tmp_path))+ monkeypatch.setattr(wp_mod, '_resolve_target', lambda s: target)+ wp_mod.inject(site, 'https://p.test/api/v1/analytics/tracker.js')+ mu = tmp_path / 'wp-content' / 'mu-plugins' / 'serverkit-analytics.php'+ assert mu.exists()+ wp_mod.remove(site)+ assert not mu.exists()+ assert site.get_settings().get('wp_injected') is False+++def test_wp_inject_no_linked_site(app):+ site = _mk_site() # app_id None+ res = wp_mod.inject(site, 'https://p.test/x')+ assert res.get('success') is False+++def test_wp_remove_all_injections(app, tmp_path, monkeypatch):+ from types import SimpleNamespace+ site = _mk_site(app_id=1)+ target = SimpleNamespace(container='wp1', is_docker=False, root=str(tmp_path))+ monkeypatch.setattr(wp_mod, '_resolve_target', lambda s: target)+ wp_mod.inject(site, 'https://p.test/api/v1/analytics/tracker.js')+ n = wp_mod.remove_all_injections()+ assert n == 1+ assert site.get_settings().get('wp_injected') is False+++def test_wordpress_available_reflects_installed(app):+ from app import db+ from app.models.plugin import InstalledPlugin+ # Control the state: remove any seeded flagship row first.+ InstalledPlugin.query.filter_by(slug='serverkit-wordpress').delete()+ db.session.commit()+ assert wp_mod.wordpress_available() is False+ db.session.add(InstalledPlugin(name='serverkit-wordpress', display_name='WP',+ slug='serverkit-wordpress', version='1.0.0',+ status=InstalledPlugin.STATUS_ACTIVE))+ db.session.commit()+ assert wp_mod.wordpress_available() is True+++# --------------------------------------------------------------------------- #+# Phase 5: nginx sub_filter injection+# --------------------------------------------------------------------------- #+_VHOST = (+ 'server {\n'+ ' listen 80;\n'+ ' server_name app.test;\n'+ ' location / {\n'+ ' proxy_pass http://127.0.0.1:8001;\n'+ ' }\n'+ '}\n'+)+++def _patch_nginx(monkeypatch, path, test_ok=True):+ monkeypatch.setattr(nginx_mod, '_vhost_path', lambda v: str(path))+ monkeypatch.setattr(nginx_mod, '_nginx_test', lambda: {'success': test_ok,+ 'message': 'ok' if test_ok else 'bad'})+ monkeypatch.setattr(nginx_mod, '_nginx_reload', lambda: {'success': True})+++def test_nginx_block_build_and_strip():+ block = nginx_mod.build_sub_filter_block('https://p/t.js', 'KEY')+ assert 'sub_filter' in block and 'KEY' in block+ content = 'server {\n}\n'+ injected = nginx_mod._insert_block(content, block)+ assert 'BEGIN serverkit-analytics' in injected+ stripped = nginx_mod._strip_block(injected)+ assert 'serverkit-analytics' not in stripped+ assert stripped == content # perfectly reversible+++def test_nginx_inject_and_idempotent(app, tmp_path, monkeypatch):+ vpath = tmp_path / 'app.test'+ vpath.write_text(_VHOST, encoding='utf-8')+ site = _mk_site()+ site.update_settings(nginx_vhost='app.test')+ from app import db+ db.session.commit()+ _patch_nginx(monkeypatch, vpath)++ res = nginx_mod.inject(site, 'https://p/t.js')+ assert res.get('success')+ body = vpath.read_text(encoding='utf-8')+ assert body.count('BEGIN serverkit-analytics') == 1+ assert site.get_settings().get('nginx_injected') is True++ nginx_mod.inject(site, 'https://p/t.js') # re-inject+ assert vpath.read_text(encoding='utf-8').count('BEGIN serverkit-analytics') == 1+++def test_nginx_inject_reverts_on_invalid_config(app, tmp_path, monkeypatch):+ vpath = tmp_path / 'app.test'+ vpath.write_text(_VHOST, encoding='utf-8')+ site = _mk_site()+ site.update_settings(nginx_vhost='app.test')+ from app import db+ db.session.commit()+ _patch_nginx(monkeypatch, vpath, test_ok=False)++ res = nginx_mod.inject(site, 'https://p/t.js')+ assert res.get('success') is False+ # File must be reverted to the original — never leave nginx broken.+ assert vpath.read_text(encoding='utf-8') == _VHOST+ assert site.get_settings().get('nginx_injected') is not True+++def test_nginx_remove(app, tmp_path, monkeypatch):+ vpath = tmp_path / 'app.test'+ vpath.write_text(_VHOST, encoding='utf-8')+ site = _mk_site()+ site.update_settings(nginx_vhost='app.test')+ from app import db+ db.session.commit()+ _patch_nginx(monkeypatch, vpath)+ nginx_mod.inject(site, 'https://p/t.js')+ nginx_mod.remove(site)+ assert 'serverkit-analytics' not in vpath.read_text(encoding='utf-8')+ assert site.get_settings().get('nginx_injected') is False+++def test_inject_endpoints_admin_gated(app, analytics_client, monkeypatch):+ from types import SimpleNamespace+ site = _mk_site(app_id=5)+ monkeypatch.setattr(wp_mod, '_resolve_target',+ lambda s: SimpleNamespace(container='c', is_docker=True, root=None))+ monkeypatch.setattr(wp_mod, '_docker_exec',+ lambda c, argv, input_text=None: {'success': True})+ viewer = _auth(_mk_viewer())+ admin = _auth(_mk_admin())+ assert analytics_client.post(f'/api/v1/analytics/sites/{site.id}/inject/wordpress',+ headers=viewer).status_code == 403+ r = analytics_client.post(f'/api/v1/analytics/sites/{site.id}/inject/wordpress',+ headers=admin)+ assert r.status_code == 200 and r.get_json().get('success')diff --git a/builtin-extensions/serverkit-analytics/backend/analytics.py b/builtin-extensions/serverkit-analytics/backend/analytics.pyindex 4a506351..54629940 100644--- a/builtin-extensions/serverkit-analytics/backend/analytics.py+++ b/builtin-extensions/serverkit-analytics/backend/analytics.py@@ -26,7 +26,10 @@ from flask import Blueprint, current_app, jsonify, requestfrom app.middleware.rbac import admin_required, viewer_requiredfrom app.utils.client_ip import get_client_ip-from . import ingest_service, report_service, rollup_service, site_service+from . import (+ ingest_service, nginx_integration, report_service, rollup_service,+ site_service, wp_integration,+)from .config import cfg_boolfrom .ingest_service import MAX_BODY_BYTES, referrer_hostfrom .models import AnalyticsSite@@ -357,3 +360,51 @@ def site_realtime(site_id):def trigger_rollup():"""Run the rollup on demand (ops/testing convenience)."""return jsonify(rollup_service.run_rollup()), 200+++# --------------------------------------------------------------------------- #+# tracker injection into managed sites (JWT: admin)+# --------------------------------------------------------------------------- #+def _tracker_url():+ return f'{_panel_base_url()}/api/v1/analytics/tracker.js'+++@analytics_bp.route('/sites/<int:site_id>/inject/wordpress', methods=['POST'])+@admin_required+def inject_wordpress(site_id):+ site, err = _site_or_404(site_id)+ if err:+ return err+ result = wp_integration.inject(site, _tracker_url())+ code = 200 if result.get('success') else 400+ return jsonify(result), code+++@analytics_bp.route('/sites/<int:site_id>/inject/wordpress', methods=['DELETE'])+@admin_required+def remove_wordpress(site_id):+ site, err = _site_or_404(site_id)+ if err:+ return err+ return jsonify(wp_integration.remove(site)), 200+++@analytics_bp.route('/sites/<int:site_id>/inject/nginx', methods=['POST'])+@admin_required+def inject_nginx(site_id):+ site, err = _site_or_404(site_id)+ if err:+ return err+ vhost = (request.get_json(silent=True) or {}).get('vhost')+ result = nginx_integration.inject(site, _tracker_url(), vhost=vhost)+ code = 200 if result.get('success') else 400+ return jsonify(result), code+++@analytics_bp.route('/sites/<int:site_id>/inject/nginx', methods=['DELETE'])+@admin_required+def remove_nginx(site_id):+ site, err = _site_or_404(site_id)+ if err:+ return err+ return jsonify(nginx_integration.remove(site)), 200diff --git a/builtin-extensions/serverkit-analytics/backend/nginx_integration.py b/builtin-extensions/serverkit-analytics/backend/nginx_integration.pynew file mode 100644index 00000000..e3ccfed3--- /dev/null+++ b/builtin-extensions/serverkit-analytics/backend/nginx_integration.py@@ -0,0 +1,207 @@+"""nginx tracker injection for serverkit-analytics.++For any managed, nginx-proxied app, ServerKit already owns the vhost. This+module injects an nginx ``sub_filter`` that rewrites ``</body>`` to include the+tracker snippet, so HTML responses carry the tracker with no app-side change.+Default OFF; opt-in per app.++Safety (blast-radius guardrails, same spirit as plan 46):+* Idempotent, reversible marker block (``# BEGIN/END serverkit-analytics``).+* Validate with ``nginx -t`` BEFORE reloading, and REVERT the file if the test+ fails, so a bad edit can never take nginx down.+* Reload (never restart) via the core ``NginxService`` seam.++Linux-only at runtime; the file/validate/reload seams are mockable for tests.+"""+import logging+import os++logger = logging.getLogger(__name__)++SLUG = 'serverkit-analytics'+BEGIN = ' # BEGIN serverkit-analytics'+END = ' # END serverkit-analytics'+++def build_sub_filter_block(tracker_url, site_key):+ """The marked nginx sub_filter block (indented for a server context)."""+ src = str(tracker_url).replace("'", '').replace('"', '')+ key = str(site_key).replace("'", '').replace('"', '')+ snippet = (f'<script defer src="{src}" data-site-key="{key}"></script>')+ return (+ f'{BEGIN}\n'+ ' # Ask upstreams for an uncompressed body so sub_filter can rewrite it\n'+ ' # (best-effort at server scope; a location proxy_set_header block\n'+ ' # would override this — regenerate the vhost if so).\n'+ ' proxy_set_header Accept-Encoding "";\n'+ ' sub_filter_once on;\n'+ ' sub_filter_types text/html;\n'+ f" sub_filter '</body>' '{snippet}</body>';\n"+ f'{END}\n'+ )+++# --------------------------------------------------------------------------- #+# mockable seams+# --------------------------------------------------------------------------- #+def _vhost_path(vhost):+ from app.services.nginx_service import NginxService+ return os.path.join(NginxService.SITES_AVAILABLE, vhost)+++def _read_vhost(path):+ with open(path, encoding='utf-8') as f:+ return f.read()+++def _write_vhost(path, content):+ with open(path, 'w', encoding='utf-8') as f:+ f.write(content)+++def _nginx_reload():+ """Validate + reload nginx. NginxService.reload() runs nginx -t first."""+ try:+ from app.services.nginx_service import NginxService+ return NginxService.reload()+ except Exception as e: # noqa: BLE001+ return {'success': False, 'error': str(e)}+++def _nginx_test():+ try:+ from app.services.nginx_service import NginxService+ return NginxService.test_config()+ except Exception as e: # noqa: BLE001+ return {'success': False, 'error': str(e)}+++# --------------------------------------------------------------------------- #+# block insert / strip+# --------------------------------------------------------------------------- #+def _strip_block(content):+ """Remove an existing marker block (if present). Returns new content."""+ start = content.find(BEGIN)+ if start == -1:+ return content+ end = content.find(END, start)+ if end == -1:+ return content+ end += len(END)+ # Swallow a trailing newline left by the block.+ if end < len(content) and content[end] == '\n':+ end += 1+ return content[:start] + content[end:]+++def _insert_block(content, block):+ """Insert the block just after the first ``server {`` (replacing any+ existing block first, so re-injection is idempotent)."""+ content = _strip_block(content)+ marker = content.find('server {')+ if marker == -1:+ return None+ brace = content.find('\n', marker)+ if brace == -1:+ return None+ at = brace + 1+ return content[:at] + block + content[at:]+++def _vhost_for(site, vhost=None):+ """Resolve the vhost filename for a site (explicit, saved, or app name)."""+ if vhost:+ return vhost+ saved = site.get_settings().get('nginx_vhost')+ if saved:+ return saved+ if site.app_id:+ try:+ from app.models import Application+ app = Application.query.get(site.app_id)+ if app:+ return app.name+ except Exception: # noqa: BLE001+ return None+ return None+++def inject(site, tracker_url, vhost=None):+ """Insert the sub_filter block into the app's vhost, validate, reload."""+ name = _vhost_for(site, vhost)+ if not name:+ return {'success': False, 'error': 'No nginx vhost resolved for site'}+ path = _vhost_path(name)+ try:+ original = _read_vhost(path)+ except OSError as e:+ return {'success': False, 'error': f'vhost not readable: {e}'}++ block = build_sub_filter_block(tracker_url, site.site_key)+ updated = _insert_block(original, block)+ if updated is None:+ return {'success': False, 'error': 'no server block found in vhost'}++ _write_vhost(path, updated)+ test = _nginx_test()+ if not test.get('success'):+ _write_vhost(path, original) # revert — never leave nginx broken+ return {'success': False, 'error': f"nginx config invalid, reverted: "+ f"{test.get('message') or test.get('error')}"}+ reload_res = _nginx_reload()+ if reload_res.get('success'):+ _mark(site, True, name)+ return reload_res+++def remove(site, vhost=None):+ """Strip the sub_filter block from the app's vhost, validate, reload."""+ name = _vhost_for(site, vhost)+ if not name:+ _mark(site, False, None)+ return {'success': True, 'note': 'no vhost to clean'}+ path = _vhost_path(name)+ try:+ original = _read_vhost(path)+ except OSError:+ _mark(site, False, None)+ return {'success': True, 'note': 'vhost already gone'}+ stripped = _strip_block(original)+ if stripped != original:+ _write_vhost(path, stripped)+ test = _nginx_test()+ if not test.get('success'):+ _write_vhost(path, original)+ return {'success': False, 'error': 'nginx invalid after strip, reverted'}+ _nginx_reload()+ _mark(site, False, None)+ return {'success': True}+++def _mark(site, injected, vhost):+ try:+ from app import db+ changes = {'nginx_injected': bool(injected)}+ if vhost and injected:+ changes['nginx_vhost'] = vhost+ site.update_settings(**changes)+ db.session.commit()+ except Exception as e: # noqa: BLE001+ logger.debug('serverkit-analytics nginx _mark failed: %s', e)+++def remove_all_injections():+ """Strip every nginx injection (called on uninstall)."""+ try:+ from .models import AnalyticsSite+ except Exception: # noqa: BLE001+ return 0+ count = 0+ for site in AnalyticsSite.query.all():+ if site.get_settings().get('nginx_injected'):+ try:+ remove(site)+ count += 1+ except Exception as e: # noqa: BLE001+ logger.debug('nginx remove_all skip %s: %s', site.id, e)+ return countdiff --git a/builtin-extensions/serverkit-analytics/backend/wp_integration.py b/builtin-extensions/serverkit-analytics/backend/wp_integration.pynew file mode 100644index 00000000..6f1dfcbd--- /dev/null+++ b/builtin-extensions/serverkit-analytics/backend/wp_integration.py@@ -0,0 +1,191 @@+"""WordPress tracker injection for serverkit-analytics.++Writes a tiny mu-plugin into a managed WordPress site's+``wp-content/mu-plugins/`` so the tracker snippet is emitted in ``wp_head`` on+every page, with no user action and surviving theme switches. This is the v1+fallback until plan 50 ships a proper companion plugin via the Plugin Library;+both paths bake the same site_key.++Design:+* The WordPress *models* (``WordPressSite`` / ``Application``) are core, so this+ module works whenever a linked site exists; it does not import the+ serverkit-wordpress *service* (which lives in the extension).+* The single write seam is :func:`_docker_exec` (Docker sites) / a host write+ (bare-metal), so tests can mock it. Everything is best-effort and never raises+ out of the lifecycle/uninstall path.++Linux-only at runtime (docker exec / www-data chown); guarded so the Windows dev+box and tests behave.+"""+import logging+import os+import subprocess+from types import SimpleNamespace++logger = logging.getLogger(__name__)++SLUG = 'serverkit-analytics'+WP_SLUG = 'serverkit-wordpress'+MU_PLUGIN_REL = 'wp-content/mu-plugins/serverkit-analytics.php'+CONTAINER_WEBROOT = '/var/www/html'+++def wordpress_available():+ """True when the serverkit-wordpress extension is installed + active."""+ try:+ from app.models.plugin import InstalledPlugin+ row = InstalledPlugin.query.filter_by(slug=WP_SLUG).first()+ return bool(row and row.status == InstalledPlugin.STATUS_ACTIVE)+ except Exception: # noqa: BLE001+ return False+++def build_mu_plugin_php(site_key, tracker_url):+ """Return the mu-plugin PHP that emits the tracker snippet in wp_head."""+ src = tracker_url.replace("'", '')+ key = str(site_key).replace("'", '')+ return (+ "<?php\n"+ "/**\n"+ " * Plugin Name: ServerKit Analytics\n"+ " * Description: Injects the privacy-first ServerKit Analytics tracker. "+ "Managed by the ServerKit panel; do not edit by hand.\n"+ " * Version: 1.0.0\n"+ " */\n"+ "if (!defined('ABSPATH')) { exit; }\n"+ "add_action('wp_head', function () {\n"+ f" $src = '{src}';\n"+ f" $key = '{key}';\n"+ " echo '<script defer src=\"' . esc_url($src) . '\" data-site-key=\"'"+ " . esc_attr($key) . '\"></script>' . \"\\n\";\n"+ "}, 1);\n"+ )+++def _docker_exec(container, argv, input_text=None):+ """Run ``docker exec [-i] <container> <argv...>``. Mockable seam."""+ cmd = ['docker', 'exec']+ if input_text is not None:+ cmd.append('-i')+ cmd += [container] + list(argv)+ try:+ result = subprocess.run(+ cmd, input=input_text, capture_output=True, text=True, timeout=30)+ return {'success': result.returncode == 0,+ 'output': result.stdout,+ 'error': result.stderr if result.returncode != 0 else None}+ except Exception as e: # noqa: BLE001+ return {'success': False, 'error': str(e)}+++def _resolve_target(site):+ """Resolve the WordPress deployment behind an analytics site.++ Returns a namespace ``(container, is_docker, root)`` or ``None`` when no+ linked WordPress site/application can be found.+ """+ if not site or not site.app_id:+ return None+ try:+ from app.models.wordpress_site import WordPressSite+ from app.models import Application+ except Exception: # noqa: BLE001+ return None+ wp = WordPressSite.query.get(site.app_id)+ if not wp:+ return None+ app = Application.query.get(wp.application_id)+ if not app:+ return None+ root = getattr(app, 'root_path', None)+ is_docker = bool(root and os.path.exists(os.path.join(root, 'docker-compose.yml')))+ return SimpleNamespace(container=app.name, is_docker=is_docker, root=root)+++def _write_mu_plugin(target, content):+ if target.is_docker:+ _docker_exec(target.container,+ ['mkdir', '-p', f'{CONTAINER_WEBROOT}/wp-content/mu-plugins'])+ return _docker_exec(target.container,+ ['tee', f'{CONTAINER_WEBROOT}/{MU_PLUGIN_REL}'],+ input_text=content)+ if not target.root:+ return {'success': False, 'error': 'no site root'}+ full = os.path.join(target.root, *MU_PLUGIN_REL.split('/'))+ try:+ os.makedirs(os.path.dirname(full), exist_ok=True)+ with open(full, 'w', encoding='utf-8') as f:+ f.write(content)+ except OSError as e:+ return {'success': False, 'error': str(e)}+ if os.name != 'nt':+ try:+ from app.utils.system import run_privileged+ run_privileged(['chown', 'www-data:www-data', full])+ except Exception: # noqa: BLE001+ pass+ return {'success': True}+++def _remove_mu_plugin(target):+ if target.is_docker:+ return _docker_exec(target.container,+ ['rm', '-f', f'{CONTAINER_WEBROOT}/{MU_PLUGIN_REL}'])+ if not target.root:+ return {'success': True}+ full = os.path.join(target.root, *MU_PLUGIN_REL.split('/'))+ try:+ if os.path.exists(full):+ os.remove(full)+ except OSError as e:+ return {'success': False, 'error': str(e)}+ return {'success': True}+++def inject(site, tracker_url):+ """Write the mu-plugin for a WordPress-linked analytics site."""+ target = _resolve_target(site)+ if not target:+ return {'success': False, 'error': 'No linked WordPress site found'}+ php = build_mu_plugin_php(site.site_key, tracker_url)+ result = _write_mu_plugin(target, php)+ if result.get('success'):+ _mark(site, True, target)+ return result+++def remove(site):+ """Remove the mu-plugin and clear the injection flag."""+ target = _resolve_target(site)+ result = _remove_mu_plugin(target) if target else {'success': True}+ _mark(site, False, target)+ return result+++def _mark(site, injected, target):+ try:+ from app import db+ changes = {'wp_injected': bool(injected)}+ if target and injected:+ changes['wp_container'] = target.container+ site.update_settings(**changes)+ db.session.commit()+ except Exception as e: # noqa: BLE001+ logger.debug('serverkit-analytics wp _mark failed: %s', e)+++def remove_all_injections():+ """Remove every WordPress mu-plugin injection (called on uninstall)."""+ try:+ from .models import AnalyticsSite+ except Exception: # noqa: BLE001+ return 0+ count = 0+ for site in AnalyticsSite.query.all():+ if site.get_settings().get('wp_injected'):+ try:+ remove(site)+ count += 1+ except Exception as e: # noqa: BLE001+ logger.debug('wp remove_all skip %s: %s', site.id, e)+ return countdiff --git a/frontend/src/components/wordpress/detail/AnalyticsTab.jsx b/frontend/src/components/wordpress/detail/AnalyticsTab.jsxindex 875fc13b..c1d32eaf 100644--- a/frontend/src/components/wordpress/detail/AnalyticsTab.jsx+++ b/frontend/src/components/wordpress/detail/AnalyticsTab.jsx@@ -1,7 +1,9 @@import React, { useState, useEffect } from 'react';+import { Link } from 'react-router-dom';import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';-import { BarChart3, Globe, HardDrive, AlertTriangle, Activity, FileText } from 'lucide-react';+import { BarChart3, Globe, HardDrive, AlertTriangle, Activity, FileText, LineChart, ExternalLink } from 'lucide-react';import wordpressApi from '../../../services/wordpress';+import api from '../../../services/api';import { useToast } from '../../../contexts/ToastContext';import { MetricCard, SegControl } from '../../ds';import { OverviewGridSkeleton, ANALYTICS_PERIODS } from './wpDetailShared';@@ -14,6 +16,23 @@ const AnalyticsTab = ({ siteId }) => {const [data, setData] = useState(null);const [loading, setLoading] = useState(true);const [hours, setHours] = useState(24);+ // Feature-detect the serverkit-analytics extension so we can point users at+ // the persistent, privacy-first dashboard when it's installed. The on-demand+ // access-log view below stays as a complementary, always-available source.+ const [analyticsExt, setAnalyticsExt] = useState(false);++ useEffect(() => {+ let alive = true;+ api.getInstalledPlugins('active')+ .then((res) => {+ if (!alive) return;+ const on = (res?.plugins || []).some(+ (p) => p.slug === 'serverkit-analytics' && p.status === 'active');+ setAnalyticsExt(on);+ })+ .catch(() => { /* extension absent — silently keep the log view */ });+ return () => { alive = false; };+ }, []);const load = React.useCallback(async () => {setLoading(true);@@ -45,6 +64,18 @@ const AnalyticsTab = ({ siteId }) => {return (<div className="app-overview-grid"><div className="app-overview-left">+ {analyticsExt && (+ <div className="wp-analytics-banner">+ <LineChart size={16} />+ <div className="wp-analytics-banner__text">+ <strong>Web Analytics is installed.</strong>+ <span> Add this site there for persistent, cookieless visitor tracking with a full dashboard. The view below is parsed on demand from access logs.</span>+ </div>+ <Link to="/analytics/sites" className="wp-analytics-banner__link">+ Open Web Analytics <ExternalLink size={13} />+ </Link>+ </div>+ )}<div className="wp-analytics-head"><h3 className="wp-eyebrow">Traffic · {hours <= 24 ? 'last 24 hours' : 'last 7 days'}</h3><SegControldiff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scssindex c5f83e1d..82e10466 100644--- a/frontend/src/styles/pages/_wordpress.scss+++ b/frontend/src/styles/pages/_wordpress.scss@@ -1469,6 +1469,34 @@}// ---- Analytics head (eyebrow + SegControl) ----+ .wp-analytics-banner {+ display: flex;+ align-items: center;+ gap: $space-3;+ margin-bottom: $space-4;+ padding: $space-3 $space-4;+ border: 1px solid rgba(129, 140, 248, 0.28);+ border-radius: var(--radius, 8px);+ background: rgba(129, 140, 248, 0.08);+ color: var(--text-primary);+ flex-wrap: wrap;++ svg { color: var(--accent-bright, #818cf8); flex-shrink: 0; }++ &__text { flex: 1 1 240px; font-size: 13px; line-height: 1.4; }+ &__text span { color: var(--text-secondary); }++ &__link {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ white-space: nowrap;+ font-size: 13px;+ font-weight: $font-weight-semibold;+ color: var(--accent-bright, #818cf8);+ }+ }+.wp-analytics-head {display: flex;justify-content: space-between;