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(analytics): scaffold serverkit-analytics extension (Phase 0)

Juan Deniscc3626267a90
diff --git a/backend/tests/test_analytics_extension.py b/backend/tests/test_analytics_extension.py
new file mode 100644
index 00000000..ea31a871
--- /dev/null
+++ b/backend/tests/test_analytics_extension.py
@@ -0,0 +1,213 @@
+"""serverkit-analytics (Web Analytics) extension tests.
+
+Loads the builtin the way production does: ``plugin_service.
+_ensure_builtin_backend_importable`` registers ``builtin-extensions/
+serverkit-analytics/backend`` as the dashed package ``app.plugins.
+serverkit-analytics``. The models module is imported at module top so its
+``ext_serverkit_analytics_*`` tables register on ``db.metadata`` before the
+``app`` fixture runs ``db.create_all()``.
+
+Nothing here shells out or talks to Docker; the collector, ingestion buffer,
+rollups, and log parsing are exercised against the in-memory test DB. Bots,
+rate-limits, and visitor hashing are pure-Python and tested directly.
+"""
+import importlib
+import json
+import os
+
+import pytest
+
+from app.services import plugin_service
+
+SLUG = 'serverkit-analytics'
+EXT_DIR = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
+ 'builtin-extensions', SLUG,
+)
+
+
+def _load_ext():
+ assert plugin_service._ensure_builtin_backend_importable(SLUG), (
+ f'builtin extension backend not importable from {EXT_DIR}')
+ mods = {}
+ for name in ('config', 'lifecycle', 'analytics'):
+ mods[name] = importlib.import_module(f'app.plugins.{SLUG}.{name}')
+ return mods
+
+
+_M = _load_ext()
+config_mod = _M['config']
+lifecycle_mod = _M['lifecycle']
+bp_mod = _M['analytics']
+
+
+# --------------------------------------------------------------------------- #
+# helpers / fixtures
+# --------------------------------------------------------------------------- #
+def _mk_plugin_row(config=None, status=None):
+ from app import db
+ from app.models.plugin import InstalledPlugin
+ row = InstalledPlugin(
+ name=SLUG, display_name='Web Analytics', slug=SLUG, version='1.0.0',
+ status=status or InstalledPlugin.STATUS_ACTIVE,
+ )
+ row.config = config or {}
+ db.session.add(row)
+ db.session.commit()
+ return row
+
+
+def _mk_admin():
+ from app import db
+ from app.models.user import User
+ from werkzeug.security import generate_password_hash
+ u = User(email='[email protected]', username='analyticsadmin',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _mk_viewer():
+ from app import db
+ from app.models.user import User
+ from werkzeug.security import generate_password_hash
+ u = User(email='[email protected]', username='analyticsviewer',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_VIEWER, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _auth(user):
+ from flask_jwt_extended import create_access_token
+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}
+
+
+def analytics_client(app):
+ if 'analytics' not in app.blueprints:
+ app.register_blueprint(bp_mod.analytics_bp, url_prefix='/api/v1/analytics')
+ return app.test_client()
+
+
+# --------------------------------------------------------------------------- #
+# manifest
+# --------------------------------------------------------------------------- #
+def _manifest():
+ with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:
+ return json.load(f)
+
+
+def test_manifest_passes_validator():
+ m = _manifest()
+ assert plugin_service._validate_manifest(m) is True
+ assert m['name'] == SLUG
+ assert m['entry_point'] == 'analytics:analytics_bp'
+ assert m['url_prefix'] == '/api/v1/analytics'
+ assert m['models'] == 'models:register'
+ nav = m['contributions']['nav'][0]
+ assert nav['route'] == '/analytics' and nav['id'] == 'analytics'
+ assert m['contributions']['page_titles']['/analytics'] == 'Web Analytics'
+
+
+def test_manifest_permissions_known_and_no_dashes():
+ from app.plugins_sdk import permissions as sdk_perms
+ m = _manifest()
+ assert sdk_perms.unknown_permissions(m['permissions']) == []
+ assert set(m['permissions']) == {'db', 'network', 'filesystem'}
+ assert '—' not in m['description'] and '–' not in m['description']
+
+
+def test_manifest_jobs_and_schedules_pair_up():
+ m = _manifest()
+ job_kinds = {j['kind'] for j in m['jobs']}
+ sched_kinds = {s['kind'] for s in m['schedules']}
+ assert sched_kinds <= job_kinds
+ assert {'analytics.rollup', 'analytics.retention_prune',
+ 'analytics.log_tail'} <= job_kinds
+
+
+def test_lifecycle_and_job_refs_resolve():
+ m = _manifest()
+ for ref in m['lifecycle'].values():
+ module_name, func_name = ref.split(':')
+ mod = importlib.import_module(f'app.plugins.{SLUG}.{module_name}')
+ assert callable(getattr(mod, func_name, None)), ref
+ for job in m['jobs']:
+ module_name, func_name = job['handler'].split(':')
+ mod = importlib.import_module(f'app.plugins.{SLUG}.{module_name}')
+ assert callable(getattr(mod, func_name, None)), job['handler']
+
+
+def test_entry_point_resolves_to_blueprint():
+ assert getattr(bp_mod, 'analytics_bp', None) is not None
+ assert bp_mod.analytics_bp.name == 'analytics'
+
+
+def test_config_schema_keys_match_defaults():
+ m = _manifest()
+ schema_keys = set(m['config_schema'].keys())
+ assert schema_keys == set(config_mod.DEFAULTS.keys())
+
+
+# --------------------------------------------------------------------------- #
+# config accessor
+# --------------------------------------------------------------------------- #
+def test_get_cfg_returns_defaults_without_row(app):
+ cfg = config_mod.get_cfg()
+ assert cfg['raw_retention_days'] == 30
+ assert cfg['honor_dnt'] is True
+ assert cfg['collect_rate_per_min'] == 600
+
+
+def test_get_cfg_merges_saved_over_defaults(app):
+ _mk_plugin_row(config={'raw_retention_days': 7, 'geo_enabled': True})
+ cfg = config_mod.get_cfg()
+ assert cfg['raw_retention_days'] == 7 # overridden
+ assert cfg['geo_enabled'] is True # overridden
+ assert cfg['rollup_retention_months'] == 13 # still default
+
+
+def test_cfg_int_clamps(app):
+ _mk_plugin_row(config={'collect_rate_per_min': 5})
+ assert config_mod.cfg_int('collect_rate_per_min', minimum=10) == 10
+
+
+def test_cfg_bool_accepts_strings(app):
+ _mk_plugin_row(config={'honor_dnt': 'false'})
+ assert config_mod.cfg_bool('honor_dnt') is False
+
+
+# --------------------------------------------------------------------------- #
+# lifecycle
+# --------------------------------------------------------------------------- #
+def test_on_install_seeds_config_defaults(app):
+ row = _mk_plugin_row(config={})
+ lifecycle_mod.on_install(row)
+ assert row.config['raw_retention_days'] == 30
+ assert row.config['log_ingestion_enabled'] is True
+
+
+def test_on_install_does_not_clobber_saved(app):
+ row = _mk_plugin_row(config={'raw_retention_days': 90})
+ lifecycle_mod.on_install(row)
+ assert row.config['raw_retention_days'] == 90 # preserved
+ assert 'buffer_max' in row.config # new key seeded
+
+
+def test_on_uninstall_is_safe_without_integrations(app):
+ row = _mk_plugin_row()
+ # wp_integration / nginx_integration may not import cleanly yet; must not raise.
+ lifecycle_mod.on_uninstall(row, purge=True)
+
+
+# --------------------------------------------------------------------------- #
+# ping route (proves the blueprint mounts; 503 status guard covered separately)
+# --------------------------------------------------------------------------- #
+def test_ping_route(analytics_client):
+ resp = analytics_client.get('/api/v1/analytics/ping')
+ assert resp.status_code == 200
+ assert resp.get_json()['plugin'] == SLUG
diff --git a/builtin-extensions/serverkit-analytics/backend/__init__.py b/builtin-extensions/serverkit-analytics/backend/__init__.py
new file mode 100644
index 00000000..823985e8
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/backend/__init__.py
@@ -0,0 +1,14 @@
+"""ServerKit Web Analytics extension backend package.
+
+Privacy-first, self-hosted web analytics for the sites this panel manages. A
+lightweight cookieless JS tracker (and optional server-log ingestion) feed a
+persistent time series stored on the panel's own database; a dashboard inside
+the panel renders visitors / pageviews / referrers / devices / realtime.
+
+The blueprint (``analytics_bp``) is the manifest ``entry_point``; everything
+else (ingestion buffer, rollups, log parsing, WordPress/nginx wiring) lives in
+sibling modules. See docs/plans/49_ANALYTICS_EXTENSION_PLAN.md.
+"""
+from .analytics import analytics_bp
+
+__all__ = ['analytics_bp']
diff --git a/builtin-extensions/serverkit-analytics/backend/analytics.py b/builtin-extensions/serverkit-analytics/backend/analytics.py
new file mode 100644
index 00000000..295ab0f3
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/backend/analytics.py
@@ -0,0 +1,31 @@
+"""Web Analytics API endpoints (serverkit-analytics extension).
+
+Mounted under ``/api/v1/analytics`` via the manifest ``url_prefix``. Thin
+routing layer over the extension services:
+
+* ``ingest_service`` — validation, bot filter, visitor hashing, buffer+flush
+* ``report_service`` — rollup-backed dashboard queries
+* ``log_ingest_service`` — access-log parsing (apache/nginx combined)
+* ``wp_integration`` / ``nginx_integration`` — one-click tracker injection
+
+Auth split mirrors serverkit-tramo / serverkit-k8s: report reads need viewer,
+site mutations need admin. The TWO exceptions are the tracker surface — the
+public ``POST /collect`` and ``GET /tracker.js`` — which carry NO JWT because a
+tracked site's visitors have none. They authenticate per-site via the site_key
+(not a JWT) and are protected by rate limiting, a body-size cap, and bot
+filtering. The plugin-disabled 503 guard (attached by plugin_service) still runs
+on every route, so disabling the extension stops collection for free.
+"""
+import logging
+
+from flask import Blueprint, jsonify
+
+logger = logging.getLogger(__name__)
+
+analytics_bp = Blueprint('analytics', __name__)
+
+
+@analytics_bp.route('/ping', methods=['GET'])
+def ping():
+ """Unauthenticated liveness probe (also proves the 503 status guard)."""
+ return jsonify({'ok': True, 'plugin': 'serverkit-analytics'}), 200
diff --git a/builtin-extensions/serverkit-analytics/backend/config.py b/builtin-extensions/serverkit-analytics/backend/config.py
new file mode 100644
index 00000000..ed76ac1b
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/backend/config.py
@@ -0,0 +1,74 @@
+"""Config defaults + accessor for the serverkit-analytics extension.
+
+The manifest's ``config_schema`` documents the fields an admin can edit
+(Marketplace → Installed → Configure), but the platform does not auto-apply the
+schema's ``default`` values — it just stores whatever the admin saves. So the
+canonical defaults live here, and :func:`get_cfg` merges the admin-saved values
+(read via the plugin SDK) over these defaults. Every backend module reads config
+through :func:`get_cfg` / :func:`cfg_*` so a fresh install behaves correctly
+before anyone opens the Configure dialog.
+
+``lifecycle.on_install`` also seeds these defaults onto the InstalledPlugin row
+so they show up pre-filled in the Configure UI.
+"""
+
+SLUG = 'serverkit-analytics'
+
+# Keep in sync with plugin.json ``config_schema`` defaults.
+DEFAULTS = {
+ 'raw_retention_days': 30,
+ 'rollup_retention_months': 13,
+ 'honor_dnt': True,
+ 'geo_enabled': False,
+ 'geo_db_path': '',
+ 'collect_rate_per_min': 600,
+ 'buffer_flush_seconds': 5,
+ 'buffer_max': 100,
+ 'store_query_strings': False,
+ 'log_ingestion_enabled': True,
+}
+
+
+def get_cfg():
+ """Return the effective config: admin-saved values merged over DEFAULTS.
+
+ Safe outside an app/request context (returns a copy of DEFAULTS) so module
+ import and background threads never explode.
+ """
+ merged = dict(DEFAULTS)
+ try:
+ from app.plugins_sdk import config as plugin_config
+ saved = plugin_config(SLUG) or {}
+ except Exception: # noqa: BLE001 - no app context / plugin row yet
+ saved = {}
+ for key in DEFAULTS:
+ if key in saved and saved[key] is not None:
+ merged[key] = saved[key]
+ return merged
+
+
+def cfg_int(key, minimum=None, maximum=None):
+ """Read an integer config value, clamped and default-safe."""
+ try:
+ val = int(get_cfg().get(key, DEFAULTS.get(key)))
+ except (TypeError, ValueError):
+ val = int(DEFAULTS.get(key, 0))
+ if minimum is not None:
+ val = max(minimum, val)
+ if maximum is not None:
+ val = min(maximum, val)
+ return val
+
+
+def cfg_bool(key):
+ """Read a boolean config value (accepts real bools and truthy strings)."""
+ val = get_cfg().get(key, DEFAULTS.get(key))
+ if isinstance(val, str):
+ return val.strip().lower() in ('1', 'true', 'yes', 'on')
+ return bool(val)
+
+
+def cfg_str(key):
+ """Read a string config value."""
+ val = get_cfg().get(key, DEFAULTS.get(key))
+ return '' if val is None else str(val)
diff --git a/builtin-extensions/serverkit-analytics/backend/jobs.py b/builtin-extensions/serverkit-analytics/backend/jobs.py
new file mode 100644
index 00000000..3ebf51d6
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/backend/jobs.py
@@ -0,0 +1,54 @@
+"""Background job handlers (serverkit-analytics extension).
+
+Registered via the manifest ``jobs`` block; each handler takes the ``job`` row
+and must never raise (a raised handler fails the job loudly — these are
+best-effort maintenance tasks, and a disabled plugin's schedules are paused by
+the platform anyway).
+
+* ``analytics.rollup`` (:func:`rollup`) — aggregate raw ``event`` rows into the
+ ``daily`` rollup table (hourly).
+* ``analytics.retention_prune`` (:func:`retention_prune`) — drop raw events past
+ ``raw_retention_days`` and rollups past ``rollup_retention_months`` (daily).
+* ``analytics.log_tail`` (:func:`log_tail`) — ingest new access-log lines for
+ sites that opted into server-log ingestion (every few minutes).
+
+The heavy lifting lives in sibling services (``rollup_service``,
+``log_ingest_service``); these wrappers keep the scheduler decoupled and
+crash-proof. Filled out in Phase 2 (rollup/retention) and Phase 6 (log tail).
+"""
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def rollup(job):
+ """Roll raw events up into the daily table. Never raises."""
+ try:
+ from .rollup_service import run_rollup
+ return run_rollup()
+ except Exception as e: # noqa: BLE001 — a maintenance job must not crash the loop
+ logger.warning('analytics rollup job failed: %s', e)
+ return {'error': str(e)}
+
+
+def retention_prune(job):
+ """Prune raw events + old rollups past their retention windows. Never raises."""
+ try:
+ from .rollup_service import run_retention_prune
+ return run_retention_prune()
+ except Exception as e: # noqa: BLE001
+ logger.warning('analytics retention_prune job failed: %s', e)
+ return {'error': str(e)}
+
+
+def log_tail(job):
+ """Ingest new access-log lines for opted-in sites. Never raises."""
+ try:
+ from .config import cfg_bool
+ if not cfg_bool('log_ingestion_enabled'):
+ return {'skipped': True, 'reason': 'log ingestion disabled'}
+ from .log_ingest_service import run_log_tail
+ return run_log_tail()
+ except Exception as e: # noqa: BLE001
+ logger.warning('analytics log_tail job failed: %s', e)
+ return {'error': str(e)}
diff --git a/builtin-extensions/serverkit-analytics/backend/lifecycle.py b/builtin-extensions/serverkit-analytics/backend/lifecycle.py
new file mode 100644
index 00000000..c89b4988
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/backend/lifecycle.py
@@ -0,0 +1,90 @@
+"""Install / upgrade / uninstall lifecycle hooks (serverkit-analytics).
+
+Contract (per the plugin SDK): a single positional arg — the InstalledPlugin
+row; ``on_uninstall`` also accepts a ``purge`` flag. Everything here is wrapped
+so a hook failure never blocks install/uninstall.
+
+* ``on_install`` — seed config defaults onto the row so they show pre-filled
+ in the Configure dialog; register notification events.
+* ``on_upgrade`` — re-seed any newly-added config keys (schema evolves without
+ Alembic; ``register_models`` + ``db.create_all`` handles new
+ tables, this backfills new config defaults).
+* ``on_uninstall`` — best-effort cleanup of injected trackers (WordPress
+ mu-plugin / nginx sub_filter) so we don't leave dead
+ snippets behind. The ``ext_serverkit_analytics_*`` tables
+ are dropped by the platform on ``--purge``.
+"""
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def _seed_config_defaults(plugin, overwrite=False):
+ """Merge DEFAULTS into the plugin's saved config so the Configure UI is
+ pre-filled. ``overwrite=False`` never clobbers an admin's saved value."""
+ try:
+ from app import db
+ from .config import DEFAULTS
+ merged = dict(plugin.config or {})
+ changed = False
+ for key, value in DEFAULTS.items():
+ if overwrite or key not in merged:
+ if merged.get(key) != value:
+ merged[key] = value
+ changed = True
+ if changed:
+ plugin.config = merged
+ db.session.commit()
+ except Exception as e: # noqa: BLE001
+ logger.warning('serverkit-analytics config seed failed: %s', e)
+
+
+def _register_events():
+ try:
+ from app.plugins_sdk import notify
+ notify.register_event(
+ 'analytics.collector_error',
+ 'The web-analytics collector hit repeated errors',
+ template='generic', severity='warning', category='system')
+ notify.register_event(
+ 'analytics.site_injection_failed',
+ 'Injecting the analytics tracker into a site failed',
+ template='generic', severity='warning', category='system')
+ except Exception as e: # noqa: BLE001
+ logger.debug('serverkit-analytics event registration failed: %s', e)
+
+
+def on_install(plugin):
+ """Seed config defaults; register notification events."""
+ _seed_config_defaults(plugin, overwrite=False)
+ _register_events()
+ logger.info('serverkit-analytics installed (config seeded, events registered)')
+
+
+def on_upgrade(plugin):
+ """Backfill newly-added config defaults on an in-place version change."""
+ _seed_config_defaults(plugin, overwrite=False)
+ _register_events()
+ logger.info('serverkit-analytics upgraded')
+
+
+def on_uninstall(plugin, purge=False):
+ """Remove any tracker injections we performed. Data tables are dropped by
+ the platform on --purge; this only unwinds the site-side snippets."""
+ try:
+ from . import wp_integration
+ removed = wp_integration.remove_all_injections()
+ if removed:
+ logger.info('serverkit-analytics: removed %s WP injection(s)', removed)
+ except Exception as e: # noqa: BLE001
+ logger.debug('serverkit-analytics WP injection cleanup skipped: %s', e)
+
+ try:
+ from . import nginx_integration
+ removed = nginx_integration.remove_all_injections()
+ if removed:
+ logger.info('serverkit-analytics: removed %s nginx injection(s)', removed)
+ except Exception as e: # noqa: BLE001
+ logger.debug('serverkit-analytics nginx injection cleanup skipped: %s', e)
+
+ logger.info('serverkit-analytics uninstalled (purge=%s)', purge)
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx b/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx
new file mode 100644
index 00000000..267281db
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx
@@ -0,0 +1,15 @@
+// Web Analytics dashboard (serverkit-analytics). Placeholder scaffold — the six
+// tabs (Overview / Pages / Referrers / Devices / Realtime / Sites) land in
+// Phase 4. Kept minimal so the frontend builds from Phase 0.
+import { PageTopbar } from '@/components/ds';
+
+export function AnalyticsPage() {
+ return (
+ <div className="analytics-page">
+ <PageTopbar title="Web Analytics" />
+ <div className="sk-tabgroup__inner">
+ <p>Web Analytics is installing. The dashboard will appear here.</p>
+ </div>
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/index.jsx b/builtin-extensions/serverkit-analytics/frontend/index.jsx
new file mode 100644
index 00000000..077ede6e
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/index.jsx
@@ -0,0 +1,10 @@
+// Web Analytics (serverkit-analytics) UI, contributed through the extension
+// system. Fully self-contained. After sync this folder lives at
+// frontend/src/plugins/serverkit-analytics/, so host '@/…' aliases resolve.
+//
+// plugin.json maps both /analytics and /analytics/:tab to AnalyticsPage (the
+// tabbed dashboard). Resolved by NAMED export.
+export { AnalyticsPage } from './components/AnalyticsPage.jsx';
+
+// No default export on purpose: PluginLoader auto-renders any plugin default
+// export globally. The route contributions resolve the named export.
diff --git a/builtin-extensions/serverkit-analytics/plugin.json b/builtin-extensions/serverkit-analytics/plugin.json
new file mode 100644
index 00000000..c4deac93
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/plugin.json
@@ -0,0 +1,71 @@
+{
+ "name": "serverkit-analytics",
+ "display_name": "Web Analytics",
+ "version": "1.0.0",
+ "description": "Privacy-first, self-hosted web analytics for the sites this panel manages. A lightweight (<4 KB) cookieless JavaScript tracker and optional server-log ingestion feed a persistent time series stored on your own server, and nothing leaves the box. Visitor identity is a daily-rotating salted hash of IP+user-agent (raw IPs are never stored), DoNotTrack is honored, and there are no cookies, fingerprinting, or third-party calls. A real dashboard inside the panel shows visitors, pageviews, top pages, referrers, devices, and a live realtime counter, with one-click wiring into managed WordPress and nginx-proxied apps.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "monitoring",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "featured": true,
+ "feature_score": 88,
+ "permissions": ["db", "network", "filesystem"],
+ "min_panel_version": "1.7.0",
+ "entry_point": "analytics:analytics_bp",
+ "url_prefix": "/api/v1/analytics",
+ "models": "models:register",
+ "lifecycle": {
+ "install": "lifecycle:on_install",
+ "upgrade": "lifecycle:on_upgrade",
+ "uninstall": "lifecycle:on_uninstall"
+ },
+ "jobs": [
+ { "kind": "analytics.rollup", "handler": "jobs:rollup" },
+ { "kind": "analytics.retention_prune", "handler": "jobs:retention_prune" },
+ { "kind": "analytics.log_tail", "handler": "jobs:log_tail" }
+ ],
+ "schedules": [
+ { "name": "analytics-rollup", "kind": "analytics.rollup", "interval_seconds": 3600 },
+ { "name": "analytics-retention-prune", "kind": "analytics.retention_prune", "cron": "17 4 * * *" },
+ { "name": "analytics-log-tail", "kind": "analytics.log_tail", "interval_seconds": 300 }
+ ],
+ "config_schema": {
+ "raw_retention_days": { "type": "integer", "default": 30, "title": "Raw event retention (days)", "description": "How long individual pageview/event rows are kept before pruning. Rollups outlive this." },
+ "rollup_retention_months": { "type": "integer", "default": 13, "title": "Rollup retention (months)", "description": "How long the daily rollup time series is kept." },
+ "honor_dnt": { "type": "boolean", "default": true, "title": "Honor Do Not Track", "description": "Drop hits from browsers sending the DNT header (server-side double-check; the tracker also honors it)." },
+ "geo_enabled": { "type": "boolean", "default": false, "title": "Country geolocation", "description": "Fill a country column from a local GeoLite2-Country MMDB. Off by default; no database ships with the panel." },
+ "geo_db_path": { "type": "string", "default": "", "title": "GeoLite2 MMDB path", "description": "Absolute path to a GeoLite2-Country.mmdb file on the panel host. Country stays null when empty or missing." },
+ "collect_rate_per_min": { "type": "integer", "default": 600, "title": "Collect rate limit (per minute)", "description": "Token-bucket cap on collect hits per site-key and per client IP." },
+ "buffer_flush_seconds": { "type": "integer", "default": 5, "title": "Buffer flush interval (seconds)", "description": "How often the in-memory event buffer is flushed to the database." },
+ "buffer_max": { "type": "integer", "default": 100, "title": "Buffer flush size", "description": "Flush the buffer early once this many events have accumulated." },
+ "store_query_strings": { "type": "boolean", "default": false, "title": "Store query strings", "description": "Persist the query part of URLs. Off by default to avoid capturing tokens/PII in URLs." },
+ "log_ingestion_enabled": { "type": "boolean", "default": true, "title": "Server-log ingestion", "description": "Allow the scheduled log-tail job to ingest access logs for sites that opt in." }
+ },
+ "icon": "<path d=\"M3 3v18h18\"/><rect x=\"7\" y=\"12\" width=\"3\" height=\"6\"/><rect x=\"12\" y=\"8\" width=\"3\" height=\"10\"/><rect x=\"17\" y=\"4\" width=\"3\" height=\"14\"/>",
+ "contributions": {
+ "nav": [
+ {
+ "id": "analytics",
+ "label": "Web Analytics",
+ "route": "/analytics",
+ "category": "operations",
+ "icon": "<path d=\"M3 3v18h18\"/><rect x=\"7\" y=\"12\" width=\"3\" height=\"6\"/><rect x=\"12\" y=\"8\" width=\"3\" height=\"10\"/><rect x=\"17\" y=\"4\" width=\"3\" height=\"14\"/>"
+ }
+ ],
+ "routes": [
+ { "path": "analytics", "component": "AnalyticsPage" },
+ { "path": "analytics/:tab", "component": "AnalyticsPage" }
+ ],
+ "page_titles": {
+ "/analytics": "Web Analytics"
+ },
+ "command_palette": [
+ {
+ "label": "Web Analytics",
+ "path": "/analytics",
+ "category": "Pages",
+ "keywords": "analytics traffic visitors pageviews stats web tracker matomo umami plausible referrers devices realtime privacy cookieless"
+ }
+ ]
+ }
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx b/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx
new file mode 100644
index 00000000..267281db
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx
@@ -0,0 +1,15 @@
+// Web Analytics dashboard (serverkit-analytics). Placeholder scaffold — the six
+// tabs (Overview / Pages / Referrers / Devices / Realtime / Sites) land in
+// Phase 4. Kept minimal so the frontend builds from Phase 0.
+import { PageTopbar } from '@/components/ds';
+
+export function AnalyticsPage() {
+ return (
+ <div className="analytics-page">
+ <PageTopbar title="Web Analytics" />
+ <div className="sk-tabgroup__inner">
+ <p>Web Analytics is installing. The dashboard will appear here.</p>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/index.jsx b/frontend/src/plugins/serverkit-analytics/index.jsx
new file mode 100644
index 00000000..077ede6e
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/index.jsx
@@ -0,0 +1,10 @@
+// Web Analytics (serverkit-analytics) UI, contributed through the extension
+// system. Fully self-contained. After sync this folder lives at
+// frontend/src/plugins/serverkit-analytics/, so host '@/…' aliases resolve.
+//
+// plugin.json maps both /analytics and /analytics/:tab to AnalyticsPage (the
+// tabbed dashboard). Resolved by NAMED export.
+export { AnalyticsPage } from './components/AnalyticsPage.jsx';
+
+// No default export on purpose: PluginLoader auto-renders any plugin default
+// export globally. The route contributions resolve the named export.
diff --git a/frontend/src/plugins/serverkit-analytics/plugin.json b/frontend/src/plugins/serverkit-analytics/plugin.json
new file mode 100644
index 00000000..30389e4e
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/plugin.json
@@ -0,0 +1,152 @@
+{
+ "name": "serverkit-analytics",
+ "display_name": "Web Analytics",
+ "version": "1.0.0",
+ "description": "Privacy-first, self-hosted web analytics for the sites this panel manages. A lightweight (<4 KB) cookieless JavaScript tracker and optional server-log ingestion feed a persistent time series stored on your own server, and nothing leaves the box. Visitor identity is a daily-rotating salted hash of IP+user-agent (raw IPs are never stored), DoNotTrack is honored, and there are no cookies, fingerprinting, or third-party calls. A real dashboard inside the panel shows visitors, pageviews, top pages, referrers, devices, and a live realtime counter, with one-click wiring into managed WordPress and nginx-proxied apps.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "monitoring",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "featured": true,
+ "feature_score": 88,
+ "permissions": [
+ "db",
+ "network",
+ "filesystem"
+ ],
+ "min_panel_version": "1.7.0",
+ "entry_point": "analytics:analytics_bp",
+ "url_prefix": "/api/v1/analytics",
+ "models": "models:register",
+ "lifecycle": {
+ "install": "lifecycle:on_install",
+ "upgrade": "lifecycle:on_upgrade",
+ "uninstall": "lifecycle:on_uninstall"
+ },
+ "jobs": [
+ {
+ "kind": "analytics.rollup",
+ "handler": "jobs:rollup"
+ },
+ {
+ "kind": "analytics.retention_prune",
+ "handler": "jobs:retention_prune"
+ },
+ {
+ "kind": "analytics.log_tail",
+ "handler": "jobs:log_tail"
+ }
+ ],
+ "schedules": [
+ {
+ "name": "analytics-rollup",
+ "kind": "analytics.rollup",
+ "interval_seconds": 3600
+ },
+ {
+ "name": "analytics-retention-prune",
+ "kind": "analytics.retention_prune",
+ "cron": "17 4 * * *"
+ },
+ {
+ "name": "analytics-log-tail",
+ "kind": "analytics.log_tail",
+ "interval_seconds": 300
+ }
+ ],
+ "config_schema": {
+ "raw_retention_days": {
+ "type": "integer",
+ "default": 30,
+ "title": "Raw event retention (days)",
+ "description": "How long individual pageview/event rows are kept before pruning. Rollups outlive this."
+ },
+ "rollup_retention_months": {
+ "type": "integer",
+ "default": 13,
+ "title": "Rollup retention (months)",
+ "description": "How long the daily rollup time series is kept."
+ },
+ "honor_dnt": {
+ "type": "boolean",
+ "default": true,
+ "title": "Honor Do Not Track",
+ "description": "Drop hits from browsers sending the DNT header (server-side double-check; the tracker also honors it)."
+ },
+ "geo_enabled": {
+ "type": "boolean",
+ "default": false,
+ "title": "Country geolocation",
+ "description": "Fill a country column from a local GeoLite2-Country MMDB. Off by default; no database ships with the panel."
+ },
+ "geo_db_path": {
+ "type": "string",
+ "default": "",
+ "title": "GeoLite2 MMDB path",
+ "description": "Absolute path to a GeoLite2-Country.mmdb file on the panel host. Country stays null when empty or missing."
+ },
+ "collect_rate_per_min": {
+ "type": "integer",
+ "default": 600,
+ "title": "Collect rate limit (per minute)",
+ "description": "Token-bucket cap on collect hits per site-key and per client IP."
+ },
+ "buffer_flush_seconds": {
+ "type": "integer",
+ "default": 5,
+ "title": "Buffer flush interval (seconds)",
+ "description": "How often the in-memory event buffer is flushed to the database."
+ },
+ "buffer_max": {
+ "type": "integer",
+ "default": 100,
+ "title": "Buffer flush size",
+ "description": "Flush the buffer early once this many events have accumulated."
+ },
+ "store_query_strings": {
+ "type": "boolean",
+ "default": false,
+ "title": "Store query strings",
+ "description": "Persist the query part of URLs. Off by default to avoid capturing tokens/PII in URLs."
+ },
+ "log_ingestion_enabled": {
+ "type": "boolean",
+ "default": true,
+ "title": "Server-log ingestion",
+ "description": "Allow the scheduled log-tail job to ingest access logs for sites that opt in."
+ }
+ },
+ "icon": "<path d=\"M3 3v18h18\"/><rect x=\"7\" y=\"12\" width=\"3\" height=\"6\"/><rect x=\"12\" y=\"8\" width=\"3\" height=\"10\"/><rect x=\"17\" y=\"4\" width=\"3\" height=\"14\"/>",
+ "contributions": {
+ "nav": [
+ {
+ "id": "analytics",
+ "label": "Web Analytics",
+ "route": "/analytics",
+ "category": "operations",
+ "icon": "<path d=\"M3 3v18h18\"/><rect x=\"7\" y=\"12\" width=\"3\" height=\"6\"/><rect x=\"12\" y=\"8\" width=\"3\" height=\"10\"/><rect x=\"17\" y=\"4\" width=\"3\" height=\"14\"/>"
+ }
+ ],
+ "routes": [
+ {
+ "path": "analytics",
+ "component": "AnalyticsPage"
+ },
+ {
+ "path": "analytics/:tab",
+ "component": "AnalyticsPage"
+ }
+ ],
+ "page_titles": {
+ "/analytics": "Web Analytics"
+ },
+ "command_palette": [
+ {
+ "label": "Web Analytics",
+ "path": "/analytics",
+ "category": "Pages",
+ "keywords": "analytics traffic visitors pageviews stats web tracker matomo umami plausible referrers devices realtime privacy cookieless"
+ }
+ ]
+ }
+}