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
refactor(extensions): extract seven builtins to standalone repos
Juan Denis9639288494f8
diff --git a/.gitignore b/.gitignoreindex bbdd4ee9..b21c5145 100644--- a/.gitignore+++ b/.gitignore@@ -165,3 +165,23 @@ docs/SERVICES_ROADMAP.md# Vite dependency pre-bundle cache (regenerated on every dev run; never commit).vite/**/.vite/++# Install artifacts of extensions that now live in their own repos.+# The panel writes these when the extension is installed from the registry+# (see PluginService._install_from_buffer). They must never be committed back+# here — the source of truth is the extension's own repo, and vendoring a copy+# guarantees the two drift apart.+backend/app/plugins/serverkit-analytics/+backend/app/plugins/serverkit-crowdsec/+backend/app/plugins/serverkit-dns-server/+backend/app/plugins/serverkit-gpu/+backend/app/plugins/serverkit-k8s/+backend/app/plugins/serverkit-mail/+backend/app/plugins/serverkit-tramo/+frontend/src/plugins/serverkit-analytics/+frontend/src/plugins/serverkit-crowdsec/+frontend/src/plugins/serverkit-dns-server/+frontend/src/plugins/serverkit-gpu/+frontend/src/plugins/serverkit-k8s/+frontend/src/plugins/serverkit-mail/+frontend/src/plugins/serverkit-tramo/diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex b491111a..4acfb281 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -422,10 +422,9 @@ def create_app(config_name=None):from app.api.waf import waf_bpapp.register_blueprint(waf_bp, url_prefix='/api/v1/waf')- # GPU monitoring moved to the serverkit-gpu builtin extension (plan 32 #7,- # first CORE_SLIM slice). Its blueprint now mounts at /api/v1/gpu via the- # builtin-extensions loader; the core app.api.gpu / app.services.gpu_service- # modules were removed.+ # GPU monitoring lives in the standalone serverkit-gpu extension (own repo,+ # installed from the registry). Its blueprint mounts at /api/v1/gpu when+ # installed; the core app.api.gpu / app.services.gpu_service modules are gone.# Register blueprints - Nginx Advancedfrom app.api.nginx_advanced import nginx_advanced_bpdiff --git a/backend/app/data/registry_index.json b/backend/app/data/registry_index.jsonindex bae5fd56..623e03e7 100644--- a/backend/app/data/registry_index.json+++ b/backend/app/data/registry_index.json@@ -1,30 +1,185 @@{"schema_version": 2,- "updated": "2026-07-12",+ "updated": "2026-07-20","note": "Bundled fallback copy of the ServerKit extension registry index. The live index is fetched from SERVERKIT_REGISTRY_URL when configured; this file is used offline and in tests. Curated via PR in the serverkit-extensions repo.","extensions": [{"slug": "serverkit-gui",- "display_name": "ServerKit Agent GUI",- "description": "Agent-powered desktop view for managed servers. Streams live screenshots when available, with a synthetic desktop fallback for headless hosts.",- "version": "0.1.0",+ "display_name": "ServerKit Agent GUI (Beta)",+ "description": "Beta: agent-powered desktop view for managed servers. Streams live Windows/Linux screenshots when available, with a synthetic desktop fallback for headless hosts.",+ "version": "0.1.0-beta.1","category": "monitoring","author": "Juan Denis",- "first_party": false,+ "first_party": true,"permissions": ["agent.command:gui:screenshot","agent.command:gui:capabilities"],- "min_panel_version": "1.7.0",+ "min_panel_version": "1.7.11","max_panel_version": null,- "sdk_version": "^1.0.0",- "source": "https://github.com/jhd3197/serverkit-gui",- "sha256": null,- "repo": "https://github.com/jhd3197/serverkit-gui",- "logo": "https://raw.githubusercontent.com/jhd3197/serverkit-extensions/main/assets/serverkit-gui/logo.svg",+ "source": "https://github.com/jhd3197/serverkit-gui/releases/download/v0.1.0-beta.1/serverkit-gui-0.1.0-beta.1.zip",+ "sha256": "432d31396075f8e72921d1c19564e1a819d7fdd674b8d73349e0c13feb51a5f5","homepage": "https://github.com/jhd3197/serverkit-gui",- "icon": "<rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\"/><line x1=\"8\" y1=\"21\" x2=\"16\" y2=\"21\"/><line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"21\"/>",- "screenshots": []+ "repo": "https://github.com/jhd3197/serverkit-gui",+ "logo": "assets/serverkit-gui/logo.svg"+ },+ {+ "slug": "serverkit-crowdsec",+ "display_name": "CrowdSec",+ "description": "CrowdSec security engine integration. Surface active decisions and alerts, ban/unban IPs, and manage allowlists straight from the panel. Read/write via cscli on the host; shows install guidance when CrowdSec is absent (never auto-installs).",+ "version": "1.0.0",+ "category": "security",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "shell"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-crowdsec/releases/download/v1.0.0/serverkit-crowdsec-1.0.0.zip",+ "sha256": "4d92982a55a0ec0b5d7e34012b0d8b0b5655247d49b5dcaf075288bed664cabc",+ "repo": "https://github.com/jhd3197/serverkit-crowdsec",+ "homepage": "https://github.com/jhd3197/serverkit-crowdsec",+ "featured": false,+ "feature_score": 0+ },+ {+ "slug": "serverkit-dns-server",+ "display_name": "DNS Server",+ "description": "Host authoritative DNS on this box with PowerDNS (SQLite backend) in a managed Docker container, covering zones, records, DNSSEC, and delegation checks from the panel. Authoritative only (no recursion); complements provider integrations like Cloudflare, never replaces them. Built for homelab and air-gapped setups.",+ "version": "1.0.0",+ "category": "networking",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "shell",+ "docker"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-dns-server/releases/download/v1.0.0/serverkit-dns-server-1.0.0.zip",+ "sha256": "e17bbc19d25a01a578a085129e786d478bea7af53dfd425f130b753da09d75d3",+ "repo": "https://github.com/jhd3197/serverkit-dns-server",+ "homepage": "https://github.com/jhd3197/serverkit-dns-server",+ "featured": false,+ "feature_score": 0+ },+ {+ "slug": "serverkit-gpu",+ "display_name": "GPU Monitor",+ "description": "Live NVIDIA GPU metrics covering utilization, memory, temperature, power and fan, for servers with a GPU. Adds a GPU Monitor page; the sidebar entry appears only on hosts where nvidia-smi is available.",+ "version": "1.0.0",+ "category": "monitoring",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "shell"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-gpu/releases/download/v1.0.0/serverkit-gpu-1.0.0.zip",+ "sha256": "c861dafadd3e5d5a72836e7d4248b18143cea1aea8c45d32d5211c83f28f9985",+ "repo": "https://github.com/jhd3197/serverkit-gpu",+ "homepage": "https://github.com/jhd3197/serverkit-gpu",+ "featured": true,+ "feature_score": 60+ },+ {+ "slug": "serverkit-mail",+ "display_name": "Mail Server",+ "description": "Self-hosted mail server powered by Stalwart in a managed Docker container, providing domains, mailboxes, forwarders, and autoresponders, with automatic DKIM/SPF/DMARC/MX record deployment, a deliverability preflight (PTR, port-25 egress, RBL) that gates outbound sending, brute-force jails, and maildir backups. Most panels never run a mail server, so it ships as an opt-in extension.",+ "version": "1.0.0",+ "category": "integration",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "shell",+ "filesystem",+ "network",+ "docker"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-mail/releases/download/v1.0.0/serverkit-mail-1.0.0.zip",+ "sha256": "0132031e6b784bde5ebb6c70b5e0b15e085ed8a51f8c0fc65c50540824fcf294",+ "repo": "https://github.com/jhd3197/serverkit-mail",+ "homepage": "https://github.com/jhd3197/serverkit-mail",+ "featured": false,+ "feature_score": 0+ },+ {+ "slug": "serverkit-k8s",+ "display_name": "Kubernetes",+ "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",+ "version": "1.0.0",+ "category": "deployment",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "shell",+ "filesystem",+ "network"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-k8s/releases/download/v1.0.0/serverkit-k8s-1.0.0.zip",+ "sha256": "aa163f3c821a69cd7b41055407c9f2425998ff0d474957cfe5bb28b7f4547702",+ "repo": "https://github.com/jhd3197/serverkit-k8s",+ "homepage": "https://github.com/jhd3197/serverkit-k8s",+ "featured": false,+ "feature_score": 0+ },+ {+ "slug": "serverkit-tramo",+ "display_name": "Automations",+ "description": "Node-based automation builder powered by tramo. Design workflows on a visual canvas (triggers, actions, branches, loops, approval gates) that react to panel events or run on a schedule, with 21 brand integration packs (Telegram, GitHub, Gmail, Discord, Notion, Stripe, Cloudflare, Postgres, Twilio and more). Enabled workflows deploy to a managed tramo container on the panel host that runs them headless, with run history, approvals, and inbound webhooks proxied through the panel. This replaces the older drag-and-drop Workflow Builder.",+ "version": "1.0.0",+ "category": "deployment",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "docker",+ "shell",+ "filesystem",+ "network"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-tramo/releases/download/v1.0.0/serverkit-tramo-1.0.0.zip",+ "sha256": "1ee46b6db2be4e04add25ab7a705f4acd590a4358808c6c2035acb950fb03b0d",+ "repo": "https://github.com/jhd3197/serverkit-tramo",+ "homepage": "https://github.com/jhd3197/serverkit-tramo",+ "featured": true,+ "feature_score": 90+ },+ {+ "slug": "serverkit-analytics",+ "display_name": "Analytics",+ "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.",+ "version": "1.0.0",+ "category": "monitoring",+ "author": "ServerKit",+ "first_party": true,+ "bundled": false,+ "permissions": [+ "db",+ "network",+ "filesystem"+ ],+ "min_panel_version": "1.7.0",+ "max_panel_version": null,+ "source": "https://github.com/jhd3197/serverkit-analytics/releases/download/v1.0.0/serverkit-analytics-1.0.0.zip",+ "sha256": "9ed7a7dad6f78bca8da3abdb4f4279853ba0fe0c174e645b95d3594b70abc843",+ "repo": "https://github.com/jhd3197/serverkit-analytics",+ "homepage": "https://github.com/jhd3197/serverkit-analytics",+ "featured": true,+ "feature_score": 88},{"slug": "serverkit-faro",diff --git a/backend/app/plugins/serverkit-gpu/__init__.py b/backend/app/plugins/serverkit-gpu/__init__.pydeleted file mode 100644index 8234c5c7..00000000--- a/backend/app/plugins/serverkit-gpu/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""ServerKit GPU Monitor extension backend package."""diff --git a/backend/app/plugins/serverkit-gpu/gpu.py b/backend/app/plugins/serverkit-gpu/gpu.pydeleted file mode 100644index 9b88e12d..00000000--- a/backend/app/plugins/serverkit-gpu/gpu.py+++ /dev/null@@ -1,20 +0,0 @@-"""GPU Monitor API endpoints (serverkit-gpu extension).--Mounted under ``/api/v1/gpu`` via the manifest's ``entry_point`` + ``url_prefix``-(the same prefix the core route used, so the frontend is unchanged — decision D9).-Thin routing layer over :class:`GpuService`; read-only metrics, JWT-protected.-"""-from flask import Blueprint, jsonify-from flask_jwt_extended import jwt_required--from .gpu_service import GpuService--gpu_bp = Blueprint('gpu', __name__)---@gpu_bp.route('/', methods=['GET'])-@jwt_required()-def gpu_info():- """Per-GPU stats (utilization, VRAM, temperature, power, fan, driver) plus- the GPU compute processes, with best-effort container resolution."""- return jsonify(GpuService.info())diff --git a/backend/app/plugins/serverkit-gpu/gpu_service.py b/backend/app/plugins/serverkit-gpu/gpu_service.pydeleted file mode 100644index 342417d3..00000000--- a/backend/app/plugins/serverkit-gpu/gpu_service.py+++ /dev/null@@ -1,130 +0,0 @@-"""NVIDIA GPU monitoring (serverkit-gpu extension).--Moved out of core as the first CORE_SLIM slice (plan 32 #7). Shells out to-``nvidia-smi`` (like the rest of the service layer) and degrades gracefully to-"no GPUs" when it isn't present, so the panel stays happy on GPU-less hosts.-"""-import logging-import re-import subprocess--logger = logging.getLogger(__name__)--# (key, caster) in the same order as GPU_QUERY below.-GPU_FIELDS = [- ('index', int),- ('name', str),- ('utilization_gpu', float), # %- ('memory_used', float), # MiB- ('memory_total', float), # MiB- ('temperature', float), # C- ('power_draw', float), # W- ('power_limit', float), # W- ('fan_speed', float), # %- ('driver_version', str),-]-GPU_QUERY = ('index,name,utilization.gpu,memory.used,memory.total,'- 'temperature.gpu,power.draw,power.limit,fan.speed,driver_version')--_NA = ('', '[N/A]', 'N/A', '[Not Supported]', '[Unknown Error]')---class GpuService:-- @staticmethod- def _run(args, timeout=10):- return subprocess.run(['nvidia-smi', *args], capture_output=True, text=True, timeout=timeout)-- @staticmethod- def _coerce(value, caster):- v = value.strip()- if v in _NA:- return None- try:- return caster(v)- except (ValueError, TypeError):- return v if caster is str else None-- @classmethod- def available(cls):- try:- return cls._run(['--query-gpu=index', '--format=csv,noheader']).returncode == 0- except Exception:- return False-- @classmethod- def list_gpus(cls):- try:- result = cls._run([f'--query-gpu={GPU_QUERY}', '--format=csv,noheader,nounits'])- if result.returncode != 0:- return []- except Exception:- return []-- gpus = []- for line in result.stdout.strip().splitlines():- if not line.strip():- continue- parts = [p.strip() for p in line.split(',')]- if len(parts) < len(GPU_FIELDS):- continue- gpu = {key: cls._coerce(raw, caster)- for (key, caster), raw in zip(GPU_FIELDS, parts)}- if gpu.get('memory_total'):- gpu['memory_percent'] = round(100.0 * (gpu.get('memory_used') or 0) / gpu['memory_total'], 1)- gpus.append(gpu)- return gpus-- @classmethod- def _container_for_pid(cls, pid):- """Best-effort: resolve a host PID to a Docker container name via its- cgroup. Returns None when it can't be determined (or off Linux)."""- if not pid:- return None- try:- with open(f'/proc/{pid}/cgroup', 'r') as fh:- match = re.search(r'docker[-/]([0-9a-f]{64})', fh.read())- if not match:- return None- cid = match.group(1)[:12]- out = subprocess.run(['docker', 'inspect', '-f', '{{.Name}}', cid],- capture_output=True, text=True, timeout=5)- return out.stdout.strip().lstrip('/') if out.returncode == 0 else cid- except Exception:- return None-- @classmethod- def processes(cls):- try:- result = cls._run(['--query-compute-apps=gpu_uuid,pid,process_name,used_memory',- '--format=csv,noheader,nounits'])- if result.returncode != 0:- return []- except Exception:- return []-- procs = []- for line in result.stdout.strip().splitlines():- if not line.strip():- continue- parts = [p.strip() for p in line.split(',')]- if len(parts) < 4:- continue- pid = cls._coerce(parts[1], int)- procs.append({- 'gpu_uuid': parts[0],- 'pid': pid,- 'process_name': parts[2],- 'used_memory': cls._coerce(parts[3], float),- 'container': cls._container_for_pid(pid),- })- return procs-- @classmethod- def info(cls):- gpus = cls.list_gpus()- return {- 'available': bool(gpus),- 'gpus': gpus,- 'processes': cls.processes() if gpus else [],- }diff --git a/backend/app/plugins/serverkit-gpu/plugin.json b/backend/app/plugins/serverkit-gpu/plugin.jsondeleted file mode 100644index f18b30f4..00000000--- a/backend/app/plugins/serverkit-gpu/plugin.json+++ /dev/null@@ -1,47 +0,0 @@-{- "name": "serverkit-gpu",- "display_name": "GPU Monitor",- "version": "1.0.0",- "description": "Live NVIDIA GPU metrics covering utilization, memory, temperature, power and fan, for servers with a GPU.",- "author": "ServerKit",- "license": "MIT",- "category": "monitoring",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell"- ],- "min_panel_version": "1.7.0",- "sdk_version": "^1.0.0",- "entry_point": "gpu:gpu_bp",- "url_prefix": "/api/v1/gpu",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>",- "contributions": {- "nav": [- {- "id": "gpu",- "label": "GPU Monitor",- "route": "/gpu",- "category": "system",- "requiresCondition": "gpuAvailable",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>"- }- ],- "routes": [- {- "path": "gpu",- "component": "GpuMonitorPage"- }- ],- "page_titles": {- "/gpu": "GPU Monitor"- },- "command_palette": [- {- "label": "GPU Monitor",- "path": "/gpu",- "category": "Pages",- "keywords": "nvidia cuda metrics gpu"- }- ]- }-}\ No newline at end of filediff --git a/backend/app/plugins/serverkit-k8s/__init__.py b/backend/app/plugins/serverkit-k8s/__init__.pydeleted file mode 100644index c7cb3d27..00000000--- a/backend/app/plugins/serverkit-k8s/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-"""ServerKit Kubernetes extension backend package (kubectl engine)."""-from .k8s import k8s_bp--__all__ = ['k8s_bp']diff --git a/backend/app/plugins/serverkit-k8s/cluster_service.py b/backend/app/plugins/serverkit-k8s/cluster_service.pydeleted file mode 100644index d2ba464f..00000000--- a/backend/app/plugins/serverkit-k8s/cluster_service.py+++ /dev/null@@ -1,365 +0,0 @@-"""High-level operations for the serverkit-k8s extension.--This is the layer the blueprint calls. It owns:--- CRUD for saved cluster connections (:class:`K8sCluster` rows), including the- single-default invariant.-- ``test_connection`` -- probe ``kubectl version`` and cache the result on the row.-- Read helpers (nodes, namespaces, workloads, pods, logs, services, ingresses,- overview) that run ``kubectl get ... -o json`` and **normalize** the verbose- Kubernetes objects down to the small flat dicts the UI actually consumes.-- Mutations (scale, restart, delete, apply) as thin ``kubectl`` wrappers.--Nothing here trusts the cluster to stay reachable: every read that hits the-cluster is wrapped by the blueprint and surfaces a clean error rather than a-stack trace.-"""-import json-import logging-from datetime import datetime--from app import db--from .models import K8sCluster-from . import kubectl_service-from .kubectl_service import KubectlError--logger = logging.getLogger(__name__)---# ---------------------------------------------------------------------------# CRUD-# ---------------------------------------------------------------------------def list_clusters():- return [c.to_dict() for c in K8sCluster.query.order_by(K8sCluster.name.asc()).all()]---def get_cluster(cluster_id):- return K8sCluster.query.get(cluster_id)---def get_default_cluster():- return (K8sCluster.query.filter_by(is_default=True).first()- or K8sCluster.query.order_by(K8sCluster.id.asc()).first())---def create_cluster(name, kubeconfig, context=None, make_default=False):- name = (name or '').strip()- if not name:- raise ValueError('A cluster name is required.')- if not (kubeconfig or '').strip():- raise ValueError('A kubeconfig is required.')- if K8sCluster.query.filter_by(name=name).first():- raise ValueError(f'A cluster named "{name}" already exists.')-- cluster = K8sCluster(name=name, context=(context or None) or None)- cluster.set_kubeconfig(kubeconfig)-- # First cluster is default automatically; otherwise honor the flag.- if make_default or K8sCluster.query.count() == 0:- _clear_default()- cluster.is_default = True-- db.session.add(cluster)- db.session.commit()- return cluster---def update_cluster(cluster_id, name=None, kubeconfig=None, context=None):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- if name is not None:- name = name.strip()- if not name:- raise ValueError('A cluster name is required.')- existing = K8sCluster.query.filter_by(name=name).first()- if existing and existing.id != cluster.id:- raise ValueError(f'A cluster named "{name}" already exists.')- cluster.name = name- if kubeconfig is not None and kubeconfig.strip():- cluster.set_kubeconfig(kubeconfig)- if context is not None:- cluster.context = context.strip() or None- db.session.commit()- return cluster---def delete_cluster(cluster_id):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- was_default = cluster.is_default- db.session.delete(cluster)- db.session.commit()- # Promote another cluster to default if we removed the default one.- if was_default:- nxt = K8sCluster.query.order_by(K8sCluster.id.asc()).first()- if nxt:- nxt.is_default = True- db.session.commit()- return True---def set_default(cluster_id):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- _clear_default()- cluster.is_default = True- db.session.commit()- return cluster---def _clear_default():- for c in K8sCluster.query.filter_by(is_default=True).all():- c.is_default = False---# ---------------------------------------------------------------------------# Connectivity-# ---------------------------------------------------------------------------def test_connection(cluster):- """Probe the cluster and cache the result on the row. Never raises."""- result = {'ok': False, 'server_version': None, 'error': None}- try:- data = kubectl_service.run_json(cluster, ['version', '-o', 'json'], timeout=15)- server = (data or {}).get('serverVersion') or {}- version = server.get('gitVersion')- if not version:- raise KubectlError('cluster did not report a server version (unreachable?)')- result['ok'] = True- result['server_version'] = version- except KubectlError as e:- result['error'] = str(e)- except Exception as e: # noqa: BLE001 - defensive: never let a probe crash the request- result['error'] = str(e)-- cluster.last_reachable = result['ok']- cluster.last_status = json.dumps({'server_version': result['server_version'], 'error': result['error']})- cluster.last_checked_at = datetime.utcnow()- db.session.commit()- return result---# ---------------------------------------------------------------------------# Reads (normalized)-# ---------------------------------------------------------------------------def _items(cluster, args):- data = kubectl_service.run_json(cluster, args)- return (data or {}).get('items', []) or []---def _ns_args(namespace):- if namespace and namespace != 'all':- return ['-n', namespace]- return ['--all-namespaces']---def get_nodes(cluster):- out = []- for n in _items(cluster, ['get', 'nodes', '-o', 'json']):- meta = n.get('metadata', {})- status = n.get('status', {})- conditions = {c.get('type'): c.get('status') for c in status.get('conditions', [])}- ready = conditions.get('Ready') == 'True'- info = status.get('nodeInfo', {})- roles = [k.split('/', 1)[1] for k in meta.get('labels', {})- if k.startswith('node-role.kubernetes.io/')]- out.append({- 'name': meta.get('name'),- 'ready': ready,- 'roles': roles or ['worker'],- 'kubelet_version': info.get('kubeletVersion'),- 'os_image': info.get('osImage'),- 'kernel_version': info.get('kernelVersion'),- 'container_runtime': info.get('containerRuntimeVersion'),- 'cpu': status.get('capacity', {}).get('cpu'),- 'memory': status.get('capacity', {}).get('memory'),- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_namespaces(cluster):- out = []- for ns in _items(cluster, ['get', 'namespaces', '-o', 'json']):- meta = ns.get('metadata', {})- out.append({- 'name': meta.get('name'),- 'phase': ns.get('status', {}).get('phase'),- 'created_at': meta.get('creationTimestamp'),- })- return out---_WORKLOAD_KINDS = {- 'deployment': 'deployments',- 'statefulset': 'statefulsets',- 'daemonset': 'daemonsets',-}---def get_workloads(cluster, namespace='all', kind='deployment'):- resource = _WORKLOAD_KINDS.get(kind, 'deployments')- out = []- for w in _items(cluster, ['get', resource] + _ns_args(namespace) + ['-o', 'json']):- meta = w.get('metadata', {})- spec = w.get('spec', {})- status = w.get('status', {})- if resource == 'daemonsets':- desired = status.get('desiredNumberScheduled', 0)- ready = status.get('numberReady', 0)- else:- desired = spec.get('replicas', 0)- ready = status.get('readyReplicas', 0) or 0- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'kind': kind,- 'desired': desired,- 'ready': ready,- 'available': status.get('availableReplicas', ready) if resource != 'daemonsets' else status.get('numberAvailable', ready),- 'healthy': bool(desired) and ready == desired,- 'images': [c.get('image') for c in spec.get('template', {}).get('spec', {}).get('containers', [])],- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_pods(cluster, namespace='all'):- out = []- for p in _items(cluster, ['get', 'pods'] + _ns_args(namespace) + ['-o', 'json']):- meta = p.get('metadata', {})- status = p.get('status', {})- container_statuses = status.get('containerStatuses', []) or []- restarts = sum(cs.get('restartCount', 0) for cs in container_statuses)- ready_count = sum(1 for cs in container_statuses if cs.get('ready'))- total = len(container_statuses) or len(p.get('spec', {}).get('containers', []))- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'phase': status.get('phase'),- 'ready': f'{ready_count}/{total}',- 'restarts': restarts,- 'node': p.get('spec', {}).get('nodeName'),- 'pod_ip': status.get('podIP'),- 'containers': [c.get('name') for c in p.get('spec', {}).get('containers', [])],- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_pod_logs(cluster, namespace, pod, container=None, tail=200):- args = ['logs', pod, '-n', namespace, '--tail', str(int(tail))]- if container:- args += ['-c', container]- return kubectl_service.run(cluster, args, timeout=30)---def get_services(cluster, namespace='all'):- out = []- for s in _items(cluster, ['get', 'services'] + _ns_args(namespace) + ['-o', 'json']):- meta = s.get('metadata', {})- spec = s.get('spec', {})- ports = ['{}/{}'.format(p.get('port'), p.get('protocol', 'TCP')) for p in spec.get('ports', [])]- ingress = s.get('status', {}).get('loadBalancer', {}).get('ingress', []) or []- external = ', '.join(filter(None, [i.get('ip') or i.get('hostname') for i in ingress])) or None- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'type': spec.get('type'),- 'cluster_ip': spec.get('clusterIP'),- 'external_ip': external,- 'ports': ports,- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_ingresses(cluster, namespace='all'):- out = []- for ing in _items(cluster, ['get', 'ingresses'] + _ns_args(namespace) + ['-o', 'json']):- meta = ing.get('metadata', {})- spec = ing.get('spec', {})- hosts = [r.get('host') for r in spec.get('rules', []) if r.get('host')]- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'class': spec.get('ingressClassName'),- 'hosts': hosts,- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_overview(cluster):- """A compact dashboard payload. Best-effort; partial data on partial failure."""- overview = {- 'cluster': cluster.to_dict(),- 'reachable': False,- 'server_version': None,- 'counts': {'nodes': 0, 'nodes_ready': 0, 'namespaces': 0, 'pods': 0, 'pods_running': 0, 'deployments': 0},- 'error': None,- }- conn = test_connection(cluster)- overview['reachable'] = conn['ok']- overview['server_version'] = conn['server_version']- if not conn['ok']:- overview['error'] = conn['error']- return overview- try:- nodes = get_nodes(cluster)- namespaces = get_namespaces(cluster)- pods = get_pods(cluster, 'all')- deployments = get_workloads(cluster, 'all', 'deployment')- overview['counts'] = {- 'nodes': len(nodes),- 'nodes_ready': sum(1 for n in nodes if n['ready']),- 'namespaces': len(namespaces),- 'pods': len(pods),- 'pods_running': sum(1 for p in pods if p['phase'] == 'Running'),- 'deployments': len(deployments),- }- except KubectlError as e:- overview['error'] = str(e)- return overview---# ---------------------------------------------------------------------------# Mutations-# ---------------------------------------------------------------------------def scale_deployment(cluster, namespace, name, replicas):- replicas = int(replicas)- if replicas < 0:- raise ValueError('replicas must be >= 0')- kubectl_service.run(- cluster,- ['scale', 'deployment', name, '-n', namespace, f'--replicas={replicas}'],- )- return {'name': name, 'namespace': namespace, 'replicas': replicas}---def restart_deployment(cluster, namespace, name):- kubectl_service.run(cluster, ['rollout', 'restart', 'deployment', name, '-n', namespace])- return {'name': name, 'namespace': namespace, 'restarted': True}---_DELETABLE_KINDS = {'pod', 'deployment', 'statefulset', 'daemonset', 'service', 'ingress'}---def delete_resource(cluster, kind, name, namespace):- kind = (kind or '').lower()- if kind not in _DELETABLE_KINDS:- raise ValueError(f'Refusing to delete unsupported resource kind "{kind}".')- if not name or not namespace:- raise ValueError('name and namespace are required.')- kubectl_service.run(cluster, ['delete', kind, name, '-n', namespace])- return {'kind': kind, 'name': name, 'namespace': namespace, 'deleted': True}---def apply_manifest(cluster, manifest_text):- if not (manifest_text or '').strip():- raise ValueError('An empty manifest cannot be applied.')- out = kubectl_service.run(cluster, ['apply', '-f', '-'], input_text=manifest_text, timeout=60)- return {'output': out.strip()}diff --git a/backend/app/plugins/serverkit-k8s/k8s.py b/backend/app/plugins/serverkit-k8s/k8s.pydeleted file mode 100644index 7d67087d..00000000--- a/backend/app/plugins/serverkit-k8s/k8s.py+++ /dev/null@@ -1,277 +0,0 @@-"""Kubernetes API endpoints (serverkit-k8s extension).--Mounted under ``/api/v1/k8s`` via the manifest's ``url_prefix``. Thin routing-layer over :mod:`cluster_service` -- all kubectl work happens there. Reads need-viewer, mutations need admin (same split as the serverkit-mail and-serverkit-dns-server extensions).--Cluster CRUD works even when ``kubectl`` is absent so an operator can stage a-connection first; only routes that actually talk to a cluster are guarded by-``_kubectl_or_error`` (503 when the binary is missing).-"""-from flask import Blueprint, jsonify, request--from app.middleware.rbac import admin_required, viewer_required--from . import cluster_service-from . import kubectl_service-from .kubectl_service import KubectlError--k8s_bp = Blueprint('k8s', __name__)---def _kubectl_or_error():- if not kubectl_service.is_available():- return jsonify({- 'error': 'kubectl is not installed on the panel host. Install kubectl '- 'to talk to clusters.'- }), 503- return None---def _cluster_or_404(cluster_id):- return cluster_service.get_cluster(cluster_id)---def _kubectl_call(fn):- """Run a cluster read/mutation, converting KubectlError to a clean 502."""- try:- return jsonify(fn())- except KubectlError as e:- return jsonify({'error': str(e)}), 502- except ValueError as e:- return jsonify({'error': str(e)}), 400---# ---------------------------------------------------------------------------# Status + cluster CRUD (no kubectl required)-# ---------------------------------------------------------------------------@k8s_bp.route('/status', methods=['GET'])-@viewer_required-def status():- default = cluster_service.get_default_cluster()- return jsonify({- 'kubectl_available': kubectl_service.is_available(),- 'clusters': cluster_service.list_clusters(),- 'default_cluster_id': default.id if default else None,- })---@k8s_bp.route('/clusters', methods=['GET'])-@viewer_required-def list_clusters():- return jsonify({'clusters': cluster_service.list_clusters()})---@k8s_bp.route('/clusters', methods=['POST'])-@admin_required-def create_cluster():- data = request.get_json(silent=True) or {}- try:- cluster = cluster_service.create_cluster(- name=data.get('name'),- kubeconfig=data.get('kubeconfig'),- context=data.get('context'),- make_default=bool(data.get('make_default')),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(cluster.to_dict()), 201---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['GET'])-@viewer_required-def get_cluster(cluster_id):- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster.to_dict())---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['PUT'])-@admin_required-def update_cluster(cluster_id):- data = request.get_json(silent=True) or {}- try:- cluster = cluster_service.update_cluster(- cluster_id,- name=data.get('name'),- kubeconfig=data.get('kubeconfig'),- context=data.get('context'),- )- except ValueError as e:- code = 404 if 'not found' in str(e).lower() else 400- return jsonify({'error': str(e)}), code- return jsonify(cluster.to_dict())---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['DELETE'])-@admin_required-def delete_cluster(cluster_id):- try:- cluster_service.delete_cluster(cluster_id)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify({'deleted': True})---@k8s_bp.route('/clusters/<int:cluster_id>/default', methods=['POST'])-@admin_required-def set_default(cluster_id):- try:- cluster = cluster_service.set_default(cluster_id)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify(cluster.to_dict())---# ---------------------------------------------------------------------------# Cluster-talking routes (kubectl required)-# ---------------------------------------------------------------------------@k8s_bp.route('/clusters/<int:cluster_id>/test', methods=['POST'])-@viewer_required-def test_connection(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster_service.test_connection(cluster))---@k8s_bp.route('/clusters/<int:cluster_id>/overview', methods=['GET'])-@viewer_required-def overview(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster_service.get_overview(cluster))---def _read_route(cluster_id, fn_name):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- namespace = request.args.get('namespace', 'all')- fn = getattr(cluster_service, fn_name)- if fn_name in ('get_nodes', 'get_namespaces'):- return _kubectl_call(lambda: {'items': fn(cluster)})- return _kubectl_call(lambda: {'items': fn(cluster, namespace)})---@k8s_bp.route('/clusters/<int:cluster_id>/nodes', methods=['GET'])-@viewer_required-def nodes(cluster_id):- return _read_route(cluster_id, 'get_nodes')---@k8s_bp.route('/clusters/<int:cluster_id>/namespaces', methods=['GET'])-@viewer_required-def namespaces(cluster_id):- return _read_route(cluster_id, 'get_namespaces')---@k8s_bp.route('/clusters/<int:cluster_id>/pods', methods=['GET'])-@viewer_required-def pods(cluster_id):- return _read_route(cluster_id, 'get_pods')---@k8s_bp.route('/clusters/<int:cluster_id>/services', methods=['GET'])-@viewer_required-def services(cluster_id):- return _read_route(cluster_id, 'get_services')---@k8s_bp.route('/clusters/<int:cluster_id>/ingresses', methods=['GET'])-@viewer_required-def ingresses(cluster_id):- return _read_route(cluster_id, 'get_ingresses')---@k8s_bp.route('/clusters/<int:cluster_id>/workloads', methods=['GET'])-@viewer_required-def workloads(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- namespace = request.args.get('namespace', 'all')- kind = request.args.get('kind', 'deployment')- return _kubectl_call(lambda: {'items': cluster_service.get_workloads(cluster, namespace, kind)})---@k8s_bp.route('/clusters/<int:cluster_id>/pods/<namespace>/<pod>/logs', methods=['GET'])-@viewer_required-def pod_logs(cluster_id, namespace, pod):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- container = request.args.get('container')- tail = request.args.get('tail', 200)- return _kubectl_call(lambda: {'logs': cluster_service.get_pod_logs(cluster, namespace, pod, container, tail)})---# ---------------------------------------------------------------------------# Mutations (admin + kubectl required)-# ---------------------------------------------------------------------------def _mutation_setup(cluster_id):- guard = _kubectl_or_error()- if guard:- return None, guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return None, (jsonify({'error': 'Cluster not found'}), 404)- return cluster, None---@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/scale', methods=['POST'])-@admin_required-def scale(cluster_id, namespace, name):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.scale_deployment(cluster, namespace, name, data.get('replicas', 0)))---@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/restart', methods=['POST'])-@admin_required-def restart(cluster_id, namespace, name):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- return _kubectl_call(lambda: cluster_service.restart_deployment(cluster, namespace, name))---@k8s_bp.route('/clusters/<int:cluster_id>/delete-resource', methods=['POST'])-@admin_required-def delete_resource(cluster_id):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.delete_resource(- cluster, data.get('kind'), data.get('name'), data.get('namespace')))---@k8s_bp.route('/clusters/<int:cluster_id>/apply', methods=['POST'])-@admin_required-def apply(cluster_id):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.apply_manifest(cluster, data.get('manifest')))diff --git a/backend/app/plugins/serverkit-k8s/kubectl_service.py b/backend/app/plugins/serverkit-k8s/kubectl_service.pydeleted file mode 100644index 5824a40e..00000000--- a/backend/app/plugins/serverkit-k8s/kubectl_service.py+++ /dev/null@@ -1,127 +0,0 @@-"""Low-level ``kubectl`` engine for the serverkit-k8s extension.--Every cluster operation runs the real ``kubectl`` binary against a per-cluster-kubeconfig that we materialize to a private temp file for the duration of one-call and delete immediately after (never left on disk between calls). This keeps-the panel host free of any standing cluster credentials.--Nothing here is Linux-specific -- ``kubectl`` runs on any OS -- so the extension-is not platform-gated. The temp-file ``chmod 0600`` is guarded with-``os.name != 'nt'`` per the repo's platform rule.-"""-import json-import logging-import os-import subprocess-import tempfile--logger = logging.getLogger(__name__)--KUBECTL_BIN = 'kubectl'-DEFAULT_TIMEOUT = 30---class KubectlError(RuntimeError):- """Raised when a kubectl invocation fails (non-zero exit)."""-- def __init__(self, message, returncode=None, stderr=None):- super().__init__(message)- self.returncode = returncode- self.stderr = stderr---def is_available():- """Return True if the ``kubectl`` binary is on the host."""- try:- from app.utils.system import is_command_available- return is_command_available(KUBECTL_BIN)- except Exception: # pragma: no cover - fall back to a direct probe- from shutil import which- return which(KUBECTL_BIN) is not None---def _write_kubeconfig(kubeconfig_text):- """Write *kubeconfig_text* to a private temp file and return its path."""- fd, path = tempfile.mkstemp(prefix='sk8s-', suffix='.yaml')- try:- with os.fdopen(fd, 'w', encoding='utf-8') as fh:- fh.write(kubeconfig_text or '')- if os.name != 'nt':- os.chmod(path, 0o600)- except Exception:- _safe_unlink(path)- raise- return path---def _safe_unlink(path):- try:- if path and os.path.exists(path):- os.unlink(path)- except OSError as e: # pragma: no cover - best effort cleanup- logger.warning('serverkit-k8s: could not remove temp kubeconfig %s: %s', path, e)---def build_argv(cluster, args):- """Return the full ``kubectl`` argv for *args* against *cluster*.-- Separated out so tests can assert on argv construction without running the- binary. The ``--kubeconfig`` path is appended by :func:`run` since it is only- known once the temp file is written.- """- argv = [KUBECTL_BIN]- if getattr(cluster, 'context', None):- argv += ['--context', cluster.context]- return argv + list(args)---def run(cluster, args, timeout=DEFAULT_TIMEOUT, input_text=None):- """Run ``kubectl <args>`` against *cluster* and return stdout as a string.-- Raises :class:`KubectlError` on a non-zero exit or missing binary.- """- if not is_available():- raise KubectlError('kubectl is not installed on the panel host.')-- kubeconfig_text = cluster.get_kubeconfig() if hasattr(cluster, 'get_kubeconfig') else cluster- path = _write_kubeconfig(kubeconfig_text)- try:- argv = build_argv(cluster, args)- argv += ['--kubeconfig', path]- try:- result = subprocess.run(- argv,- capture_output=True,- text=True,- timeout=timeout,- input=input_text,- )- except subprocess.TimeoutExpired as e:- raise KubectlError(f'kubectl timed out after {timeout}s') from e- except (OSError, subprocess.SubprocessError) as e:- raise KubectlError(f'kubectl could not be executed: {e}') from e-- if result.returncode != 0:- stderr = (result.stderr or '').strip()- raise KubectlError(- stderr or f'kubectl exited with code {result.returncode}',- returncode=result.returncode,- stderr=stderr,- )- return result.stdout or ''- finally:- _safe_unlink(path)---def run_json(cluster, args, timeout=DEFAULT_TIMEOUT):- """Run a kubectl command that emits JSON and return the parsed object.-- The caller is expected to include ``-o json`` (or a get with it) in *args*.- """- out = run(cluster, args, timeout=timeout)- if not out.strip():- return {}- try:- return json.loads(out)- except ValueError as e:- raise KubectlError(f'kubectl returned unparseable JSON: {e}') from ediff --git a/backend/app/plugins/serverkit-k8s/lifecycle.py b/backend/app/plugins/serverkit-k8s/lifecycle.pydeleted file mode 100644index c999df1d..00000000--- a/backend/app/plugins/serverkit-k8s/lifecycle.py+++ /dev/null@@ -1,32 +0,0 @@-"""Install / uninstall lifecycle hooks (serverkit-k8s extension).--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.--There is no engine to provision: the extension only talks to *remote* clusters-through kubectl, so install just registers a notification event and uninstall is-a no-op (the ``ext_serverkit_k8s_*`` table is dropped by the platform on-``--purge``).-"""-import logging--logger = logging.getLogger(__name__)---def on_install(plugin):- """Register the extension's notification events. Best-effort."""- try:- from app.plugins_sdk import notify- notify.register_event(- 'k8s.cluster_unreachable',- 'A Kubernetes cluster became unreachable',- template='generic', severity='warning', category='system')- logger.info('serverkit-k8s installed: notification events registered')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-k8s on_install hook error: %s', e)---def on_uninstall(plugin, purge=False):- """Nothing to tear down -- clusters are remote and hold no local resources."""- logger.info('serverkit-k8s on_uninstall (purge=%s): no local resources to remove', purge)diff --git a/backend/app/plugins/serverkit-k8s/models.py b/backend/app/plugins/serverkit-k8s/models.pydeleted file mode 100644index 80a7741a..00000000--- a/backend/app/plugins/serverkit-k8s/models.py+++ /dev/null@@ -1,101 +0,0 @@-"""Data models for the serverkit-k8s extension.--A :class:`K8sCluster` row is a saved *connection* to an external Kubernetes-cluster: a friendly name, the cluster's **kubeconfig** (stored encrypted with the-panel key), an optional context to select within that kubeconfig, a default flag,-and a small cache of the last reachability probe so the Overview can render-without blocking on a live ``kubectl`` call.--The panel host is never assumed to be a cluster member. All cluster access goes-through ``kubectl --kubeconfig <the decrypted blob>`` (see ``kubectl_service``),-so the only secret we hold is the kubeconfig, and it is **never** returned by-:meth:`K8sCluster.to_dict`.--Tables are namespaced ``ext_serverkit_k8s_*`` (dash -> underscore) per the-extension convention, so ``--purge`` on uninstall drops exactly these.--Registration: importing this module defines the table on the shared metadata as-a side effect; the manifest's ``models: "models:register"`` then calls-:func:`register` (a no-op passthrough) and the platform runs ``db.create_all()``.-"""-import json-from datetime import datetime--from app import db--try:- from app.utils.crypto import encrypt_secret, decrypt_secret_safe-except Exception: # pragma: no cover - crypto util should always be present- encrypt_secret = None- decrypt_secret_safe = None---class K8sCluster(db.Model):- __tablename__ = 'ext_serverkit_k8s_clusters'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), unique=True, nullable=False, index=True)-- # Encrypted kubeconfig YAML. Read/written only through the helpers below so- # the plaintext never lands in a column or a log line.- kubeconfig_encrypted = db.Column(db.Text, nullable=False)-- # Optional context to select inside the kubeconfig (kubectl --context).- context = db.Column(db.String(255), nullable=True)-- is_default = db.Column(db.Boolean, default=False, nullable=False)-- # Cached result of the last reachability probe (test_connection).- last_reachable = db.Column(db.Boolean, nullable=True)- last_status = db.Column(db.Text, nullable=True) # JSON: {server_version, error}- last_checked_at = db.Column(db.DateTime, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- # --- secret helpers -------------------------------------------------- def set_kubeconfig(self, plaintext):- """Encrypt and store a kubeconfig YAML string."""- if encrypt_secret is None:- # No key configured: store as-is so dev boxes still work. Encryption- # is expected in any real deployment.- self.kubeconfig_encrypted = plaintext or ''- else:- self.kubeconfig_encrypted = encrypt_secret(plaintext or '')-- def get_kubeconfig(self):- """Return the decrypted kubeconfig YAML string."""- if not self.kubeconfig_encrypted:- return ''- if decrypt_secret_safe is None:- return self.kubeconfig_encrypted- return decrypt_secret_safe(self.kubeconfig_encrypted)-- # --- serialization --------------------------------------------------- def to_dict(self):- status = None- if self.last_status:- try:- status = json.loads(self.last_status)- except (ValueError, TypeError):- status = None- return {- 'id': self.id,- 'name': self.name,- 'context': self.context,- 'is_default': self.is_default,- 'last_reachable': self.last_reachable,- 'status': status,- 'last_checked_at': self.last_checked_at.isoformat() if self.last_checked_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }---def register(db): # noqa: A002 - signature dictated by the platform (fn(db))- """No-op passthrough required by the manifest ``models: "models:register"``.-- Importing this module already defined the table on ``db.metadata``; the- platform creates it. Nothing else to do here.- """- return [K8sCluster]diff --git a/backend/app/plugins/serverkit-k8s/plugin.json b/backend/app/plugins/serverkit-k8s/plugin.jsondeleted file mode 100644index 3450ea1c..00000000--- a/backend/app/plugins/serverkit-k8s/plugin.json+++ /dev/null@@ -1,56 +0,0 @@-{- "name": "serverkit-k8s",- "display_name": "Kubernetes",- "version": "1.0.0",- "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell",- "filesystem",- "network"- ],- "min_panel_version": "1.7.0",- "entry_point": "k8s:k8s_bp",- "url_prefix": "/api/v1/k8s",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>",- "contributions": {- "nav": [- {- "id": "k8s",- "label": "Kubernetes",- "route": "/k8s",- "category": "infrastructure",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>"- }- ],- "routes": [- {- "path": "k8s",- "component": "K8sPage"- },- {- "path": "k8s/:tab",- "component": "K8sPage"- }- ],- "page_titles": {- "/k8s": "Kubernetes"- },- "command_palette": [- {- "label": "Kubernetes",- "path": "/k8s",- "category": "Pages",- "keywords": "k8s kubernetes kubectl cluster node namespace pod deployment workload statefulset daemonset service ingress scale restart apply kubeconfig"- }- ]- }-}\ No newline at end of filediff --git a/backend/app/plugins/serverkit-tramo/__init__.py b/backend/app/plugins/serverkit-tramo/__init__.pydeleted file mode 100644index b86d1323..00000000--- a/backend/app/plugins/serverkit-tramo/__init__.py+++ /dev/null@@ -1,10 +0,0 @@-"""ServerKit Automations extension backend package (tramo engine).--Embeds tramo (github.com/jhd3197/tramo) as the panel's workflow-automation-surface. The panel is the system of record for workflow docs; a managed-``@tramo/server`` Docker container on the panel host is the executor. See-docs/plans/45_TRAMO_AUTOMATIONS_EXTENSION_PLAN.md.-"""-from .tramo import tramo_bp--__all__ = ['tramo_bp']diff --git a/backend/app/plugins/serverkit-tramo/events_bridge.py b/backend/app/plugins/serverkit-tramo/events_bridge.pydeleted file mode 100644index 1bb35df2..00000000--- a/backend/app/plugins/serverkit-tramo/events_bridge.py+++ /dev/null@@ -1,166 +0,0 @@-"""Panel <-> tramo wiring (serverkit-tramo / Automations extension, plan 45 Phase 3).--Two integrations that let panel automations reach the outside world and act back-on the panel:--* **Events bridge** — one managed :class:`EventSubscription` whose ``url`` points- at the container's ``serverkit:event`` webhook trigger (``/sk/events`` via the- hooks passthrough). Subscribing to ``["*"]`` means every panel event is POSTed- to tramo; workflows filter with ``if``/``switch`` on ``trigger.body.event``.- Toggled on/off from the Settings tab; its id is remembered in plugin config.--* **Call-back key** — a scoped :class:`ApiKey` named ``serverkit-tramo`` issued- on engine install and injected into the container as ``SERVERKIT_API_KEY`` so- the ``@tramo/serverkit`` pack can start/stop/deploy apps, run backups, and send- notifications. Revoked on uninstall.--All helpers are best-effort and never raise into install/uninstall.-"""-import logging--from app import db--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Scopes the call-back key is granted. Matches the @tramo/serverkit pack actions:-# app-control/deploy (apps:*), backup-run (backups:write), list/get (read).-CALLBACK_KEY_NAME = 'serverkit-tramo'-CALLBACK_SCOPES = ['read', 'apps:read', 'apps:write', 'apps:deploy', 'backups:write']--# The path (under the hooks passthrough) the managed subscription targets, and-# which the container maps to a serverkit:event webhook-trigger node.-EVENTS_TRIGGER_PATH = 'sk/events'---def _config():- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)---def _save_config(updates):- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True---def _admin_user_id():- """Owner for the managed ApiKey / EventSubscription (first admin, else any)."""- from app.models.user import User- admin = User.query.filter_by(role=User.ROLE_ADMIN).order_by(User.id).first()- if admin:- return admin.id- any_user = User.query.order_by(User.id).first()- return any_user.id if any_user else None---# --------------------------------------------------------------------------- #-# Call-back key-# --------------------------------------------------------------------------- #--def issue_callback_key():- """Issue (or reissue) the scoped ``serverkit-tramo`` ApiKey.-- Returns the RAW key string (only available at creation) or None on failure.- The key id is stored in plugin config for later revocation.- """- from app.models.api_key import ApiKey-- user_id = _admin_user_id()- if not user_id:- logger.warning('tramo: no user to own the call-back API key')- return None-- # Revoke any previous managed key first (rotate).- revoke_callback_key()-- raw, prefix, key_hash = ApiKey.generate_key()- key = ApiKey(- user_id=user_id,- name=CALLBACK_KEY_NAME,- key_prefix=prefix,- key_hash=key_hash,- )- key.set_scopes(CALLBACK_SCOPES)- db.session.add(key)- db.session.commit()- _save_config({'callback_key_id': key.id})- return raw---def revoke_callback_key():- """Revoke the managed call-back ApiKey (best-effort)."""- from datetime import datetime- from app.models.api_key import ApiKey-- key_id = _config().get('callback_key_id')- if not key_id:- return False- key = ApiKey.query.get(key_id)- if key:- key.is_active = False- key.revoked_at = datetime.utcnow()- db.session.commit()- _save_config({'callback_key_id': None})- return True---# --------------------------------------------------------------------------- #-# Events bridge-# --------------------------------------------------------------------------- #--def is_events_bridge_enabled():- return bool(_config().get('events_subscription_id'))---def enable_events_bridge():- """Create the managed EventSubscription (idempotent). Returns its id or None."""- from app.models.event_subscription import EventSubscription-- existing_id = _config().get('events_subscription_id')- if existing_id and EventSubscription.query.get(existing_id):- return existing_id-- user_id = _admin_user_id()- if not user_id:- logger.warning('tramo: no user to own the events subscription')- return None-- from .host_service import TramoHostService- port = TramoHostService.host_port()- secret = EventSubscription.generate_secret()-- sub = EventSubscription(- user_id=user_id,- name='Automations (tramo) events bridge',- url=f'http://127.0.0.1:{port}/{EVENTS_TRIGGER_PATH}',- secret=secret,- is_active=True,- )- sub.set_events(['*'])- db.session.add(sub)- db.session.commit()- _save_config({'events_subscription_id': sub.id, 'events_secret': secret})- return sub.id---def disable_events_bridge():- """Delete the managed EventSubscription (best-effort). Returns True if removed."""- from app.models.event_subscription import EventSubscription-- sub_id = _config().get('events_subscription_id')- if not sub_id:- return False- sub = EventSubscription.query.get(sub_id)- if sub:- db.session.delete(sub)- db.session.commit()- _save_config({'events_subscription_id': None, 'events_secret': None})- return Truediff --git a/backend/app/plugins/serverkit-tramo/host_service.py b/backend/app/plugins/serverkit-tramo/host_service.pydeleted file mode 100644index a1f38e66..00000000--- a/backend/app/plugins/serverkit-tramo/host_service.py+++ /dev/null@@ -1,423 +0,0 @@-"""tramo engine host service (serverkit-tramo / Automations extension).--Runs ``@tramo/server`` (the headless tramo workflow host) in a managed Docker-container so the panel host can execute automation workflows: webhooks, cron,-run history, approvals. Driven through tramo's HTTP API, published on loopback-only.--Design mirrors serverkit-mail's :class:`StalwartService` exactly:--* **Two choke-points** — every Docker invocation goes through :meth:`_docker`- (privilege escalation, timeouts, error shaping) and every tramo-API call goes- through :meth:`_api` (Bearer auth, JSON, error shaping). Nothing else shells- out or talks HTTP.-* **Best-effort, Linux-only** — on Windows (dev) or when Docker is absent, calls- return a clean error dict instead of raising.-* **Panel DB is the source of truth** — workflow docs live in- ``ext_serverkit_tramo_*``; :mod:`workflow_store` materializes enabled docs into- the bind-mounted workflows dir and this service restarts the container.-* **Secrets in the config store** — the generated Bearer API key, the container- ``host_port``, an encrypted map of pack credentials (TELEGRAM_BOT_TOKEN, ...),- and the scoped panel call-back key all live in the plugin config store- (``plugins_sdk.config`` + the ``_save_config`` pattern), encrypted at rest.--The container is a *stateless executor*: it reads workflow ``.json`` files once-at boot (no server-side editing) and keeps run history in an in-memory ring, so-the panel harvests runs (see jobs) and re-deploys by restarting the container.-"""-import logging-import os-import secrets-import subprocess--import requests--from app.utils.system import run_privileged, is_command_available--try:- from app.utils.crypto import encrypt_secret, decrypt_secret_safe-except Exception: # pragma: no cover - crypto util should always be present- encrypt_secret = None- decrypt_secret_safe = None--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Pinned tramo-server image (GHCR, full-pack entry). Bumped deliberately like the-# Stalwart image, not floated. Published by the tramo repo's docker CI (plan 45-# Phase 0); until that ships this tag will not pull on a real box.-IMAGE = 'ghcr.io/jhd3197/tramo-server:0.1.1'-CONTAINER_NAME = 'serverkit-tramo'--# Host data dirs (bind-mounted). workflows/ holds the materialized <slug>.json-# docs; state/ is tramo's durable checkpoint store (suspend/resume survives a-# restart, so re-deploy = restart is safe).-DATA_DIR = '/var/serverkit/tramo'-HOST_WORKFLOWS_DIR = f'{DATA_DIR}/workflows'-HOST_STATE_DIR = f'{DATA_DIR}/state'-CONTAINER_WORKFLOWS_DIR = '/workflows'-CONTAINER_STATE_DIR = '/state'-CONTAINER_PORT = 3000--# tramo HTTP API — published on 127.0.0.1 only, never reachable off-host.-API_HOST = '127.0.0.1'-DEFAULT_HOST_PORT = 8377-API_TIMEOUT = 15-RUN_TIMEOUT = 120-DOCKER_TIMEOUT = 180--DOCS_URL = 'https://github.com/jhd3197/tramo'---class TramoHostService:- """Stateless wrapper around Docker + the tramo-server HTTP API."""-- # ---------- config (plugin config store) ------------ @classmethod- def _config(cls):- """Saved extension settings from the plugin config store."""- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)-- @classmethod- def _save_config(cls, updates):- """Merge *updates* into the plugin's stored config.-- The SDK ``config()`` helper is read-only (the panel owns writes), so- generated secrets are persisted through the InstalledPlugin row directly.- Returns False when the plugin row is absent (dev shells / tests without a- row).- """- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- logger.warning('%s: no InstalledPlugin row; config not persisted', SLUG)- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True-- # ---------- secret helpers ------------ @classmethod- def _encrypt(cls, plaintext):- if not plaintext:- return plaintext- if encrypt_secret is None:- return plaintext- return encrypt_secret(plaintext)-- @classmethod- def _decrypt(cls, value):- if not value:- return value- if decrypt_secret_safe is None:- return value- return decrypt_secret_safe(value)-- @classmethod- def _is_windows(cls):- """Windows (dev) has no Docker engine for us. Single testable seam so- tests can force either platform without touching the global ``os.name``- (which would break ``pathlib``)."""- return os.name == 'nt'-- @classmethod- def host_port(cls):- """Loopback host port the container's API is published on."""- try:- return int(cls._config().get('host_port') or DEFAULT_HOST_PORT)- except (TypeError, ValueError):- return DEFAULT_HOST_PORT-- @classmethod- def api_base(cls):- return f'http://{API_HOST}:{cls.host_port()}/api'-- @classmethod- def api_key(cls):- """Decrypted Bearer API key (empty string when not installed)."""- return cls._decrypt(cls._config().get('api_key')) or ''-- @classmethod- def get_pack_secrets(cls):- """Decrypted {ENV_NAME: value} map of pack credentials."""- stored = cls._config().get('pack_secrets') or {}- out = {}- for k, v in stored.items():- out[k] = cls._decrypt(v)- return out-- @classmethod- def set_pack_secrets(cls, secrets_map):- """Encrypt and persist a {ENV_NAME: value} map. Empty value deletes a key.-- Returns the new set of configured env-var names (values never returned).- """- current = dict(cls._config().get('pack_secrets') or {})- for name, value in (secrets_map or {}).items():- name = (name or '').strip()- if not name:- continue- if value in (None, ''):- current.pop(name, None)- else:- current[name] = cls._encrypt(str(value))- cls._save_config({'pack_secrets': current})- return sorted(current.keys())-- # ---------- docker choke-point ------------ @classmethod- def _docker(cls, args, timeout=DOCKER_TIMEOUT):- """Run ``docker <args>`` and return a normalized result dict. Never raises."""- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- if not is_command_available('docker'):- return {'success': False, 'not_installed': True,- 'error': 'Docker is not installed on this host.'}- cmd = ['docker'] + list(args)- try:- result = run_privileged(cmd, timeout=timeout)- except subprocess.TimeoutExpired:- return {'success': False, 'error': f'docker timed out after {timeout}s'}- except (OSError, subprocess.SubprocessError) as e:- return {'success': False, 'error': f'Failed to run docker: {e}'}- out = {- 'success': result.returncode == 0,- 'returncode': result.returncode,- 'stdout': result.stdout or '',- 'stderr': result.stderr or '',- }- if not out['success']:- out['error'] = (out['stderr'] or out['stdout'] or 'docker failed').strip()- return out-- # ---------- tramo API choke-point ------------ @classmethod- def _api(cls, method, path, payload=None, timeout=API_TIMEOUT):- """Call the container's tramo HTTP API (loopback only).-- Returns ``{'success': True, 'data': <json-or-None>, 'status_code': int}``- or an error dict. Auth is Bearer with the generated API key. Never raises.- """- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- key = cls.api_key()- if not key:- return {'success': False,- 'error': 'tramo API key is not configured. Reinstall the engine.'}- headers = {'Authorization': f'Bearer {key}'}- try:- resp = requests.request(- method, cls.api_base() + path,- headers=headers, json=payload, timeout=timeout,- )- except requests.RequestException as e:- return {'success': False,- 'error': f'tramo API is unreachable: {e}'}- result = {'success': resp.status_code < 400, 'status_code': resp.status_code}- if resp.status_code >= 400:- try:- body = resp.json()- detail = (body.get('error') or body.get('message')- or body.get('detail') or resp.text)- except ValueError:- detail = resp.text- result['error'] = f'tramo API error ({resp.status_code}): {detail}'.strip()- return result- if not resp.content:- result['data'] = None- return result- try:- result['data'] = resp.json()- except ValueError:- result['data'] = resp.text- return result-- # ---------- container lifecycle ------------ @classmethod- def is_installed(cls):- """True when the managed container exists (running or not)."""- if cls._is_windows():- return False- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- return bool(res.get('success'))-- @classmethod- def _panel_port(cls):- """Port the panel API listens on (for the container's call-back URL)."""- return str(cls._config().get('panel_port')- or os.environ.get('PORT') or '5000')-- @classmethod- def get_status(cls):- """Installed / running / health summary, best-effort."""- status = {- 'installed': False,- 'running': False,- 'healthy': None,- 'state': 'not_installed', # not_installed|stopped|unhealthy|ready- 'engine': 'tramo',- 'image': IMAGE,- 'container': CONTAINER_NAME,- 'host_port': cls.host_port(),- 'api': f'{API_HOST}:{cls.host_port()}',- 'docs_url': DOCS_URL,- }- if cls._is_windows():- status['error'] = 'The Automations extension is not supported on Windows.'- return status- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- if not res.get('success'):- return status- status['installed'] = True- running = res.get('stdout', '').strip() == 'true'- status['running'] = running- if not running:- status['state'] = 'stopped'- return status- # Running: probe health to distinguish ready from starting/unhealthy.- probe = cls._api('GET', '/health', timeout=8)- if probe.get('success'):- status['healthy'] = True- status['state'] = 'ready'- data = probe.get('data')- if isinstance(data, dict):- status['version'] = data.get('version')- else:- status['healthy'] = False- status['state'] = 'unhealthy'- status['health_error'] = probe.get('error')- return status-- @classmethod- def health(cls):- """Raw health probe (GET /api/health). Best-effort dict."""- if not cls.is_installed():- return {'success': False, 'error': 'The Automations engine is not installed.'}- return cls._api('GET', '/health', timeout=8)-- @classmethod- def install(cls, host_port=None, callback_url=None, callback_api_key=None):- """Create and start the tramo-server container.-- * Workflows + checkpoint state bind-mounted under ``DATA_DIR``.- * HTTP API published on **127.0.0.1 only** with a generated Bearer key.- * Pack credentials + the scoped panel call-back key (SERVERKIT_URL /- SERVERKIT_API_KEY) injected as container env.- """- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- if cls.is_installed():- return {'success': False,- 'error': 'The Automations container already exists. Uninstall it first.'}-- port = int(host_port or cls.host_port())-- dir_res = run_privileged(['mkdir', '-p', HOST_WORKFLOWS_DIR, HOST_STATE_DIR])- if getattr(dir_res, 'returncode', 1) != 0:- return {'success': False,- 'error': f'Could not create data directory {DATA_DIR}: '- f'{(getattr(dir_res, "stderr", "") or "").strip()}'}-- api_key = secrets.token_urlsafe(32)-- run_args = cls._build_run_args(port, api_key, callback_url, callback_api_key)- res = cls._docker(run_args)- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to start the tramo container')}-- persisted = cls._save_config({- 'api_key': cls._encrypt(api_key),- 'host_port': port,- 'panel_port': cls._panel_port(),- })- result = {'success': True,- 'message': 'Automations engine installed',- 'container': CONTAINER_NAME,- 'host_port': port,- 'state': 'ready'}- if not persisted:- result['warning'] = ('Container started but the API key could not be '- 'persisted to the plugin config store.')- return result-- @classmethod- def _build_run_args(cls, port, api_key, callback_url=None, callback_api_key=None):- """Assemble the ``docker run`` argv. Split out so tests can assert it."""- run_args = [- 'run', '-d',- '--name', CONTAINER_NAME,- '--restart', 'unless-stopped',- # Let workflows call back to the panel on the host loopback.- '--add-host', 'host.docker.internal:host-gateway',- ]- # API published on 127.0.0.1 only.- run_args += ['-p', f'{API_HOST}:{port}:{CONTAINER_PORT}']- run_args += [- '-v', f'{HOST_WORKFLOWS_DIR}:{CONTAINER_WORKFLOWS_DIR}',- '-v', f'{HOST_STATE_DIR}:{CONTAINER_STATE_DIR}',- ]- # Bearer auth + load all first-party integration packs (full-pack entry).- run_args += ['-e', f'TRAMO_API_KEY={api_key}']- run_args += ['-e', 'TRAMO_PACKS=all']- # Panel call-back (SERVERKIT_URL/SERVERKIT_API_KEY consumed by the- # @tramo/serverkit pack via env fallback).- url = callback_url or f'http://host.docker.internal:{cls._panel_port()}'- run_args += ['-e', f'SERVERKIT_URL={url}']- if callback_api_key:- run_args += ['-e', f'SERVERKIT_API_KEY={callback_api_key}']- # Pack credentials (decrypted from the config store).- for name, value in cls.get_pack_secrets().items():- run_args += ['-e', f'{name}={value}']- run_args += [IMAGE]- return run_args-- @classmethod- def uninstall(cls, keep_data=True):- """Remove the container; optionally delete the data directory."""- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- res = cls._docker(['rm', '-f', CONTAINER_NAME])- if not res.get('success'):- # A missing container is not an error for uninstall.- if 'No such container' not in (res.get('error') or ''):- return {'success': False,- 'error': res.get('error', 'Failed to remove the tramo container')}- if not keep_data:- rm = run_privileged(['rm', '-rf', DATA_DIR])- if getattr(rm, 'returncode', 1) != 0:- return {'success': True,- 'warning': f'Container removed but data at {DATA_DIR} could '- f'not be deleted: {(getattr(rm, "stderr", "") or "").strip()}'}- cls._save_config({'api_key': None})- return {'success': True,- 'message': 'Automations engine removed'- + ('' if keep_data else ' (data deleted)')}-- @classmethod- def control(cls, action):- """Start / stop / restart the managed container."""- if action not in ('start', 'stop', 'restart'):- return {'success': False, 'error': f'Invalid action: {action!r}'}- if not cls.is_installed():- return {'success': False, 'error': 'The Automations engine is not installed.'}- res = cls._docker([action, CONTAINER_NAME], timeout=60)- if not res.get('success'):- return {'success': False, 'error': res.get('error', f'docker {action} failed')}- return {'success': True, 'message': f'Automations engine {action}ed', 'action': action}diff --git a/backend/app/plugins/serverkit-tramo/jobs.py b/backend/app/plugins/serverkit-tramo/jobs.pydeleted file mode 100644index cd152d5d..00000000--- a/backend/app/plugins/serverkit-tramo/jobs.py+++ /dev/null@@ -1,126 +0,0 @@-"""Background job handlers (serverkit-tramo / Automations 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).--* ``tramo.harvest_runs`` (:func:`harvest_runs`) -- pull recent runs from the- engine and upsert them into ``ext_serverkit_tramo_runs`` before the container's- in-memory ring evicts them; notify admins once per newly-seen failed run.-* ``tramo.health_check`` (:func:`health_check`) -- probe ``GET /api/health`` and- notify ``tramo.host_unreachable`` after repeated failures.-"""-import logging--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Consecutive health failures before we notify (avoids flapping on a restart).-_HEALTH_FAIL_THRESHOLD = 2---def harvest_runs(job):- """Harvest recent runs from the engine into the DB. Never raises."""- try:- from .host_service import TramoHostService- from .run_sync import upsert_run-- if not TramoHostService.is_installed():- return {'skipped': True, 'reason': 'engine not installed'}-- res = TramoHostService._api('GET', '/runs?limit=200')- if not res.get('success'):- return {'skipped': True, 'reason': res.get('error', 'runs fetch failed')}-- data = res.get('data')- runs = data if isinstance(data, list) else (data or {}).get('runs') \- or (data or {}).get('items') or []-- harvested = 0- new_failures = 0- for run_json in runs:- row, is_new = upsert_run(run_json)- if row is None:- continue- harvested += 1- if is_new and (row.status or '').lower() in ('failed', 'error'):- _notify_run_failed(row)- new_failures += 1-- return {'harvested': harvested, 'new_failures': new_failures}- except Exception as e: # noqa: BLE001 -- a maintenance job must not crash the loop- logger.warning('tramo harvest_runs job failed: %s', e)- return {'error': str(e)}---def _notify_run_failed(row):- try:- from app.plugins_sdk import notify- notify.send('tramo.run_failed', to='admins',- data={'run_id': row.run_id,- 'workflow': row.workflow_slug,- 'error': row.error},- category='system')- except Exception as e: # noqa: BLE001- logger.debug('tramo.run_failed notify failed: %s', e)---def health_check(job):- """Probe engine health; notify after repeated failure. Never raises."""- try:- from .host_service import TramoHostService-- if not TramoHostService.is_installed():- _reset_health_streak()- return {'skipped': True, 'reason': 'engine not installed'}-- res = TramoHostService.health()- if res.get('success'):- _reset_health_streak()- return {'healthy': True}-- streak = _bump_health_streak()- if streak == _HEALTH_FAIL_THRESHOLD:- _notify_unreachable(res.get('error'))- return {'healthy': False, 'streak': streak}- except Exception as e: # noqa: BLE001- logger.warning('tramo health_check job failed: %s', e)- return {'error': str(e)}---def _health_config():- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)---def _save_health(updates):- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- return- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()---def _bump_health_streak():- streak = int(_health_config().get('health_fail_streak') or 0) + 1- _save_health({'health_fail_streak': streak})- return streak---def _reset_health_streak():- if _health_config().get('health_fail_streak'):- _save_health({'health_fail_streak': 0})---def _notify_unreachable(error):- try:- from app.plugins_sdk import notify- notify.send('tramo.host_unreachable', to='admins',- data={'error': error}, category='system')- except Exception as e: # noqa: BLE001- logger.debug('tramo.host_unreachable notify failed: %s', e)diff --git a/backend/app/plugins/serverkit-tramo/lifecycle.py b/backend/app/plugins/serverkit-tramo/lifecycle.pydeleted file mode 100644index aedd4fd1..00000000--- a/backend/app/plugins/serverkit-tramo/lifecycle.py+++ /dev/null@@ -1,78 +0,0 @@-"""Install / uninstall lifecycle hooks (serverkit-tramo / Automations extension).--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`` registers the extension's notification events and retires any-ghost ``serverkit-workflows`` row left over from the builder this extension-replaces (plan 45 Phase 4). It does NOT start the container -- the operator does-that from the Automations Settings tab (mail pattern).--``on_uninstall`` tears down everything provisioned by the engine: the container,-the scoped call-back ApiKey, and the managed events-bridge subscription. Data-dirs are deleted only on ``--purge``.-"""-import logging--logger = logging.getLogger(__name__)---def on_install(plugin):- """Register notification events; retire the replaced Workflow Builder row."""- try:- from app.plugins_sdk import notify- notify.register_event(- 'tramo.host_unreachable',- 'The Automations engine became unreachable',- template='generic', severity='warning', category='system')- notify.register_event(- 'tramo.run_failed',- 'An automation run failed',- template='generic', severity='warning', category='system')- logger.info('serverkit-tramo installed: notification events registered')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_install notify hook error: %s', e)-- _retire_workflow_builder_row()---def _retire_workflow_builder_row():- """Remove any lingering serverkit-workflows InstalledPlugin row.-- The Workflow Builder extension is deleted from disk in plan 45 Phase 4, so- its backend/frontend no longer load, but an old InstalledPlugin row would- otherwise haunt the Marketplace as a broken entry (uninstall deletes the- row, so we mirror that). Best-effort.- """- try:- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug='serverkit-workflows').first()- if row:- db.session.delete(row)- db.session.commit()- logger.info('serverkit-tramo: retired ghost serverkit-workflows row')- except Exception as e: # noqa: BLE001- logger.debug('serverkit-tramo: could not retire workflows row: %s', e)---def on_uninstall(plugin, purge=False):- """Stop/remove the container, revoke the call-back key, drop the events sub."""- try:- from .host_service import TramoHostService- if TramoHostService.is_installed():- result = TramoHostService.uninstall(keep_data=not purge)- logger.info('serverkit-tramo on_uninstall container: %s', result)- else:- logger.info('serverkit-tramo on_uninstall: container not present')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_uninstall container error: %s', e)-- try:- from . import events_bridge- events_bridge.revoke_callback_key()- events_bridge.disable_events_bridge()- logger.info('serverkit-tramo on_uninstall: call-back key + events bridge removed')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_uninstall bridge error: %s', e)diff --git a/backend/app/plugins/serverkit-tramo/models.py b/backend/app/plugins/serverkit-tramo/models.pydeleted file mode 100644index 9b508030..00000000--- a/backend/app/plugins/serverkit-tramo/models.py+++ /dev/null@@ -1,146 +0,0 @@-"""Data models for the serverkit-tramo (Automations) extension.--Two tables, both namespaced ``ext_serverkit_tramo_*`` (dash -> underscore) so-``--purge`` on uninstall drops exactly these:--* :class:`TramoWorkflow` — a workflow *document* the panel owns. The ``doc``- column holds a tramo ``WorkflowDoc`` (plain JSON) edited in the browser; the- ``slug`` doubles as the server-side workflow id and the ``<slug>.json``- filename materialized into the container's bind-mounted workflows dir.-* :class:`TramoRun` — a persisted summary of one execution, harvested from the- container's in-memory run ring (which evicts after 1000 runs) so run history- survives a restart.--Registration mirrors the serverkit-k8s pattern: importing this module defines-the tables on the shared metadata as a side effect; the manifest's-``models: "models:register"`` then calls :func:`register` (a no-op passthrough)-and the platform runs ``db.create_all()``.-"""-import json-from datetime import datetime--from app import db---class TramoWorkflow(db.Model):- __tablename__ = 'ext_serverkit_tramo_workflows'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), nullable=False)- # Server-side workflow id + <slug>.json filename. Unique, URL-safe.- slug = db.Column(db.String(255), unique=True, nullable=False, index=True)-- # tramo WorkflowDoc JSON (edited by the embedded editor).- doc = db.Column(db.Text, nullable=True)-- enabled = db.Column(db.Boolean, default=True, nullable=False)- # Bumped on every doc save so the editor/UI can detect stale state.- doc_version = db.Column(db.Integer, default=1, nullable=False)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)- # Stamped when this workflow was last materialized + deployed to the engine.- deployed_at = db.Column(db.DateTime, nullable=True)- # doc_version captured at the last deploy. Dirty detection compares this to- # the live doc_version -- a version counter, not a timestamp, so the deploy- # commit's own updated_at bump can't make a just-deployed row look dirty.- deployed_version = db.Column(db.Integer, nullable=True)-- def get_doc(self):- """Return the parsed WorkflowDoc (empty dict if unset/invalid)."""- if not self.doc:- return {}- try:- return json.loads(self.doc)- except (ValueError, TypeError):- return {}-- def set_doc(self, doc):- """Store a WorkflowDoc (dict or JSON string)."""- if doc is None:- self.doc = None- elif isinstance(doc, str):- self.doc = doc- else:- self.doc = json.dumps(doc)-- def is_dirty(self):- """True when an enabled workflow needs a (re)deploy.-- Dirty when it has never been deployed or its doc changed since the last- deploy (``doc_version`` moved past ``deployed_version``). Disabled- workflows are never dirty -- they materialize to nothing.- """- if not self.enabled:- return False- if not self.deployed_at:- return True- return (self.doc_version or 1) > (self.deployed_version or 0)-- def to_dict(self, include_doc=False):- out = {- 'id': self.id,- 'name': self.name,- 'slug': self.slug,- 'enabled': self.enabled,- 'doc_version': self.doc_version,- 'dirty': self.is_dirty(),- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- 'deployed_at': self.deployed_at.isoformat() if self.deployed_at else None,- }- if include_doc:- out['doc'] = self.get_doc()- return out---class TramoRun(db.Model):- __tablename__ = 'ext_serverkit_tramo_runs'-- id = db.Column(db.Integer, primary_key=True)- # tramo's own run id (from GET /api/runs). Unique so harvest upserts.- run_id = db.Column(db.String(255), unique=True, nullable=False, index=True)- workflow_slug = db.Column(db.String(255), nullable=True, index=True)- status = db.Column(db.String(32), nullable=True) # running|success|failed|suspended...- source = db.Column(db.String(32), nullable=True) # api|webhook|cron|replay- error = db.Column(db.Text, nullable=True)-- usage = db.Column(db.Text, nullable=True) # JSON token/cost usage- pending_approvals = db.Column(db.Text, nullable=True) # JSON list- raw = db.Column(db.Text, nullable=True) # full run JSON as returned-- started_at = db.Column(db.DateTime, nullable=True)- finished_at = db.Column(db.DateTime, nullable=True)- created_at = db.Column(db.DateTime, default=datetime.utcnow)-- def _json(self, value):- if not value:- return None- try:- return json.loads(value)- except (ValueError, TypeError):- return None-- def to_dict(self):- return {- 'id': self.id,- 'run_id': self.run_id,- 'workflow_slug': self.workflow_slug,- 'status': self.status,- 'source': self.source,- 'error': self.error,- 'usage': self._json(self.usage),- 'pending_approvals': self._json(self.pending_approvals) or [],- 'started_at': self.started_at.isoformat() if self.started_at else None,- 'finished_at': self.finished_at.isoformat() if self.finished_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- }---def register(db): # noqa: A002 - signature dictated by the platform (fn(db))- """No-op passthrough required by the manifest ``models: "models:register"``.-- Importing this module already defined the tables on ``db.metadata``; the- platform runs ``db.create_all()``. Nothing else to do here.- """- return [TramoWorkflow, TramoRun]diff --git a/backend/app/plugins/serverkit-tramo/plugin.json b/backend/app/plugins/serverkit-tramo/plugin.jsondeleted file mode 100644index 46ea234b..00000000--- a/backend/app/plugins/serverkit-tramo/plugin.json+++ /dev/null@@ -1,55 +0,0 @@-{- "name": "serverkit-tramo",- "display_name": "Automations",- "version": "1.0.0",- "description": "Node-based automation builder powered by tramo. Design workflows on a visual canvas (triggers, actions, branches, loops, approval gates) that react to panel events or run on a schedule, with 21 brand integration packs (Telegram, GitHub, Gmail, Discord, Notion, Stripe, Cloudflare, Postgres, Twilio and more). Enabled workflows deploy to a managed tramo container on the panel host that runs them headless, with run history, approvals, and inbound webhooks proxied through the panel. This replaces the older drag-and-drop Workflow Builder.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["docker", "shell", "filesystem", "network"],- "min_panel_version": "1.7.0",- "entry_point": "tramo:tramo_bp",- "url_prefix": "/api/v1/tramo",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "jobs": [- { "kind": "tramo.harvest_runs", "handler": "jobs:harvest_runs" },- { "kind": "tramo.health_check", "handler": "jobs:health_check" }- ],- "schedules": [- { "name": "tramo-harvest-runs", "kind": "tramo.harvest_runs", "interval_seconds": 120 },- { "name": "tramo-health-check", "kind": "tramo.health_check", "interval_seconds": 300 }- ],- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>",- "contributions": {- "nav": [- {- "id": "automations",- "label": "Automations",- "route": "/automations",- "category": "operations",- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>"- }- ],- "routes": [- { "path": "automations", "component": "AutomationsPage" },- { "path": "automations/:tab", "component": "AutomationsPage" },- { "path": "automations/edit/:slug", "component": "AutomationEditorPage", "layout": "full" }- ],- "page_titles": {- "/automations": "Automations"- },- "command_palette": [- {- "label": "Automations",- "path": "/automations",- "category": "Pages",- "keywords": "automation workflow tramo trigger action schedule webhook telegram github integration pipeline event"- }- ]- }-}diff --git a/backend/app/plugins/serverkit-tramo/run_sync.py b/backend/app/plugins/serverkit-tramo/run_sync.pydeleted file mode 100644index dc3effa7..00000000--- a/backend/app/plugins/serverkit-tramo/run_sync.py+++ /dev/null@@ -1,94 +0,0 @@-"""Run persistence helpers (serverkit-tramo / Automations extension).--``@tramo/server`` keeps run history in an in-memory ring of 1000 (it evicts old-runs and loses everything on restart), so the panel harvests run summaries into-:class:`TramoRun`. Both the harvest job and the manual-run proxy funnel through-:func:`upsert_run` (keyed on the tramo run id) so a run is never duplicated.--tramo's run JSON field names are not frozen, so :func:`parse_run` reads a few-aliases defensively and keeps the untouched original in ``raw``.-"""-import json-import logging-from datetime import datetime--from app import db--from .models import TramoRun--logger = logging.getLogger(__name__)---def _first(d, *keys):- for k in keys:- if isinstance(d, dict) and d.get(k) not in (None, ''):- return d.get(k)- return None---def _parse_dt(value):- if not value:- return None- if isinstance(value, (int, float)):- try:- return datetime.utcfromtimestamp(value / 1000 if value > 1e12 else value)- except (ValueError, OSError):- return None- try:- return datetime.fromisoformat(str(value).replace('Z', '+00:00')).replace(tzinfo=None)- except (ValueError, TypeError):- return None---def _json_dump(value):- if value is None:- return None- if isinstance(value, str):- return value- try:- return json.dumps(value)- except (TypeError, ValueError):- return None---def parse_run(run_json):- """Map a tramo run object to TramoRun column values (dict)."""- run_id = _first(run_json, 'id', 'runId', 'run_id')- return {- 'run_id': str(run_id) if run_id is not None else None,- 'workflow_slug': _first(run_json, 'workflowId', 'workflow_id',- 'workflowSlug', 'workflow_slug', 'workflow'),- 'status': _first(run_json, 'status', 'state'),- 'source': _first(run_json, 'source', 'trigger', 'triggerType', 'trigger_type'),- 'error': _first(run_json, 'error', 'errorMessage', 'error_message'),- 'usage': _json_dump(_first(run_json, 'usage', 'cost', 'tokens')),- 'pending_approvals': _json_dump(_first(run_json, 'pendingApprovals',- 'pending_approvals', 'approvals')),- 'started_at': _parse_dt(_first(run_json, 'startedAt', 'started_at', 'startTime')),- 'finished_at': _parse_dt(_first(run_json, 'finishedAt', 'finished_at',- 'endTime', 'completedAt')),- 'raw': _json_dump(run_json),- }---def upsert_run(run_json):- """Insert or update a TramoRun from a tramo run object.-- Returns ``(row, is_new)``. ``is_new`` is True only when the row did not exist- before, so callers can fire a one-shot notification on first sight.- """- fields = parse_run(run_json)- if not fields.get('run_id'):- return None, False-- row = TramoRun.query.filter_by(run_id=fields['run_id']).first()- is_new = row is None- if is_new:- row = TramoRun(run_id=fields['run_id'])- db.session.add(row)- for key, value in fields.items():- if key == 'run_id':- continue- setattr(row, key, value)- db.session.commit()- return row, is_newdiff --git a/backend/app/plugins/serverkit-tramo/templates.py b/backend/app/plugins/serverkit-tramo/templates.pydeleted file mode 100644index e8cfcc78..00000000--- a/backend/app/plugins/serverkit-tramo/templates.py+++ /dev/null@@ -1,97 +0,0 @@-"""Starter workflow templates (serverkit-tramo / Automations extension, Phase 3).--A small set of seed :class:`WorkflowDoc` fixtures the Workflows tab offers as-"New from template", so a fresh install has something runnable to start from.-These are node-vocabulary sketches for the embedded editor -- the operator fills-in credentials (pack secrets) and adjusts nodes before deploying.--Kept as plain Python dicts (not files) so they ship with the backend package and-need no bundling. Each template's ``doc`` is a minimal tramo WorkflowDoc.-"""--STARTER_TEMPLATES = [- {- 'id': 'backup-failed-telegram',- 'name': 'Backup failed -> Telegram',- 'description': 'When a panel backup fails, send a Telegram message.',- 'doc': {- 'name': 'Backup failed -> Telegram',- 'nodes': [- {'id': 'trigger', 'type': 'webhook-trigger:serverkit:event',- 'position': {'x': 80, 'y': 120},- 'config': {'path': '/sk/events'}},- {'id': 'filter', 'type': 'if',- 'position': {'x': 360, 'y': 120},- 'config': {'expression': "{{trigger.body.event}} == 'backup.restored'"}},- {'id': 'notify', 'type': 'telegram:send-message',- 'position': {'x': 640, 'y': 120},- 'config': {'text': 'A ServerKit backup event fired: {{trigger.body.event}}'}},- ],- 'edges': [- {'id': 'e1', 'source': 'trigger', 'target': 'filter'},- {'id': 'e2', 'source': 'filter', 'target': 'notify'},- ],- },- },- {- 'id': 'nightly-health-github',- 'name': 'Nightly health ping -> GitHub issue',- 'description': 'On a nightly cron, check something and open a GitHub issue on failure.',- 'doc': {- 'name': 'Nightly health ping -> GitHub issue',- 'nodes': [- {'id': 'cron', 'type': 'cron-trigger',- 'position': {'x': 80, 'y': 120},- 'config': {'cron': '0 3 * * *'}},- {'id': 'ping', 'type': 'http-request',- 'position': {'x': 360, 'y': 120},- 'config': {'method': 'GET', 'url': 'https://example.com/health'}},- {'id': 'issue', 'type': 'github:create-issue',- 'position': {'x': 640, 'y': 120},- 'config': {'title': 'Nightly health check failed',- 'body': 'The nightly health ping did not pass.'}},- ],- 'edges': [- {'id': 'e1', 'source': 'cron', 'target': 'ping'},- {'id': 'e2', 'source': 'ping', 'target': 'issue'},- ],- },- },- {- 'id': 'panel-event-discord',- 'name': 'Panel event -> Discord webhook',- 'description': 'Relay any panel event to a Discord channel via webhook.',- 'doc': {- 'name': 'Panel event -> Discord webhook',- 'nodes': [- {'id': 'trigger', 'type': 'webhook-trigger:serverkit:event',- 'position': {'x': 80, 'y': 120},- 'config': {'path': '/sk/events'}},- {'id': 'discord', 'type': 'discord:send-message',- 'position': {'x': 400, 'y': 120},- 'config': {'content': 'ServerKit event: {{trigger.body.event}}'}},- ],- 'edges': [- {'id': 'e1', 'source': 'trigger', 'target': 'discord'},- ],- },- },-]---def list_templates(include_doc=False):- """Template summaries (or full docs when include_doc)."""- out = []- for t in STARTER_TEMPLATES:- entry = {'id': t['id'], 'name': t['name'], 'description': t['description']}- if include_doc:- entry['doc'] = t['doc']- out.append(entry)- return out---def get_template(template_id):- for t in STARTER_TEMPLATES:- if t['id'] == template_id:- return t- return Nonediff --git a/backend/app/plugins/serverkit-tramo/tramo.py b/backend/app/plugins/serverkit-tramo/tramo.pydeleted file mode 100644index fefaed6c..00000000--- a/backend/app/plugins/serverkit-tramo/tramo.py+++ /dev/null@@ -1,387 +0,0 @@-"""Automations API endpoints (serverkit-tramo extension, tramo engine).--Mounted under ``/api/v1/tramo`` via the manifest's ``url_prefix``. Thin routing-layer over the extension services -- all Docker, tramo-API, and DB work happens-in :mod:`host_service`, :mod:`workflow_store`, :mod:`run_sync`, and-:mod:`events_bridge`.--Auth split (same as serverkit-mail / serverkit-k8s): reads need viewer, mutations-need admin. The ONE exception is the inbound-webhook passthrough-(``/hooks/<path>``) which is intentionally auth-exempt so external services can-POST to a workflow's ``webhook-trigger`` node through the panel's public domain;-per-trigger HMAC (tramo native) covers spoofing and the container stays-loopback-only. The plugin-disabled 503 guard (attached by plugin_service) still-runs on every route including the passthrough.-"""-import logging--import requests-from flask import Blueprint, jsonify, request, Response--from app.middleware.rbac import admin_required, viewer_required--from .host_service import TramoHostService, RUN_TIMEOUT-from .workflow_store import WorkflowStore-from . import events_bridge-from .run_sync import upsert_run-from .models import TramoRun--logger = logging.getLogger(__name__)--tramo_bp = Blueprint('tramo', __name__)--_NOT_INSTALLED = ('The Automations engine is not installed. Install it from the '- 'Automations Settings tab (admin only).')--# Response/hop headers we must not blindly relay when proxying.-_HOP_HEADERS = {'content-length', 'transfer-encoding', 'connection',- 'content-encoding', 'host'}---def _installed_or_error():- if not TramoHostService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503- return None---# ── Workflows CRUD ──--@tramo_bp.route('/workflows', methods=['GET'])-@viewer_required-def list_workflows():- return jsonify({'workflows': WorkflowStore.list_workflows()}), 200---@tramo_bp.route('/workflows/<slug>', methods=['GET'])-@viewer_required-def get_workflow(slug):- wf = WorkflowStore.get(slug)- if not wf:- return jsonify({'error': 'Workflow not found'}), 404- return jsonify(wf.to_dict(include_doc=True)), 200---@tramo_bp.route('/workflows', methods=['POST'])-@admin_required-def create_workflow():- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.create(- name=data.get('name'),- doc=data.get('doc'),- enabled=data.get('enabled', True),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(wf.to_dict(include_doc=True)), 201---@tramo_bp.route('/workflows/<slug>', methods=['PUT'])-@admin_required-def update_workflow(slug):- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.update(- slug,- name=data.get('name'),- doc=data.get('doc'),- enabled=data.get('enabled'),- )- except ValueError as e:- code = 404 if 'not found' in str(e).lower() else 400- return jsonify({'error': str(e)}), code- return jsonify(wf.to_dict(include_doc=True)), 200---@tramo_bp.route('/workflows/<slug>', methods=['DELETE'])-@admin_required-def delete_workflow(slug):- try:- WorkflowStore.delete(slug)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify({'deleted': True}), 200---@tramo_bp.route('/deploy', methods=['POST'])-@admin_required-def deploy():- result = WorkflowStore.deploy()- if not result.get('success'):- code = 503 if 'not installed' in (result.get('error') or '') else 400- return jsonify({'error': result.get('error', 'Deploy failed'),- 'materialized': result.get('materialized')}), code- return jsonify(result), 200---# ── Starter templates ──--@tramo_bp.route('/templates', methods=['GET'])-@viewer_required-def list_starter_templates():- from .templates import list_templates- return jsonify({'templates': list_templates()}), 200---@tramo_bp.route('/workflows/from-template/<template_id>', methods=['POST'])-@admin_required-def create_from_template(template_id):- from .templates import get_template- tpl = get_template(template_id)- if not tpl:- return jsonify({'error': 'Template not found'}), 404- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.create(- name=data.get('name') or tpl['name'],- doc=tpl['doc'],- enabled=data.get('enabled', True),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(wf.to_dict(include_doc=True)), 201---# ── Runs / approvals (proxied to the engine) ──--@tramo_bp.route('/workflows/<slug>/run', methods=['POST'])-@admin_required-def run_workflow(slug):- guard = _installed_or_error()- if guard:- return guard- wf = WorkflowStore.get(slug)- if not wf:- return jsonify({'error': 'Workflow not found'}), 404- payload = request.get_json(silent=True) or {}- res = TramoHostService._api('POST', f'/workflows/{slug}/run', payload,- timeout=RUN_TIMEOUT)- if not res.get('success'):- return jsonify({'error': res.get('error', 'Run failed')}), 502- summary = res.get('data') or {}- try:- row, _ = upsert_run(summary if isinstance(summary, dict) else {})- run_dict = row.to_dict() if row else None- except Exception as e: # noqa: BLE001- logger.warning('tramo: failed to persist run summary: %s', e)- run_dict = None- return jsonify({'run': run_dict, 'result': summary}), 200---@tramo_bp.route('/runs', methods=['GET'])-@viewer_required-def list_runs():- q = TramoRun.query- slug = request.args.get('workflow')- status = request.args.get('status')- if slug:- q = q.filter_by(workflow_slug=slug)- if status:- q = q.filter_by(status=status)- try:- limit = min(int(request.args.get('limit', 100)), 500)- except (TypeError, ValueError):- limit = 100- rows = q.order_by(TramoRun.id.desc()).limit(limit).all()- return jsonify({'runs': [r.to_dict() for r in rows]}), 200---@tramo_bp.route('/runs/<run_id>', methods=['GET'])-@viewer_required-def get_run(run_id):- row = TramoRun.query.filter_by(run_id=run_id).first()- if not row:- return jsonify({'error': 'Run not found'}), 404- return jsonify(row.to_dict()), 200---@tramo_bp.route('/runs/<run_id>/replay', methods=['POST'])-@admin_required-def replay_run(run_id):- guard = _installed_or_error()- if guard:- return guard- res = TramoHostService._api('POST', f'/runs/{run_id}/replay')- if not res.get('success'):- return jsonify({'error': res.get('error', 'Replay failed')}), 502- try:- if isinstance(res.get('data'), dict):- upsert_run(res['data'])- except Exception as e: # noqa: BLE001- logger.debug('replay upsert failed: %s', e)- return jsonify(res.get('data') or {'replayed': True}), 200---@tramo_bp.route('/approvals', methods=['GET'])-@viewer_required-def list_approvals():- guard = _installed_or_error()- if guard:- return guard- res = TramoHostService._api('GET', '/approvals')- if not res.get('success'):- return jsonify({'approvals': [], 'note': res.get('error')}), 200- data = res.get('data')- approvals = data if isinstance(data, list) else (data or {}).get('approvals', [])- return jsonify({'approvals': approvals}), 200---@tramo_bp.route('/runs/<run_id>/approve', methods=['POST'])-@admin_required-def approve_run(run_id):- guard = _installed_or_error()- if guard:- return guard- payload = request.get_json(silent=True) or {}- res = TramoHostService._api('POST', f'/runs/{run_id}/approve', payload)- if not res.get('success'):- return jsonify({'error': res.get('error', 'Approve failed')}), 502- return jsonify(res.get('data') or {'approved': True}), 200---# ── Host (engine) lifecycle ──--@tramo_bp.route('/host/status', methods=['GET'])-@viewer_required-def host_status():- return jsonify(TramoHostService.get_status()), 200---@tramo_bp.route('/host/install', methods=['POST'])-@admin_required-def host_install():- data = request.get_json(silent=True) or {}- # Issue the scoped call-back key so workflows can act back on the panel.- callback_key = events_bridge.issue_callback_key()- result = TramoHostService.install(- host_port=data.get('host_port'),- callback_api_key=callback_key,- )- if not result.get('success'):- # Roll back the key we just issued if the container didn't start.- events_bridge.revoke_callback_key()- return jsonify({'error': result.get('error', 'Install failed')}), 400- return jsonify(result), 201---@tramo_bp.route('/host/install', methods=['DELETE'])-@admin_required-def host_uninstall():- keep_data = (request.args.get('keep_data', 'true').lower()- not in ('false', '0', 'no'))- result = TramoHostService.uninstall(keep_data=keep_data)- events_bridge.revoke_callback_key()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Uninstall failed')}), 400- return jsonify(result), 200---@tramo_bp.route('/host/control/<action>', methods=['POST'])-@admin_required-def host_control(action):- guard = _installed_or_error()- if guard:- return guard- result = TramoHostService.control(action)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Control failed')}), 400- return jsonify(result), 200---# ── Settings ──--@tramo_bp.route('/settings', methods=['GET'])-@viewer_required-def get_settings():- return jsonify({- 'host_port': TramoHostService.host_port(),- 'events_bridge_enabled': events_bridge.is_events_bridge_enabled(),- # Names only -- secret values are never returned.- 'pack_secret_names': sorted(TramoHostService.get_pack_secrets().keys()),- }), 200---@tramo_bp.route('/settings', methods=['PUT'])-@admin_required-def update_settings():- data = request.get_json(silent=True) or {}- out = {}-- if 'pack_secrets' in data and isinstance(data['pack_secrets'], dict):- out['pack_secret_names'] = TramoHostService.set_pack_secrets(data['pack_secrets'])-- if 'host_port' in data:- try:- port = int(data['host_port'])- if not (1024 <= port <= 65535):- raise ValueError- TramoHostService._save_config({'host_port': port})- out['host_port'] = port- except (TypeError, ValueError):- return jsonify({'error': 'host_port must be an integer 1024-65535'}), 400-- if 'events_bridge_enabled' in data:- if data['events_bridge_enabled']:- events_bridge.enable_events_bridge()- else:- events_bridge.disable_events_bridge()- out['events_bridge_enabled'] = events_bridge.is_events_bridge_enabled()-- return jsonify(out), 200---# ── Legacy Workflow Builder export (read-only, admin) ──--@tramo_bp.route('/legacy-workflows', methods=['GET'])-@admin_required-def legacy_workflows():- """Read-only dump of the retired Workflow Builder's rows (plan 45 Phase 4).-- The old ``workflows`` tables are kept (no data loss); this lets an operator- rebuild those flows by hand in tramo. Never fails if the model is gone.- """- try:- from app.models.workflow import Workflow- except Exception: # noqa: BLE001- return jsonify({'workflows': [], 'note': 'legacy workflow model not present'}), 200- try:- rows = Workflow.query.all()- out = [w.to_dict() if hasattr(w, 'to_dict') else {'id': w.id, 'name': getattr(w, 'name', None)}- for w in rows]- except Exception as e: # noqa: BLE001- return jsonify({'workflows': [], 'note': f'could not read legacy workflows: {e}'}), 200- return jsonify({'workflows': out}), 200---# ── Inbound webhook passthrough (AUTH-EXEMPT) ──--@tramo_bp.route('/hooks/<path:subpath>',- methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])-def hooks_passthrough(subpath):- """Forward an external webhook to the engine's trigger dispatcher.-- Intentionally has NO auth decorator: external services POST here through the- panel's public domain to fire a ``webhook-trigger`` node. The container is- loopback-only, so this is the only way in; per-trigger HMAC (configured on- the node) authenticates the payload.- """- if not TramoHostService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503-- target = f'http://127.0.0.1:{TramoHostService.host_port()}/hooks/{subpath}'- fwd_headers = {k: v for k, v in request.headers- if k.lower() not in _HOP_HEADERS}- try:- upstream = requests.request(- request.method, target,- params=request.args,- data=request.get_data(),- headers=fwd_headers,- timeout=30,- )- except requests.RequestException as e:- return jsonify({'error': f'Automations engine unreachable: {e}'}), 502-- resp_headers = [(k, v) for k, v in upstream.headers.items()- if k.lower() not in _HOP_HEADERS]- return Response(upstream.content, status=upstream.status_code, headers=resp_headers)diff --git a/backend/app/plugins/serverkit-tramo/workflow_store.py b/backend/app/plugins/serverkit-tramo/workflow_store.pydeleted file mode 100644index aeccc709..00000000--- a/backend/app/plugins/serverkit-tramo/workflow_store.py+++ /dev/null@@ -1,212 +0,0 @@-"""Workflow document store (serverkit-tramo / Automations extension).--CRUD over :class:`TramoWorkflow` rows plus the two engine-facing operations:--* :meth:`WorkflowStore.materialize` — write every *enabled* workflow's doc as- ``<slug>.json`` into the container's bind-mounted workflows dir and prune the- files of disabled/deleted workflows.-* :meth:`WorkflowStore.deploy` — materialize, then restart the container so- ``@tramo/server`` re-reads the dir (it loads workflows once at boot), then- stamp ``deployed_at`` on the enabled rows.--File I/O goes through small choke-point classmethods (``_write_file`` /-``_remove_file`` / ``_list_files``) so it stays privileged (the data dir is-root-owned) and mockable in tests.-"""-import json-import logging-import os-import re-import tempfile--from app import db--from .models import TramoWorkflow-from .host_service import TramoHostService, HOST_WORKFLOWS_DIR--logger = logging.getLogger(__name__)--_SLUG_RE = re.compile(r'[^a-z0-9]+')---def slugify(value):- """Lowercase, hyphenated, URL/filename-safe slug."""- base = _SLUG_RE.sub('-', (value or '').strip().lower()).strip('-')- return base or 'workflow'---class WorkflowStore:- """DB CRUD + engine materialization for automation workflows."""-- # ---------- CRUD ------------ @classmethod- def list_workflows(cls):- rows = TramoWorkflow.query.order_by(TramoWorkflow.updated_at.desc()).all()- return [w.to_dict() for w in rows]-- @classmethod- def get(cls, slug):- return TramoWorkflow.query.filter_by(slug=slug).first()-- @classmethod- def _unique_slug(cls, name, ignore_id=None):- base = slugify(name)- candidate = base- n = 2- while True:- existing = TramoWorkflow.query.filter_by(slug=candidate).first()- if not existing or existing.id == ignore_id:- return candidate- candidate = f'{base}-{n}'- n += 1-- @classmethod- def create(cls, name, doc=None, enabled=True):- name = (name or '').strip()- if not name:- raise ValueError('A workflow name is required')- wf = TramoWorkflow(- name=name,- slug=cls._unique_slug(name),- enabled=bool(enabled),- doc_version=1,- )- wf.set_doc(doc if doc is not None else cls._empty_doc(wf.slug, name))- db.session.add(wf)- db.session.commit()- return wf-- @classmethod- def update(cls, slug, name=None, doc=None, enabled=None):- wf = cls.get(slug)- if not wf:- raise ValueError('Workflow not found')- if name is not None:- name = name.strip()- if not name:- raise ValueError('A workflow name is required')- wf.name = name- if enabled is not None:- wf.enabled = bool(enabled)- if doc is not None:- wf.set_doc(doc)- wf.doc_version = (wf.doc_version or 1) + 1- db.session.commit()- return wf-- @classmethod- def delete(cls, slug):- wf = cls.get(slug)- if not wf:- raise ValueError('Workflow not found')- db.session.delete(wf)- db.session.commit()- # Best-effort prune the materialized file.- try:- cls._remove_file(slug)- except Exception as e: # noqa: BLE001- logger.debug('could not remove workflow file for %s: %s', slug, e)- return True-- @staticmethod- def _empty_doc(slug, name):- """A minimal valid tramo WorkflowDoc so a new workflow opens cleanly.-- Mirrors tramo's own ``emptyDoc()`` — ``version`` and ``meta`` must be- present, since the editor's Canvas reads ``doc.meta.mcpServers``- unconditionally and crashes on a doc without ``meta``.- """- return {- 'version': 1,- 'id': slug,- 'name': name,- 'nodes': [],- 'edges': [],- 'meta': {},- }-- # ---------- engine materialization ------------ @classmethod- def _write_file(cls, slug, doc):- """Write ``<slug>.json`` into the workflows dir (privileged). Linux-only."""- if os.name == 'nt':- return- payload = json.dumps(doc, indent=2)- dest = f'{HOST_WORKFLOWS_DIR}/{slug}.json'- from app.utils.system import run_privileged- run_privileged(['mkdir', '-p', HOST_WORKFLOWS_DIR])- with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as tmp:- tmp.write(payload)- tmp_path = tmp.name- try:- run_privileged(['cp', tmp_path, dest])- finally:- try:- os.unlink(tmp_path)- except OSError:- pass-- @classmethod- def _remove_file(cls, slug):- if os.name == 'nt':- return- from app.utils.system import run_privileged- run_privileged(['rm', '-f', f'{HOST_WORKFLOWS_DIR}/{slug}.json'])-- @classmethod- def _list_files(cls):- """Slugs currently materialized in the workflows dir."""- if os.name == 'nt':- return []- from app.utils.system import run_privileged- res = run_privileged(['ls', '-1', HOST_WORKFLOWS_DIR])- if getattr(res, 'returncode', 1) != 0:- return []- out = getattr(res, 'stdout', '') or ''- return [line[:-5] for line in out.splitlines()- if line.strip().endswith('.json')]-- @classmethod- def materialize(cls):- """Write enabled docs, prune the rest. Returns a summary dict."""- enabled = TramoWorkflow.query.filter_by(enabled=True).all()- enabled_slugs = {w.slug for w in enabled}- written = []- for wf in enabled:- cls._write_file(wf.slug, wf.get_doc())- written.append(wf.slug)- pruned = []- for slug in cls._list_files():- if slug not in enabled_slugs:- cls._remove_file(slug)- pruned.append(slug)- return {'written': written, 'pruned': pruned}-- @classmethod- def deploy(cls):- """Materialize + restart the engine + stamp ``deployed_at``.-- Restart is required because ``@tramo/server`` reads the workflows dir- only at boot (no reload endpoint yet). The checkpoint store preserves any- suspended runs across the restart.- """- from datetime import datetime-- if not TramoHostService.is_installed():- return {'success': False,- 'error': 'The Automations engine is not installed. Install it '- 'from the Automations Settings tab first.'}- summary = cls.materialize()- restart = TramoHostService.control('restart')- if not restart.get('success'):- return {'success': False,- 'error': restart.get('error', 'Failed to restart the engine'),- 'materialized': summary}- now = datetime.utcnow()- for wf in TramoWorkflow.query.filter_by(enabled=True).all():- wf.deployed_at = now- wf.deployed_version = wf.doc_version- db.session.commit()- return {'success': True, 'message': 'Automations deployed', 'materialized': summary}diff --git a/backend/app/services/extension_migration.py b/backend/app/services/extension_migration.pyindex 219082af..e4204b90 100644--- a/backend/app/services/extension_migration.py+++ b/backend/app/services/extension_migration.py@@ -89,22 +89,11 @@ def _email_was_configured():return False-def _gpu_present():- """True if this host has an NVIDIA GPU toolchain (nvidia-smi on PATH). Used to- gate serverkit-gpu auto-install so only panels on GPU hosts get it back- automatically; everyone else uses the Marketplace."""- try:- return shutil.which('nvidia-smi') is not None- except Exception:- return False--# Builtins auto-installed on upgrade ONLY when a usage predicate says the panel# actually used the feature (D3/#34). Fresh installs and panels that never used# the feature just see it in the Marketplace.GATED_BUILTIN_SLUGS = {'serverkit-email': _email_was_configured,- 'serverkit-gpu': _gpu_present,}_MARKER_KEY = 'extensions.auto_installed_slugs'diff --git a/backend/tests/test_analytics_extension.py b/backend/tests/test_analytics_extension.pydeleted file mode 100644index 0d8af9be..00000000--- a/backend/tests/test_analytics_extension.py+++ /dev/null@@ -1,1070 +0,0 @@-"""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', 'models', 'ingest_service', 'rollup_service',- 'report_service', 'site_service', 'wp_integration',- 'nginx_integration', 'log_ingest_service', 'geo', 'lifecycle',- 'jobs', 'analytics'):- mods[name] = importlib.import_module(f'app.plugins.{SLUG}.{name}')- return mods---_M = _load_ext()-config_mod = _M['config']-models_mod = _M['models']-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']-log_mod = _M['log_ingest_service']-geo_mod = _M['geo']-lifecycle_mod = _M['lifecycle']-jobs_mod = _M['jobs']-bp_mod = _M['analytics']--AnalyticsSite = models_mod.AnalyticsSite-AnalyticsEvent = models_mod.AnalyticsEvent-AnalyticsDaily = models_mod.AnalyticsDaily-AnalyticsLogCursor = models_mod.AnalyticsLogCursor--# A realistic desktop UA so happy-path hits aren't bot/empty-UA filtered.-UA_CHROME = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '- '(KHTML, like Gecko) Chrome/120.0 Safari/537.36')---# --------------------------------------------------------------------------- #-# 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)}'}--[email protected](autouse=True)-def _clean_ingest_state():- """Reset the process-global ingest buffer + rate limiter between tests."""- ingest_mod.reset_buffer()- ingest_mod.reset_rate_limits()- yield- ingest_mod.reset_buffer()- ingest_mod.reset_rate_limits()---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()---def _mk_site(**kwargs):- from app import db- kwargs.setdefault('name', 'Test Site')- kwargs.setdefault('hostnames', 'example.com')- site = AnalyticsSite(**kwargs)- db.session.add(site)- db.session.commit()- return site---def _collect(client, site_key, path='/home', ua=UA_CHROME, extra_headers=None,- body=None, **payload):- headers = {'User-Agent': ua, 'Content-Type': 'text/plain'}- if extra_headers:- headers.update(extra_headers)- if body is None:- data = {'k': site_key, 'p': path}- data.update(payload)- body = json.dumps(data)- return client.post('/api/v1/analytics/collect', data=body, headers=headers)---# --------------------------------------------------------------------------- #-# 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---# --------------------------------------------------------------------------- #-# models + purge-# --------------------------------------------------------------------------- #-def test_models_register_and_tables_exist(app):- from app import db- from sqlalchemy import inspect- assert set(models_mod.register(db)) == {- AnalyticsSite, AnalyticsEvent, AnalyticsDaily, AnalyticsLogCursor}- tables = [t for t in inspect(db.engine).get_table_names()- if t.startswith('ext_serverkit_analytics')]- assert 'ext_serverkit_analytics_sites' in tables- assert 'ext_serverkit_analytics_events' in tables- assert 'ext_serverkit_analytics_daily' in tables- assert 'ext_serverkit_analytics_log_cursors' in tables---def test_purge_drops_only_prefixed_tables(app):- from app import db- from app.services import extension_lifecycle- from sqlalchemy import inspect- from types import SimpleNamespace- dropped = extension_lifecycle.purge_models(SimpleNamespace(slug=SLUG))- assert dropped >= 4- remaining = [t for t in inspect(db.engine).get_table_names()- if t.startswith('ext_serverkit_analytics')]- assert remaining == []- assert 'users' in inspect(db.engine).get_table_names() # core survives- db.create_all() # restore for later tests in this module---def test_site_key_is_generated_and_unique(app):- a = _mk_site(name='A')- b = _mk_site(name='B')- assert a.site_key and b.site_key and a.site_key != b.site_key---# --------------------------------------------------------------------------- #-# ingest units: bot filter, UA parse, visitor hash, helpers-# --------------------------------------------------------------------------- #-def test_is_bot_matches_common_agents():- assert ingest_mod.is_bot('curl/7.68.0')- assert ingest_mod.is_bot('Googlebot/2.1')- assert ingest_mod.is_bot('python-requests/2.31')- assert not ingest_mod.is_bot(UA_CHROME)---def test_parse_ua_classifies():- browser, os_family, device = ingest_mod.parse_ua(UA_CHROME)- assert browser == 'Chrome'- assert os_family == 'Windows'- assert device == 'desktop'- iphone = ('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) '- 'AppleWebKit/605 (KHTML, like Gecko) Version/17 Mobile/15E Safari/604')- b2, os2, d2 = ingest_mod.parse_ua(iphone)- assert os2 == 'iOS' and d2 == 'mobile'---def test_visitor_hash_stable_and_scoped(app):- h1 = ingest_mod.visitor_hash(1, '1.2.3.4', UA_CHROME)- h2 = ingest_mod.visitor_hash(1, '1.2.3.4', UA_CHROME)- h_other_site = ingest_mod.visitor_hash(2, '1.2.3.4', UA_CHROME)- h_other_ip = ingest_mod.visitor_hash(1, '9.9.9.9', UA_CHROME)- assert h1 == h2 # deterministic within the day- assert len(h1) == 32- assert h1 != h_other_site # scoped by site- assert h1 != h_other_ip # scoped by ip- assert '1.2.3.4' not in h1 # raw ip never leaks into the digest---def test_referrer_host_and_clean_path():- assert ingest_mod.referrer_host('https://google.com/search?q=x') == 'google.com'- assert ingest_mod.referrer_host('') is None- assert ingest_mod._clean_path('https://example.com/a/b?x=1#frag') == '/a/b'- assert ingest_mod._clean_path('') == '/'- assert ingest_mod._clean_path('noslash') == '/noslash'---# --------------------------------------------------------------------------- #-# collector route-# --------------------------------------------------------------------------- #-def test_collect_happy_path_buffers_and_flushes(app, analytics_client):- site = _mk_site()- resp = _collect(analytics_client, site.site_key, path='/home', r='https://google.com/')- assert resp.status_code == 204- assert ingest_mod.buffer_size() == 1- written = ingest_mod.flush_buffer(app)- assert written == 1- ev = AnalyticsEvent.query.filter_by(site_id=site.id).one()- assert ev.url_path == '/home'- assert ev.referrer_host == 'google.com'- assert ev.ua_family == 'Chrome'- assert ev.source == 'js'- assert ev.visitor_hash and len(ev.visitor_hash) == 32---def test_collect_unknown_key_404(app, analytics_client):- resp = _collect(analytics_client, 'nope-not-a-real-key')- assert resp.status_code == 404- assert ingest_mod.buffer_size() == 0---def test_collect_disabled_site_403(app, analytics_client):- site = _mk_site(enabled=False)- resp = _collect(analytics_client, site.site_key)- assert resp.status_code == 403---def test_collect_missing_key_400(app, analytics_client):- resp = analytics_client.post('/api/v1/analytics/collect',- data=json.dumps({'p': '/x'}),- headers={'User-Agent': UA_CHROME})- assert resp.status_code == 400---def test_collect_malformed_json_400(app, analytics_client):- resp = analytics_client.post('/api/v1/analytics/collect',- data='{not json',- headers={'User-Agent': UA_CHROME})- assert resp.status_code == 400---def test_collect_oversized_body_413(app, analytics_client):- site = _mk_site()- big = json.dumps({'k': site.site_key, 'p': '/x', 'pad': 'A' * 9000})- resp = _collect(analytics_client, site.site_key, body=big)- assert resp.status_code == 413---def test_collect_bot_ua_dropped(app, analytics_client):- site = _mk_site()- resp = _collect(analytics_client, site.site_key, ua='curl/7.68.0')- assert resp.status_code == 204- assert ingest_mod.buffer_size() == 0 # accepted but not stored---def test_collect_empty_ua_dropped(app, analytics_client):- site = _mk_site()- resp = _collect(analytics_client, site.site_key, ua='')- assert resp.status_code == 204- assert ingest_mod.buffer_size() == 0---def test_collect_honors_dnt(app, analytics_client):- site = _mk_site()- resp = _collect(analytics_client, site.site_key, extra_headers={'DNT': '1'})- assert resp.status_code == 204- assert ingest_mod.buffer_size() == 0---def test_collect_per_site_dnt_override(app, analytics_client):- # Global honor_dnt default True; a site opting OUT still records a DNT hit.- site = _mk_site(honor_dnt=False)- resp = _collect(analytics_client, site.site_key, extra_headers={'DNT': '1'})- assert resp.status_code == 204- assert ingest_mod.buffer_size() == 1---def test_collect_rate_limited_429(app, analytics_client):- _mk_plugin_row(config={'collect_rate_per_min': 2})- site = _mk_site()- assert _collect(analytics_client, site.site_key).status_code == 204- assert _collect(analytics_client, site.site_key).status_code == 204- assert _collect(analytics_client, site.site_key).status_code == 429---def test_collect_origin_allowlist_enforced(app, analytics_client):- site = _mk_site(allowed_origins='https://example.com')- ok = _collect(analytics_client, site.site_key,- extra_headers={'Origin': 'https://example.com'})- assert ok.status_code == 204- assert ok.headers.get('Access-Control-Allow-Origin') == 'https://example.com'- bad = _collect(analytics_client, site.site_key,- extra_headers={'Origin': 'https://evil.test'})- assert bad.status_code == 403---def test_collect_reflects_origin_by_default(app, analytics_client):- site = _mk_site() # no allowlist => reflect- resp = _collect(analytics_client, site.site_key,- extra_headers={'Origin': 'https://anything.test'})- assert resp.headers.get('Access-Control-Allow-Origin') == 'https://anything.test'---def test_collect_options_preflight(app, analytics_client):- resp = analytics_client.options('/api/v1/analytics/collect',- headers={'Origin': 'https://example.com'})- assert resp.status_code == 204- assert resp.headers.get('Access-Control-Allow-Methods') == 'POST, OPTIONS'---def test_collect_stores_query_only_when_enabled(app, analytics_client):- _mk_plugin_row(config={'store_query_strings': True})- site = _mk_site()- _collect(analytics_client, site.site_key, path='/search', q='term=hats')- ingest_mod.flush_buffer(app)- ev = AnalyticsEvent.query.filter_by(site_id=site.id).one()- assert ev.url_query == 'term=hats'---def test_tracker_js_served_public(app, analytics_client):- resp = analytics_client.get('/api/v1/analytics/tracker.js')- assert resp.status_code == 200- assert 'javascript' in resp.headers['Content-Type']- assert resp.headers.get('Access-Control-Allow-Origin') == '*'- assert resp.headers.get('Cache-Control') == 'no-cache'---# --------------------------------------------------------------------------- #-# retention prune-# --------------------------------------------------------------------------- #-def test_retention_prune_deletes_old_events(app):- from app import db- from datetime import datetime, timedelta- site = _mk_site()- old = AnalyticsEvent(site_id=site.id, type='pageview', url_path='/old',- ts=datetime.utcnow() - timedelta(days=99), source='js')- fresh = AnalyticsEvent(site_id=site.id, type='pageview', url_path='/new',- ts=datetime.utcnow(), source='js')- db.session.add_all([old, fresh])- db.session.commit()- _mk_plugin_row(config={'raw_retention_days': 30})- result = rollup_mod.run_retention_prune()- assert result['deleted_events'] == 1- remaining = [e.url_path for e in AnalyticsEvent.query.filter_by(site_id=site.id)]- assert remaining == ['/new']---def test_retention_job_handler_never_raises(app):- _mk_plugin_row()- out = jobs_mod.retention_prune(job=None)- assert 'deleted_events' in out or 'error' in out---# --------------------------------------------------------------------------- #-# Phase 2: rollup + report API-# --------------------------------------------------------------------------- #-def _mk_event(site_id, visitor='v1', path='/home', ref=None, device='desktop',- browser='Chrome', os_family='Windows', country=None, load_ms=None,- days_ago=0, etype='pageview'):- from app import db- from datetime import datetime, timedelta- ev = AnalyticsEvent(- site_id=site_id, type=etype, url_path=path, referrer_host=ref,- visitor_hash=visitor, device_class=device, ua_family=browser,- os_family=os_family, country=country, load_ms=load_ms, source='js',- ts=datetime.utcnow() - timedelta(days=days_ago))- db.session.add(ev)- db.session.commit()- return ev---def test_rollup_aggregates_overall(app):- site = _mk_site()- # Two visitors today: v1 has 2 pageviews (not a bounce), v2 has 1 (a bounce).- _mk_event(site.id, visitor='v1', path='/a', load_ms=100)- _mk_event(site.id, visitor='v1', path='/b', load_ms=200)- _mk_event(site.id, visitor='v2', path='/a', load_ms=300)- out = rollup_mod.run_rollup()- assert out['rows'] > 0- row = AnalyticsDaily.query.filter_by(site_id=site.id, dim_type='overall').one()- assert row.visitors == 2- assert row.pageviews == 3- assert row.bounces == 1 # only v2 had a single pageview- assert row.avg_load_ms == 200.0 # (100+200+300)/3---def test_rollup_is_idempotent(app):- site = _mk_site()- _mk_event(site.id, visitor='v1', path='/a')- rollup_mod.run_rollup()- rollup_mod.run_rollup() # second run must not double-count- row = AnalyticsDaily.query.filter_by(site_id=site.id, dim_type='overall').one()- assert row.pageviews == 1---def test_rollup_dimensions(app):- site = _mk_site()- _mk_event(site.id, visitor='v1', path='/a', ref='google.com', device='mobile',- browser='Firefox', os_family='Android', country='US')- _mk_event(site.id, visitor='v2', path='/a', ref='google.com', device='desktop',- browser='Chrome', os_family='Windows', country='CA')- rollup_mod.run_rollup()- page = AnalyticsDaily.query.filter_by(site_id=site.id, dim_type='page',- dim_value='/a').one()- assert page.pageviews == 2 and page.visitors == 2- ref = AnalyticsDaily.query.filter_by(site_id=site.id, dim_type='referrer',- dim_value='google.com').one()- assert ref.pageviews == 2- countries = {r.dim_value for r in AnalyticsDaily.query.filter_by(- site_id=site.id, dim_type='country')}- assert countries == {'US', 'CA'}---def test_report_overview_and_pages(app):- from datetime import datetime, timedelta- site = _mk_site()- _mk_event(site.id, visitor='v1', path='/a')- _mk_event(site.id, visitor='v2', path='/a')- _mk_event(site.id, visitor='v1', path='/b')- rollup_mod.run_rollup()- end = datetime.utcnow().date()- start = end - timedelta(days=6)- ov = report_mod.overview(site.id, start, end)- assert ov['totals']['pageviews'] == 3- assert ov['totals']['visitors'] == 2- assert len(ov['timeseries']) == 7 # zero-filled 7-day window- top = {p['value']: p['pageviews'] for p in ov['top_pages']}- assert top['/a'] == 2 and top['/b'] == 1---def test_report_realtime_reads_raw_events(app):- site = _mk_site()- _mk_event(site.id, visitor='v1', path='/live')- _mk_event(site.id, visitor='v1', path='/live2')- _mk_event(site.id, visitor='v2', path='/live')- rt = report_mod.realtime(site.id, minutes=30)- assert rt['active_visitors'] == 2- assert rt['pageviews'] == 3- assert rt['recent'][0]['path'] in ('/live', '/live2')---def test_parse_range_defaults_and_explicit():- from datetime import datetime- s, e = report_mod.parse_range({})- assert (e - s).days == 6 # default 7d inclusive- s2, e2 = report_mod.parse_range({'range': '30d'})- assert (e2 - s2).days == 29- s3, e3 = report_mod.parse_range({'start': '2026-01-01', 'end': '2026-01-10'})- assert s3.isoformat() == '2026-01-01' and e3.isoformat() == '2026-01-10'---# --- site CRUD + RBAC ----def test_sites_crud_flow(app, analytics_client):- admin = _auth(_mk_admin())- # create- r = analytics_client.post('/api/v1/analytics/sites', headers=admin,- json={'name': 'Blog', 'hostnames': ['blog.example.com']})- assert r.status_code == 201- body = r.get_json()- sid = body['id']- assert body['site_key']- assert body['hostnames'] == ['blog.example.com']- # list- r = analytics_client.get('/api/v1/analytics/sites', headers=admin)- assert any(s['id'] == sid for s in r.get_json()['sites'])- # update- r = analytics_client.put(f'/api/v1/analytics/sites/{sid}', headers=admin,- json={'enabled': False})- assert r.get_json()['enabled'] is False- # rotate key- old_key = body['site_key']- r = analytics_client.post(f'/api/v1/analytics/sites/{sid}/rotate-key', headers=admin)- assert r.get_json()['site_key'] != old_key- # delete- r = analytics_client.delete(f'/api/v1/analytics/sites/{sid}', headers=admin)- assert r.status_code == 200- assert AnalyticsSite.query.get(sid) is None---def test_create_site_requires_name_400(app, analytics_client):- admin = _auth(_mk_admin())- r = analytics_client.post('/api/v1/analytics/sites', headers=admin, json={})- assert r.status_code == 400---def test_reads_allow_viewer(app, analytics_client):- viewer = _auth(_mk_viewer())- site = _mk_site()- r = analytics_client.get('/api/v1/analytics/sites', headers=viewer)- assert r.status_code == 200- r = analytics_client.get(f'/api/v1/analytics/sites/{site.id}/overview',- headers=viewer)- assert r.status_code == 200---def test_mutations_deny_viewer_403(app, analytics_client):- viewer = _auth(_mk_viewer())- r = analytics_client.post('/api/v1/analytics/sites', headers=viewer,- json={'name': 'x'})- assert r.status_code == 403---def test_reports_require_auth_401(app, analytics_client):- site = _mk_site()- r = analytics_client.get(f'/api/v1/analytics/sites/{site.id}/overview')- assert r.status_code in (401, 422) # missing/invalid JWT---def test_overview_endpoint_shape(app, analytics_client):- admin = _auth(_mk_admin())- site = _mk_site()- _mk_event(site.id, visitor='v1', path='/a')- rollup_mod.run_rollup()- r = analytics_client.get(f'/api/v1/analytics/sites/{site.id}/overview?range=30d',- headers=admin)- assert r.status_code == 200- body = r.get_json()- assert set(body) >= {'totals', 'timeseries', 'top_pages', 'top_referrers',- 'realtime', 'range'}---def test_devices_endpoint(app, analytics_client):- admin = _auth(_mk_admin())- site = _mk_site()- _mk_event(site.id, visitor='v1', device='mobile', browser='Safari',- os_family='iOS', country='US')- rollup_mod.run_rollup()- r = analytics_client.get(f'/api/v1/analytics/sites/{site.id}/devices',- headers=admin)- body = r.get_json()- assert body['device'][0]['value'] == 'mobile'- assert body['os'][0]['value'] == 'iOS'---def test_rollup_endpoint_admin_only(app, analytics_client):- viewer = _auth(_mk_viewer())- assert analytics_client.post('/api/v1/analytics/rollup',- headers=viewer).status_code == 403- admin = _auth(_mk_admin())- assert analytics_client.post('/api/v1/analytics/rollup',- headers=admin).status_code == 200---def test_rollup_job_handler_never_raises(app):- _mk_plugin_row()- out = jobs_mod.rollup(job=None)- assert 'rows' in out or 'error' in out or 'sites_dates' in out---# --------------------------------------------------------------------------- #-# Phase 3: tracker JS artifact + snippet-# --------------------------------------------------------------------------- #-def test_tracker_min_artifact_exists_and_bounded():- path = os.path.join(EXT_DIR, 'backend', 'tracker', 'sk.min.js')- assert os.path.exists(path), 'run scripts/build-analytics-tracker.mjs'- body = open(path, encoding='utf-8').read()- assert len(body.encode('utf-8')) < 4096 # <4 KB budget- assert '/*' not in body and '*/' not in body # comments stripped- assert 'sendBeacon' in body and 'data-site-key' in body---def test_tracker_js_serves_real_build(app, analytics_client):- bp_mod._TRACKER_CACHE['js'] = None # bypass any placeholder cached earlier- resp = analytics_client.get('/api/v1/analytics/tracker.js')- assert resp.status_code == 200- body = resp.get_data(as_text=True)- assert 'placeholder' not in body- assert 'sendBeacon' in body---def test_snippet_endpoint(app, analytics_client):- viewer = _auth(_mk_viewer())- site = _mk_site()- r = analytics_client.get(f'/api/v1/analytics/sites/{site.id}/snippet',- headers=viewer)- assert r.status_code == 200- body = r.get_json()- assert body['site_key'] == site.site_key- assert '/api/v1/analytics/tracker.js' in body['tracker_url']- assert f'data-site-key="{site.site_key}"' in body['snippet']- assert body['snippet'].startswith('<script defer')---def test_snippet_outlinks_flag(app, analytics_client):- viewer = _auth(_mk_viewer())- site = _mk_site()- r = analytics_client.get(- f'/api/v1/analytics/sites/{site.id}/snippet?outlinks=true', headers=viewer)- assert 'data-outlinks="true"' in r.get_json()['snippet']---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')---# --------------------------------------------------------------------------- #-# Phase 6: log ingestion + geo-# --------------------------------------------------------------------------- #-_LOG_LINE = (- '203.0.113.9 - - [10/Oct/2024:13:55:36 +0000] "GET /blog/post HTTP/1.1" '- '200 5120 "https://google.com/search" '- '"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 Chrome/120 Safari/537.36"'-)-_LOG_ASSET = (- '203.0.113.9 - - [10/Oct/2024:13:55:37 +0000] "GET /style.css HTTP/1.1" '- '200 1000 "-" "Mozilla/5.0 Chrome/120"'-)-_LOG_BOT = (- '203.0.113.9 - - [10/Oct/2024:13:55:38 +0000] "GET / HTTP/1.1" '- '200 1000 "-" "Googlebot/2.1"'-)-_LOG_POST = (- '203.0.113.9 - - [10/Oct/2024:13:55:39 +0000] "POST /wp-login.php HTTP/1.1" '- '200 1000 "-" "Mozilla/5.0 Chrome/120"'-)---def test_parse_combined_line():- p = log_mod.parse_combined_line(_LOG_LINE)- assert p['ip'] == '203.0.113.9'- assert p['path'] == '/blog/post'- assert p['status'] == '200'- assert 'google' in p['referer']- # assets, bots-by-request, and non-GET are filtered at parse time.- assert log_mod.parse_combined_line(_LOG_ASSET) is None # asset- assert log_mod.parse_combined_line(_LOG_POST) is None # non-GET- assert log_mod.parse_combined_line('garbage line') is None---def test_ingest_lines_creates_log_events(app):- site = _mk_site()- written, max_ts = log_mod.ingest_lines(site, [_LOG_LINE, _LOG_ASSET, _LOG_BOT])- assert written == 1 # only the real pageview (asset + bot dropped)- ev = AnalyticsEvent.query.filter_by(site_id=site.id).one()- assert ev.source == 'log'- assert ev.url_path == '/blog/post'- assert ev.referrer_host == 'google.com'- assert ev.ua_family == 'Chrome'- assert ev.visitor_hash and '203.0.113.9' not in ev.visitor_hash---def test_ingest_lines_dedup_by_since(app):- from datetime import datetime- site = _mk_site()- # since_ts at/after the line's ts => skipped.- boundary = datetime(2024, 10, 10, 14, 0, 0)- written, _ = log_mod.ingest_lines(site, [_LOG_LINE], since_ts=boundary)- assert written == 0---def test_log_file_cursor_advances(app, tmp_path):- site = _mk_site()- logf = tmp_path / 'access.log'- logf.write_text(_LOG_LINE + '\n', encoding='utf-8')- site.update_settings(log_ingestion=True, log_source_kind='file',- log_source_ref=str(logf))- from app import db- db.session.commit()-- res1 = log_mod.ingest_site(site)- assert res1['written'] == 1- # Second run with no new lines writes nothing (cursor advanced).- res2 = log_mod.ingest_site(site)- assert res2['written'] == 0- # Append a new line -> ingested on the next run.- with open(logf, 'a', encoding='utf-8') as f:- f.write(_LOG_LINE.replace('/blog/post', '/blog/post2') + '\n')- res3 = log_mod.ingest_site(site)- assert res3['written'] == 1- assert AnalyticsEvent.query.filter_by(site_id=site.id).count() == 2---def test_ingest_site_skips_when_disabled(app):- site = _mk_site() # no log_ingestion setting- assert log_mod.ingest_site(site).get('skipped') is True---def test_run_log_tail_iterates_enabled_sites(app, tmp_path):- _mk_plugin_row(config={'log_ingestion_enabled': True})- site = _mk_site()- logf = tmp_path / 'a.log'- logf.write_text(_LOG_LINE + '\n', encoding='utf-8')- site.update_settings(log_ingestion=True, log_source_kind='file',- log_source_ref=str(logf))- from app import db- db.session.commit()- out = log_mod.run_log_tail()- assert out['sites'] == 1 and out['written'] == 1---def test_run_log_tail_respects_global_toggle(app):- _mk_plugin_row(config={'log_ingestion_enabled': False})- out = log_mod.run_log_tail()- assert out.get('skipped') is True---def test_log_tail_job_handler_never_raises(app):- _mk_plugin_row(config={'log_ingestion_enabled': False})- out = jobs_mod.log_tail(job=None)- assert 'skipped' in out or 'sites' in out or 'error' in out---def test_ingest_logs_endpoint(app, analytics_client, tmp_path):- admin = _auth(_mk_admin())- site = _mk_site()- logf = tmp_path / 'x.log'- logf.write_text(_LOG_LINE + '\n', encoding='utf-8')- site.update_settings(log_ingestion=True, log_source_kind='file',- log_source_ref=str(logf))- from app import db- db.session.commit()- r = analytics_client.post(f'/api/v1/analytics/sites/{site.id}/ingest-logs',- headers=admin)- assert r.status_code == 200 and r.get_json()['written'] == 1---# --- geo ----def test_geo_disabled_returns_none(app):- _mk_plugin_row(config={'geo_enabled': False})- assert geo_mod.lookup_country('8.8.8.8') is None---def test_geo_enabled_but_no_db(app):- _mk_plugin_row(config={'geo_enabled': True, 'geo_db_path': '/nonexistent/GeoLite2.mmdb'})- geo_mod.reset()- assert geo_mod.lookup_country('8.8.8.8') is None---def test_build_event_country_none_by_default(app):- site = _mk_site()- event = ingest_mod.build_event(site, {'k': site.site_key, 'p': '/x'},- '8.8.8.8', UA_CHROME)- assert event['country'] is Nonediff --git a/backend/tests/test_crowdsec_extension.py b/backend/tests/test_crowdsec_extension.pydeleted file mode 100644index e77c4e9e..00000000--- a/backend/tests/test_crowdsec_extension.py+++ /dev/null@@ -1,427 +0,0 @@-"""serverkit-crowdsec extension tests (Panel Improvements #17).--Covers: manifest validity, cscli JSON parsing (decisions/alerts/status),-argv construction for mutations (subprocess stubbed), allowlist feature-detection + fallback, the not-installed path, and blueprint auth/happy-paths with the service stubbed.--The extension backend is loaded exactly the way production loads builtins:-``plugin_service._ensure_builtin_backend_importable`` registers-``builtin-extensions/serverkit-crowdsec/backend`` as ``app.plugins.serverkit-crowdsec``.-"""-import importlib-import json-import os-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-crowdsec'-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}')- svc_mod = importlib.import_module(f'app.plugins.{SLUG}.crowdsec_service')- bp_mod = importlib.import_module(f'app.plugins.{SLUG}.crowdsec')- return svc_mod, bp_mod---svc_mod, bp_mod = _load_ext()-CrowdSecService = svc_mod.CrowdSecService---# ----------------------------------------------------------------------------# fixtures-# -----------------------------------------------------------------------------DECISIONS_JSON = json.dumps([- {- 'id': 1,- 'scenario': 'crowdsecurity/ssh-bf',- 'created_at': '2026-07-01T10:00:00Z',- 'events_count': 6,- 'source': {- 'ip': '203.0.113.7', 'scope': 'Ip', 'value': '203.0.113.7',- 'cn': 'US', 'as_name': 'ExampleNet',- },- 'decisions': [- {- 'id': 42, 'origin': 'crowdsec', 'type': 'ban', 'scope': 'Ip',- 'value': '203.0.113.7', 'duration': '3h59m',- 'scenario': 'crowdsecurity/ssh-bf',- },- {- 'id': 43, 'origin': 'cscli', 'type': 'captcha', 'scope': 'Ip',- 'value': '203.0.113.7', 'duration': '1h',- 'scenario': 'manual',- },- ],- },-])--ALERTS_JSON = json.dumps([- {- 'id': 7,- 'scenario': 'crowdsecurity/http-probing',- 'created_at': '2026-07-02T08:30:00Z',- 'events_count': 11,- 'source': {'ip': '198.51.100.3', 'value': '198.51.100.3', 'cn': 'DE'},- 'decisions': [{'id': 99, 'type': 'ban', 'value': '198.51.100.3'}],- },-])---def _proc(returncode=0, stdout='', stderr=''):- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)---def linux(monkeypatch):- """Pretend we're on Linux with cscli installed."""- monkeypatch.setattr(svc_mod.os, 'name', 'posix')- monkeypatch.setattr(svc_mod, 'is_command_available', lambda c: True)---def calls(monkeypatch, linux):- """Capture every cscli argv; return success with empty output."""- seen = []-- def fake_run(cmd, timeout=None, **kwargs):- seen.append(list(cmd))- return _proc()-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- return seen---# ----------------------------------------------------------------------------# manifest-# -----------------------------------------------------------------------------def test_manifest_passes_validator():- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert plugin_service._validate_manifest(manifest) is True- assert manifest['name'] == SLUG- assert manifest['category'] == 'security'- assert manifest['entry_point'] == 'crowdsec:crowdsec_bp'- assert manifest['url_prefix'] == '/api/v1/crowdsec'- nav = manifest['contributions']['nav'][0]- assert nav['route'] == '/crowdsec'- routes = manifest['contributions']['routes']- assert {'path': 'crowdsec', 'component': 'CrowdSecPage'} in routes---def test_entry_point_resolves_to_blueprint():- assert getattr(bp_mod, 'crowdsec_bp', None) is not None- assert bp_mod.crowdsec_bp.name == 'crowdsec'---def test_frontend_exports_route_component():- with open(os.path.join(EXT_DIR, 'frontend', 'index.jsx'), encoding='utf-8') as f:- src = f.read()- assert 'CrowdSecPage' in src---# ----------------------------------------------------------------------------# service: parsing-# -----------------------------------------------------------------------------def test_list_decisions_flattens_alert_nesting(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout=DECISIONS_JSON))- result = CrowdSecService.list_decisions()- assert result['success'] is True- assert len(result['decisions']) == 2- first = result['decisions'][0]- assert first['value'] == '203.0.113.7'- assert first['type'] == 'ban'- assert first['scope'] == 'Ip'- assert first['duration'] == '3h59m'- assert first['reason'] == 'crowdsecurity/ssh-bf'- assert first['country'] == 'US'- assert first['created_at'] == '2026-07-01T10:00:00Z'- assert result['decisions'][1]['type'] == 'captcha'---def test_list_decisions_null_output_is_empty(monkeypatch, linux):- # cscli prints the literal string "null" when nothing matches.- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout='null\n'))- result = CrowdSecService.list_decisions()- assert result['success'] is True- assert result['decisions'] == []---def test_list_alerts_normalizes(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout=ALERTS_JSON))- result = CrowdSecService.list_alerts(limit=10)- assert result['success'] is True- a = result['alerts'][0]- assert a['scenario'] == 'crowdsecurity/http-probing'- assert a['source'] == '198.51.100.3'- assert a['events_count'] == 11- assert a['decisions'] == 1---def test_get_status_parses_version_and_lapi(monkeypatch, linux):- def fake_run(cmd, timeout=None, **kwargs):- if cmd[:2] == ['cscli', 'version']:- # cscli historically prints version info to stderr.- return _proc(stderr='version: v1.6.8\nBuildDate: 2026-05-01\n')- if cmd[:3] == ['cscli', 'lapi', 'status']:- return _proc(stderr='You can successfully interact with Local API (LAPI)')- if cmd[:2] == ['cscli', 'allowlists']:- return _proc(stdout='[]')- return _proc()-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- monkeypatch.setattr(svc_mod.ServiceControl, 'is_active',- staticmethod(lambda s: True))- status = CrowdSecService.get_status()- assert status['installed'] is True- assert status['running'] is True- assert status['version'] == '1.6.8'- assert status['lapi_ok'] is True- assert status['allowlists_supported'] is True- assert status['docs_url']---def test_invalid_json_is_clean_error(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout='not json {'))- result = CrowdSecService.list_decisions()- assert result['success'] is False- assert 'JSON' in result['error']---# ----------------------------------------------------------------------------# service: argv construction-# -----------------------------------------------------------------------------def test_add_decision_builds_correct_argv(calls):- result = CrowdSecService.add_decision('203.0.113.7', duration='4h', reason='bad actor')- assert result['success'] is True- assert calls == [[- 'cscli', 'decisions', 'add', '--ip', '203.0.113.7',- '--duration', '4h', '--reason', 'bad actor', '--type', 'ban',- ]]---def test_add_decision_range_uses_range_flag(calls):- result = CrowdSecService.add_decision('203.0.113.0/24', duration='1h', reason='sweep')- assert result['success'] is True- assert calls[0][:5] == ['cscli', 'decisions', 'add', '--range', '203.0.113.0/24']---def test_delete_decision_builds_correct_argv(calls):- result = CrowdSecService.delete_decision('203.0.113.7')- assert result['success'] is True- assert calls == [['cscli', 'decisions', 'delete', '--ip', '203.0.113.7']]---def test_add_decision_rejects_bad_input(calls):- assert CrowdSecService.add_decision('not-an-ip')['success'] is False- assert CrowdSecService.add_decision('1.2.3.4; rm -rf /')['success'] is False- assert CrowdSecService.add_decision('1.2.3.4', duration='4 hours')['success'] is False- assert calls == [] # nothing ever reached cscli---def test_allowlist_add_builds_correct_argv(calls):- result = CrowdSecService.add_allowlist_entry(- 'trusted', '10.0.0.0/8', expiration='24h', comment='office')- assert result['success'] is True- assert calls == [[- 'cscli', 'allowlists', 'add', 'trusted', '10.0.0.0/8',- '--expiration', '24h', '--comment', 'office',- ]]---# ----------------------------------------------------------------------------# service: feature detection + not-installed-# -----------------------------------------------------------------------------def test_allowlists_unsupported_falls_back_to_message(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(- returncode=1, stderr='unknown command "allowlists" for "cscli"'))- assert CrowdSecService.allowlists_supported() is False- result = CrowdSecService.list_allowlists()- assert result['success'] is True- assert result['supported'] is False- assert result['allowlists'] == []- assert 'does not support' in result['message']---def test_allowlists_supported_when_command_exists(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(- stdout='[{"name": "trusted", "description": "office"}]'))- result = CrowdSecService.list_allowlists()- assert result['supported'] is True- assert result['allowlists'][0]['name'] == 'trusted'---def test_not_installed_is_clean(monkeypatch):- monkeypatch.setattr(svc_mod.os, 'name', 'posix')- monkeypatch.setattr(svc_mod, 'is_command_available', lambda c: False)- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda *a, **kw: pytest.fail('cscli must not run when not installed'))- assert CrowdSecService.is_installed() is False- status = CrowdSecService.get_status()- assert status['installed'] is False- assert status['docs_url']- result = CrowdSecService.list_decisions()- assert result['success'] is False- assert result.get('not_installed') is True---def test_windows_is_unsupported(monkeypatch):- monkeypatch.setattr(svc_mod.os, 'name', 'nt')- assert CrowdSecService.is_installed() is False- result = CrowdSecService._cscli(['decisions', 'list'])- assert result['success'] is False- assert 'Windows' in result['error']---# ----------------------------------------------------------------------------# blueprint routes-# -----------------------------------------------------------------------------def cs_app(app):- """Register the extension blueprint on the test app (name-guarded)."""- if 'crowdsec' not in app.blueprints:- app.register_blueprint(bp_mod.crowdsec_bp, url_prefix='/api/v1/crowdsec')- return app---def cs_client(cs_app):- return cs_app.test_client()---def test_routes_require_auth(cs_client):- assert cs_client.get('/api/v1/crowdsec/status').status_code == 401- assert cs_client.post('/api/v1/crowdsec/decisions', json={'ip': '1.2.3.4'}).status_code == 401- assert cs_client.delete('/api/v1/crowdsec/decisions/1.2.3.4').status_code == 401---def test_status_route(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(- CrowdSecService, 'get_status',- classmethod(lambda cls: {- 'installed': True, 'running': True, 'version': '1.6.8',- 'lapi_ok': True, 'allowlists_supported': True,- 'docs_url': svc_mod.DOCS_URL,- }))- resp = cs_client.get('/api/v1/crowdsec/status', headers=auth_headers)- assert resp.status_code == 200- data = resp.get_json()- assert data['installed'] is True- assert data['version'] == '1.6.8'---def test_decisions_routes_happy_path(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(CrowdSecService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- CrowdSecService, 'list_decisions',- classmethod(lambda cls, ip=None, scope=None, dtype=None: {- 'success': True,- 'decisions': [{'id': 42, 'value': '203.0.113.7', 'type': 'ban'}],- }))- resp = cs_client.get('/api/v1/crowdsec/decisions', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['decisions'][0]['value'] == '203.0.113.7'-- added = {}-- def fake_add(cls, ip, duration='4h', reason='', dtype='ban'):- added.update(ip=ip, duration=duration, reason=reason)- return {'success': True, 'message': 'ok'}-- monkeypatch.setattr(CrowdSecService, 'add_decision', classmethod(fake_add))- resp = cs_client.post(- '/api/v1/crowdsec/decisions',- json={'ip': '203.0.113.7', 'duration': '12h', 'reason': 'test'},- headers=auth_headers)- assert resp.status_code == 201- assert added == {'ip': '203.0.113.7', 'duration': '12h', 'reason': 'test'}-- monkeypatch.setattr(- CrowdSecService, 'delete_decision',- classmethod(lambda cls, ip: {'success': True, 'message': f'deleted {ip}'}))- resp = cs_client.delete('/api/v1/crowdsec/decisions/203.0.113.7', headers=auth_headers)- assert resp.status_code == 200---def test_post_decision_requires_ip(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(CrowdSecService, 'is_installed', classmethod(lambda cls: True))- resp = cs_client.post('/api/v1/crowdsec/decisions', json={}, headers=auth_headers)- assert resp.status_code == 400- assert 'error' in resp.get_json()---def test_routes_report_not_installed(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(CrowdSecService, 'is_installed', classmethod(lambda cls: False))- for method, path in [- ('get', '/api/v1/crowdsec/decisions'),- ('get', '/api/v1/crowdsec/alerts'),- ('get', '/api/v1/crowdsec/allowlists'),- ('get', '/api/v1/crowdsec/metrics'),- ('post', '/api/v1/crowdsec/decisions'),- ]:- resp = getattr(cs_client, method)(path, headers=auth_headers, json={})- assert resp.status_code == 503, path- assert 'error' in resp.get_json()---def test_allowlists_route_unsupported_fallback(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(CrowdSecService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- CrowdSecService, 'list_allowlists',- classmethod(lambda cls: {- 'success': True, 'supported': False, 'allowlists': [],- 'message': CrowdSecService._ALLOWLISTS_UNSUPPORTED_MSG,- }))- resp = cs_client.get('/api/v1/crowdsec/allowlists', headers=auth_headers)- assert resp.status_code == 200- data = resp.get_json()- assert data['supported'] is False- assert data['allowlists'] == []- assert data['message']---def test_alerts_and_metrics_routes(cs_client, auth_headers, monkeypatch):- monkeypatch.setattr(CrowdSecService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- CrowdSecService, 'list_alerts',- classmethod(lambda cls, limit=50: {- 'success': True, 'alerts': [{'id': 7, 'scenario': 'x'}]}))- monkeypatch.setattr(- CrowdSecService, 'get_metrics',- classmethod(lambda cls: {'success': True, 'metrics': {'acquisition': {}}}))-- resp = cs_client.get('/api/v1/crowdsec/alerts', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['alerts'][0]['id'] == 7-- resp = cs_client.get('/api/v1/crowdsec/metrics', headers=auth_headers)- assert resp.status_code == 200- assert 'metrics' in resp.get_json()diff --git a/backend/tests/test_dns_server_extension.py b/backend/tests/test_dns_server_extension.pydeleted file mode 100644index 3816fcfd..00000000--- a/backend/tests/test_dns_server_extension.py+++ /dev/null@@ -1,674 +0,0 @@-"""serverkit-dns-server extension tests (Panel Improvements #28).--Covers: manifest validity, install argv construction (docker stubbed) incl.-the localhost-only API binding and generated-api-key persistence, zone-creation SOA/NS bootstrap, rrset upsert/delete PowerDNS API call shapes-(requests stubbed), record-type/name validation, DNSSEC enable returning DS-records, the hand-rolled delegation-check DNS parser on fixture packet-bytes, and blueprint auth/503/happy paths with the service stubbed.--The extension backend is loaded exactly the way production loads builtins:-``plugin_service._ensure_builtin_backend_importable`` registers-``builtin-extensions/serverkit-dns-server/backend`` as-``app.plugins.serverkit-dns-server``.-"""-import importlib-import json-import os-import struct-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-dns-server'-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}')- svc_mod = importlib.import_module(f'app.plugins.{SLUG}.dns_server_service')- bp_mod = importlib.import_module(f'app.plugins.{SLUG}.dns_server')- return svc_mod, bp_mod---svc_mod, bp_mod = _load_ext()-DnsServerService = svc_mod.DnsServerService--CFG = {- 'api_key': 'test-api-key',- 'ns_hostname': 'ns1.example.com',- 'admin_email': '[email protected]',-}---def _proc(returncode=0, stdout='', stderr=''):- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)---class FakeResponse:- def __init__(self, status_code=200, data=None, text=''):- self.status_code = status_code- self._data = data- self.text = text or (json.dumps(data) if data is not None else '')- self.content = self.text.encode()-- def json(self):- if self._data is None:- raise ValueError('no json')- return self._data---def linux(monkeypatch):- """Pretend we're on Linux with docker installed and config saved."""- monkeypatch.setattr(svc_mod.os, 'name', 'posix')- monkeypatch.setattr(svc_mod, 'is_command_available', lambda c: True)- monkeypatch.setattr(DnsServerService, '_config', classmethod(lambda cls: dict(CFG)))---def api_calls(monkeypatch, linux):- """Capture every PowerDNS API request; return success with empty body."""- seen = []-- def fake_request(method, url, headers=None, json=None, timeout=None):- seen.append({'method': method, 'url': url, 'headers': headers, 'json': json})- return FakeResponse(204, None, '')-- monkeypatch.setattr(svc_mod.requests, 'request', fake_request)- return seen---# ----------------------------------------------------------------------------# manifest-# -----------------------------------------------------------------------------def test_manifest_passes_validator():- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert plugin_service._validate_manifest(manifest) is True- assert manifest['name'] == SLUG- assert manifest['category'] == 'networking'- assert set(manifest['permissions']) == {'shell', 'docker'}- assert manifest['entry_point'] == 'dns_server:dns_server_bp'- assert manifest['url_prefix'] == '/api/v1/dns-server'- nav = manifest['contributions']['nav'][0]- assert nav['route'] == '/dns-server'- routes = manifest['contributions']['routes']- assert {'path': 'dns-server', 'component': 'DnsServerPage'} in routes- assert manifest['contributions']['page_titles']['/dns-server'] == 'DNS Server'---def test_manifest_permissions_are_known():- from app.plugins_sdk import permissions as sdk_perms- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert sdk_perms.unknown_permissions(manifest['permissions']) == []---def test_entry_point_resolves_to_blueprint():- assert getattr(bp_mod, 'dns_server_bp', None) is not None- assert bp_mod.dns_server_bp.name == 'dns_server'---def test_frontend_exports_route_component():- with open(os.path.join(EXT_DIR, 'frontend', 'index.jsx'), encoding='utf-8') as f:- src = f.read()- assert 'export { default as DnsServerPage }' in src- # No module-level default export: PluginLoader legacy-auto-renders those.- assert 'export default' not in src---# ----------------------------------------------------------------------------# service: install / uninstall argv-# -----------------------------------------------------------------------------def test_install_builds_correct_docker_run(monkeypatch, linux):- calls = []- saved = {}-- def fake_run(cmd, timeout=None, **kwargs):- calls.append(list(cmd))- if cmd[:2] == ['docker', 'inspect']:- return _proc(returncode=1, stderr='No such object')- return _proc(stdout='abc123\n')-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- monkeypatch.setattr(DnsServerService, '_save_config',- classmethod(lambda cls, updates: saved.update(updates) or True))-- result = DnsServerService.install('NS1.Example.COM.', '[email protected]')- assert result['success'] is True, result-- # Data dir created, container started.- assert ['mkdir', '-p', svc_mod.DATA_DIR] in calls- run_cmd = next(c for c in calls if c[:2] == ['docker', 'run'])-- # Port 53 published tcp+udp; API published on loopback ONLY.- assert '53:53/udp' in run_cmd- assert '53:53/tcp' in run_cmd- assert '127.0.0.1:8081:8081' in run_cmd- assert not any(a == '8081:8081' for a in run_cmd)-- # SQLite volume + official image.- assert f'{svc_mod.DATA_DIR}:{svc_mod.CONTAINER_DB_DIR}' in run_cmd- assert svc_mod.IMAGE in run_cmd- assert '--restart' in run_cmd-- # API enabled with a generated key... that was persisted to the config store.- assert '--api=yes' in run_cmd- key_args = [a for a in run_cmd if a.startswith('--api-key=')]- assert len(key_args) == 1- generated = key_args[0].split('=', 1)[1]- assert len(generated) == 48 # token_hex(24)- assert saved['api_key'] == generated- assert saved['ns_hostname'] == 'ns1.example.com'- assert saved['admin_email'] == '[email protected]'---def test_install_rejects_bad_params(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda *a, **kw: pytest.fail('docker must not run on invalid input'))- assert DnsServerService.install('', '[email protected]')['success'] is False- assert DnsServerService.install('not a hostname!', '[email protected]')['success'] is False- assert DnsServerService.install('ns1.example.com', 'not-an-email')['success'] is False- assert DnsServerService.install('ns1.example.com', '')['success'] is False---def test_install_refuses_when_container_exists(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout='true\n')) # inspect succeeds- result = DnsServerService.install('ns1.example.com', '[email protected]')- assert result['success'] is False- assert 'already exists' in result['error']---def test_uninstall_keep_data_leaves_data_dir(monkeypatch, linux):- calls = []-- def fake_run(cmd, timeout=None, **kwargs):- calls.append(list(cmd))- return _proc()-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- monkeypatch.setattr(DnsServerService, '_save_config',- classmethod(lambda cls, updates: True))-- result = DnsServerService.uninstall(keep_data=True)- assert result['success'] is True- assert ['docker', 'rm', '-f', svc_mod.CONTAINER_NAME] in calls- assert not any(c[:1] == ['rm'] for c in calls)-- calls.clear()- result = DnsServerService.uninstall(keep_data=False)- assert result['success'] is True- assert ['rm', '-rf', svc_mod.DATA_DIR] in calls---def test_windows_is_unsupported(monkeypatch):- monkeypatch.setattr(svc_mod.os, 'name', 'nt')- assert DnsServerService.is_installed() is False- result = DnsServerService.install('ns1.example.com', '[email protected]')- assert result['success'] is False- assert 'Windows' in result['error']- status = DnsServerService.get_status()- assert status['installed'] is False- assert status['authoritative_only'] is True---# ----------------------------------------------------------------------------# service: status-# -----------------------------------------------------------------------------def test_status_running_reads_version_from_api(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(stdout='true\n'))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda method, url, **kw: FakeResponse(200, {'version': '4.9.3'}))- status = DnsServerService.get_status()- assert status['installed'] is True- assert status['running'] is True- assert status['version'] == '4.9.3'- assert status['ns_hostname'] == 'ns1.example.com'---def test_status_not_installed(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(returncode=1, stderr='No such object'))- status = DnsServerService.get_status()- assert status['installed'] is False- assert status['running'] is False---# ----------------------------------------------------------------------------# service: zones + rrsets (PowerDNS API call shapes)-# -----------------------------------------------------------------------------def test_create_zone_bootstraps_soa_and_ns(api_calls):- result = DnsServerService.create_zone('Example.COM')- assert result['success'] is True, result- assert len(api_calls) == 1- call = api_calls[0]- assert call['method'] == 'POST'- assert call['url'].endswith('/servers/localhost/zones')- assert call['url'].startswith('http://127.0.0.1:8081')- assert call['headers']['X-API-Key'] == 'test-api-key'-- payload = call['json']- assert payload['name'] == 'example.com.'- assert payload['kind'] == 'Native'- rrsets = {r['type']: r for r in payload['rrsets']}- assert rrsets['SOA']['records'][0]['content'] == (- 'ns1.example.com. hostmaster.example.com. 1 10800 3600 604800 3600')- assert rrsets['NS']['records'][0]['content'] == 'ns1.example.com.'- assert all(r['name'] == 'example.com.' for r in payload['rrsets'])---def test_create_zone_rejects_junk(api_calls):- assert DnsServerService.create_zone('')['success'] is False- assert DnsServerService.create_zone('no spaces allowed.com')['success'] is False- assert DnsServerService.create_zone('*.example.com')['success'] is False- assert api_calls == []---def test_upsert_rrset_builds_replace_patch(api_calls):- result = DnsServerService.upsert_rrset(- 'example.com', 'www', 'a', 300, ['203.0.113.7', '203.0.113.8'])- assert result['success'] is True, result- call = api_calls[0]- assert call['method'] == 'PATCH'- assert call['url'].endswith('/servers/localhost/zones/example.com.')- rrset = call['json']['rrsets'][0]- assert rrset['name'] == 'www.example.com.'- assert rrset['type'] == 'A'- assert rrset['ttl'] == 300- assert rrset['changetype'] == 'REPLACE'- assert rrset['records'] == [- {'content': '203.0.113.7', 'disabled': False},- {'content': '203.0.113.8', 'disabled': False},- ]---def test_upsert_rrset_apex_and_absolute_names(api_calls):- assert DnsServerService.upsert_rrset(- 'example.com', '@', 'TXT', 3600, ['"v=spf1 -all"'])['success'] is True- assert api_calls[-1]['json']['rrsets'][0]['name'] == 'example.com.'-- assert DnsServerService.upsert_rrset(- 'example.com', 'mail.example.com.', 'MX', 3600,- ['10 mail.example.com.'])['success'] is True- assert api_calls[-1]['json']['rrsets'][0]['name'] == 'mail.example.com.'---def test_rrset_validation_rejects_junk(api_calls):- # Unknown record type.- assert DnsServerService.upsert_rrset(- 'example.com', 'www', 'ANAME', 300, ['x'])['success'] is False- # Out-of-zone absolute name.- assert DnsServerService.upsert_rrset(- 'example.com', 'www.other.org.', 'A', 300, ['1.2.3.4'])['success'] is False- # Bad label characters.- assert DnsServerService.upsert_rrset(- 'example.com', 'bad label', 'A', 300, ['1.2.3.4'])['success'] is False- # Bad TTL / empty records.- assert DnsServerService.upsert_rrset(- 'example.com', 'www', 'A', 'soon', ['1.2.3.4'])['success'] is False- assert DnsServerService.upsert_rrset(- 'example.com', 'www', 'A', 300, [])['success'] is False- # SOA delete is refused.- assert DnsServerService.delete_rrset(- 'example.com', '@', 'SOA')['success'] is False- assert api_calls == [] # nothing ever reached the PowerDNS API---def test_delete_rrset_builds_delete_patch(api_calls):- result = DnsServerService.delete_rrset('example.com', 'www', 'A')- assert result['success'] is True- rrset = api_calls[0]['json']['rrsets'][0]- assert rrset['changetype'] == 'DELETE'- assert rrset['name'] == 'www.example.com.'- assert rrset['records'] == []---def test_wildcard_record_names_allowed(api_calls):- result = DnsServerService.upsert_rrset(- 'example.com', '*', 'A', 300, ['203.0.113.7'])- assert result['success'] is True- assert api_calls[0]['json']['rrsets'][0]['name'] == '*.example.com.'---# ----------------------------------------------------------------------------# service: DNSSEC-# -----------------------------------------------------------------------------def test_dnssec_enable_returns_ds_records(monkeypatch, linux):- calls = []- DS = ['12345 13 2 aabbccdd...', '12345 13 4 eeff0011...']-- def fake_request(method, url, headers=None, json=None, timeout=None):- calls.append({'method': method, 'url': url, 'json': json})- if method == 'GET' and url.endswith('/cryptokeys'):- return FakeResponse(200, [- {'active': True, 'ds': DS},- {'active': False, 'ds': ['ignored inactive key']},- ])- return FakeResponse(204, None, '')-- monkeypatch.setattr(svc_mod.requests, 'request', fake_request)- result = DnsServerService.set_dnssec('example.com', True)- assert result['success'] is True- assert result['dnssec'] is True- assert result['ds_records'] == DS-- put = calls[0]- assert put['method'] == 'PUT'- assert put['url'].endswith('/servers/localhost/zones/example.com.')- assert put['json'] == {'dnssec': True, 'api_rectify': True}---def test_dnssec_disable(api_calls):- result = DnsServerService.set_dnssec('example.com', False)- assert result['success'] is True- assert result['dnssec'] is False- assert api_calls[0]['json'] == {'dnssec': False}---def test_api_error_is_clean(monkeypatch, linux):- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda method, url, **kw: FakeResponse(422, {'error': 'Domain already exists'}))- result = DnsServerService.create_zone('example.com')- assert result['success'] is False- assert 'Domain already exists' in result['error']---def test_api_requires_key(monkeypatch, linux):- monkeypatch.setattr(DnsServerService, '_config', classmethod(lambda cls: {}))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda *a, **kw: pytest.fail('API must not be called without a key'))- result = DnsServerService.list_zones()- assert result['success'] is False- assert 'API key' in result['error']---# ----------------------------------------------------------------------------# service: delegation check (mini DNS client)-# -----------------------------------------------------------------------------def _ns_response_packet(query_id):- """A DNS response for `example.com NS` with two compressed NS answers."""- header = struct.pack('>HHHHHH', query_id, 0x8180, 1, 2, 0, 0)- qname = b'\x07example\x03com\x00'- question = qname + struct.pack('>HH', 2, 1)- # Answers use a compression pointer back to offset 12 for both the owner- # name and the rdata suffix.- ptr = b'\xc0\x0c'- answer1 = ptr + struct.pack('>HHIH', 2, 1, 3600, 6) + b'\x03ns1' + ptr- answer2 = ptr + struct.pack('>HHIH', 2, 1, 3600, 6) + b'\x03ns2' + ptr- return header + question + answer1 + answer2---def test_parse_ns_response_fixture_packet():- packet = _ns_response_packet(0x1234)- names = DnsServerService._parse_ns_response(packet, 0x1234)- assert names == ['ns1.example.com', 'ns2.example.com']---def test_parse_ns_response_rejects_id_mismatch():- packet = _ns_response_packet(0x1234)- with pytest.raises(ValueError):- DnsServerService._parse_ns_response(packet, 0x9999)---def test_parse_ns_response_rejects_truncated():- with pytest.raises(ValueError):- DnsServerService._parse_ns_response(b'\x00\x01\x02', 1)---def test_build_ns_query_roundtrip():- packet = DnsServerService._build_ns_query('example.com.', 0x4242)- rid, flags, qdcount, ancount, _, _ = struct.unpack('>HHHHHH', packet[:12])- assert rid == 0x4242- assert flags == 0x0100 # RD- assert (qdcount, ancount) == (1, 0)- assert b'\x07example\x03com\x00' in packet- assert packet.endswith(struct.pack('>HH', 2, 1))---def test_check_delegation_match(monkeypatch, linux):- monkeypatch.setattr(- DnsServerService, 'get_zone',- classmethod(lambda cls, z: {'success': True, 'zone': {'rrsets': [- {'name': 'example.com.', 'type': 'NS',- 'records': ['ns1.example.com.', 'ns2.example.com.']},- ]}}))- monkeypatch.setattr(- DnsServerService, '_query_public_ns',- classmethod(lambda cls, z: ['ns2.example.com', 'ns1.example.com']))- result = DnsServerService.check_delegation('example.com')- assert result['success'] is True- assert result['checked'] is True- assert result['delegated'] is True- assert result['zone_ns'] == ['ns1.example.com', 'ns2.example.com']---def test_check_delegation_mismatch_and_unreachable(monkeypatch, linux):- monkeypatch.setattr(- DnsServerService, 'get_zone',- classmethod(lambda cls, z: {'success': True, 'zone': {'rrsets': [- {'name': 'example.com.', 'type': 'NS', 'records': ['ns1.example.com.']},- ]}}))- monkeypatch.setattr(- DnsServerService, '_query_public_ns',- classmethod(lambda cls, z: ['dns1.registrar-parking.net']))- result = DnsServerService.check_delegation('example.com')- assert result['delegated'] is False- assert result['note']-- def boom(cls, z):- raise OSError('network down')-- monkeypatch.setattr(DnsServerService, '_query_public_ns', classmethod(boom))- result = DnsServerService.check_delegation('example.com')- assert result['success'] is True # best-effort, never a hard failure- assert result['checked'] is False- assert 'network down' in result['note']---# ----------------------------------------------------------------------------# blueprint routes-# -----------------------------------------------------------------------------def dns_app(app):- """Register the extension blueprint on the test app (name-guarded)."""- if 'dns_server' not in app.blueprints:- app.register_blueprint(bp_mod.dns_server_bp, url_prefix='/api/v1/dns-server')- return app---def dns_client(dns_app):- return dns_app.test_client()---def test_routes_require_auth(dns_client):- assert dns_client.get('/api/v1/dns-server/status').status_code == 401- assert dns_client.post('/api/v1/dns-server/install', json={}).status_code == 401- assert dns_client.get('/api/v1/dns-server/zones').status_code == 401- assert dns_client.post('/api/v1/dns-server/zones', json={}).status_code == 401---def test_status_route(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(- DnsServerService, 'get_status',- classmethod(lambda cls: {- 'installed': True, 'running': True, 'version': '4.9.3',- 'image': svc_mod.IMAGE, 'container': svc_mod.CONTAINER_NAME,- 'ns_hostname': 'ns1.example.com', 'authoritative_only': True,- 'docs_url': svc_mod.DOCS_URL,- }))- resp = dns_client.get('/api/v1/dns-server/status', headers=auth_headers)- assert resp.status_code == 200- data = resp.get_json()- assert data['installed'] is True- assert data['version'] == '4.9.3'- assert data['authoritative_only'] is True---def test_install_route(dns_client, auth_headers, monkeypatch):- captured = {}-- def fake_install(cls, ns_hostname, admin_email):- captured.update(ns=ns_hostname, email=admin_email)- return {'success': True, 'message': 'ok', 'container': svc_mod.CONTAINER_NAME}-- monkeypatch.setattr(DnsServerService, 'install', classmethod(fake_install))- resp = dns_client.post(- '/api/v1/dns-server/install',- json={'ns_hostname': 'ns1.example.com', 'admin_email': '[email protected]'},- headers=auth_headers)- assert resp.status_code == 201- assert captured == {'ns': 'ns1.example.com', 'email': '[email protected]'}-- # Missing fields are a 400 before the service is touched.- resp = dns_client.post('/api/v1/dns-server/install', json={}, headers=auth_headers)- assert resp.status_code == 400- assert 'error' in resp.get_json()---def test_uninstall_route_parses_keep_data(dns_client, auth_headers, monkeypatch):- seen = {}- monkeypatch.setattr(- DnsServerService, 'uninstall',- classmethod(lambda cls, keep_data=True: seen.update(keep=keep_data)- or {'success': True, 'message': 'removed'}))- resp = dns_client.delete('/api/v1/dns-server/install?keep_data=false',- headers=auth_headers)- assert resp.status_code == 200- assert seen['keep'] is False- dns_client.delete('/api/v1/dns-server/install', headers=auth_headers)- assert seen['keep'] is True---def test_routes_report_not_installed(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: False))- for method, path in [- ('get', '/api/v1/dns-server/zones'),- ('post', '/api/v1/dns-server/zones'),- ('get', '/api/v1/dns-server/zones/example.com'),- ('delete', '/api/v1/dns-server/zones/example.com'),- ('post', '/api/v1/dns-server/zones/example.com/rrsets'),- ('delete', '/api/v1/dns-server/zones/example.com/rrsets'),- ('post', '/api/v1/dns-server/zones/example.com/dnssec'),- ]:- resp = getattr(dns_client, method)(path, headers=auth_headers, json={})- assert resp.status_code == 503, path- assert 'error' in resp.get_json()---def test_zones_routes_happy_path(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- DnsServerService, 'list_zones',- classmethod(lambda cls: {'success': True, 'zones': [- {'name': 'example.com.', 'kind': 'Native', 'serial': 1, 'dnssec': False},- ]}))- resp = dns_client.get('/api/v1/dns-server/zones', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['zones'][0]['name'] == 'example.com.'-- monkeypatch.setattr(- DnsServerService, 'create_zone',- classmethod(lambda cls, name: {'success': True, 'zone': 'example.com.',- 'message': 'created'}))- resp = dns_client.post('/api/v1/dns-server/zones',- json={'name': 'example.com'}, headers=auth_headers)- assert resp.status_code == 201-- resp = dns_client.post('/api/v1/dns-server/zones', json={}, headers=auth_headers)- assert resp.status_code == 400---def test_zone_detail_route_includes_ds_and_delegation(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- DnsServerService, 'get_zone',- classmethod(lambda cls, z: {'success': True, 'zone': {- 'name': 'example.com.', 'kind': 'Native', 'serial': 1,- 'dnssec': True, 'rrsets': [],- }}))- monkeypatch.setattr(- DnsServerService, 'get_ds_records',- classmethod(lambda cls, z: {'success': True, 'ds_records': ['12345 13 2 aa']}))- monkeypatch.setattr(- DnsServerService, 'check_delegation',- classmethod(lambda cls, z: {'success': True, 'checked': True,- 'delegated': True, 'zone_ns': [],- 'public_ns': [], 'note': None}))- resp = dns_client.get('/api/v1/dns-server/zones/example.com', headers=auth_headers)- assert resp.status_code == 200- data = resp.get_json()- assert data['zone']['dnssec'] is True- assert data['ds_records'] == ['12345 13 2 aa']- assert data['delegation']['delegated'] is True---def test_rrset_routes(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))- captured = {}-- def fake_upsert(cls, zone, name, rtype, ttl, records):- captured.update(zone=zone, name=name, rtype=rtype, ttl=ttl, records=records)- return {'success': True, 'message': 'saved'}-- monkeypatch.setattr(DnsServerService, 'upsert_rrset', classmethod(fake_upsert))- resp = dns_client.post(- '/api/v1/dns-server/zones/example.com/rrsets',- json={'name': 'www', 'type': 'A', 'ttl': 300, 'records': ['203.0.113.7']},- headers=auth_headers)- assert resp.status_code == 200- assert captured == {'zone': 'example.com', 'name': 'www', 'rtype': 'A',- 'ttl': 300, 'records': ['203.0.113.7']}-- resp = dns_client.post('/api/v1/dns-server/zones/example.com/rrsets',- json={'name': 'www'}, headers=auth_headers)- assert resp.status_code == 400 # type is required-- monkeypatch.setattr(- DnsServerService, 'delete_rrset',- classmethod(lambda cls, zone, name, rtype: {'success': True, 'message': 'gone'}))- resp = dns_client.delete(- '/api/v1/dns-server/zones/example.com/rrsets?name=www&type=A',- headers=auth_headers)- assert resp.status_code == 200---def test_dnssec_route(dns_client, auth_headers, monkeypatch):- monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- DnsServerService, 'set_dnssec',- classmethod(lambda cls, zone, enabled: {- 'success': True, 'dnssec': enabled,- 'ds_records': ['12345 13 2 aa'] if enabled else [],- }))- resp = dns_client.post('/api/v1/dns-server/zones/example.com/dnssec',- json={'action': 'enable'}, headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['ds_records'] == ['12345 13 2 aa']-- resp = dns_client.post('/api/v1/dns-server/zones/example.com/dnssec',- json={'action': 'sideways'}, headers=auth_headers)- assert resp.status_code == 400diff --git a/backend/tests/test_gpu_extension.py b/backend/tests/test_gpu_extension.pydeleted file mode 100644index 9945c94f..00000000--- a/backend/tests/test_gpu_extension.py+++ /dev/null@@ -1,148 +0,0 @@-"""serverkit-gpu extension tests (plan 32 #7/#8 — first CORE_SLIM slice).--GPU monitoring moved out of core into the builtin extension: the nvidia-smi-parsing service + its blueprint now live under builtin-extensions/serverkit-gpu/-backend and mount at /api/v1/gpu via the manifest's entry_point + url_prefix-(the same prefix the deleted core route used, so the frontend is unchanged).--The backend is loaded exactly the way production loads builtins:-``plugin_service._ensure_builtin_backend_importable`` registers-``builtin-extensions/serverkit-gpu/backend`` as ``app.plugins.serverkit-gpu``-(mirrors the WordPress/CrowdSec extraction pattern).-"""-import importlib-import json-import os-import types--import pytest--from app.services import plugin_service--SLUG = 'serverkit-gpu'-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}')- svc_mod = importlib.import_module(f'app.plugins.{SLUG}.gpu_service')- bp_mod = importlib.import_module(f'app.plugins.{SLUG}.gpu')- return svc_mod, bp_mod---svc_mod, bp_mod = _load_ext()-GpuService = svc_mod.GpuService--SAMPLE = "0, NVIDIA GeForce RTX 3090, 15, 2048, 24576, 45, 120.50, 350.00, 30, 535.104.05\n"---def _fake_run(stdout, rc=0):- return lambda *a, **k: types.SimpleNamespace(returncode=rc, stdout=stdout, stderr='')---# ----------------------------------------------------------------------------# manifest + bridge wiring-# -----------------------------------------------------------------------------def test_manifest_declares_bridge_and_sdk():- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert plugin_service._validate_manifest(manifest) is True- assert manifest['name'] == SLUG- assert manifest['category'] == 'monitoring'- assert manifest['entry_point'] == 'gpu:gpu_bp'- assert manifest['url_prefix'] == '/api/v1/gpu'- # sdk_version drives the runtime SDK gate; it must satisfy the panel's SDK.- from app.utils.sdk import SDK_VERSION, sdk_version_satisfies- assert manifest['sdk_version']- assert sdk_version_satisfies(manifest['sdk_version'], SDK_VERSION)- routes = manifest['contributions']['routes']- assert {'path': 'gpu', 'component': 'GpuMonitorPage'} in routes---def test_entry_point_resolves_to_blueprint():- assert getattr(bp_mod, 'gpu_bp', None) is not None- assert bp_mod.gpu_bp.name == 'gpu'---def test_frontend_exports_route_component():- with open(os.path.join(EXT_DIR, 'frontend', 'index.jsx'), encoding='utf-8') as f:- src = f.read()- assert 'GpuMonitorPage' in src---def test_core_gpu_module_is_gone():- """The core page/blueprint/service were deleted — nothing should import them."""- import importlib.util- assert importlib.util.find_spec('app.api.gpu') is None- assert importlib.util.find_spec('app.services.gpu_service') is None---# ----------------------------------------------------------------------------# service: nvidia-smi parsing (moved from the core test)-# -----------------------------------------------------------------------------class TestGpuService:- def test_list_gpus_parses_a_row(self, monkeypatch):- monkeypatch.setattr(GpuService, '_run', _fake_run(SAMPLE))- gpus = GpuService.list_gpus()- assert len(gpus) == 1- g = gpus[0]- assert g['index'] == 0- assert g['name'] == 'NVIDIA GeForce RTX 3090'- assert g['memory_total'] == 24576.0- assert g['memory_percent'] == round(100 * 2048 / 24576, 1)- assert g['driver_version'] == '535.104.05'-- def test_coerces_na_to_none(self, monkeypatch):- line = "0, GPU, [N/A], 100, 1000, [N/A], 50, 100, [N/A], 535\n"- monkeypatch.setattr(GpuService, '_run', _fake_run(line))- g = GpuService.list_gpus()[0]- assert g['utilization_gpu'] is None- assert g['temperature'] is None- assert g['fan_speed'] is None- assert g['memory_percent'] == 10.0-- def test_available_false_on_nonzero_exit(self, monkeypatch):- monkeypatch.setattr(GpuService, '_run', _fake_run('', rc=1))- assert GpuService.available() is False-- def test_info_when_no_gpus(self, monkeypatch):- monkeypatch.setattr(GpuService, '_run', _fake_run('', rc=1))- info = GpuService.info()- assert info['available'] is False- assert info['gpus'] == [] and info['processes'] == []---# ----------------------------------------------------------------------------# blueprint routes (registered like production does)-# -----------------------------------------------------------------------------def gpu_app(app):- if 'gpu' not in app.blueprints:- app.register_blueprint(bp_mod.gpu_bp, url_prefix='/api/v1/gpu')- return app---def gpu_client(gpu_app):- return gpu_app.test_client()---def test_gpu_endpoint_returns_info(gpu_client, auth_headers, monkeypatch):- monkeypatch.setattr(GpuService, 'list_gpus', classmethod(lambda cls: [{'index': 0, 'name': 'RTX 3090'}]))- monkeypatch.setattr(GpuService, 'processes', classmethod(lambda cls: []))- resp = gpu_client.get('/api/v1/gpu/', headers=auth_headers)- assert resp.status_code == 200- body = resp.get_json()- assert body['available'] is True- assert len(body['gpus']) == 1---def test_gpu_requires_auth(gpu_client):- assert gpu_client.get('/api/v1/gpu/').status_code == 401diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.pyindex e22bbf0f..439c30f3 100644--- a/backend/tests/test_jobs.py+++ b/backend/tests/test_jobs.py@@ -460,4 +460,4 @@ class TestBackupScheduleHandler:# TestWorkflowEventDispatch removed in plan 45 Phase 4: the React-Flow Workflow# Builder engine (WorkflowEngine / WorkflowEventBus) was retired. Its four event# emitters were ported to EventService (health.check_failed, git.push,-# monitor.high_cpu/high_memory); those are covered in test_tramo_extension.py.+# monitor.high_cpu/high_memory); those are covered in test_tramo_panel_core.py.diff --git a/backend/tests/test_serverkit_k8s_extension.py b/backend/tests/test_serverkit_k8s_extension.pydeleted file mode 100644index 855386ba..00000000--- a/backend/tests/test_serverkit_k8s_extension.py+++ /dev/null@@ -1,385 +0,0 @@-"""serverkit-k8s extension tests — manifest, models, kubectl engine, service, blueprint.--Loads the builtin the way production does:-``plugin_service._ensure_builtin_backend_importable`` registers-``builtin-extensions/serverkit-k8s/backend`` as the dashed package-``app.plugins.serverkit-k8s``. The models module is imported at module top so-its ``ext_serverkit_k8s_*`` table registers on ``db.metadata`` before the ``app``-fixture runs ``db.create_all()``.--Proven here: manifest validity + permissions + entry point + lifecycle keys +-frontend export; the K8sCluster model (encryption round-trip, ``to_dict`` never-leaks the kubeconfig, single-default invariant); the kubectl engine (argv build,-temp-file materialize + guaranteed cleanup, error mapping); the cluster_service-normalizers turning canned ``kubectl -o json`` into compact UI dicts; and the-blueprint RBAC + kubectl-availability guards.-"""-import importlib-import json-import os-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-k8s'-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}')- models = importlib.import_module(f'app.plugins.{SLUG}.models')- kubectl = importlib.import_module(f'app.plugins.{SLUG}.kubectl_service')- cluster = importlib.import_module(f'app.plugins.{SLUG}.cluster_service')- bp = importlib.import_module(f'app.plugins.{SLUG}.k8s')- return models, kubectl, cluster, bp---models_mod, kubectl_mod, cluster_mod, bp_mod = _load_ext()-K8sCluster = models_mod.K8sCluster---def _proc(returncode=0, stdout='', stderr=''):- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)---def _mk_cluster(app, name='c1', kubeconfig='apiVersion: v1\nkind: Config\n', context=None, default=False):- from app import db- c = K8sCluster(name=name, context=context, is_default=default)- c.set_kubeconfig(kubeconfig)- db.session.add(c)- db.session.commit()- return c---# ----------------------------------------------------------------------------# 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['category'] == 'deployment'- assert m['entry_point'] == 'k8s:k8s_bp'- assert m['url_prefix'] == '/api/v1/k8s'- assert m['models'] == 'models:register'- nav = m['contributions']['nav'][0]- assert nav['route'] == '/k8s' and nav['id'] == 'k8s'- routes = m['contributions']['routes']- assert {'path': 'k8s', 'component': 'K8sPage'} in routes- assert m['contributions']['page_titles']['/k8s'] == 'Kubernetes'---def test_manifest_permissions_are_known():- from app.plugins_sdk import permissions as sdk_perms- assert sdk_perms.unknown_permissions(_manifest()['permissions']) == []---def test_manifest_description_has_no_em_or_en_dash():- desc = _manifest().get('description', '')- assert '—' not in desc and '–' not in desc---def test_lifecycle_hook_keys_resolve():- lifecycle = _manifest()['lifecycle']- assert set(lifecycle) <= {'install', 'upgrade', 'uninstall'}- assert 'install' in lifecycle and 'uninstall' in lifecycle- for ref in 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---def test_entry_point_resolves_to_blueprint():- assert getattr(bp_mod, 'k8s_bp', None) is not None- assert bp_mod.k8s_bp.name == 'k8s'---def test_models_register_returns_model_list():- from app import db- assert models_mod.register(db) == [K8sCluster]---def test_frontend_exports_route_component():- index = os.path.join(EXT_DIR, 'frontend', 'index.jsx')- if not os.path.isfile(index):- pytest.skip('serverkit-k8s frontend/index.jsx not present in this build')- with open(index, encoding='utf-8') as f:- src = f.read()- assert 'export { default as K8sPage }' in src- assert 'export default' not in src---# ----------------------------------------------------------------------------# model-# ----------------------------------------------------------------------------def test_cluster_persists_and_to_dict_hides_kubeconfig(app):- c = _mk_cluster(app, name='prod', context='ctx-a')- d = c.to_dict()- assert d['name'] == 'prod'- assert d['context'] == 'ctx-a'- # The secret must never appear in the serialized form (any key or value).- assert 'kubeconfig' not in d- assert 'kubeconfig_encrypted' not in d- blob = json.dumps(d)- assert 'apiVersion' not in blob---def test_kubeconfig_encryption_round_trips(app):- secret = 'apiVersion: v1\nclusters:\n- name: x\n'- c = _mk_cluster(app, name='enc', kubeconfig=secret)- # Round-trips back to plaintext...- assert c.get_kubeconfig() == secret- # ...and (when a key is configured) is not stored verbatim.- from app.utils.crypto import is_encryption_configured- if is_encryption_configured():- assert c.kubeconfig_encrypted != secret---def test_name_is_unique(app):- from app import db- _mk_cluster(app, name='dup')- dupe = K8sCluster(name='dup')- dupe.set_kubeconfig('x')- db.session.add(dupe)- with pytest.raises(Exception):- db.session.commit()- db.session.rollback()---# ----------------------------------------------------------------------------# cluster_service CRUD + invariants-# ----------------------------------------------------------------------------def test_create_first_cluster_is_default(app):- c = cluster_mod.create_cluster('a', 'kc')- assert c.is_default is True---def test_set_default_is_exclusive(app):- a = cluster_mod.create_cluster('a', 'kc')- b = cluster_mod.create_cluster('b', 'kc')- assert a.is_default and not b.is_default- cluster_mod.set_default(b.id)- from app import db- db.session.refresh(a)- db.session.refresh(b)- assert b.is_default and not a.is_default---def test_delete_default_promotes_another(app):- a = cluster_mod.create_cluster('a', 'kc')- b = cluster_mod.create_cluster('b', 'kc')- cluster_mod.delete_cluster(a.id) # a was default- from app import db- db.session.refresh(b)- assert b.is_default is True---def test_create_rejects_blank_name_and_kubeconfig(app):- with pytest.raises(ValueError):- cluster_mod.create_cluster('', 'kc')- with pytest.raises(ValueError):- cluster_mod.create_cluster('x', '')---# ----------------------------------------------------------------------------# kubectl engine-# ----------------------------------------------------------------------------def test_build_argv_with_and_without_context():- no_ctx = SimpleNamespace(context=None)- assert kubectl_mod.build_argv(no_ctx, ['get', 'pods']) == ['kubectl', 'get', 'pods']- with_ctx = SimpleNamespace(context='prod')- assert kubectl_mod.build_argv(with_ctx, ['get', 'nodes']) == [- 'kubectl', '--context', 'prod', 'get', 'nodes']---def test_run_materializes_kubeconfig_and_cleans_up(monkeypatch, app):- c = _mk_cluster(app, name='run', kubeconfig='THE-CONFIG')- monkeypatch.setattr(kubectl_mod, 'is_available', lambda: True)-- seen = {}-- def fake_run(argv, **kwargs):- # --kubeconfig <path> is appended; capture it and prove the file exists now.- assert '--kubeconfig' in argv- path = argv[argv.index('--kubeconfig') + 1]- seen['path'] = path- with open(path, encoding='utf-8') as f:- seen['contents'] = f.read()- return _proc(returncode=0, stdout='ok')-- monkeypatch.setattr(kubectl_mod.subprocess, 'run', fake_run)- out = kubectl_mod.run(c, ['version'])- assert out == 'ok'- assert seen['contents'] == 'THE-CONFIG'- # Temp kubeconfig is deleted after the call regardless of success.- assert not os.path.exists(seen['path'])---def test_run_raises_kubectlerror_on_nonzero(monkeypatch, app):- c = _mk_cluster(app, name='err')- monkeypatch.setattr(kubectl_mod, 'is_available', lambda: True)- monkeypatch.setattr(kubectl_mod.subprocess, 'run',- lambda argv, **kw: _proc(returncode=1, stderr='boom'))- with pytest.raises(kubectl_mod.KubectlError) as ei:- kubectl_mod.run(c, ['get', 'pods'])- assert 'boom' in str(ei.value)---def test_run_raises_when_kubectl_absent(monkeypatch, app):- c = _mk_cluster(app, name='absent')- monkeypatch.setattr(kubectl_mod, 'is_available', lambda: False)- with pytest.raises(kubectl_mod.KubectlError):- kubectl_mod.run(c, ['version'])---# ----------------------------------------------------------------------------# cluster_service normalizers (canned kubectl -o json)-# ----------------------------------------------------------------------------def _patch_json(monkeypatch, payload):- monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json', lambda cluster, args, **kw: payload)---NODE_JSON = {'items': [{- 'metadata': {'name': 'node-1', 'labels': {'node-role.kubernetes.io/control-plane': ''}},- 'status': {- 'conditions': [{'type': 'Ready', 'status': 'True'}],- 'nodeInfo': {'kubeletVersion': 'v1.29.0', 'osImage': 'Ubuntu 22.04'},- 'capacity': {'cpu': '4', 'memory': '8Gi'},- },-}]}--POD_JSON = {'items': [{- 'metadata': {'name': 'web-abc', 'namespace': 'default'},- 'spec': {'nodeName': 'node-1', 'containers': [{'name': 'web'}]},- 'status': {'phase': 'Running', 'podIP': '10.0.0.5',- 'containerStatuses': [{'ready': True, 'restartCount': 2}]},-}]}--DEPLOY_JSON = {'items': [{- 'metadata': {'name': 'web', 'namespace': 'default'},- 'spec': {'replicas': 3, 'template': {'spec': {'containers': [{'image': 'nginx:1.25'}]}}},- 'status': {'readyReplicas': 3, 'availableReplicas': 3},-}]}---def test_get_nodes_normalizes(monkeypatch, app):- c = _mk_cluster(app)- _patch_json(monkeypatch, NODE_JSON)- nodes = cluster_mod.get_nodes(c)- assert nodes[0]['name'] == 'node-1'- assert nodes[0]['ready'] is True- assert 'control-plane' in nodes[0]['roles']- assert nodes[0]['kubelet_version'] == 'v1.29.0'- assert nodes[0]['cpu'] == '4'---def test_get_pods_normalizes(monkeypatch, app):- c = _mk_cluster(app)- _patch_json(monkeypatch, POD_JSON)- pods = cluster_mod.get_pods(c, 'default')- assert pods[0]['name'] == 'web-abc'- assert pods[0]['ready'] == '1/1'- assert pods[0]['restarts'] == 2- assert pods[0]['phase'] == 'Running'---def test_get_workloads_marks_healthy(monkeypatch, app):- c = _mk_cluster(app)- _patch_json(monkeypatch, DEPLOY_JSON)- w = cluster_mod.get_workloads(c, 'default', 'deployment')- assert w[0]['name'] == 'web'- assert w[0]['desired'] == 3 and w[0]['ready'] == 3- assert w[0]['healthy'] is True- assert w[0]['images'] == ['nginx:1.25']---def test_scale_rejects_negative(monkeypatch, app):- c = _mk_cluster(app)- monkeypatch.setattr(cluster_mod.kubectl_service, 'run', lambda *a, **kw: '')- with pytest.raises(ValueError):- cluster_mod.scale_deployment(c, 'default', 'web', -1)---def test_delete_resource_rejects_unknown_kind(monkeypatch, app):- c = _mk_cluster(app)- monkeypatch.setattr(cluster_mod.kubectl_service, 'run', lambda *a, **kw: '')- with pytest.raises(ValueError):- cluster_mod.delete_resource(c, 'namespace', 'kube-system', 'kube-system')---def test_apply_rejects_empty_manifest(app):- c = _mk_cluster(app)- with pytest.raises(ValueError):- cluster_mod.apply_manifest(c, ' ')---def test_test_connection_caches_result(monkeypatch, app):- c = _mk_cluster(app, name='probe')- monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json',- lambda cluster, args, **kw: {'serverVersion': {'gitVersion': 'v1.29.3'}})- res = cluster_mod.test_connection(c)- assert res['ok'] is True and res['server_version'] == 'v1.29.3'- assert c.last_reachable is True- assert json.loads(c.last_status)['server_version'] == 'v1.29.3'---def test_test_connection_records_unreachable(monkeypatch, app):- c = _mk_cluster(app, name='down')-- def boom(cluster, args, **kw):- raise kubectl_mod.KubectlError('connection refused')- monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json', boom)- res = cluster_mod.test_connection(c)- assert res['ok'] is False- assert 'refused' in res['error']- assert c.last_reachable is False---# ----------------------------------------------------------------------------# blueprint (RBAC + kubectl guard)-# ----------------------------------------------------------------------------def k8s_client(app):- """Register the extension blueprint on the test app and return a client."""- if 'k8s' not in app.blueprints:- app.register_blueprint(bp_mod.k8s_bp, url_prefix='/api/v1/k8s')- return app.test_client()---def test_status_route_lists_clusters(monkeypatch, k8s_client, auth_headers, app):- _mk_cluster(app, name='s1', default=True)- monkeypatch.setattr(bp_mod.kubectl_service, 'is_available', lambda: True)- r = k8s_client.get('/api/v1/k8s/status', headers=auth_headers)- assert r.status_code == 200- body = r.get_json()- assert body['kubectl_available'] is True- assert any(c['name'] == 's1' for c in body['clusters'])---def test_read_route_503_when_kubectl_absent(monkeypatch, k8s_client, auth_headers, app):- c = _mk_cluster(app, name='nok')- monkeypatch.setattr(bp_mod.kubectl_service, 'is_available', lambda: False)- r = k8s_client.get(f'/api/v1/k8s/clusters/{c.id}/nodes', headers=auth_headers)- assert r.status_code == 503---def test_routes_require_auth(k8s_client):- assert k8s_client.get('/api/v1/k8s/status').status_code in (401, 422)---def test_create_cluster_route(monkeypatch, k8s_client, auth_headers):- r = k8s_client.post('/api/v1/k8s/clusters', headers=auth_headers,- json={'name': 'viaroute', 'kubeconfig': 'kc-blob'})- assert r.status_code == 201- assert r.get_json()['name'] == 'viaroute'diff --git a/backend/tests/test_serverkit_mail_extension.py b/backend/tests/test_serverkit_mail_extension.pydeleted file mode 100644index e668fd9b..00000000--- a/backend/tests/test_serverkit_mail_extension.py+++ /dev/null@@ -1,729 +0,0 @@-"""serverkit-mail extension tests — manifest, models, engine, blueprint.--Covers the Stalwart-based builtin mail extension the same way production loads a-builtin: ``plugin_service._ensure_builtin_backend_importable`` registers-``builtin-extensions/serverkit-mail/backend`` as the dashed package-``app.plugins.serverkit-mail``. The models module is imported at test-module top-level so its ``ext_serverkit_mail_*`` tables register on ``db.metadata`` before-the ``app`` fixture runs ``db.create_all()``.--This file proves: manifest validity + permissions + entry point + frontend-export, the SQLAlchemy models (create + ``to_dict`` + no mailbox password column +-the unique constraint), the StalwartService Docker/API choke-points (install argv-with a loopback-only admin API, status parsing, Windows gating, clean API error-dicts, best-effort reconcile methods), and the blueprint auth/validation paths.--Preflight, the activation gate, DKIM/DNS, and the fail2ban jail live in-``test_serverkit_mail_preflight_dns.py``.-"""-import importlib-import json-import os-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-mail'-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}')- # Import models at module top so the ext_serverkit_mail_* tables register on- # db.metadata before any app fixture calls db.create_all().- models = importlib.import_module(f'app.plugins.{SLUG}.models')- stalwart = importlib.import_module(f'app.plugins.{SLUG}.stalwart_service')- bp = importlib.import_module(f'app.plugins.{SLUG}.mail')- return models, stalwart, bp---models_mod, svc_mod, bp_mod = _load_ext()-StalwartService = svc_mod.StalwartService-MailDomain = models_mod.MailDomain-Mailbox = models_mod.Mailbox-Forwarder = models_mod.Forwarder-Autoresponder = models_mod.Autoresponder-PreflightResult = models_mod.PreflightResult--CFG = {'admin_password': 'test-admin-pw', 'hostname': 'mail.example.com'}---def _proc(returncode=0, stdout='', stderr=''):- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)---class FakeResponse:- def __init__(self, status_code=200, data=None, text=''):- self.status_code = status_code- self._data = data- self.text = text or (json.dumps(data) if data is not None else '')- self.content = self.text.encode()-- def json(self):- if self._data is None:- raise ValueError('no json')- return self._data---def linux(monkeypatch):- """Pretend we're on Linux with docker installed and admin creds saved."""- monkeypatch.setattr(svc_mod.os, 'name', 'posix')- monkeypatch.setattr(svc_mod, 'is_command_available', lambda c: True)- monkeypatch.setattr(StalwartService, '_config', classmethod(lambda cls: dict(CFG)))---# ----------------------------------------------------------------------------# manifest-# -----------------------------------------------------------------------------def test_manifest_passes_validator():- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert plugin_service._validate_manifest(manifest) is True- assert manifest['name'] == SLUG- assert manifest['category'] == 'integration'- assert manifest['entry_point'] == 'mail:mail_bp'- assert manifest['url_prefix'] == '/api/v1/mail'- assert manifest['models'] == 'models:register'- assert set(manifest['permissions']) == {'shell', 'filesystem', 'network', 'docker'}- nav = manifest['contributions']['nav'][0]- assert nav['route'] == '/mail'- assert nav['id'] == 'mail'- routes = manifest['contributions']['routes']- assert {'path': 'mail', 'component': 'MailPage'} in routes- assert manifest['contributions']['page_titles']['/mail'] == 'Mail Server'---def test_manifest_permissions_are_known():- from app.plugins_sdk import permissions as sdk_perms- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- assert sdk_perms.unknown_permissions(manifest['permissions']) == []---def test_lifecycle_hook_keys_match_loader():- """The loader reads lifecycle.get('install')/('uninstall') — the manifest must- use those exact keys (not 'on_install'/'on_uninstall'), else the hooks that- register notify events and tear down the container silently never fire. The- _validate_manifest check only vets the VALUES, so this guards the KEYS and- proves each referenced hook actually resolves + is importable."""- import importlib- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- lifecycle = json.load(f)['lifecycle']- assert set(lifecycle) <= {'install', 'upgrade', 'uninstall'}- assert 'install' in lifecycle and 'uninstall' in lifecycle- for ref in 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---def test_manifest_jobs_and_schedule_resolve():- """Job handlers + the daily preflight schedule are wired to real callables."""- import importlib- with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:- manifest = json.load(f)- kinds = {j['kind'] for j in manifest['jobs']}- assert 'mail.preflight.run' in kinds- for job in manifest['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']- sched = manifest['schedules'][0]- assert sched['kind'] in kinds and sched.get('cron')---def test_entry_point_resolves_to_blueprint():- assert getattr(bp_mod, 'mail_bp', None) is not None- assert bp_mod.mail_bp.name == 'mail'---def test_models_register_is_a_noop_passthrough():- # Manifest declares models: "models:register"; the callable must exist and be- # a harmless passthrough (tables register as an import side effect).- from app import db- assert models_mod.register(db) is None---def test_frontend_exports_route_component():- index = os.path.join(EXT_DIR, 'frontend', 'index.jsx')- if not os.path.isfile(index):- pytest.skip('serverkit-mail frontend/index.jsx not present in this build')- with open(index, encoding='utf-8') as f:- src = f.read()- assert 'export { default as MailPage }' in src- # No module-level default export: PluginLoader legacy-auto-renders those.- assert 'export default' not in src---# ----------------------------------------------------------------------------# models-# -----------------------------------------------------------------------------def test_mail_domain_persists_and_to_dict(app):- from app import db- row = MailDomain(name='example.com', catch_all_target='[email protected]',- is_active=False, sync_state='pending')- db.session.add(row)- db.session.commit()-- d = row.to_dict()- for key in ('id', 'name', 'is_active', 'catch_all_target', 'dkim_selector',- 'dkim_public_key', 'dkim_configured', 'dns_deployed',- 'dns_last_result', 'sync_state', 'sync_error', 'mailboxes_count',- 'forwarders_count', 'created_at', 'updated_at'):- assert key in d, key- assert d['name'] == 'example.com'- assert d['is_active'] is False- assert d['dkim_selector'] == 'serverkit' # column default- assert d['dkim_configured'] is False- assert d['mailboxes_count'] == 0---def test_mailbox_has_no_password_and_to_dict(app):- from app import db- domain = MailDomain(name='mailbox-test.com')- db.session.add(domain)- db.session.commit()-- box = Mailbox(domain_id=domain.id, local_part='alice', quota_mb=512,- display_name='Alice')- db.session.add(box)- db.session.commit()-- # Passwords are NEVER persisted panel-side.- assert not hasattr(box, 'password')- assert 'password' not in Mailbox.__table__.columns- assert 'password_hash' not in Mailbox.__table__.columns-- d = box.to_dict()- assert 'password' not in d- assert d['local_part'] == 'alice'- assert d['email'] == '[email protected]'- assert d['quota_mb'] == 512- assert d['domain_name'] == 'mailbox-test.com'---def test_mailbox_unique_domain_local_part(app):- from app import db- from sqlalchemy.exc import IntegrityError- domain = MailDomain(name='dupe.com')- db.session.add(domain)- db.session.commit()-- db.session.add(Mailbox(domain_id=domain.id, local_part='postmaster'))- db.session.commit()-- db.session.add(Mailbox(domain_id=domain.id, local_part='postmaster'))- with pytest.raises(IntegrityError):- db.session.commit()- db.session.rollback()---def test_forwarder_and_autoresponder_persist(app):- from app import db- domain = MailDomain(name='fwd.com')- db.session.add(domain)- db.session.commit()-- fwd = Forwarder(domain_id=domain.id, source_local_part='sales',- destination='[email protected]', keep_copy=True)- db.session.add(fwd)- db.session.commit()- fd = fwd.to_dict()- assert fd['source'] == '[email protected]'- assert fd['destination'] == '[email protected]'- assert fd['keep_copy'] is True-- box = Mailbox(domain_id=domain.id, local_part='bob')- db.session.add(box)- db.session.commit()- ar = Autoresponder(mailbox_id=box.id, enabled=True, subject='OOO', body='Away')- db.session.add(ar)- db.session.commit()- ad = ar.to_dict()- assert ad['mailbox_id'] == box.id- assert ad['enabled'] is True- assert ad['subject'] == 'OOO'---def test_preflight_result_persist_and_to_dict(app):- from app import db- row = PreflightResult(hostname='mail.example.com', server_ip='203.0.113.5',- ptr_ok=True, ptr_value='mail.example.com',- port25_ok=True, rbl_ok=True,- rbl_hits=json.dumps([]), ports_ok=True, passed=True,- detail=json.dumps({'ptr': {'ok': True}}))- db.session.add(row)- db.session.commit()- d = row.to_dict()- for key in ('id', 'hostname', 'server_ip', 'ptr_ok', 'ptr_value', 'port25_ok',- 'rbl_ok', 'rbl_hits', 'ports_ok', 'passed', 'detail', 'checked_at'):- assert key in d, key- assert d['passed'] is True- assert d['rbl_hits'] == [] # JSON text decoded back to a list- assert d['detail'] == {'ptr': {'ok': True}}---# ----------------------------------------------------------------------------# StalwartService: install / lifecycle argv-# -----------------------------------------------------------------------------def test_install_builds_correct_docker_run(monkeypatch, linux):- calls = []- saved = {}-- def fake_run(cmd, timeout=None, **kwargs):- calls.append(list(cmd))- if cmd[:2] == ['docker', 'inspect']:- return _proc(returncode=1, stderr='No such object') # not installed- return _proc(returncode=0, stdout='container123\n')-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- monkeypatch.setattr(StalwartService, '_save_config',- classmethod(lambda cls, updates: saved.update(updates) or True))-- result = StalwartService.install('Mail.Example.COM.')- assert result['success'] is True, result-- # Config + data dirs created, container started.- assert ['mkdir', '-p', svc_mod.HOST_CONFIG_DIR, svc_mod.HOST_DATA_DIR] in calls- run_cmd = next(c for c in calls if c[:2] == ['docker', 'run'])-- # Mail ports published on the host.- for port in ('25', '465', '587', '993'):- assert f'{port}:{port}' in run_cmd, port-- # Admin API published on loopback ONLY — never a bare 8080:8080.- assert f'{svc_mod.API_HOST}:{svc_mod.API_PORT}:{svc_mod.API_PORT}' in run_cmd- assert '127.0.0.1:8080:8080' in run_cmd- assert not any(a == '8080:8080' for a in run_cmd)-- # Live-verified image (stalwartlabs/stalwart, NOT the defunct mail-server),- # restart policy, and the split config/data bind mounts.- assert svc_mod.IMAGE in run_cmd- assert svc_mod.IMAGE.startswith('stalwartlabs/stalwart')- assert '--restart' in run_cmd- assert f'{svc_mod.HOST_CONFIG_DIR}:{svc_mod.CONTAINER_CONFIG_DIR}' in run_cmd- assert f'{svc_mod.HOST_DATA_DIR}:{svc_mod.CONTAINER_DATA_DIR}' in run_cmd-- # A generated admin password was pinned via the single recovery-admin env- # var (user:secret) AND persisted to the config store.- recovery_args = [a for a in run_cmd if a.startswith('STALWART_RECOVERY_ADMIN=')]- assert len(recovery_args) == 1- user, _, generated = recovery_args[0].split('=', 1)[1].partition(':')- assert user == svc_mod.ADMIN_USER- assert generated # non-empty generated secret- assert saved['admin_password'] == generated- assert saved['hostname'] == 'mail.example.com' # normalized (lowercased, no dot)- # install() tells the caller setup is still required.- assert result['needs_setup'] is True and result['setup_url']---def test_install_requires_hostname(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda *a, **kw: pytest.fail('docker must not run on invalid input'))- assert StalwartService.install('')['success'] is False- assert StalwartService.install(' ')['success'] is False---def test_install_refuses_when_container_exists(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(returncode=0, stdout='true\n'))- result = StalwartService.install('mail.example.com')- assert result['success'] is False- assert 'already exists' in result['error']---def test_uninstall_keep_data_vs_purge(monkeypatch, linux):- calls = []-- def fake_run(cmd, timeout=None, **kwargs):- calls.append(list(cmd))- return _proc(returncode=0)-- monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)- monkeypatch.setattr(StalwartService, '_save_config',- classmethod(lambda cls, updates: True))-- result = StalwartService.uninstall(keep_data=True)- assert result['success'] is True- assert ['docker', 'rm', '-f', svc_mod.CONTAINER_NAME] in calls- assert not any(c[:1] == ['rm'] for c in calls) # data dir untouched-- calls.clear()- result = StalwartService.uninstall(keep_data=False)- assert result['success'] is True- assert ['rm', '-rf', svc_mod.DATA_DIR] in calls---def test_windows_is_unsupported(monkeypatch):- monkeypatch.setattr(svc_mod.os, 'name', 'nt')- assert StalwartService.is_installed() is False- result = StalwartService.install('mail.example.com')- assert result['success'] is False- assert 'Windows' in result['error']- status = StalwartService.get_status()- assert status['installed'] is False- assert status['running'] is False- # _api short-circuits on Windows without touching the network.- api = StalwartService._api('GET', '/principal')- assert api['success'] is False- assert 'Windows' in api['error']---# ----------------------------------------------------------------------------# StalwartService: status + admin API choke-point-# -----------------------------------------------------------------------------def test_status_running_reads_version(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(returncode=0, stdout='true\n'))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda method, url, **kw: FakeResponse(200, {'version': '0.11.1'}))- status = StalwartService.get_status()- assert status['installed'] is True- assert status['running'] is True- # A 200 from the session probe means setup is complete (ready).- assert status['needs_setup'] is False- assert status['version'] == '0.11.1'- assert status['engine'] == 'stalwart'- assert status['admin_api'] == f'{svc_mod.API_HOST}:{svc_mod.API_PORT}'---def test_status_bootstrap_reports_needs_setup(monkeypatch, linux):- """A fresh Stalwart container is running but in bootstrap mode: every /api/*- is a 404 (RFC-7807 problem+json) until the one-time setup completes. This is- the exact contract verified against live Stalwart 0.16.11 — the panel must- report needs_setup + a setup_url instead of a false 'ready' state."""- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(returncode=0, stdout='true\n'))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda method, url, **kw: FakeResponse(- 404, {'type': 'about:blank', 'status': 404, 'title': 'Not Found',- 'detail': 'The requested resource does not exist on this server.'}))- status = StalwartService.get_status()- assert status['installed'] is True- assert status['running'] is True- assert status['needs_setup'] is True- assert status['setup_url'] and svc_mod.ADMIN_UI in status['setup_url']---def test_api_parses_problem_json_detail(monkeypatch, linux):- """_api extracts the RFC-7807 `detail` (then `title`) from Stalwart errors."""- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda method, url, **kw: FakeResponse(- 404, {'status': 404, 'title': 'Not Found', 'detail': 'nope'}))- res = StalwartService._api('GET', '/principal')- assert res['success'] is False- assert res['status_code'] == 404- assert 'nope' in res['error']---def test_status_not_installed(monkeypatch, linux):- monkeypatch.setattr(- svc_mod, 'run_privileged',- lambda cmd, timeout=None, **kw: _proc(returncode=1, stderr='No such object'))- status = StalwartService.get_status()- assert status['installed'] is False- assert status['running'] is False---def test_api_uses_basic_auth_and_returns_data(monkeypatch, linux):- seen = {}-- def fake_request(method, url, auth=None, json=None, timeout=None):- seen.update(method=method, url=url, auth=auth, json=json)- return FakeResponse(200, {'ok': True})-- monkeypatch.setattr(svc_mod.requests, 'request', fake_request)- res = StalwartService._api('POST', '/principal', {'name': '[email protected]'})- assert res['success'] is True- assert res['data'] == {'ok': True}- assert seen['method'] == 'POST'- assert seen['url'] == svc_mod.API_BASE + '/principal'- assert seen['auth'] == (svc_mod.ADMIN_USER, CFG['admin_password'])---def test_api_error_status_is_clean(monkeypatch, linux):- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda *a, **kw: FakeResponse(422, {'error': 'principal exists'}))- res = StalwartService._api('POST', '/principal', {})- assert res['success'] is False- assert res['status_code'] == 422- assert 'principal exists' in res['error']---def test_api_unreachable_is_clean(monkeypatch, linux):- def boom(*a, **kw):- raise svc_mod.requests.RequestException('connection refused')- monkeypatch.setattr(svc_mod.requests, 'request', boom)- res = StalwartService._api('GET', '/principal')- assert res['success'] is False- assert 'unreachable' in res['error']---def test_api_requires_admin_password(monkeypatch, linux):- monkeypatch.setattr(StalwartService, '_config', classmethod(lambda cls: {}))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda *a, **kw: pytest.fail('API must not be called without a password'))- res = StalwartService._api('GET', '/principal')- assert res['success'] is False- assert 'password is not configured' in res['error']---# ----------------------------------------------------------------------------# StalwartService: best-effort reconcile methods (never raise)-# -----------------------------------------------------------------------------def test_reconcile_methods_skip_when_not_installed(monkeypatch, linux):- monkeypatch.setattr(StalwartService, 'is_installed', classmethod(lambda cls: False))- monkeypatch.setattr(- svc_mod.requests, 'request',- lambda *a, **kw: pytest.fail('no API call when engine is absent'))- for res in (StalwartService.upsert_account('[email protected]', password='x'),- StalwartService.upsert_domain('b.co'),- StalwartService.delete_account('[email protected]'),- StalwartService.set_password('[email protected]', 'x'),- StalwartService.flush_queue()):- assert res['success'] is False- assert res.get('skipped') is True- # Queue introspection degrades to an empty list, not an error.- q = StalwartService.list_queue()- assert q == {'success': True, 'messages': []}---def test_reconcile_upsert_account_success_and_error(monkeypatch, linux):- monkeypatch.setattr(StalwartService, 'is_installed', classmethod(lambda cls: True))-- calls = []-- def ok_api(cls, method, path, payload=None):- calls.append((method, path, payload))- return {'success': True, 'data': None}- monkeypatch.setattr(StalwartService, '_api', classmethod(ok_api))- res = StalwartService.upsert_account('[email protected]', password='pw',- quota_mb=100, display_name='Alice')- assert res == {'success': True, 'email': '[email protected]'}- method, path, payload = calls[0]- assert method == 'POST'- assert path == svc_mod.EP_PRINCIPAL- assert payload['type'] == 'individual'- assert payload['name'] == '[email protected]'- assert payload['secrets'] == ['pw']- assert payload['quota'] == 100 * 1024 * 1024-- monkeypatch.setattr(- StalwartService, '_api',- classmethod(lambda cls, m, p, payload=None: {'success': False, 'error': 'boom'}))- res = StalwartService.upsert_account('[email protected]')- assert res['success'] is False- assert 'boom' in res['error']---def test_list_queue_shapes(monkeypatch, linux):- monkeypatch.setattr(StalwartService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- StalwartService, '_api',- classmethod(lambda cls, m, p, payload=None: {'success': True,- 'data': [{'id': 1}, {'id': 2}]}))- res = StalwartService.list_queue()- assert res['success'] is True- assert res['messages'] == [{'id': 1}, {'id': 2}]-- # A dict payload with items is unwrapped; an API failure degrades to [].- monkeypatch.setattr(- StalwartService, '_api',- classmethod(lambda cls, m, p, payload=None: {'success': True,- 'data': {'items': [{'id': 9}]}}))- assert StalwartService.list_queue()['messages'] == [{'id': 9}]- monkeypatch.setattr(- StalwartService, '_api',- classmethod(lambda cls, m, p, payload=None: {'success': False, 'error': 'down'}))- res = StalwartService.list_queue()- assert res['messages'] == []- assert res['note'] == 'down'---# ----------------------------------------------------------------------------# blueprint routes-# -----------------------------------------------------------------------------def mail_app(app):- """Register the extension blueprint on the test app (name-guarded)."""- if 'mail' not in app.blueprints:- app.register_blueprint(bp_mod.mail_bp, url_prefix='/api/v1/mail')- return app---def mail_client(mail_app):- return mail_app.test_client()---def test_routes_require_auth(mail_client):- assert mail_client.get('/api/v1/mail/status').status_code == 401- assert mail_client.post('/api/v1/mail/install', json={}).status_code == 401- assert mail_client.get('/api/v1/mail/domains').status_code == 401- assert mail_client.post('/api/v1/mail/domains', json={}).status_code == 401- assert mail_client.get('/api/v1/mail/queue').status_code == 401---def test_status_route(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(- bp_mod.MailService, 'get_status',- classmethod(lambda cls: {- 'installed': True, 'running': True, 'version': '0.11',- 'engine': 'stalwart', 'preflight': None, 'domains_count': 0,- 'docs_url': svc_mod.DOCS_URL,- }))- resp = mail_client.get('/api/v1/mail/status', headers=auth_headers)- assert resp.status_code == 200- data = resp.get_json()- assert data['installed'] is True- assert data['engine'] == 'stalwart'---def test_preflight_get_route(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(- bp_mod.PreflightService, 'latest',- classmethod(lambda cls: {'passed': True, 'hostname': 'mail.example.com'}))- resp = mail_client.get('/api/v1/mail/preflight', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['preflight']['passed'] is True---def test_preflight_post_route(mail_client, auth_headers, monkeypatch):- captured = {}-- def fake_run(cls, hostname, server_ip=None):- captured.update(hostname=hostname, server_ip=server_ip)- return {'passed': False, 'hostname': hostname}- monkeypatch.setattr(bp_mod.PreflightService, 'run', classmethod(fake_run))- resp = mail_client.post('/api/v1/mail/preflight',- json={'hostname': 'mail.example.com', 'server_ip': '1.2.3.4'},- headers=auth_headers)- assert resp.status_code == 200- assert captured['hostname'] == 'mail.example.com'- assert captured['server_ip'] == '1.2.3.4'-- # hostname is required.- resp = mail_client.post('/api/v1/mail/preflight', json={}, headers=auth_headers)- assert resp.status_code == 400- assert 'error' in resp.get_json()---def test_install_route(mail_client, auth_headers, monkeypatch):- captured = {}-- def fake_install(cls, hostname):- captured['hostname'] = hostname- return {'success': True, 'message': 'ok', 'container': svc_mod.CONTAINER_NAME}- monkeypatch.setattr(bp_mod.StalwartService, 'install', classmethod(fake_install))- resp = mail_client.post('/api/v1/mail/install',- json={'hostname': 'mail.example.com'}, headers=auth_headers)- assert resp.status_code == 201- assert captured['hostname'] == 'mail.example.com'-- resp = mail_client.post('/api/v1/mail/install', json={}, headers=auth_headers)- assert resp.status_code == 400- assert 'error' in resp.get_json()---def test_domains_routes_happy_path(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(- bp_mod.MailService, 'list_domains',- classmethod(lambda cls: [{'id': 1, 'name': 'example.com'}]))- resp = mail_client.get('/api/v1/mail/domains', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['domains'][0]['name'] == 'example.com'-- captured = {}-- def fake_add(cls, name, catch_all_target=None):- captured.update(name=name, catch_all_target=catch_all_target)- return {'success': True, 'domain': {'id': 1, 'name': name}}- monkeypatch.setattr(bp_mod.MailService, 'add_domain', classmethod(fake_add))- resp = mail_client.post('/api/v1/mail/domains',- json={'name': 'example.com', 'catch_all_target': '[email protected]'},- headers=auth_headers)- assert resp.status_code == 201- assert captured == {'name': 'example.com', 'catch_all_target': '[email protected]'}-- # name is required.- resp = mail_client.post('/api/v1/mail/domains', json={}, headers=auth_headers)- assert resp.status_code == 400- assert 'error' in resp.get_json()---def test_add_domain_service_error_is_400(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(- bp_mod.MailService, 'add_domain',- classmethod(lambda cls, name, catch_all_target=None: {- 'success': False, 'error': 'Domain example.com already exists'}))- resp = mail_client.post('/api/v1/mail/domains',- json={'name': 'example.com'}, headers=auth_headers)- assert resp.status_code == 400- assert 'already exists' in resp.get_json()['error']---def test_mailbox_create_validation(mail_client, auth_headers, monkeypatch):- captured = {}-- def fake_add(cls, domain_id, local_part, password, quota_mb=0, display_name=None):- captured.update(domain_id=domain_id, local_part=local_part, password=password)- return {'success': True, 'mailbox': {'id': 1, 'local_part': local_part}}- monkeypatch.setattr(bp_mod.MailService, 'add_mailbox', classmethod(fake_add))-- # Missing password -> 400 before the service runs.- resp = mail_client.post('/api/v1/mail/domains/1/mailboxes',- json={'local_part': 'alice'}, headers=auth_headers)- assert resp.status_code == 400- assert captured == {}-- # Missing local_part -> 400.- resp = mail_client.post('/api/v1/mail/domains/1/mailboxes',- json={'password': 'x'}, headers=auth_headers)- assert resp.status_code == 400-- # Happy path -> 201, password forwarded to the service (never persisted).- resp = mail_client.post('/api/v1/mail/domains/1/mailboxes',- json={'local_part': 'alice', 'password': 's3cret'},- headers=auth_headers)- assert resp.status_code == 201- assert captured['local_part'] == 'alice'- assert captured['password'] == 's3cret'---def test_queue_route_503_when_not_installed(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(bp_mod.StalwartService, 'is_installed', classmethod(lambda cls: False))- resp = mail_client.get('/api/v1/mail/queue', headers=auth_headers)- assert resp.status_code == 503- assert 'error' in resp.get_json()---def test_queue_route_ok_when_installed(mail_client, auth_headers, monkeypatch):- monkeypatch.setattr(bp_mod.StalwartService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(- bp_mod.StalwartService, 'list_queue',- classmethod(lambda cls: {'success': True, 'messages': [{'id': 1}]}))- resp = mail_client.get('/api/v1/mail/queue', headers=auth_headers)- assert resp.status_code == 200- assert resp.get_json()['messages'] == [{'id': 1}]diff --git a/backend/tests/test_serverkit_mail_preflight_dns.py b/backend/tests/test_serverkit_mail_preflight_dns.pydeleted file mode 100644index 88d5b8bb..00000000--- a/backend/tests/test_serverkit_mail_preflight_dns.py+++ /dev/null@@ -1,396 +0,0 @@-"""serverkit-mail extension tests — preflight, activation gate, DKIM/DNS, jail.--Loads the builtin backend exactly like production-(``plugin_service._ensure_builtin_backend_importable`` -> dashed package-``app.plugins.serverkit-mail``) and imports the models module at test-module top-level so its tables register before the ``app`` fixture's ``db.create_all()``.--Proves the safety-critical behaviors:--* PreflightService: all-pass -> ``passed`` + a persisted row; an RBL hit or a- blocked port 25 -> ``passed=False`` with the failing check surfaced;- Windows/dev -> skipped and never raises; ``latest()`` returns the newest row.-* The activation gate: ``MailService.set_domain_active(id, True)`` is REFUSED- without a passing preflight and ALLOWED with ``force=True`` (audit path).-* DkimDnsService: DKIM keygen -> a ``v=DKIM1; k=rsa; p=...`` TXT value + stored- keys; the pure ``build_records`` shapes; ``deploy_dns`` calls- ``DNSProviderService.set_record`` with the exact record types/names/values and- ``source='mail'``, and the no-provider path returns manual instructions.-* MailJailService: unavailable on Windows; enable writes a ``serverkit-mail-*``- jail via a stubbed ``run_privileged(['tee', ...])`` and never raises.-"""-import importlib-import json-import os-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-mail'-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}')- models = importlib.import_module(f'app.plugins.{SLUG}.models')- preflight = importlib.import_module(f'app.plugins.{SLUG}.preflight_service')- dns = importlib.import_module(f'app.plugins.{SLUG}.dns_mail_service')- mailsvc = importlib.import_module(f'app.plugins.{SLUG}.mail_service')- jail = importlib.import_module(f'app.plugins.{SLUG}.mail_jail_service')- return models, preflight, dns, mailsvc, jail---models_mod, preflight_mod, dns_mod, mailsvc_mod, jail_mod = _load_ext()-PreflightService = preflight_mod.PreflightService-DkimDnsService = dns_mod.DkimDnsService-MailService = mailsvc_mod.MailService-MailJailService = jail_mod.MailJailService-MailDomain = models_mod.MailDomain-PreflightResult = models_mod.PreflightResult---def _proc(returncode=0, stdout='', stderr=''):- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)---def _patch_checks(monkeypatch, *, ptr=(True, 'mail.example.com', None),- port25=(True, None), rbl=(True, [], None), ports=(True, None)):- """Stub every individual preflight helper so run() is hermetic."""- monkeypatch.setattr(PreflightService, '_check_ptr',- staticmethod(lambda hostname, server_ip: ptr))- monkeypatch.setattr(PreflightService, '_check_port25',- staticmethod(lambda: port25))- monkeypatch.setattr(PreflightService, '_check_rbl',- classmethod(lambda cls, server_ip: rbl))- monkeypatch.setattr(PreflightService, '_check_local_ports',- staticmethod(lambda: ports))- # Keep the verdict OS-independent even though the machine may be Windows.- monkeypatch.setattr(preflight_mod.os, 'name', 'posix')---# ----------------------------------------------------------------------------# preflight-# -----------------------------------------------------------------------------def test_preflight_all_pass_persists_row(app, monkeypatch):- _patch_checks(monkeypatch)- result = PreflightService.run('mail.example.com', server_ip='203.0.113.5')- assert result['passed'] is True- assert result['ptr_ok'] is True- assert result['port25_ok'] is True- assert result['rbl_ok'] is True- # A row was persisted and is the latest.- assert PreflightResult.query.count() == 1- latest = PreflightService.latest()- assert latest['passed'] is True- assert latest['hostname'] == 'mail.example.com'---def test_preflight_rbl_hit_fails(app, monkeypatch):- _patch_checks(monkeypatch, rbl=(False, ['zen.spamhaus.org'], 'Listed on: zen.spamhaus.org'))- result = PreflightService.run('mail.example.com', server_ip='203.0.113.5')- assert result['passed'] is False- assert result['rbl_ok'] is False- assert 'zen.spamhaus.org' in result['rbl_hits']- assert result['detail']['rbl']['hits'] == ['zen.spamhaus.org']---def test_preflight_blocked_port25_fails(app, monkeypatch):- _patch_checks(monkeypatch, port25=(False, 'provider blocks port 25'))- result = PreflightService.run('mail.example.com', server_ip='203.0.113.5')- assert result['passed'] is False- assert result['port25_ok'] is False- assert result['detail']['port25']['ok'] is False---def test_preflight_windows_skips_and_never_raises(app, monkeypatch):- # Do NOT stub the checks; force the real OS gate to skip host-dependent work.- monkeypatch.setattr(preflight_mod.os, 'name', 'nt')- result = PreflightService.run('mail.example.com', server_ip='203.0.113.5')- assert result['passed'] is False # skipped checks never green-light sending- assert 'dev_note' in result['detail']---def test_preflight_latest_returns_newest(app, monkeypatch):- from app import db- from datetime import datetime, timedelta- old = PreflightResult(hostname='old.example.com', passed=False,- checked_at=datetime.utcnow() - timedelta(hours=2))- new = PreflightResult(hostname='new.example.com', passed=True,- checked_at=datetime.utcnow())- db.session.add_all([old, new])- db.session.commit()- latest = PreflightService.latest()- assert latest['hostname'] == 'new.example.com'---def test_preflight_latest_none_when_empty(app):- assert PreflightService.latest() is None---# ----------------------------------------------------------------------------# activation gate (the key safety property)-# -----------------------------------------------------------------------------def _make_domain(active=False):- from app import db- row = MailDomain(name='gate.example.com', is_active=active, sync_state='pending')- db.session.add(row)- db.session.commit()- return row---def test_activation_refused_without_passing_preflight(app):- row = _make_domain()- result = MailService.set_domain_active(row.id, True)- assert result['success'] is False- assert result['code'] == 'preflight_required'- # The domain stays inactive.- from app import db- db.session.refresh(row)- assert row.is_active is False---def test_activation_allowed_with_force_and_audits(app, monkeypatch):- row = _make_domain()- audits = []- monkeypatch.setattr(- MailService, '_audit',- staticmethod(lambda action, target_id, details: audits.append(- (action, target_id, details))))- result = MailService.set_domain_active(row.id, True, force=True)- assert result['success'] is True- from app import db- db.session.refresh(row)- assert row.is_active is True- # The force override was recorded on the audit ledger.- assert audits and audits[0][0] == 'mail.domain.activate_forced'- assert audits[0][1] == row.id---def test_activation_allowed_with_passing_preflight(app):- from app import db- db.session.add(PreflightResult(hostname='gate.example.com', passed=True))- db.session.commit()- row = _make_domain()- result = MailService.set_domain_active(row.id, True) # no force needed- assert result['success'] is True- db.session.refresh(row)- assert row.is_active is True---def test_deactivation_is_never_gated(app):- row = _make_domain(active=True)- result = MailService.set_domain_active(row.id, False)- assert result['success'] is True- from app import db- db.session.refresh(row)- assert row.is_active is False---# ----------------------------------------------------------------------------# DKIM keygen + record builder-# -----------------------------------------------------------------------------def test_generate_dkim_stores_keys_and_txt_value(app):- from app import db- row = MailDomain(name='dkim.example.com')- db.session.add(row)- db.session.commit()-- result = DkimDnsService.generate_dkim(row)- assert result['success'] is True, result- assert result['selector'] == 'serverkit'- assert result['dkim_value'].startswith('v=DKIM1; k=rsa; p=')-- db.session.refresh(row)- assert row.dkim_private_key and 'PRIVATE KEY' in row.dkim_private_key- assert row.dkim_public_key- # The stored public key round-trips into the same TXT value.- assert result['dkim_value'].endswith(row.dkim_public_key)---def test_build_records_shapes():- domain = MailDomain(name='Example.COM', dkim_selector='serverkit',- dkim_public_key='PUBKEYB64')- records = DkimDnsService.build_records(domain, server_ip='203.0.113.5')- by_type = {}- for r in records:- by_type.setdefault(r['type'], []).append(r)-- mx = by_type['MX'][0]- assert mx['name'] == 'example.com'- assert mx['value'] == '10 mail.example.com'- assert mx['priority'] == 10-- txts = {r['name']: r['value'] for r in by_type['TXT']}- assert txts['example.com'] == 'v=spf1 mx a ~all'- assert txts['_dmarc.example.com'].startswith('v=DMARC1; p=quarantine')- assert txts['serverkit._domainkey.example.com'] == 'v=DKIM1; k=rsa; p=PUBKEYB64'-- a = by_type['A'][0]- assert a['name'] == 'mail.example.com'- assert a['value'] == '203.0.113.5'---def test_build_records_omits_dkim_and_a_when_absent():- domain = MailDomain(name='bare.example.com', dkim_selector='serverkit',- dkim_public_key=None)- records = DkimDnsService.build_records(domain, server_ip=None)- names = {(r['type'], r['name']) for r in records}- assert ('A', 'mail.bare.example.com') not in names- assert not any(r['name'].startswith('serverkit._domainkey') for r in records)---# ----------------------------------------------------------------------------# DNS deployment via DNSProviderService-# -----------------------------------------------------------------------------def _patch_provider(monkeypatch, zone=('cfg', 'zone')):- """Patch DNSProviderService.find_zone_for_domain + set_record; return the- captured set_record calls."""- from app.services.dns_provider_service import DNSProviderService- calls = []-- config = SimpleNamespace(id=7, name='cloudflare')- zone_dict = {'id': 'zone-abc', 'name': 'example.com'}-- monkeypatch.setattr(DNSProviderService, 'find_zone_for_domain',- classmethod(lambda cls, name: (config, zone_dict)))-- def fake_set_record(cls, provider_id, zone_id, record_type, name, value,- ttl=3600, proxied=False, priority=None, source='provider'):- calls.append({'provider_id': provider_id, 'zone_id': zone_id,- 'type': record_type, 'name': name, 'value': value,- 'priority': priority, 'source': source})- return {'success': True}- monkeypatch.setattr(DNSProviderService, 'set_record', classmethod(fake_set_record))- return calls, config, zone_dict---def test_deploy_dns_pushes_exact_records(app, monkeypatch):- from app import db- row = MailDomain(name='example.com', dkim_selector='serverkit',- dkim_public_key='PUBKEYB64')- db.session.add(row)- db.session.commit()-- calls, config, zone = _patch_provider(monkeypatch)- result = DkimDnsService.deploy_dns(row.id, server_ip='203.0.113.5')- assert result['success'] is True- assert result['deployed'] is True- assert result['manual'] is False-- by = {(c['type'], c['name']): c for c in calls}- # Every write is tagged source='mail' for the ownership ledger.- assert all(c['source'] == 'mail' for c in calls)- assert all(c['provider_id'] == 7 and c['zone_id'] == 'zone-abc' for c in calls)-- mx = by[('MX', 'example.com')]- assert mx['value'] == '10 mail.example.com'- assert mx['priority'] == 10- assert by[('TXT', 'example.com')]['value'] == 'v=spf1 mx a ~all'- assert by[('TXT', '_dmarc.example.com')]['value'].startswith('v=DMARC1; p=quarantine')- assert by[('TXT', 'serverkit._domainkey.example.com')]['value'] == \- 'v=DKIM1; k=rsa; p=PUBKEYB64'- assert by[('A', 'mail.example.com')]['value'] == '203.0.113.5'-- # The deployment ledger was recorded on the row.- db.session.refresh(row)- assert row.dns_deployed is True- ledger = json.loads(row.dns_last_result)- assert ledger['all_ok'] is True- assert ledger['provider'] == 'cloudflare'---def test_deploy_dns_no_provider_returns_manual(app, monkeypatch):- from app import db- from app.services.dns_provider_service import DNSProviderService- row = MailDomain(name='noprovider.example.com')- db.session.add(row)- db.session.commit()-- monkeypatch.setattr(DNSProviderService, 'find_zone_for_domain',- classmethod(lambda cls, name: (None, None)))- monkeypatch.setattr(- DNSProviderService, 'set_record',- classmethod(lambda *a, **kw: pytest.fail('set_record must not run without a zone')))-- result = DkimDnsService.deploy_dns(row.id, server_ip='203.0.113.5')- assert result['success'] is True- assert result['deployed'] is False- assert result['manual'] is True- assert isinstance(result['records'], list) and result['records']---def test_dns_instructions_shape(app):- from app import db- row = MailDomain(name='inst.example.com', dkim_selector='serverkit',- dkim_public_key='PUB')- db.session.add(row)- db.session.commit()- out = DkimDnsService.dns_instructions(row, server_ip='203.0.113.5')- assert out['domain'] == 'inst.example.com'- assert out['dns_deployed'] is False- assert out['dkim_configured'] is False # only public key set here, no private- assert any(r['type'] == 'MX' for r in out['records'])---def test_request_cert_skips_on_windows(monkeypatch):- monkeypatch.setattr(dns_mod.os, 'name', 'nt')- result = DkimDnsService.request_cert('mail.example.com')- assert result['success'] is False- assert result['skipped'] is True---# ----------------------------------------------------------------------------# fail2ban jail-# -----------------------------------------------------------------------------def test_jail_unavailable_on_windows(monkeypatch):- monkeypatch.setattr(jail_mod.os, 'name', 'nt')- assert MailJailService.available() is False- # Mutating calls degrade to a skipped descriptor, never raise.- res = MailJailService.enable_auth_jail()- assert res['success'] is True- assert res['skipped'] is True- assert res['available'] is False---def test_jail_enable_writes_serverkit_mail_conf(monkeypatch):- monkeypatch.setattr(jail_mod.os, 'name', 'posix')- monkeypatch.setattr(jail_mod, 'is_command_available', lambda c: True)-- writes = []-- def fake_run(cmd, timeout=None, input=None, **kwargs):- writes.append({'cmd': list(cmd), 'input': input})- return _proc(returncode=0)- monkeypatch.setattr(jail_mod, 'run_privileged', fake_run)-- res = MailJailService.enable_auth_jail()- assert res['success'] is True- assert res['jail'] == 'serverkit-mail-auth'- assert res['path'].endswith('serverkit-mail-auth.conf')-- tee = next(w for w in writes if w['cmd'][:1] == ['tee'])- assert tee['cmd'][1].endswith('serverkit-mail-auth.conf')- assert '/etc/fail2ban/jail.d' in tee['cmd'][1]- assert '[serverkit-mail-auth]' in tee['input']- assert 'enabled = true' in tee['input']- # fail2ban was reloaded after the write.- assert any(w['cmd'][:2] == ['fail2ban-client', 'reload'] for w in writes)---def test_jail_status_reports_availability(monkeypatch):- monkeypatch.setattr(jail_mod.os, 'name', 'nt')- info = MailJailService.status()- assert info['available'] is False- assert info['enabled'] is False- assert info['jail'] == 'serverkit-mail-auth'diff --git a/backend/tests/test_tramo_extension.py b/backend/tests/test_tramo_extension.pydeleted file mode 100644index 67c438e1..00000000--- a/backend/tests/test_tramo_extension.py+++ /dev/null@@ -1,612 +0,0 @@-"""serverkit-tramo (Automations) extension tests.--Loads the builtin the way production does: ``plugin_service.-_ensure_builtin_backend_importable`` registers ``builtin-extensions/-serverkit-tramo/backend`` as the dashed package ``app.plugins.serverkit-tramo``.-The models module is imported at module top so its ``ext_serverkit_tramo_*``-tables register on ``db.metadata`` before the ``app`` fixture runs-``db.create_all()``.--Docker and the tramo HTTP API are mocked at the two service choke-points-(``TramoHostService._docker`` / ``._api``) so nothing shells out or talks HTTP.-Cross-platform: tests that exercise the ``os.name == 'nt'`` gate force it-explicitly so they behave the same on the Windows dev box and Linux CI.--Also covers plan 45 Phase 4: the retired ``/api/v1/workflows`` routes are gone,-the four ported event emitters reach EventService, ``app.stopped`` is no longer-double-emitted by docker_service, and the admin-only legacy export.-"""-import importlib-import json-import os-from types import SimpleNamespace--import pytest--from app.services import plugin_service--SLUG = 'serverkit-tramo'-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 ('models', 'host_service', 'workflow_store', 'events_bridge',- 'run_sync', 'jobs', 'templates', 'lifecycle', 'tramo'):- mods[name] = importlib.import_module(f'app.plugins.{SLUG}.{name}')- return mods---_M = _load_ext()-models_mod = _M['models']-host_mod = _M['host_service']-store_mod = _M['workflow_store']-eb_mod = _M['events_bridge']-run_sync_mod = _M['run_sync']-jobs_mod = _M['jobs']-templates_mod = _M['templates']-bp_mod = _M['tramo']--TramoWorkflow = models_mod.TramoWorkflow-TramoRun = models_mod.TramoRun-TramoHostService = host_mod.TramoHostService-WorkflowStore = store_mod.WorkflowStore---# --------------------------------------------------------------------------- #-# helpers / fixtures-# --------------------------------------------------------------------------- #-def _mk_plugin_row(config=None):- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin(- name=SLUG, display_name='Automations', slug=SLUG, version='1.0.0',- status=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='tramoadmin',- password_hash=generate_password_hash('x'),- role=User.ROLE_ADMIN, is_active=True)- db.session.add(u)- db.session.commit()- return u---def posix(monkeypatch):- """Force the Linux path through the host service's Windows gate.-- Patches the ``_is_windows`` seam (never the global ``os.name`` -- that would- swap ``pathlib`` to ``PosixPath`` and crash on the Windows dev box).- """- monkeypatch.setattr(TramoHostService, '_is_windows', classmethod(lambda cls: False))- return True---def tramo_client(app):- if 'tramo' not in app.blueprints:- app.register_blueprint(bp_mod.tramo_bp, url_prefix='/api/v1/tramo')- 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'] == 'tramo:tramo_bp'- assert m['url_prefix'] == '/api/v1/tramo'- assert m['models'] == 'models:register'- nav = m['contributions']['nav'][0]- assert nav['route'] == '/automations' and nav['id'] == 'automations'- assert m['contributions']['page_titles']['/automations'] == 'Automations'---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 '—' not in m['description'] and '–' not in m['description']---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, 'tramo_bp', None) is not None- assert bp_mod.tramo_bp.name == 'tramo'---# --------------------------------------------------------------------------- #-# models + purge-# --------------------------------------------------------------------------- #-def test_models_register_and_tables_exist(app):- from app import db- from sqlalchemy import inspect- assert set(models_mod.register(db)) == {TramoWorkflow, TramoRun}- tables = [t for t in inspect(db.engine).get_table_names()- if t.startswith('ext_serverkit_tramo')]- assert 'ext_serverkit_tramo_workflows' in tables- assert 'ext_serverkit_tramo_runs' in tables---def test_purge_drops_only_prefixed_tables(app):- from app import db- from app.services import extension_lifecycle- from sqlalchemy import inspect- plugin = SimpleNamespace(slug=SLUG)- dropped = extension_lifecycle.purge_models(plugin)- assert dropped >= 2- remaining = [t for t in inspect(db.engine).get_table_names()- if t.startswith('ext_serverkit_tramo')]- assert remaining == []- # A core table must survive.- assert 'users' in inspect(db.engine).get_table_names()- db.create_all() # restore for later tests in this module---# --------------------------------------------------------------------------- #-# workflow store CRUD + slug + materialize + deploy-# --------------------------------------------------------------------------- #-def test_create_slugifies_and_uniquifies(app):- a = WorkflowStore.create('My Flow!')- b = WorkflowStore.create('My Flow!')- assert a.slug == 'my-flow'- assert b.slug == 'my-flow-2'- assert a.get_doc().get('nodes') == []---def test_create_doc_has_meta_and_version(app):- """A brand-new workflow doc must carry `meta` (and `version`): the editor's- Canvas reads `doc.meta.mcpServers` unconditionally and crashes without it."""- doc = WorkflowStore.create('needs-meta').get_doc()- assert doc.get('meta') == {}- assert doc.get('version') == 1---def test_create_rejects_blank_name(app):- with pytest.raises(ValueError):- WorkflowStore.create(' ')---def test_update_bumps_doc_version_and_dirty(app):- wf = WorkflowStore.create('flow')- assert wf.doc_version == 1- WorkflowStore.update(wf.slug, doc={'nodes': [{'id': 'n1'}], 'edges': []})- assert wf.doc_version == 2- # Never deployed + enabled => dirty.- assert wf.is_dirty() is True---def test_delete_removes_row(app):- wf = WorkflowStore.create('gone')- WorkflowStore.delete(wf.slug)- assert WorkflowStore.get('gone') is None---def test_materialize_writes_only_enabled(app, monkeypatch, posix):- on = WorkflowStore.create('on-flow', enabled=True)- WorkflowStore.create('off-flow', enabled=False)- written = {}- removed = []- monkeypatch.setattr(WorkflowStore, '_write_file',- classmethod(lambda cls, slug, doc: written.__setitem__(slug, doc)))- monkeypatch.setattr(WorkflowStore, '_list_files',- classmethod(lambda cls: ['on-flow', 'stale-flow']))- monkeypatch.setattr(WorkflowStore, '_remove_file',- classmethod(lambda cls, slug: removed.append(slug)))- summary = WorkflowStore.materialize()- assert summary['written'] == ['on-flow']- assert 'on-flow' in written and 'off-flow' not in written- # stale + disabled files pruned.- assert 'stale-flow' in removed---def test_deploy_stamps_deployed_at(app, monkeypatch, posix):- wf = WorkflowStore.create('dep')- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(WorkflowStore, 'materialize',- classmethod(lambda cls: {'written': ['dep'], 'pruned': []}))- monkeypatch.setattr(TramoHostService, 'control',- classmethod(lambda cls, action: {'success': True}))- res = WorkflowStore.deploy()- assert res['success'] is True- assert wf.deployed_at is not None- assert wf.is_dirty() is False---def test_deploy_requires_installed_engine(app, monkeypatch):- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: False))- res = WorkflowStore.deploy()- assert res['success'] is False- assert 'not installed' in res['error']---# --------------------------------------------------------------------------- #-# host service: argv, control, status, nt guard-# --------------------------------------------------------------------------- #-def test_build_run_args_argv(app):- argv = TramoHostService._build_run_args(8377, 'SECRETKEY', callback_api_key='CBKEY')- joined = ' '.join(argv)- assert argv[0] == 'run' and '-d' in argv- assert '127.0.0.1:8377:3000' in argv # loopback publish only- assert f'{host_mod.HOST_WORKFLOWS_DIR}:/workflows' in argv- assert f'{host_mod.HOST_STATE_DIR}:/state' in argv- assert 'TRAMO_API_KEY=SECRETKEY' in argv- assert 'TRAMO_PACKS=all' in argv- assert 'SERVERKIT_API_KEY=CBKEY' in argv- assert any(a.startswith('SERVERKIT_URL=') for a in argv)- assert 'host.docker.internal:host-gateway' in argv- assert argv[-1] == host_mod.IMAGE- assert 'ghcr.io/jhd3197/tramo-server:0.1.1' == host_mod.IMAGE---def test_build_run_args_includes_pack_secrets(app, monkeypatch):- _mk_plugin_row()- TramoHostService.set_pack_secrets({'TELEGRAM_BOT_TOKEN': 'abc123'})- argv = TramoHostService._build_run_args(8377, 'KEY')- assert 'TELEGRAM_BOT_TOKEN=abc123' in argv---def test_pack_secrets_round_trip_encrypted(app):- _mk_plugin_row()- TramoHostService.set_pack_secrets({'GMAIL_OAUTH_TOKEN': 'tok'})- # Stored value must not be the plaintext (when encryption is configured).- from app.utils.crypto import is_encryption_configured- raw = TramoHostService._config().get('pack_secrets', {}).get('GMAIL_OAUTH_TOKEN')- if is_encryption_configured():- assert raw != 'tok'- assert TramoHostService.get_pack_secrets()['GMAIL_OAUTH_TOKEN'] == 'tok'---def test_set_pack_secret_empty_value_deletes(app):- _mk_plugin_row()- TramoHostService.set_pack_secrets({'X_TOKEN': 'v'})- names = TramoHostService.set_pack_secrets({'X_TOKEN': ''})- assert 'X_TOKEN' not in names---def test_control_maps_actions(app, monkeypatch, posix):- calls = []- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(TramoHostService, '_docker',- classmethod(lambda cls, args, **kw: calls.append(args) or {'success': True}))- for action in ('start', 'stop', 'restart'):- res = TramoHostService.control(action)- assert res['success'] and res['action'] == action- assert calls[0] == ['start', host_mod.CONTAINER_NAME]- assert calls[2] == ['restart', host_mod.CONTAINER_NAME]---def test_control_rejects_bad_action(app):- assert TramoHostService.control('nuke')['success'] is False---def test_status_states(app, monkeypatch, posix):- # not installed- monkeypatch.setattr(TramoHostService, '_docker',- classmethod(lambda cls, args, **kw: {'success': False}))- assert TramoHostService.get_status()['state'] == 'not_installed'-- # stopped- monkeypatch.setattr(TramoHostService, '_docker',- classmethod(lambda cls, args, **kw: {'success': True, 'stdout': 'false'}))- assert TramoHostService.get_status()['state'] == 'stopped'-- # running + unhealthy- monkeypatch.setattr(TramoHostService, '_docker',- classmethod(lambda cls, args, **kw: {'success': True, 'stdout': 'true'}))- monkeypatch.setattr(TramoHostService, '_api',- classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': False, 'error': 'x'}))- assert TramoHostService.get_status()['state'] == 'unhealthy'-- # running + ready- monkeypatch.setattr(TramoHostService, '_api',- classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': True, 'data': {'version': '0.1.1'}}))- st = TramoHostService.get_status()- assert st['state'] == 'ready' and st['healthy'] is True---def test_nt_guard_returns_graceful_error(app, monkeypatch):- monkeypatch.setattr(TramoHostService, '_is_windows', classmethod(lambda cls: True))- assert TramoHostService.is_installed() is False- d = TramoHostService._docker(['ps'])- assert d['success'] is False and 'Windows' in d['error']- st = TramoHostService.get_status()- assert st['state'] == 'not_installed'- inst = TramoHostService.install()- assert inst['success'] is False and 'Windows' in inst['error']---# --------------------------------------------------------------------------- #-# run_sync-# --------------------------------------------------------------------------- #-def test_upsert_run_inserts_then_updates(app):- row1, new1 = run_sync_mod.upsert_run({'id': 'r1', 'status': 'running',- 'workflowId': 'flow-a'})- assert new1 is True and row1.status == 'running'- row2, new2 = run_sync_mod.upsert_run({'id': 'r1', 'status': 'success'})- assert new2 is False and row2.status == 'success'- assert TramoRun.query.filter_by(run_id='r1').count() == 1---def test_upsert_run_ignores_missing_id(app):- row, new = run_sync_mod.upsert_run({'status': 'success'})- assert row is None and new is False---# --------------------------------------------------------------------------- #-# jobs-# --------------------------------------------------------------------------- #-def test_harvest_upserts_and_notifies_once(app, monkeypatch):- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))- runs = [{'id': 'a', 'status': 'success'}, {'id': 'b', 'status': 'failed'}]- monkeypatch.setattr(TramoHostService, '_api',- classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': True, 'data': runs}))- sent = []- monkeypatch.setattr('app.plugins_sdk.notify.send',- lambda *a, **k: sent.append((a, k)))- r1 = jobs_mod.harvest_runs(None)- assert r1['harvested'] == 2 and r1['new_failures'] == 1- # Second harvest: no new rows, no new failure notifications.- r2 = jobs_mod.harvest_runs(None)- assert r2['new_failures'] == 0- assert len(sent) == 1- assert TramoRun.query.count() == 2---def test_health_check_notifies_after_threshold(app, monkeypatch):- _mk_plugin_row()- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(TramoHostService, 'health',- classmethod(lambda cls: {'success': False, 'error': 'down'}))- sent = []- monkeypatch.setattr('app.plugins_sdk.notify.send', lambda *a, **k: sent.append(k))- jobs_mod.health_check(None) # streak 1: no notify- assert len(sent) == 0- jobs_mod.health_check(None) # streak 2: notify- assert len(sent) == 1- # Recovery resets the streak.- monkeypatch.setattr(TramoHostService, 'health',- classmethod(lambda cls: {'success': True}))- jobs_mod.health_check(None)- assert TramoHostService._config().get('health_fail_streak') == 0---# --------------------------------------------------------------------------- #-# events bridge + call-back key-# --------------------------------------------------------------------------- #-def test_events_bridge_toggle(app):- _mk_plugin_row()- _mk_admin()- from app.models.event_subscription import EventSubscription- sub_id = eb_mod.enable_events_bridge()- assert sub_id is not None- sub = EventSubscription.query.get(sub_id)- assert sub.get_events() == ['*']- assert '/sk/events' in sub.url- assert eb_mod.is_events_bridge_enabled() is True- # Idempotent.- assert eb_mod.enable_events_bridge() == sub_id- # Disable removes it.- assert eb_mod.disable_events_bridge() is True- assert EventSubscription.query.get(sub_id) is None- assert eb_mod.is_events_bridge_enabled() is False---def test_callback_key_issue_and_revoke(app):- _mk_plugin_row()- _mk_admin()- from app.models.api_key import ApiKey- raw = eb_mod.issue_callback_key()- assert raw and raw.startswith('sk_')- key_id = eb_mod._config().get('callback_key_id')- key = ApiKey.query.get(key_id)- assert key.name == 'serverkit-tramo'- assert 'apps:deploy' in key.get_scopes()- assert key.is_valid() is True- eb_mod.revoke_callback_key()- from app import db- db.session.refresh(key)- assert key.is_active is False and key.revoked_at is not None---def test_uninstall_revokes_key_and_subscription(app, monkeypatch):- _mk_plugin_row()- _mk_admin()- from app.models.api_key import ApiKey- from app.models.event_subscription import EventSubscription- eb_mod.issue_callback_key()- eb_mod.enable_events_bridge()- key_id = eb_mod._config().get('callback_key_id')- sub_id = eb_mod._config().get('events_subscription_id')- # Container teardown is a no-op here (not installed).- monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: False))- lifecycle = importlib.import_module(f'app.plugins.{SLUG}.lifecycle')- lifecycle.on_uninstall(SimpleNamespace(slug=SLUG), purge=False)- from app import db- key = ApiKey.query.get(key_id)- assert key.is_active is False- assert EventSubscription.query.get(sub_id) is None---# --------------------------------------------------------------------------- #-# blueprint: auth, run proxy, runs filter, settings mask, hooks passthrough-# --------------------------------------------------------------------------- #-def test_routes_require_auth(tramo_client):- assert tramo_client.get('/api/v1/tramo/workflows').status_code in (401, 422)- assert tramo_client.get('/api/v1/tramo/host/status').status_code in (401, 422)---def test_workflow_crud_via_routes(tramo_client, auth_headers):- r = tramo_client.post('/api/v1/tramo/workflows', headers=auth_headers,- json={'name': 'Route Flow'})- assert r.status_code == 201- slug = r.get_json()['slug']- assert tramo_client.get(f'/api/v1/tramo/workflows/{slug}',- headers=auth_headers).status_code == 200- lst = tramo_client.get('/api/v1/tramo/workflows', headers=auth_headers).get_json()- assert any(w['slug'] == slug for w in lst['workflows'])---def test_run_proxy_persists_row(tramo_client, auth_headers, monkeypatch):- WorkflowStore.create('runme')- monkeypatch.setattr(bp_mod.TramoHostService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(bp_mod.TramoHostService, '_api',- classmethod(lambda cls, m, p, payload=None, timeout=None:- {'success': True, 'data': {'id': 'run-77', 'status': 'success',- 'workflowId': 'runme'}}))- r = tramo_client.post('/api/v1/tramo/workflows/runme/run', headers=auth_headers, json={})- assert r.status_code == 200- assert r.get_json()['run']['run_id'] == 'run-77'- assert TramoRun.query.filter_by(run_id='run-77').count() == 1---def test_runs_list_filters_by_workflow(tramo_client, auth_headers, app):- run_sync_mod.upsert_run({'id': 'x1', 'status': 'success', 'workflowId': 'flowA'})- run_sync_mod.upsert_run({'id': 'x2', 'status': 'success', 'workflowId': 'flowB'})- r = tramo_client.get('/api/v1/tramo/runs?workflow=flowA', headers=auth_headers)- runs = r.get_json()['runs']- assert len(runs) == 1 and runs[0]['run_id'] == 'x1'---def test_settings_masks_secret_values(tramo_client, auth_headers, app):- _mk_plugin_row()- tramo_client.put('/api/v1/tramo/settings', headers=auth_headers,- json={'pack_secrets': {'TELEGRAM_BOT_TOKEN': 'shh'}})- body = tramo_client.get('/api/v1/tramo/settings', headers=auth_headers).get_json()- assert 'TELEGRAM_BOT_TOKEN' in body['pack_secret_names']- # The value must never be echoed anywhere in the settings response.- assert 'shh' not in json.dumps(body)---def test_hooks_passthrough_is_auth_exempt_and_forwards(tramo_client, monkeypatch):- monkeypatch.setattr(bp_mod.TramoHostService, 'is_installed', classmethod(lambda cls: True))- monkeypatch.setattr(bp_mod.TramoHostService, 'host_port', classmethod(lambda cls: 8377))- captured = {}-- def fake_request(method, url, **kw):- captured['method'] = method- captured['url'] = url- captured['data'] = kw.get('data')- return SimpleNamespace(status_code=200, content=b'{"ok":true}',- headers={'Content-Type': 'application/json'})-- monkeypatch.setattr(bp_mod.requests, 'request', fake_request)- # NO auth headers -> still reachable (auth-exempt).- r = tramo_client.post('/api/v1/tramo/hooks/my-trigger', data=b'{"a":1}',- content_type='application/json')- assert r.status_code == 200- assert captured['method'] == 'POST'- assert captured['url'].endswith('/hooks/my-trigger')- assert captured['data'] == b'{"a":1}'---def test_starter_templates_route(tramo_client, auth_headers):- r = tramo_client.get('/api/v1/tramo/templates', headers=auth_headers)- ids = [t['id'] for t in r.get_json()['templates']]- assert 'backup-failed-telegram' in ids- # Instantiate one.- c = tramo_client.post('/api/v1/tramo/workflows/from-template/backup-failed-telegram',- headers=auth_headers, json={})- assert c.status_code == 201- assert c.get_json()['doc']['nodes']---# --------------------------------------------------------------------------- #-# Phase 4: retired engine + ported emitters + legacy export-# --------------------------------------------------------------------------- #-def test_legacy_workflows_route_admin_only(tramo_client, auth_headers, app):- # Admin gets a (possibly empty) list, never a 500.- r = tramo_client.get('/api/v1/tramo/legacy-workflows', headers=auth_headers)- assert r.status_code == 200- assert 'workflows' in r.get_json()---def test_old_workflows_routes_are_gone(client, auth_headers):- # The /api/v1/workflows blueprint was removed in Phase 4.- r = client.get('/api/v1/workflows', headers=auth_headers)- assert r.status_code == 404- # The execute route no longer has a POST handler; the SPA catch-all is- # GET-only, so an unmatched POST is 404/405 -- either proves it is gone.- r2 = client.post('/api/v1/workflows/1/execute', headers=auth_headers, json={})- assert r2.status_code in (404, 405)---def test_event_catalog_has_ported_types():- from app.services.event_service import EVENT_CATALOG- types = {e['type'] for e in EVENT_CATALOG}- assert {'health.check_failed', 'git.push',- 'monitor.high_cpu', 'monitor.high_memory'} <= types---def _wildcard_sub(app):- from app import db- from app.models.event_subscription import EventSubscription- admin = _mk_admin()- sub = EventSubscription(user_id=admin.id, name='cap', url='http://x/y', is_active=True)- sub.set_events(['*'])- db.session.add(sub)- db.session.commit()- return sub---def test_ported_emitters_reach_event_service(app, monkeypatch):- from app.services.event_service import EventService- from app.models.event_subscription import EventDelivery- _wildcard_sub(app)- enqueued = []- monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',- lambda did: enqueued.append(did))- for evt in ('health.check_failed', 'git.push', 'monitor.high_cpu'):- EventService.emit(evt, {'event': evt})- delivered = {d.event_type for d in EventDelivery.query.all()}- assert {'health.check_failed', 'git.push', 'monitor.high_cpu'} <= delivered- assert len(enqueued) == 3---def test_app_stopped_not_double_emitted_by_docker_service(app, monkeypatch):- """docker_service.stop_container no longer emits app.stopped itself."""- from app.models.event_subscription import EventDelivery- _wildcard_sub(app)- from app.services.docker_service import DockerService- monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',- lambda did: None)- monkeypatch.setattr(- 'app.services.docker_service.subprocess.run',- lambda *a, **k: SimpleNamespace(returncode=0, stdout='', stderr=''))- res = DockerService.stop_container('abc123')- assert res['success'] is True- # No app.stopped delivery came from the low-level stop helper.- assert EventDelivery.query.filter_by(event_type='app.stopped').count() == 0diff --git a/backend/tests/test_tramo_panel_core.py b/backend/tests/test_tramo_panel_core.pynew file mode 100644index 00000000..dfc95adf--- /dev/null+++ b/backend/tests/test_tramo_panel_core.py@@ -0,0 +1,79 @@+"""Panel-core coverage that used to live at the bottom of+backend/tests/test_tramo_extension.py.++When serverkit-tramo moved to its own standalone repo its extension tests moved+with it, but these four exercise CORE behavior (the retired /api/v1/workflows+blueprint, the plan-45 event emitters ported to EventService, and the+docker_service double-emit fix) — so they stay in the panel.+"""+from types import SimpleNamespace++from app import db+from app.models.user import User+++def _mk_admin():+ from werkzeug.security import generate_password_hash+ u = User(email='[email protected]', username='tramoadmin',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(u)+ db.session.commit()+ return u+++def _wildcard_sub(app):+ from app.models.event_subscription import EventSubscription+ admin = _mk_admin()+ sub = EventSubscription(user_id=admin.id, name='cap', url='http://x/y', is_active=True)+ sub.set_events(['*'])+ db.session.add(sub)+ db.session.commit()+ return sub+++def test_old_workflows_routes_are_gone(client, auth_headers):+ # The /api/v1/workflows blueprint was removed in Phase 4.+ r = client.get('/api/v1/workflows', headers=auth_headers)+ assert r.status_code == 404+ # The execute route no longer has a POST handler; the SPA catch-all is+ # GET-only, so an unmatched POST is 404/405 -- either proves it is gone.+ r2 = client.post('/api/v1/workflows/1/execute', headers=auth_headers, json={})+ assert r2.status_code in (404, 405)+++def test_event_catalog_has_ported_types():+ from app.services.event_service import EVENT_CATALOG+ types = {e['type'] for e in EVENT_CATALOG}+ assert {'health.check_failed', 'git.push',+ 'monitor.high_cpu', 'monitor.high_memory'} <= types+++def test_ported_emitters_reach_event_service(app, monkeypatch):+ from app.services.event_service import EventService+ from app.models.event_subscription import EventDelivery+ _wildcard_sub(app)+ enqueued = []+ monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',+ lambda did: enqueued.append(did))+ for evt in ('health.check_failed', 'git.push', 'monitor.high_cpu'):+ EventService.emit(evt, {'event': evt})+ delivered = {d.event_type for d in EventDelivery.query.all()}+ assert {'health.check_failed', 'git.push', 'monitor.high_cpu'} <= delivered+ assert len(enqueued) == 3+++def test_app_stopped_not_double_emitted_by_docker_service(app, monkeypatch):+ """docker_service.stop_container no longer emits app.stopped itself."""+ from app.models.event_subscription import EventDelivery+ _wildcard_sub(app)+ from app.services.docker_service import DockerService+ monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',+ lambda did: None)+ monkeypatch.setattr(+ 'app.services.docker_service.subprocess.run',+ lambda *a, **k: SimpleNamespace(returncode=0, stdout='', stderr=''))+ res = DockerService.stop_container('abc123')+ assert res['success'] is True+ # No app.stopped delivery came from the low-level stop helper.+ assert EventDelivery.query.filter_by(event_type='app.stopped').count() == 0diff --git a/builtin-extensions/serverkit-analytics/backend/__init__.py b/builtin-extensions/serverkit-analytics/backend/__init__.pydeleted file mode 100644index 823985e8..00000000--- a/builtin-extensions/serverkit-analytics/backend/__init__.py+++ /dev/null@@ -1,14 +0,0 @@-"""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.pydeleted file mode 100644index e60e7c43..00000000--- a/builtin-extensions/serverkit-analytics/backend/analytics.py+++ /dev/null@@ -1,420 +0,0 @@-"""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 (Phase 2)-* ``log_ingest_service`` — access-log parsing (Phase 6)-* ``wp_integration`` / ``nginx_integration`` — one-click tracker injection (Ph5)--Auth split mirrors serverkit-tramo / serverkit-k8s: report reads need viewer,-site mutations need admin. The public tracker surface — ``POST /collect`` and-``GET /tracker.js`` — carries NO JWT because a tracked site's visitors have-none. It authenticates per-site via the ``site_key`` (not a JWT) and is-protected by a body-size cap, per-site origin allowlist, an in-process token-bucket, and bot/DNT filtering. The plugin-disabled 503 guard (attached by-plugin_service) still runs on every route, so disabling the extension stops-collection for free; the tracker fails silently on any non-2xx.-"""-import json-import logging-import os--from flask import Blueprint, current_app, jsonify, request--from app.middleware.rbac import admin_required, viewer_required-from app.utils.client_ip import get_client_ip--from . import (- ingest_service, log_ingest_service, nginx_integration, report_service,- rollup_service, site_service, wp_integration,-)-from .config import cfg_bool-from .ingest_service import MAX_BODY_BYTES, referrer_host-from .models import AnalyticsSite--logger = logging.getLogger(__name__)--analytics_bp = Blueprint('analytics', __name__)--_TRACKER_CACHE = {'js': None}---# --------------------------------------------------------------------------- #-# helpers-# --------------------------------------------------------------------------- #-def _plain(body='', status=204):- """A bare Response (empty by default) used for accept-and-drop / success."""- return current_app.make_response((body, status))---def _origin_allowed(origin, allowed):- ohost = referrer_host(origin) or origin- for entry in allowed:- ehost = referrer_host(entry) or entry- if origin == entry or ohost == ehost:- return True- return False---def _acao(site, origin):- """The Access-Control-Allow-Origin value for this site+origin, or None."""- if not origin:- return None- allowed = site.allowed_origin_list()- if allowed:- return origin if _origin_allowed(origin, allowed) else None- return origin # default: reflect the origin (token already validated)---def _cors(resp, site, origin):- acao = _acao(site, origin)- if acao:- resp.headers['Access-Control-Allow-Origin'] = acao- resp.headers['Vary'] = 'Origin'- return resp---def _preflight(origin):- resp = _plain('', 204)- if origin:- resp.headers['Access-Control-Allow-Origin'] = origin- resp.headers['Vary'] = 'Origin'- resp.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'- resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'- resp.headers['Access-Control-Max-Age'] = '86400'- return resp---# --------------------------------------------------------------------------- #-# public collector (NO auth — per-site token + rate limit + bot filter)-# --------------------------------------------------------------------------- #-@analytics_bp.route('/collect', methods=['POST', 'OPTIONS'])-def collect():- origin = request.headers.get('Origin')- if request.method == 'OPTIONS':- return _preflight(origin)-- # Body-size cap (declared length first, then actual bytes).- if request.content_length and request.content_length > MAX_BODY_BYTES:- return jsonify({'error': 'payload too large'}), 413- raw = request.get_data(cache=False) or b''- if len(raw) > MAX_BODY_BYTES:- return jsonify({'error': 'payload too large'}), 413-- # Beacons send text/plain (a CORS-safelisted content-type) to avoid a- # preflight, so parse the body ourselves regardless of Content-Type.- try:- payload = json.loads(raw.decode('utf-8', 'ignore') or '{}')- except (ValueError, TypeError):- return jsonify({'error': 'invalid payload'}), 400- if not isinstance(payload, dict):- return jsonify({'error': 'invalid payload'}), 400-- site_key = payload.get('k') or payload.get('site_key')- if not site_key or not isinstance(site_key, str):- return jsonify({'error': 'missing site_key'}), 400-- site = AnalyticsSite.query.filter_by(site_key=site_key).first()- if not site:- return jsonify({'error': 'unknown site'}), 404- if not site.enabled:- return jsonify({'error': 'site disabled'}), 403-- # Per-site origin allowlist (empty list => reflect after token check).- allowed = site.allowed_origin_list()- if allowed and origin and not _origin_allowed(origin, allowed):- return jsonify({'error': 'origin not allowed'}), 403-- ip = get_client_ip()- ua = request.headers.get('User-Agent', '') or ''-- # Rate limit (per site_key AND per IP).- if not ingest_service.rate_ok(site_key, ip):- resp = jsonify({'error': 'rate limited'})- resp.status_code = 429- return _cors(resp, site, origin)-- # Do Not Track — accepted but not stored (server double-checks the tracker).- honor_dnt = site.honor_dnt if site.honor_dnt is not None else cfg_bool('honor_dnt')- if honor_dnt and request.headers.get('DNT') == '1':- return _cors(_plain(), site, origin)-- # Bot filter: known bots and empty-UA JS hits are silently dropped (204) so- # we never reveal filtering to an abuser.- if not ua or ingest_service.is_bot(ua):- return _cors(_plain(), site, origin)-- event = ingest_service.build_event(site, payload, ip, ua)- if event is None:- return _cors(_plain(), site, origin)-- ingest_service.record_event(event)- ingest_service.ensure_flush_thread(current_app._get_current_object())- return _cors(_plain(), site, origin)---# --------------------------------------------------------------------------- #-# public tracker script-# --------------------------------------------------------------------------- #-def _load_tracker_js():- """Return the tracker JS body. Prefers a checked-in minified artifact- (Phase 3 build output) and falls back to a tiny placeholder."""- if _TRACKER_CACHE['js'] is not None:- return _TRACKER_CACHE['js']- here = os.path.dirname(os.path.abspath(__file__))- for rel in (os.path.join('tracker', 'sk.min.js'),- os.path.join('tracker', 'sk.js')):- path = os.path.join(here, rel)- try:- with open(path, encoding='utf-8') as f:- _TRACKER_CACHE['js'] = f.read()- return _TRACKER_CACHE['js']- except OSError:- continue- _TRACKER_CACHE['js'] = (- '/* serverkit-analytics tracker (placeholder; real build in Phase 3) */\n'- '(function(){})();\n'- )- return _TRACKER_CACHE['js']---@analytics_bp.route('/tracker.js', methods=['GET'])-def tracker_js():- resp = current_app.make_response(_load_tracker_js())- resp.headers['Content-Type'] = 'application/javascript; charset=utf-8'- resp.headers['Cache-Control'] = 'no-cache'- resp.headers['Access-Control-Allow-Origin'] = '*' # a public static script- return resp---@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---# --------------------------------------------------------------------------- #-# site CRUD (JWT: viewer reads, admin mutations)-# --------------------------------------------------------------------------- #-def _site_or_404(site_id):- site = site_service.get_site(site_id)- if not site:- return None, (jsonify({'error': 'Site not found'}), 404)- return site, None---@analytics_bp.route('/sites', methods=['GET'])-@viewer_required-def list_sites():- return jsonify({'sites': site_service.list_sites()}), 200---@analytics_bp.route('/sites', methods=['POST'])-@admin_required-def create_site():- data = request.get_json(silent=True) or {}- try:- site = site_service.create_site(data)- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(site.to_dict()), 201---@analytics_bp.route('/sites/<int:site_id>', methods=['GET'])-@viewer_required-def get_site(site_id):- site, err = _site_or_404(site_id)- if err:- return err- return jsonify(site.to_dict()), 200---@analytics_bp.route('/sites/<int:site_id>', methods=['PUT', 'PATCH'])-@admin_required-def update_site(site_id):- data = request.get_json(silent=True) or {}- try:- site = site_service.update_site(site_id, data)- except ValueError as e:- return jsonify({'error': str(e)}), 400- if not site:- return jsonify({'error': 'Site not found'}), 404- return jsonify(site.to_dict()), 200---@analytics_bp.route('/sites/<int:site_id>', methods=['DELETE'])-@admin_required-def delete_site(site_id):- if not site_service.delete_site(site_id):- return jsonify({'error': 'Site not found'}), 404- return jsonify({'deleted': True}), 200---@analytics_bp.route('/sites/<int:site_id>/rotate-key', methods=['POST'])-@admin_required-def rotate_key(site_id):- site = site_service.rotate_key(site_id)- if not site:- return jsonify({'error': 'Site not found'}), 404- return jsonify(site.to_dict()), 200---def _panel_base_url():- """Best public base URL for the tracker script, preferring a configured- public URL over the request host so a copied snippet works off-panel."""- from flask import current_app as _app- configured = (_app.config.get('SERVERKIT_PUBLIC_URL')- or _app.config.get('PUBLIC_URL') or '').strip()- if configured:- return configured.rstrip('/')- return (request.host_url or '').rstrip('/')---@analytics_bp.route('/sites/<int:site_id>/snippet', methods=['GET'])-@viewer_required-def site_snippet(site_id):- """Return the ready-to-paste tracker snippet for a site."""- site, err = _site_or_404(site_id)- if err:- return err- tracker_url = f'{_panel_base_url()}/api/v1/analytics/tracker.js'- outlinks = str(request.args.get('outlinks', '')).lower() in ('1', 'true', 'yes')- attrs = f' src="{tracker_url}" data-site-key="{site.site_key}"'- if outlinks:- attrs += ' data-outlinks="true"'- snippet = f'<script defer{attrs}></script>'- return jsonify({- 'snippet': snippet,- 'tracker_url': tracker_url,- 'site_key': site.site_key,- }), 200---# --------------------------------------------------------------------------- #-# report queries (JWT: viewer)-# --------------------------------------------------------------------------- #-@analytics_bp.route('/sites/<int:site_id>/overview', methods=['GET'])-@viewer_required-def site_overview(site_id):- site, err = _site_or_404(site_id)- if err:- return err- start, end = report_service.parse_range(request.args)- return jsonify(report_service.overview(site_id, start, end)), 200---@analytics_bp.route('/sites/<int:site_id>/timeseries', methods=['GET'])-@viewer_required-def site_timeseries(site_id):- site, err = _site_or_404(site_id)- if err:- return err- start, end = report_service.parse_range(request.args)- return jsonify({'series': report_service.timeseries(site_id, start, end)}), 200---@analytics_bp.route('/sites/<int:site_id>/pages', methods=['GET'])-@viewer_required-def site_pages(site_id):- site, err = _site_or_404(site_id)- if err:- return err- start, end = report_service.parse_range(request.args)- return jsonify(report_service.pages(site_id, start, end)), 200---@analytics_bp.route('/sites/<int:site_id>/referrers', methods=['GET'])-@viewer_required-def site_referrers(site_id):- site, err = _site_or_404(site_id)- if err:- return err- start, end = report_service.parse_range(request.args)- return jsonify(report_service.referrers(site_id, start, end)), 200---@analytics_bp.route('/sites/<int:site_id>/devices', methods=['GET'])-@viewer_required-def site_devices(site_id):- site, err = _site_or_404(site_id)- if err:- return err- start, end = report_service.parse_range(request.args)- return jsonify(report_service.devices(site_id, start, end)), 200---@analytics_bp.route('/sites/<int:site_id>/realtime', methods=['GET'])-@viewer_required-def site_realtime(site_id):- site, err = _site_or_404(site_id)- if err:- return err- minutes = request.args.get('minutes', 30)- return jsonify(report_service.realtime(site_id, minutes)), 200---@analytics_bp.route('/rollup', methods=['POST'])-@admin_required-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)), 200---@analytics_bp.route('/sites/<int:site_id>/ingest-logs', methods=['POST'])-@admin_required-def ingest_logs(site_id):- """Run server-log ingestion for one site on demand (ops/testing)."""- site, err = _site_or_404(site_id)- if err:- return err- return jsonify(log_ingest_service.ingest_site(site)), 200diff --git a/builtin-extensions/serverkit-analytics/backend/config.py b/builtin-extensions/serverkit-analytics/backend/config.pydeleted file mode 100644index ed76ac1b..00000000--- a/builtin-extensions/serverkit-analytics/backend/config.py+++ /dev/null@@ -1,74 +0,0 @@-"""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/geo.py b/builtin-extensions/serverkit-analytics/backend/geo.pydeleted file mode 100644index 8889aed6..00000000--- a/builtin-extensions/serverkit-analytics/backend/geo.py+++ /dev/null@@ -1,69 +0,0 @@-"""Optional country-level geolocation for serverkit-analytics.--Off by default. When the operator enables ``geo_enabled`` AND drops a-GeoLite2-Country MMDB at ``geo_db_path``, we fill a 2-letter country code from-the client IP. No database ships with the panel (licensing), and no IP is ever-stored — only the derived country. Any failure (feature off, no DB, no-``geoip2`` package, private IP) yields ``None`` and the country column stays-null.-"""-import logging--logger = logging.getLogger(__name__)--# Cache one reader per DB path so we don't reopen the MMDB on every hit.-_readers = {}-_unavailable = set()---def _reader(path):- if path in _unavailable:- return None- reader = _readers.get(path)- if reader is not None:- return reader- try:- import geoip2.database # noqa: PLC0415 - optional dependency- reader = geoip2.database.Reader(path)- _readers[path] = reader- return reader- except Exception as e: # noqa: BLE001 - missing package / bad file- logger.debug('geoip2 reader unavailable for %s: %s', path, e)- _unavailable.add(path)- return None---def lookup_country(ip):- """Return an ISO-3166-1 alpha-2 country code for ``ip``, or ``None``."""- if not ip:- return None- try:- from .config import cfg_bool, cfg_str- if not cfg_bool('geo_enabled'):- return None- path = cfg_str('geo_db_path')- if not path:- return None- import os- if not os.path.exists(path):- return None- reader = _reader(path)- if reader is None:- return None- resp = reader.country(ip)- code = getattr(getattr(resp, 'country', None), 'iso_code', None)- return code or None- except Exception as e: # noqa: BLE001 - private/unknown IP, lookup miss- logger.debug('geo lookup miss for %s: %s', ip, e)- return None---def reset():- """Test/shutdown helper — drop cached readers."""- for reader in _readers.values():- try:- reader.close()- except Exception: # noqa: BLE001- pass- _readers.clear()- _unavailable.clear()diff --git a/builtin-extensions/serverkit-analytics/backend/ingest_service.py b/builtin-extensions/serverkit-analytics/backend/ingest_service.pydeleted file mode 100644index e1b70c2d..00000000--- a/builtin-extensions/serverkit-analytics/backend/ingest_service.py+++ /dev/null@@ -1,366 +0,0 @@-"""Ingestion for the serverkit-analytics collector.--The public ``POST /collect`` route is a thin wrapper; the real work lives here:--* **Visitor hashing** — cookieless identity is ``HMAC(daily_salt, site|ip|ua)``.- The salt is generated in-process, rotates at UTC midnight, and is NEVER- persisted. Raw IPs and UAs are hashed and discarded; only the digest is- stored. A panel restart mid-day rotates the salt early (a documented,- acceptable cookieless imprecision).-* **Bot filtering** — UA denylist + empty-UA rejection for JS-source hits.-* **Rate limiting** — an in-process token bucket per site_key and per client IP- (single-worker safe, same constraint as the login throttle and the api- self-telemetry buffer).-* **Buffering** — events accumulate in an in-memory buffer and a daemon thread- batch-inserts them every ``buffer_flush_seconds`` (or early at ``buffer_max``),- mirroring ``app/middleware/api_analytics.py``. Under TESTING the thread is not- started; tests call :func:`flush_buffer` directly.--Client IP always comes from the plan-48 trusted-proxy helper-(``app.utils.client_ip.get_client_ip``), never ``request.remote_addr`` raw, so a-reverse proxy doesn't turn every visitor into the nginx box.-"""-import hashlib-import hmac-import logging-import re-import secrets-import threading-import time-from datetime import datetime, timezone-from urllib.parse import urlsplit--from .config import cfg_bool, cfg_int--logger = logging.getLogger(__name__)--# Hard body cap for a collect payload (bytes). Larger => 413.-MAX_BODY_BYTES = 8192--# --------------------------------------------------------------------------- #-# Daily-rotating salt (in-memory, never persisted)-# --------------------------------------------------------------------------- #-_salt_lock = threading.Lock()-_salt_day = None # 'YYYY-MM-DD' (UTC) the current salt belongs to-_salt_value = None # bytes---def _today_utc():- return datetime.now(timezone.utc).strftime('%Y-%m-%d')---def _current_salt():- """Return today's salt, rotating (and discarding yesterday's) on day change."""- global _salt_day, _salt_value- day = _today_utc()- with _salt_lock:- if _salt_day != day or _salt_value is None:- _salt_day = day- _salt_value = secrets.token_bytes(32)- return _salt_value---def visitor_hash(site_id, ip, ua):- """Cookieless visitor id: HMAC(daily_salt, site|ip|ua), hex-truncated to 32."""- msg = f'{site_id}|{ip or ""}|{ua or ""}'.encode('utf-8', 'ignore')- digest = hmac.new(_current_salt(), msg, hashlib.sha256).hexdigest()- return digest[:32]---# --------------------------------------------------------------------------- #-# Bot filtering + lightweight UA parsing (no heavy dependency)-# --------------------------------------------------------------------------- #-_BOT_RE = re.compile(- r'(bot|crawl|spider|slurp|curl|wget|python-requests|python-urllib|'- r'httpclient|headless|phantomjs|puppeteer|playwright|scrapy|libwww|'- r'go-http-client|okhttp|axios|node-fetch|facebookexternalhit|'- r'pingdom|uptimerobot|monitor|semrush|ahrefs|mj12bot|dotbot)',- re.IGNORECASE,-)--_OS_PATTERNS = [- ('Windows', re.compile(r'Windows NT', re.I)),- ('iOS', re.compile(r'iPhone|iPad|iPod', re.I)),- ('Android', re.compile(r'Android', re.I)),- ('macOS', re.compile(r'Mac OS X|Macintosh', re.I)),- ('Linux', re.compile(r'Linux', re.I)),- ('Chrome OS', re.compile(r'CrOS', re.I)),-]-# Order matters: Edge/OPR/Samsung before Chrome, Chrome before Safari.-_BROWSER_PATTERNS = [- ('Edge', re.compile(r'Edg[/A ]', re.I)),- ('Opera', re.compile(r'OPR/|Opera', re.I)),- ('Samsung Internet', re.compile(r'SamsungBrowser', re.I)),- ('Firefox', re.compile(r'Firefox/', re.I)),- ('Chrome', re.compile(r'Chrome/|CriOS', re.I)),- ('Safari', re.compile(r'Safari/', re.I)),-]-_MOBILE_RE = re.compile(r'Mobile|iPhone|Android.*Mobile', re.I)-_TABLET_RE = re.compile(r'iPad|Tablet|Android(?!.*Mobile)', re.I)---def is_bot(ua):- """True for known bot/automation user agents."""- if not ua:- return False # emptiness handled separately (js-source empty UA rejected)- return bool(_BOT_RE.search(ua))---def parse_ua(ua):- """Return (browser_family, os_family, device_class) from a UA string.-- Deliberately tiny and heuristic — v1 accepts imperfection (no ua-parser- dependency). Bots are classed device='bot'.- """- if not ua:- return (None, None, None)- if is_bot(ua):- return ('Bot', None, 'bot')- browser = next((name for name, rx in _BROWSER_PATTERNS if rx.search(ua)), 'Other')- os_family = next((name for name, rx in _OS_PATTERNS if rx.search(ua)), 'Other')- if _TABLET_RE.search(ua):- device = 'tablet'- elif _MOBILE_RE.search(ua):- device = 'mobile'- else:- device = 'desktop'- return (browser, os_family, device)---# --------------------------------------------------------------------------- #-# In-process token-bucket rate limiter (per site_key + per IP)-# --------------------------------------------------------------------------- #-_rl_lock = threading.Lock()-_rl_buckets = {} # key -> [tokens, last_refill_epoch]-_rl_last_sweep = 0.0---def _sweep_buckets(now):- """Drop idle buckets so the map can't grow unbounded."""- global _rl_last_sweep- if now - _rl_last_sweep < 300:- return- _rl_last_sweep = now- stale = [k for k, (_, last) in _rl_buckets.items() if now - last > 600]- for k in stale:- _rl_buckets.pop(k, None)---def _allow_one(key, rate_per_min, now):- """Token bucket: capacity == rate_per_min, refill rate == rate/60 per sec."""- capacity = float(rate_per_min)- refill = capacity / 60.0- tokens, last = _rl_buckets.get(key, (capacity, now))- tokens = min(capacity, tokens + (now - last) * refill)- if tokens < 1.0:- _rl_buckets[key] = (tokens, now)- return False- _rl_buckets[key] = (tokens - 1.0, now)- return True---def rate_ok(site_key, ip):- """Return True if this hit is under the per-key AND per-IP limits."""- rate = cfg_int('collect_rate_per_min', minimum=1)- now = time.monotonic()- with _rl_lock:- _sweep_buckets(now)- ok_key = _allow_one(f'k:{site_key}', rate, now)- ok_ip = _allow_one(f'i:{ip or "?"}', rate, now)- return ok_key and ok_ip---def reset_rate_limits():- """Test/shutdown helper."""- with _rl_lock:- _rl_buckets.clear()---# --------------------------------------------------------------------------- #-# Buffer + flush-# --------------------------------------------------------------------------- #-_buffer = []-_buffer_lock = threading.Lock()-_flush_started = False-_flush_lock = threading.Lock()-# Safety cap so a stalled flusher can't OOM the process on a traffic spike.-_HARD_BUFFER_CAP = 50000---def buffer_size():- with _buffer_lock:- return len(_buffer)---def reset_buffer():- """Test/shutdown helper — drop any un-flushed events."""- with _buffer_lock:- _buffer.clear()---def record_event(entry):- """Append a built event dict to the in-memory buffer (drops oldest on- overflow so memory stays bounded)."""- with _buffer_lock:- _buffer.append(entry)- if len(_buffer) > _HARD_BUFFER_CAP:- drop = len(_buffer) - _HARD_BUFFER_CAP- del _buffer[:drop]- logger.warning('analytics buffer overflow; dropped %s oldest events', drop)---def flush_buffer(app):- """Batch-insert buffered events. Returns the number written. Best-effort."""- with _buffer_lock:- if not _buffer:- return 0- entries = _buffer[:]- _buffer.clear()- from app import db- from .models import AnalyticsEvent- written = 0- try:- with app.app_context():- for entry in entries:- db.session.add(AnalyticsEvent(**entry))- written += 1- db.session.commit()- except Exception as e: # noqa: BLE001- logger.warning('analytics flush failed (%s events lost): %s', len(entries), e)- try:- db.session.rollback()- except Exception: # noqa: BLE001- pass- return 0- return written---def _flush_loop(app):- """Daemon loop: flush on the configured interval OR early at buffer_max."""- elapsed = 0- while True:- time.sleep(1)- elapsed += 1- interval = cfg_int('buffer_flush_seconds', minimum=1, maximum=3600)- maxsize = cfg_int('buffer_max', minimum=1)- if elapsed >= interval or buffer_size() >= maxsize:- elapsed = 0- try:- flush_buffer(app)- except Exception as e: # noqa: BLE001- logger.warning('analytics flush loop error: %s', e)---def ensure_flush_thread(app):- """Start the background flush thread once (skipped under TESTING — tests- flush synchronously)."""- global _flush_started- if app.config.get('TESTING') or app.config.get('ENV') == 'testing':- return- with _flush_lock:- if _flush_started:- return- t = threading.Thread(target=_flush_loop, args=(app,),- daemon=True, name='analytics-flush')- t.start()- _flush_started = True---# --------------------------------------------------------------------------- #-# Payload validation + event build-# --------------------------------------------------------------------------- #-_VALID_TYPES = {'pageview', 'event', 'outlink', 'download'}-_SCREEN_CLASSES = {'xs', 'sm', 'md', 'lg', 'xl'}---def _clean_path(raw):- """Normalize a URL path: strip origin, cap length, default '/'."""- if not raw:- return '/'- raw = str(raw)- # Accept a full URL or a bare path; keep only the path component.- if '://' in raw:- raw = urlsplit(raw).path or '/'- raw = raw.split('#', 1)[0]- if not raw.startswith('/'):- raw = '/' + raw- return raw[:512]---def referrer_host(raw):- """Extract a bare host from a referrer URL (None if same-page/empty)."""- if not raw:- return None- try:- host = urlsplit(str(raw)).hostname- except ValueError:- return None- return host[:255] if host else None---def build_event(site, payload, ip, ua):- """Build a persisted-event dict from a validated collect payload.-- Returns ``None`` if the payload is unusable. Does NOT enforce bot/DNT/rate- policy — that's the collector route's job (so it can pick the right status).- """- etype = str(payload.get('t') or payload.get('type') or 'pageview').lower()- if etype not in _VALID_TYPES:- etype = 'event'-- raw_path = payload.get('p') if payload.get('p') is not None else payload.get('path')- path = _clean_path(raw_path)-- query = None- if cfg_bool('store_query_strings'):- q = payload.get('q') or payload.get('query')- if q:- query = str(q)[:512]- elif raw_path and '?' in str(raw_path):- query = str(raw_path).split('?', 1)[1][:512]-- browser, os_family, device = parse_ua(ua)-- screen = payload.get('s') or payload.get('screen')- screen = screen if screen in _SCREEN_CLASSES else None-- lang = payload.get('l') or payload.get('lang')- lang = str(lang)[:16] if lang else None-- load_ms = payload.get('ms') or payload.get('load_ms')- try:- load_ms = int(load_ms) if load_ms is not None else None- if load_ms is not None and (load_ms < 0 or load_ms > 3600000):- load_ms = None- except (TypeError, ValueError):- load_ms = None-- name = payload.get('n') or payload.get('name')- name = str(name)[:128] if name else None-- return {- 'site_id': site.id,- 'ts': datetime.utcnow(),- 'type': etype,- 'event_name': name,- 'url_path': path,- 'url_query': query,- 'referrer_host': referrer_host(payload.get('r') or payload.get('referrer')),- 'visitor_hash': visitor_hash(site.id, ip, ua),- 'ua_family': browser,- 'os_family': os_family,- 'device_class': device,- 'screen_class': screen,- 'lang': lang,- 'country': _country(ip), # None unless geo is enabled + a GeoLite2 DB is present- 'source': 'js',- 'load_ms': load_ms,- }---def _country(ip):- try:- from .geo import lookup_country- return lookup_country(ip)- except Exception: # noqa: BLE001- return Nonediff --git a/builtin-extensions/serverkit-analytics/backend/jobs.py b/builtin-extensions/serverkit-analytics/backend/jobs.pydeleted file mode 100644index 3ebf51d6..00000000--- a/builtin-extensions/serverkit-analytics/backend/jobs.py+++ /dev/null@@ -1,54 +0,0 @@-"""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.pydeleted file mode 100644index c89b4988..00000000--- a/builtin-extensions/serverkit-analytics/backend/lifecycle.py+++ /dev/null@@ -1,90 +0,0 @@-"""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/backend/log_ingest_service.py b/builtin-extensions/serverkit-analytics/backend/log_ingest_service.pydeleted file mode 100644index e6ad9670..00000000--- a/builtin-extensions/serverkit-analytics/backend/log_ingest_service.py+++ /dev/null@@ -1,252 +0,0 @@-"""Server-log ingestion for serverkit-analytics.--A complementary, script-free source: parse apache/nginx **combined** access logs-into the same event table as the JS tracker, tagged ``source='log'`` so JS-source-and log-source hits stay comparable. Generalizes the on-demand-``WpAnalyticsService.get_traffic`` parse into a persistent, incremental one.--Per-site opt-in via ``site.settings``:- log_ingestion : bool (enable)- log_source_kind : 'file' | 'docker'- log_source_ref : file path (file) or container name (docker)--Incrementality uses :class:`AnalyticsLogCursor`:-* file — (inode, byte_offset); a changed inode or shrunken file resets to 0- (rotation/truncation safe).-* docker — ``docker logs --since <last_ts>`` with a ts-based skip, since docker- logs has no byte offset.--Only page-like GET hits are counted (assets and non-GET are skipped) and bots-are dropped, mirroring the JS collector so the two sources line up. Visitor-hashing reuses the collector's daily salt; log lines older than today are hashed-with today's salt (a documented cookieless imprecision — tail runs every few-minutes, so this is the rare backfill case).--Linux-only at runtime (docker logs / access-log files); reading seams are-mockable for tests.-"""-import logging-import os-import re-import subprocess-from datetime import datetime--from .config import cfg_bool-from .ingest_service import is_bot, parse_ua, referrer_host, visitor_hash--logger = logging.getLogger(__name__)--# apache/nginx "combined" log format:-# %h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"-COMBINED_RE = re.compile(- r'(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] "(?P<request>[^"]*)" '- r'(?P<status>\d{3}) (?P<bytes>\S+) "(?P<referer>[^"]*)" "(?P<ua>[^"]*)"'-)-_TIME_FMT = '%d/%b/%Y:%H:%M:%S %z'--# Skip static assets so log hits approximate real pageviews.-_ASSET_RE = re.compile(- r'\.(?:css|js|mjs|png|jpe?g|gif|svg|webp|ico|bmp|woff2?|ttf|eot|otf|map|'- r'json|xml|txt|mp4|webm|mp3|wav|pdf|zip|gz)(?:$|\?)', re.IGNORECASE)--# Cap lines processed per source per run so a huge backlog can't stall a job.-MAX_LINES_PER_RUN = 20000---def parse_combined_line(line):- """Parse one combined-log line into a dict, or ``None`` if it doesn't match- or isn't a page-like GET."""- m = COMBINED_RE.match(line.strip())- if not m:- return None- request = m.group('request') or ''- parts = request.split()- if len(parts) < 2 or parts[0].upper() != 'GET':- return None- path = parts[1].split('#', 1)[0]- if _ASSET_RE.search(path):- return None- try:- ts = datetime.strptime(m.group('time'), _TIME_FMT)- ts = ts.replace(tzinfo=None) - _utc_offset(ts)- except (ValueError, TypeError):- ts = datetime.utcnow()- referer = m.group('referer')- return {- 'ip': m.group('ip'),- 'ts': ts,- 'path': path.split('?', 1)[0][:512],- 'status': m.group('status'),- 'referer': None if referer in ('', '-') else referer,- 'ua': m.group('ua') or '',- }---def _utc_offset(dt):- from datetime import timedelta- off = dt.utcoffset()- return off if off is not None else timedelta(0)---def build_log_event(site, parsed):- """Build a persisted-event dict from a parsed log line (source='log')."""- ua = parsed['ua']- if not ua or is_bot(ua):- return None- browser, os_family, device = parse_ua(ua)- country = None- try:- from .geo import lookup_country- country = lookup_country(parsed['ip'])- except Exception: # noqa: BLE001- country = None- return {- 'site_id': site.id,- 'ts': parsed['ts'],- 'type': 'pageview',- 'event_name': None,- 'url_path': parsed['path'],- 'url_query': None,- 'referrer_host': referrer_host(parsed['referer']),- 'visitor_hash': visitor_hash(site.id, parsed['ip'], ua),- 'ua_family': browser,- 'os_family': os_family,- 'device_class': device,- 'screen_class': None,- 'lang': None,- 'country': country,- 'source': 'log',- 'load_ms': None,- }---def ingest_lines(site, lines, since_ts=None):- """Parse + persist log lines for a site. Returns (written, max_ts)."""- from app import db- from .models import AnalyticsEvent- written = 0- max_ts = since_ts- for line in lines[:MAX_LINES_PER_RUN]:- parsed = parse_combined_line(line)- if not parsed:- continue- if since_ts and parsed['ts'] <= since_ts:- continue # already ingested (docker --since boundary)- event = build_log_event(site, parsed)- if not event:- continue- db.session.add(AnalyticsEvent(**event))- written += 1- if max_ts is None or parsed['ts'] > max_ts:- max_ts = parsed['ts']- if written:- db.session.commit()- return written, max_ts---# --------------------------------------------------------------------------- #-# source readers (mockable)-# --------------------------------------------------------------------------- #-def _read_file_lines(cursor, path):- """Return new lines from a file, advancing the (inode, byte_offset) cursor."""- try:- st = os.stat(path)- except OSError:- return []- inode = str(getattr(st, 'st_ino', '') or '')- offset = cursor.byte_offset or 0- if cursor.inode and inode and cursor.inode != inode:- offset = 0 # rotated- if offset > st.st_size:- offset = 0 # truncated- try:- with open(path, 'rb') as f:- f.seek(offset)- data = f.read()- new_offset = f.tell()- except OSError:- return []- cursor.inode = inode- cursor.byte_offset = new_offset- return data.decode('utf-8', 'ignore').splitlines()---def _read_docker_lines(cursor, container):- """Return recent access-log lines from a container's stdout."""- args = ['docker', 'logs']- if cursor.last_ts:- args += ['--since', cursor.last_ts.strftime('%Y-%m-%dT%H:%M:%S')]- else:- args += ['--tail', '2000']- args.append(container)- try:- result = subprocess.run(args, capture_output=True, text=True, timeout=25)- except Exception as e: # noqa: BLE001- logger.debug('docker logs failed for %s: %s', container, e)- return []- return (result.stdout or '').splitlines()---# --------------------------------------------------------------------------- #-# orchestration-# --------------------------------------------------------------------------- #-def _get_cursor(site_id, source_ref, source_kind):- from app import db- from .models import AnalyticsLogCursor- cur = AnalyticsLogCursor.query.filter_by(- site_id=site_id, source_ref=source_ref).first()- if not cur:- cur = AnalyticsLogCursor(site_id=site_id, source_ref=source_ref,- source_kind=source_kind, byte_offset=0)- db.session.add(cur)- db.session.commit()- return cur---def ingest_site(site):- """Ingest new log lines for one site. Returns a status dict."""- settings = site.get_settings()- if not settings.get('log_ingestion'):- return {'skipped': True, 'reason': 'log ingestion off for site'}- kind = settings.get('log_source_kind') or 'docker'- ref = settings.get('log_source_ref')- if not ref:- return {'skipped': True, 'reason': 'no log source configured'}-- cursor = _get_cursor(site.id, ref, kind)- if kind == 'file':- # File dedup is by byte offset, so DON'T also filter by ts (that would- # drop same-second appends that the offset already advanced past).- lines = _read_file_lines(cursor, ref)- since = None- else:- # docker logs --since re-reads the boundary second; ts-filter dedups it.- lines = _read_docker_lines(cursor, ref)- since = cursor.last_ts-- written, max_ts = ingest_lines(site, lines, since_ts=since)- if max_ts:- cursor.last_ts = max_ts- from app import db- cursor.updated_at = datetime.utcnow()- db.session.commit()- return {'site_id': site.id, 'written': written, 'lines': len(lines)}---def run_log_tail():- """Ingest logs for every opted-in site (called by the scheduled job)."""- if not cfg_bool('log_ingestion_enabled'):- return {'skipped': True, 'reason': 'log ingestion globally disabled'}- from .models import AnalyticsSite- total = 0- sites = 0- for site in AnalyticsSite.query.filter_by(enabled=True).all():- if not site.get_settings().get('log_ingestion'):- continue- try:- res = ingest_site(site)- total += res.get('written', 0)- sites += 1- except Exception as e: # noqa: BLE001- logger.warning('log ingest failed for site %s: %s', site.id, e)- return {'sites': sites, 'written': total}diff --git a/builtin-extensions/serverkit-analytics/backend/models.py b/builtin-extensions/serverkit-analytics/backend/models.pydeleted file mode 100644index e2aeb541..00000000--- a/builtin-extensions/serverkit-analytics/backend/models.py+++ /dev/null@@ -1,242 +0,0 @@-"""Data models for the serverkit-analytics (Web Analytics) extension.--Four tables, all namespaced ``ext_serverkit_analytics_*`` (dash -> underscore)-so ``--purge`` on uninstall drops exactly these:--* :class:`AnalyticsSite` — a tracked site: name, hostnames, the public- ``site_key`` baked into the tracker snippet (NOT a JWT), per-site settings.-* :class:`AnalyticsEvent` — raw, append-only pageview/event rows (short- retention). Visitor identity is a daily-rotating salted hash; raw IP/UA are- never stored.-* :class:`AnalyticsDaily` — the rollup time series (long retention), one row- per (site, date, dimension, value).-* :class:`AnalyticsLogCursor` — per-site incremental server-log offsets so log- ingestion is restart-safe.--Registration mirrors the serverkit-tramo / serverkit-k8s pattern: importing this-module defines the tables on the shared metadata as a side effect; the manifest's-``models: "models:register"`` then calls :func:`register` (a passthrough) and the-platform runs ``db.create_all()``.-"""-import json-import secrets-from datetime import datetime--from app import db---def generate_site_key():- """A URL-safe public token embedded in the tracker snippet (not a secret in- the JWT sense — it only names a site; abuse is handled by rate limits + bot- filtering + origin allowlist)."""- return secrets.token_urlsafe(16)---class AnalyticsSite(db.Model):- __tablename__ = 'ext_serverkit_analytics_sites'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), nullable=False)- # Newline/comma-normalized list of hostnames this site serves.- hostnames = db.Column(db.Text, nullable=True)- # Public, URL-safe token baked into the snippet. Unique + indexed for the- # collector's hot-path lookup.- site_key = db.Column(db.String(64), unique=True, nullable=False, index=True,- default=generate_site_key)-- # manual | wordpress | template | nginx- created_from = db.Column(db.String(32), nullable=False, default='manual')- # Optional link to a managed app/site id (WordPress site id, service id, ...).- app_id = db.Column(db.Integer, nullable=True, index=True)-- # Per-site override of the global honor_dnt config. NULL = inherit global.- honor_dnt = db.Column(db.Boolean, nullable=True)- # Comma/newline list of allowed origins. Empty/NULL = reflect the request- # origin after the site_key check (the default per the plan).- allowed_origins = db.Column(db.Text, nullable=True)-- enabled = db.Column(db.Boolean, nullable=False, default=True)- # Extensible per-site flags as JSON: wp_injected, nginx_injected,- # log_ingestion, log_source_kind, log_source_ref, container_name, vhost_path…- settings = db.Column(db.Text, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- # ---- helpers ----- def get_settings(self):- if not self.settings:- return {}- try:- return json.loads(self.settings)- except (ValueError, TypeError):- return {}-- def set_settings(self, value):- self.settings = json.dumps(value or {})-- def update_settings(self, **changes):- cur = self.get_settings()- cur.update(changes)- self.set_settings(cur)-- def hostname_list(self):- return _split_list(self.hostnames)-- def allowed_origin_list(self):- return _split_list(self.allowed_origins)-- def to_dict(self, include_key=True):- out = {- 'id': self.id,- 'name': self.name,- 'hostnames': self.hostname_list(),- 'created_from': self.created_from,- 'app_id': self.app_id,- 'honor_dnt': self.honor_dnt,- 'allowed_origins': self.allowed_origin_list(),- 'enabled': self.enabled,- 'settings': self.get_settings(),- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }- if include_key:- out['site_key'] = self.site_key- return out---class AnalyticsEvent(db.Model):- __tablename__ = 'ext_serverkit_analytics_events'-- id = db.Column(db.Integer, primary_key=True)- site_id = db.Column(db.Integer, nullable=False, index=True)- ts = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, index=True)-- # pageview | event | outlink | download- type = db.Column(db.String(16), nullable=False, default='pageview')- event_name = db.Column(db.String(128), nullable=True)-- url_path = db.Column(db.String(512), nullable=True)- url_query = db.Column(db.String(512), nullable=True) # only if store_query_strings- referrer_host = db.Column(db.String(255), nullable=True)-- # HMAC(daily_salt, site_id|ip|ua) — the cookieless visitor id. Never a raw IP.- visitor_hash = db.Column(db.String(64), nullable=True, index=True)-- ua_family = db.Column(db.String(64), nullable=True)- os_family = db.Column(db.String(64), nullable=True)- device_class = db.Column(db.String(16), nullable=True) # desktop|mobile|tablet|bot- screen_class = db.Column(db.String(16), nullable=True) # xs|sm|md|lg|xl- lang = db.Column(db.String(16), nullable=True)- country = db.Column(db.String(2), nullable=True) # ISO-3166-1 alpha-2, optional-- source = db.Column(db.String(8), nullable=False, default='js') # js | log- load_ms = db.Column(db.Integer, nullable=True)-- __table_args__ = (- db.Index('ix_ext_analytics_event_site_ts', 'site_id', 'ts'),- )-- def to_dict(self):- return {- 'id': self.id,- 'site_id': self.site_id,- 'ts': self.ts.isoformat() if self.ts else None,- 'type': self.type,- 'event_name': self.event_name,- 'url_path': self.url_path,- 'referrer_host': self.referrer_host,- 'ua_family': self.ua_family,- 'os_family': self.os_family,- 'device_class': self.device_class,- 'country': self.country,- 'source': self.source,- 'load_ms': self.load_ms,- }---class AnalyticsDaily(db.Model):- __tablename__ = 'ext_serverkit_analytics_daily'-- id = db.Column(db.Integer, primary_key=True)- site_id = db.Column(db.Integer, nullable=False, index=True)- date = db.Column(db.Date, nullable=False, index=True)-- # overall | page | referrer | device | browser | os | country- dim_type = db.Column(db.String(16), nullable=False)- dim_value = db.Column(db.String(512), nullable=False, default='')-- visitors = db.Column(db.Integer, nullable=False, default=0)- visits = db.Column(db.Integer, nullable=False, default=0)- pageviews = db.Column(db.Integer, nullable=False, default=0)- bounces = db.Column(db.Integer, nullable=False, default=0)- avg_load_ms = db.Column(db.Float, nullable=True)-- __table_args__ = (- db.UniqueConstraint('site_id', 'date', 'dim_type', 'dim_value',- name='uq_ext_analytics_daily_dim'),- )-- def to_dict(self):- return {- 'id': self.id,- 'site_id': self.site_id,- 'date': self.date.isoformat() if self.date else None,- 'dim_type': self.dim_type,- 'dim_value': self.dim_value,- 'visitors': self.visitors,- 'visits': self.visits,- 'pageviews': self.pageviews,- 'bounces': self.bounces,- 'avg_load_ms': self.avg_load_ms,- }---class AnalyticsLogCursor(db.Model):- __tablename__ = 'ext_serverkit_analytics_log_cursors'-- id = db.Column(db.Integer, primary_key=True)- site_id = db.Column(db.Integer, nullable=False, index=True)- source_kind = db.Column(db.String(16), nullable=False, default='docker') # docker|file- source_ref = db.Column(db.String(512), nullable=False) # container name or file path- inode = db.Column(db.String(64), nullable=True)- byte_offset = db.Column(db.BigInteger, nullable=False, default=0)- last_ts = db.Column(db.DateTime, nullable=True)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- __table_args__ = (- db.UniqueConstraint('site_id', 'source_ref',- name='uq_ext_analytics_log_cursor'),- )-- def to_dict(self):- return {- 'id': self.id,- 'site_id': self.site_id,- 'source_kind': self.source_kind,- 'source_ref': self.source_ref,- 'byte_offset': self.byte_offset,- 'last_ts': self.last_ts.isoformat() if self.last_ts else None,- }---def _split_list(text):- """Split a comma/newline/whitespace-separated string into a clean list."""- if not text:- return []- parts = []- for chunk in str(text).replace('\r', '\n').replace(',', '\n').split('\n'):- item = chunk.strip()- if item:- parts.append(item)- return parts---def register(db): # noqa: A002 - signature dictated by the platform (fn(db))- """Passthrough required by the manifest ``models: "models:register"``.-- Importing this module already defined the tables on ``db.metadata``; the- platform runs ``db.create_all()``. Returning the classes is convenient for- tests.- """- return [AnalyticsSite, AnalyticsEvent, AnalyticsDaily, AnalyticsLogCursor]diff --git a/builtin-extensions/serverkit-analytics/backend/nginx_integration.py b/builtin-extensions/serverkit-analytics/backend/nginx_integration.pydeleted file mode 100644index e3ccfed3..00000000--- a/builtin-extensions/serverkit-analytics/backend/nginx_integration.py+++ /dev/null@@ -1,207 +0,0 @@-"""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/report_service.py b/builtin-extensions/serverkit-analytics/backend/report_service.pydeleted file mode 100644index 57b5e4f3..00000000--- a/builtin-extensions/serverkit-analytics/backend/report_service.py+++ /dev/null@@ -1,169 +0,0 @@-"""Read-side report queries for the serverkit-analytics dashboard.--Everything the dashboard renders comes from the ``daily`` rollup table (fast,-long-retention) EXCEPT the realtime tab, which reads the raw ``event`` table for-the last N minutes.--Range caveat (documented in docs/ANALYTICS.md): "unique visitors" over a-multi-day range is the SUM of each day's uniques — a visitor active on two days-counts twice. This is inherent to daily rollups and, combined with cookieless-hashing, means visitor counts are close approximations, not exact identities.-Pageviews sum exactly.-"""-from datetime import date, datetime, timedelta--_RANGE_DAYS = {'1d': 1, '7d': 7, '14d': 14, '30d': 30, '90d': 90, '180d': 180,- '365d': 365, '12mo': 365, '13mo': 396}---def parse_range(args):- """Resolve (start_date, end_date) from query args.-- Accepts ``?range=7d`` (default 7d) or explicit ``?start=YYYY-MM-DD&- end=YYYY-MM-DD``. End defaults to today (UTC), inclusive.- """- today = datetime.utcnow().date()- start_raw = (args.get('start') or '').strip()- end_raw = (args.get('end') or '').strip()- if start_raw:- try:- start = datetime.strptime(start_raw[:10], '%Y-%m-%d').date()- end = (datetime.strptime(end_raw[:10], '%Y-%m-%d').date()- if end_raw else today)- if end < start:- start, end = end, start- return start, end- except ValueError:- pass- days = _RANGE_DAYS.get((args.get('range') or '7d').strip(), 7)- return today - timedelta(days=days - 1), today---def _overall_query(site_id, start, end):- from .models import AnalyticsDaily- return (AnalyticsDaily.query- .filter(AnalyticsDaily.site_id == site_id,- AnalyticsDaily.dim_type == 'overall',- AnalyticsDaily.date >= start,- AnalyticsDaily.date <= end))---def _totals(site_id, start, end):- from app import db- from sqlalchemy import func- from .models import AnalyticsDaily- row = (db.session.query(- func.coalesce(func.sum(AnalyticsDaily.visitors), 0),- func.coalesce(func.sum(AnalyticsDaily.pageviews), 0),- func.coalesce(func.sum(AnalyticsDaily.bounces), 0),- func.avg(AnalyticsDaily.avg_load_ms),- ).filter(AnalyticsDaily.site_id == site_id,- AnalyticsDaily.dim_type == 'overall',- AnalyticsDaily.date >= start,- AnalyticsDaily.date <= end).one())- visitors, pageviews, bounces, avg_load = row- bounce_rate = round(100.0 * bounces / visitors, 1) if visitors else 0.0- return {- 'visitors': int(visitors or 0),- 'pageviews': int(pageviews or 0),- 'bounces': int(bounces or 0),- 'bounce_rate': bounce_rate,- 'avg_load_ms': round(avg_load, 1) if avg_load is not None else None,- }---def timeseries(site_id, start, end):- """Per-day visitors + pageviews across the range, zero-filled."""- rows = {r.date: r for r in _overall_query(site_id, start, end).all()}- out = []- d = start- while d <= end:- r = rows.get(d)- out.append({- 'date': d.isoformat(),- 'visitors': r.visitors if r else 0,- 'pageviews': r.pageviews if r else 0,- })- d += timedelta(days=1)- return out---def _dim_table(site_id, start, end, dim_type, limit=None):- from app import db- from sqlalchemy import func- from .models import AnalyticsDaily- q = (db.session.query(- AnalyticsDaily.dim_value,- func.sum(AnalyticsDaily.visitors).label('visitors'),- func.sum(AnalyticsDaily.pageviews).label('pageviews'),- func.avg(AnalyticsDaily.avg_load_ms).label('avg_load'),- ).filter(AnalyticsDaily.site_id == site_id,- AnalyticsDaily.dim_type == dim_type,- AnalyticsDaily.date >= start,- AnalyticsDaily.date <= end)- .group_by(AnalyticsDaily.dim_value)- .order_by(func.sum(AnalyticsDaily.pageviews).desc()))- if limit:- q = q.limit(limit)- return [{- 'value': value or '',- 'visitors': int(visitors or 0),- 'pageviews': int(pageviews or 0),- 'avg_load_ms': round(avg_load, 1) if avg_load is not None else None,- } for value, visitors, pageviews, avg_load in q.all()]---def realtime(site_id, minutes=30):- """Live view from RAW events (last N minutes): active visitors, pageviews,- and the most recent hits."""- from .models import AnalyticsEvent- minutes = max(1, min(int(minutes or 30), 1440))- since = datetime.utcnow() - timedelta(minutes=minutes)- q = (AnalyticsEvent.query- .filter(AnalyticsEvent.site_id == site_id, AnalyticsEvent.ts >= since))- events = q.order_by(AnalyticsEvent.ts.desc()).limit(100).all()- active = {e.visitor_hash for e in q.all() if e.visitor_hash}- return {- 'minutes': minutes,- 'active_visitors': len(active),- 'pageviews': q.filter(AnalyticsEvent.type == 'pageview').count(),- 'recent': [{- 'ts': e.ts.isoformat() if e.ts else None,- 'path': e.url_path,- 'referrer_host': e.referrer_host,- 'device_class': e.device_class,- 'country': e.country,- } for e in events],- }---def overview(site_id, start, end):- """Headline KPIs + sparkline + top pages/referrers + a live counter."""- return {- 'range': {'start': start.isoformat(), 'end': end.isoformat()},- 'totals': _totals(site_id, start, end),- 'timeseries': timeseries(site_id, start, end),- 'top_pages': _dim_table(site_id, start, end, 'page', limit=8),- 'top_referrers': _dim_table(site_id, start, end, 'referrer', limit=8),- 'realtime': realtime(site_id, minutes=30),- }---def pages(site_id, start, end, limit=200):- return {'range': {'start': start.isoformat(), 'end': end.isoformat()},- 'rows': _dim_table(site_id, start, end, 'page', limit=limit)}---def referrers(site_id, start, end, limit=200):- return {'range': {'start': start.isoformat(), 'end': end.isoformat()},- 'rows': _dim_table(site_id, start, end, 'referrer', limit=limit)}---def devices(site_id, start, end):- return {- 'range': {'start': start.isoformat(), 'end': end.isoformat()},- 'device': _dim_table(site_id, start, end, 'device'),- 'browser': _dim_table(site_id, start, end, 'browser'),- 'os': _dim_table(site_id, start, end, 'os'),- 'country': _dim_table(site_id, start, end, 'country'),- }diff --git a/builtin-extensions/serverkit-analytics/backend/rollup_service.py b/builtin-extensions/serverkit-analytics/backend/rollup_service.pydeleted file mode 100644index 743dbb6a..00000000--- a/builtin-extensions/serverkit-analytics/backend/rollup_service.py+++ /dev/null@@ -1,151 +0,0 @@-"""Rollups + retention for serverkit-analytics.--* :func:`run_retention_prune` — drop raw ``event`` rows older than- ``raw_retention_days`` and ``daily`` rollups older than- ``rollup_retention_months``. Implemented in Phase 1 (operates on the event- table that exists from Phase 1; the daily table is pruned harmlessly while- empty until Phase 2 populates it).-* :func:`run_rollup` — aggregate raw events into the daily table. Implemented in- Phase 2.--Both are called by the scheduled jobs in ``jobs.py`` and must be safe to call-repeatedly (idempotent) and outside a request context (they open their own-session via the shared ``db``).-"""-import logging-from datetime import datetime, timedelta--logger = logging.getLogger(__name__)---def run_retention_prune():- """Delete raw events + rollups past their retention windows. Idempotent."""- from app import db- from .config import cfg_int- from .models import AnalyticsEvent, AnalyticsDaily-- raw_days = cfg_int('raw_retention_days', minimum=1, maximum=3650)- rollup_months = cfg_int('rollup_retention_months', minimum=1, maximum=120)-- event_cutoff = datetime.utcnow() - timedelta(days=raw_days)- daily_cutoff = (datetime.utcnow() - timedelta(days=rollup_months * 31)).date()-- deleted_events = (AnalyticsEvent.query- .filter(AnalyticsEvent.ts < event_cutoff)- .delete(synchronize_session=False))- deleted_daily = (AnalyticsDaily.query- .filter(AnalyticsDaily.date < daily_cutoff)- .delete(synchronize_session=False))- db.session.commit()-- return {- 'deleted_events': int(deleted_events or 0),- 'deleted_daily': int(deleted_daily or 0),- 'event_cutoff': event_cutoff.isoformat(),- 'daily_cutoff': daily_cutoff.isoformat(),- }---def _as_date(value):- """Normalize a grouped day value (SQLite returns a str, PG a date)."""- if isinstance(value, str):- return datetime.strptime(value[:10], '%Y-%m-%d').date()- if isinstance(value, datetime):- return value.date()- return value---# Dimension rollups: (dim_type, event column attribute, skip-null?).-_DIMENSIONS = [- ('page', 'url_path', False),- ('referrer', 'referrer_host', True),- ('device', 'device_class', False),- ('browser', 'ua_family', False),- ('os', 'os_family', False),- ('country', 'country', True),-]---def run_rollup():- """Aggregate raw pageview events into the ``daily`` rollup table.-- Idempotent and backfill-safe: recomputes every (site, date) that currently- has raw events (bounded by ``raw_retention_days``), deleting and re-inserting- that day's rollup rows. Aggregation runs DB-side (grouped queries) so only- summary rows — not raw events — reach Python; on a very busy SQLite panel the- per-hour recompute is the documented pressure point (recommend PostgreSQL).-- Only ``type == 'pageview'`` events feed the rollup in v1; outlink/download/- custom events are stored but not summarized here.- """- from app import db- from sqlalchemy import distinct, func- from .models import AnalyticsDaily, AnalyticsEvent-- day = func.date(AnalyticsEvent.ts)- pageview = AnalyticsEvent.type == 'pageview'-- pairs = (db.session.query(AnalyticsEvent.site_id, day)- .filter(pageview).distinct().all())- date_set = {(sid, _as_date(d)) for sid, d in pairs}- if not date_set:- return {'sites_dates': 0, 'rows': 0}-- # Clear the days we're about to recompute (keeps late arrivals correct).- for sid, d in date_set:- AnalyticsDaily.query.filter_by(site_id=sid, date=d).delete(- synchronize_session=False)-- rows = 0-- # --- overall (per site+day) + bounce (single-pageview visitors) ---- overall = (db.session.query(- AnalyticsEvent.site_id, day.label('d'),- func.count(distinct(AnalyticsEvent.visitor_hash)).label('visitors'),- func.count().label('pageviews'),- func.avg(AnalyticsEvent.load_ms).label('avg_load'),- ).filter(pageview).group_by(AnalyticsEvent.site_id, day).all())-- per_visitor = (db.session.query(- AnalyticsEvent.site_id, day.label('d'), AnalyticsEvent.visitor_hash,- func.count().label('c'),- ).filter(pageview)- .group_by(AnalyticsEvent.site_id, day, AnalyticsEvent.visitor_hash)- .subquery())- bounce_rows = (db.session.query(- per_visitor.c.site_id, per_visitor.c.d, func.count().label('b'))- .filter(per_visitor.c.c == 1)- .group_by(per_visitor.c.site_id, per_visitor.c.d).all())- bounce_map = {(sid, _as_date(d)): b for sid, d, b in bounce_rows}-- for sid, d, visitors, pageviews, avg_load in overall:- dd = _as_date(d)- db.session.add(AnalyticsDaily(- site_id=sid, date=dd, dim_type='overall', dim_value='',- visitors=visitors or 0, visits=visitors or 0,- pageviews=pageviews or 0, bounces=bounce_map.get((sid, dd), 0),- avg_load_ms=avg_load))- rows += 1-- # --- dimension rollups ---- for dim_type, attr, skip_null in _DIMENSIONS:- col = getattr(AnalyticsEvent, attr)- q = db.session.query(- AnalyticsEvent.site_id, day.label('d'), col.label('v'),- func.count(distinct(AnalyticsEvent.visitor_hash)).label('visitors'),- func.count().label('pageviews'),- func.avg(AnalyticsEvent.load_ms).label('avg_load'),- ).filter(pageview)- if skip_null:- q = q.filter(col.isnot(None))- q = q.group_by(AnalyticsEvent.site_id, day, col)- for sid, d, value, visitors, pageviews, avg_load in q.all():- db.session.add(AnalyticsDaily(- site_id=sid, date=_as_date(d), dim_type=dim_type,- dim_value=(str(value) if value is not None else '')[:512],- visitors=visitors or 0, visits=visitors or 0,- pageviews=pageviews or 0, bounces=0, avg_load_ms=avg_load))- rows += 1-- db.session.commit()- return {'sites_dates': len(date_set), 'rows': rows}diff --git a/builtin-extensions/serverkit-analytics/backend/site_service.py b/builtin-extensions/serverkit-analytics/backend/site_service.pydeleted file mode 100644index f951e63f..00000000--- a/builtin-extensions/serverkit-analytics/backend/site_service.py+++ /dev/null@@ -1,105 +0,0 @@-"""Tracked-site CRUD for serverkit-analytics.--A ``site`` groups one or more hostnames under a public ``site_key`` (baked into-the tracker snippet). Mutations are admin-gated at the route layer; this module-is pure data logic and raises ``ValueError`` for bad input (routes translate to-400/404).-"""-from .models import AnalyticsSite, generate_site_key---def _normalize_hostnames(value):- """Accept a list or a comma/newline string; return a newline-joined string."""- if value is None:- return None- if isinstance(value, (list, tuple)):- items = [str(v).strip() for v in value if str(v).strip()]- else:- items = [c.strip() for c in str(value).replace(',', '\n').splitlines()- if c.strip()]- return '\n'.join(items) if items else None---def list_sites():- return [s.to_dict() for s in AnalyticsSite.query.order_by(AnalyticsSite.id).all()]---def get_site(site_id):- return AnalyticsSite.query.get(site_id)---def get_by_key(site_key):- return AnalyticsSite.query.filter_by(site_key=site_key).first()---def create_site(data):- from app import db- name = (data.get('name') or '').strip()- if not name:- raise ValueError('name is required')- site = AnalyticsSite(- name=name[:255],- hostnames=_normalize_hostnames(data.get('hostnames')),- site_key=generate_site_key(),- created_from=(data.get('created_from') or 'manual')[:32],- app_id=data.get('app_id'),- honor_dnt=data.get('honor_dnt'),- allowed_origins=_normalize_hostnames(data.get('allowed_origins')),- enabled=bool(data.get('enabled', True)),- )- if data.get('settings'):- site.set_settings(data.get('settings'))- db.session.add(site)- db.session.commit()- return site---def update_site(site_id, data):- from app import db- site = get_site(site_id)- if not site:- return None- if 'name' in data:- name = (data.get('name') or '').strip()- if not name:- raise ValueError('name cannot be blank')- site.name = name[:255]- if 'hostnames' in data:- site.hostnames = _normalize_hostnames(data.get('hostnames'))- if 'allowed_origins' in data:- site.allowed_origins = _normalize_hostnames(data.get('allowed_origins'))- if 'honor_dnt' in data:- site.honor_dnt = data.get('honor_dnt')- if 'enabled' in data:- site.enabled = bool(data.get('enabled'))- if 'app_id' in data:- site.app_id = data.get('app_id')- if 'settings' in data and isinstance(data.get('settings'), dict):- site.update_settings(**data['settings'])- db.session.commit()- return site---def rotate_key(site_id):- from app import db- site = get_site(site_id)- if not site:- return None- site.site_key = generate_site_key()- db.session.commit()- return site---def delete_site(site_id):- """Delete a site and all of its data (events, rollups, log cursors)."""- from app import db- from .models import AnalyticsEvent, AnalyticsDaily, AnalyticsLogCursor- site = get_site(site_id)- if not site:- return False- AnalyticsEvent.query.filter_by(site_id=site_id).delete(synchronize_session=False)- AnalyticsDaily.query.filter_by(site_id=site_id).delete(synchronize_session=False)- AnalyticsLogCursor.query.filter_by(site_id=site_id).delete(synchronize_session=False)- db.session.delete(site)- db.session.commit()- return Truediff --git a/builtin-extensions/serverkit-analytics/backend/tracker/sk.js b/builtin-extensions/serverkit-analytics/backend/tracker/sk.jsdeleted file mode 100644index 26d24580..00000000--- a/builtin-extensions/serverkit-analytics/backend/tracker/sk.js+++ /dev/null@@ -1,151 +0,0 @@-/* serverkit-analytics tracker (sk.js) — privacy-first, cookieless.- Source of truth. Build the served artifact with:- node scripts/build-analytics-tracker.mjs- which strips comments + trims whitespace into sk.min.js (served by the- backend at GET /api/v1/analytics/tracker.js).-- No cookies. No localStorage. No fingerprinting. No third-party calls.- Sends one small JSON beacon per pageview via navigator.sendBeacon (text/plain- so no CORS preflight), honoring Do Not Track. Fails silently on any error so a- disabled/removed panel never breaks the tracked site. */-(function () {- var d = document;- var s = d.currentScript;- if (!s) { return; }-- var siteKey = s.getAttribute('data-site-key');- if (!siteKey) { return; }-- /* Derive the collect endpoint from this script's own URL. */- var src = s.src || '';- var endpoint = src.replace(/tracker\.js(\?.*)?$/, 'collect');- if (endpoint === src) { return; }-- /* Opt-in behaviors via data-* attributes. */- var trackOutlinks = s.getAttribute('data-outlinks') === 'true';- var honorDnt = s.getAttribute('data-respect-dnt') !== 'false';-- function dntOn() {- var v = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;- return v === '1' || v === 'yes';- }- if (honorDnt && dntOn()) { return; }-- function screenClass() {- var w = window.innerWidth || d.documentElement.clientWidth || 0;- if (w < 576) { return 'xs'; }- if (w < 768) { return 'sm'; }- if (w < 992) { return 'md'; }- if (w < 1200) { return 'lg'; }- return 'xl';- }-- function externalReferrer() {- var r = d.referrer;- if (!r) { return ''; }- try {- var u = new URL(r);- if (u.host === location.host) { return ''; }- return r;- } catch (e) { return ''; }- }-- function loadMs() {- try {- var nav = performance.getEntriesByType('navigation')[0];- if (nav && nav.duration) { return Math.round(nav.duration); }- var t = performance.timing;- if (t && t.loadEventEnd && t.navigationStart) {- return Math.max(0, t.loadEventEnd - t.navigationStart);- }- } catch (e) { }- return null;- }-- function post(body) {- var payload = JSON.stringify(body);- try {- if (navigator.sendBeacon) {- var blob = new Blob([payload], { type: 'text/plain' });- if (navigator.sendBeacon(endpoint, blob)) { return; }- }- } catch (e) { }- try {- fetch(endpoint, {- method: 'POST', body: payload, keepalive: true,- headers: { 'Content-Type': 'text/plain' }, credentials: 'omit'- });- } catch (e) { }- }-- var firstView = true;- function send(type, extra) {- var body = {- k: siteKey,- t: type,- p: location.pathname,- r: externalReferrer(),- s: screenClass(),- l: (navigator.language || '').slice(0, 16)- };- if (type === 'pageview' && firstView) {- body.ms = loadMs();- firstView = false;- }- if (extra) {- for (var key in extra) {- if (Object.prototype.hasOwnProperty.call(extra, key)) {- body[key] = extra[key];- }- }- }- post(body);- }-- function pageview() { send('pageview'); }-- /* SPA navigations: patch history + listen for popstate; fire on path change. */- var lastPath = location.pathname;- function onNav() {- if (location.pathname !== lastPath) {- lastPath = location.pathname;- pageview();- }- }- function patch(name) {- var orig = history[name];- if (typeof orig !== 'function') { return; }- history[name] = function () {- var ret = orig.apply(this, arguments);- setTimeout(onNav, 0);- return ret;- };- }- patch('pushState');- patch('replaceState');- window.addEventListener('popstate', onNav);-- /* Optional outbound + download click tracking. */- var DOWNLOAD_RE = /\.(zip|rar|7z|gz|tar|pdf|docx?|xlsx?|pptx?|csv|dmg|exe|pkg|apk|mp3|mp4|mov|avi|iso)(\?|$)/i;- if (trackOutlinks) {- d.addEventListener('click', function (ev) {- var a = ev.target && ev.target.closest ? ev.target.closest('a') : null;- if (!a || !a.href) { return; }- try {- var u = new URL(a.href);- if (u.host !== location.host) {- send('outlink', { n: u.host });- } else if (DOWNLOAD_RE.test(u.pathname)) {- send('download', { n: u.pathname.slice(0, 128) });- }- } catch (e) { }- }, true);- }-- /* First pageview: wait for load so the timing metric is available. */- if (d.readyState === 'complete') {- pageview();- } else {- window.addEventListener('load', pageview);- }-})();diff --git a/builtin-extensions/serverkit-analytics/backend/tracker/sk.min.js b/builtin-extensions/serverkit-analytics/backend/tracker/sk.min.jsdeleted file mode 100644index f51f1d64..00000000--- a/builtin-extensions/serverkit-analytics/backend/tracker/sk.min.js+++ /dev/null@@ -1,123 +0,0 @@-(function () {-var d = document;-var s = d.currentScript;-if (!s) { return; }-var siteKey = s.getAttribute('data-site-key');-if (!siteKey) { return; }-var src = s.src || '';-var endpoint = src.replace(/tracker\.js(\?.*)?$/, 'collect');-if (endpoint === src) { return; }-var trackOutlinks = s.getAttribute('data-outlinks') === 'true';-var honorDnt = s.getAttribute('data-respect-dnt') !== 'false';-function dntOn() {-var v = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;-return v === '1' || v === 'yes';-}-if (honorDnt && dntOn()) { return; }-function screenClass() {-var w = window.innerWidth || d.documentElement.clientWidth || 0;-if (w < 576) { return 'xs'; }-if (w < 768) { return 'sm'; }-if (w < 992) { return 'md'; }-if (w < 1200) { return 'lg'; }-return 'xl';-}-function externalReferrer() {-var r = d.referrer;-if (!r) { return ''; }-try {-var u = new URL(r);-if (u.host === location.host) { return ''; }-return r;-} catch (e) { return ''; }-}-function loadMs() {-try {-var nav = performance.getEntriesByType('navigation')[0];-if (nav && nav.duration) { return Math.round(nav.duration); }-var t = performance.timing;-if (t && t.loadEventEnd && t.navigationStart) {-return Math.max(0, t.loadEventEnd - t.navigationStart);-}-} catch (e) { }-return null;-}-function post(body) {-var payload = JSON.stringify(body);-try {-if (navigator.sendBeacon) {-var blob = new Blob([payload], { type: 'text/plain' });-if (navigator.sendBeacon(endpoint, blob)) { return; }-}-} catch (e) { }-try {-fetch(endpoint, {-method: 'POST', body: payload, keepalive: true,-headers: { 'Content-Type': 'text/plain' }, credentials: 'omit'-});-} catch (e) { }-}-var firstView = true;-function send(type, extra) {-var body = {-k: siteKey,-t: type,-p: location.pathname,-r: externalReferrer(),-s: screenClass(),-l: (navigator.language || '').slice(0, 16)-};-if (type === 'pageview' && firstView) {-body.ms = loadMs();-firstView = false;-}-if (extra) {-for (var key in extra) {-if (Object.prototype.hasOwnProperty.call(extra, key)) {-body[key] = extra[key];-}-}-}-post(body);-}-function pageview() { send('pageview'); }-var lastPath = location.pathname;-function onNav() {-if (location.pathname !== lastPath) {-lastPath = location.pathname;-pageview();-}-}-function patch(name) {-var orig = history[name];-if (typeof orig !== 'function') { return; }-history[name] = function () {-var ret = orig.apply(this, arguments);-setTimeout(onNav, 0);-return ret;-};-}-patch('pushState');-patch('replaceState');-window.addEventListener('popstate', onNav);-var DOWNLOAD_RE = /\.(zip|rar|7z|gz|tar|pdf|docx?|xlsx?|pptx?|csv|dmg|exe|pkg|apk|mp3|mp4|mov|avi|iso)(\?|$)/i;-if (trackOutlinks) {-d.addEventListener('click', function (ev) {-var a = ev.target && ev.target.closest ? ev.target.closest('a') : null;-if (!a || !a.href) { return; }-try {-var u = new URL(a.href);-if (u.host !== location.host) {-send('outlink', { n: u.host });-} else if (DOWNLOAD_RE.test(u.pathname)) {-send('download', { n: u.pathname.slice(0, 128) });-}-} catch (e) { }-}, true);-}-if (d.readyState === 'complete') {-pageview();-} else {-window.addEventListener('load', pageview);-}-})();diff --git a/builtin-extensions/serverkit-analytics/backend/wp_integration.py b/builtin-extensions/serverkit-analytics/backend/wp_integration.pydeleted file mode 100644index 6f1dfcbd..00000000--- a/builtin-extensions/serverkit-analytics/backend/wp_integration.py+++ /dev/null@@ -1,191 +0,0 @@-"""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/builtin-extensions/serverkit-analytics/dev/test-tracker.html b/builtin-extensions/serverkit-analytics/dev/test-tracker.htmldeleted file mode 100644index 3b279865..00000000--- a/builtin-extensions/serverkit-analytics/dev/test-tracker.html+++ /dev/null@@ -1,72 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <title>serverkit-analytics tracker — manual test</title>- <style>- body { font: 15px/1.5 system-ui, sans-serif; max-width: 720px; margin: 40px auto; padding: 0 16px; }- fieldset { border: 1px solid #ccc; border-radius: 8px; margin: 16px 0; padding: 12px 16px; }- label { display: block; margin: 8px 0 4px; font-weight: 600; }- input { width: 100%; padding: 8px; box-sizing: border-box; }- button { padding: 8px 14px; margin: 6px 6px 0 0; cursor: pointer; }- code { background: #f4f4f4; padding: 1px 5px; border-radius: 4px; }- #log { white-space: pre-wrap; background: #111; color: #6f6; padding: 12px; border-radius: 8px; min-height: 80px; }- </style>-</head>-<body>- <h1>serverkit-analytics — tracker smoke test</h1>- <p>Loads <code>tracker.js</code> from a dev panel and lets you fire pageviews,- SPA navigations, and outbound/download clicks. Open the browser Network tab- to watch the beacons to <code>/api/v1/analytics/collect</code>.</p>-- <fieldset>- <label for="base">Panel base URL</label>- <input id="base" value="http://localhost:47927" />- <label for="key">Site key (from Sites tab / POST /sites)</label>- <input id="key" placeholder="paste the site_key" />- <button id="load">Load tracker</button>- </fieldset>-- <fieldset>- <strong>Simulate activity</strong><br />- <button id="spa">SPA navigate (pushState → /virtual/<random>)</button>- <button id="manual">Manual pageview beacon</button>- <a id="out" href="https://example.com/" target="_blank" rel="noopener">Outbound link</a>- <a id="dl" href="/files/report.pdf">Download-style link</a>- </fieldset>-- <label>Event log</label>- <div id="log"></div>-- <script>- var logEl = document.getElementById('log');- function log(m) { logEl.textContent += m + '\n'; }-- document.getElementById('load').addEventListener('click', function () {- var base = document.getElementById('base').value.replace(/\/$/, '');- var key = document.getElementById('key').value.trim();- if (!key) { log('! enter a site key first'); return; }- var s = document.createElement('script');- s.defer = true;- s.src = base + '/api/v1/analytics/tracker.js';- s.setAttribute('data-site-key', key);- s.setAttribute('data-outlinks', 'true');- s.onload = function () { log('tracker.js loaded from ' + s.src); };- s.onerror = function () { log('! failed to load tracker.js (panel up? extension enabled?)'); };- document.head.appendChild(s);- });-- document.getElementById('spa').addEventListener('click', function () {- var p = '/virtual/' + Math.floor(Math.random() * 1e6);- history.pushState({}, '', p);- log('pushState -> ' + p + ' (tracker should send a pageview)');- });-- document.getElementById('manual').addEventListener('click', function () {- window.dispatchEvent(new Event('load'));- log('dispatched load (fires first pageview if not already sent)');- });- </script>-</body>-</html>diff --git a/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx b/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsxdeleted file mode 100644index 41bdb9f1..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx+++ /dev/null@@ -1,142 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { NavLink, useParams, useNavigate } from 'react-router-dom';-import { BarChart3, FileText, Link2, Monitor, Radio, Globe, Plus } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';-import { useToast } from '@/contexts/ToastContext';--import OverviewTab from './tabs/OverviewTab.jsx';-import PagesTab from './tabs/PagesTab.jsx';-import ReferrersTab from './tabs/ReferrersTab.jsx';-import DevicesTab from './tabs/DevicesTab.jsx';-import RealtimeTab from './tabs/RealtimeTab.jsx';-import SitesTab from './tabs/SitesTab.jsx';--import '../styles/analytics.scss';--// Route-driven tabs. plugin.json maps /analytics and /analytics/:tab here, so the-// active tab is read from useParams().tab (undefined => overview).-const TABS = [- { slug: 'overview', to: '/analytics', label: 'Overview', end: true, icon: <BarChart3 size={15} /> },- { slug: 'pages', to: '/analytics/pages', label: 'Pages', icon: <FileText size={15} /> },- { slug: 'referrers', to: '/analytics/referrers', label: 'Referrers', icon: <Link2 size={15} /> },- { slug: 'devices', to: '/analytics/devices', label: 'Devices', icon: <Monitor size={15} /> },- { slug: 'realtime', to: '/analytics/realtime', label: 'Realtime', icon: <Radio size={15} /> },- { slug: 'sites', to: '/analytics/sites', label: 'Sites', icon: <Globe size={15} /> },-];-const VALID_TABS = TABS.map((t) => t.slug);-const REPORT_TABS = ['overview', 'pages', 'referrers', 'devices', 'realtime'];--export function AnalyticsPage() {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [sites, setSites] = useState([]);- const [sitesLoading, setSitesLoading] = useState(true);- const [selectedSiteId, setSelectedSiteId] = useState(null);-- const loadSites = useCallback(async () => {- setSitesLoading(true);- try {- const data = await api.request('/analytics/sites');- setSites(data?.sites || []);- } catch (error) {- toast.error(`Could not load sites: ${error.message}`);- setSites([]);- } finally {- setSitesLoading(false);- }- }, [toast]);-- useEffect(() => { loadSites(); }, [loadSites]);-- // Keep a valid selection: default to the first site, and re-point if the- // current selection disappears (e.g. after a delete).- useEffect(() => {- if (sites.length === 0) { setSelectedSiteId(null); return; }- setSelectedSiteId((prev) => {- if (prev != null && sites.some((s) => String(s.id) === String(prev))) return prev;- return String(sites[0].id);- });- }, [sites]);-- const isReport = REPORT_TABS.includes(activeTab);-- const renderReportBody = () => {- if (sitesLoading || (sites.length > 0 && selectedSiteId == null)) {- return <EmptyState loading title="Loading analytics…" />;- }- if (sites.length === 0) {- return (- <div className="analytics-empty">- <EmptyState- icon={Globe}- title="No tracked sites yet"- description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."- action={(- <Button variant="default" size="sm" onClick={() => navigate('/analytics/sites')}>- <Plus size={14} /> Add a site- </Button>- )}- />- </div>- );- }- // Remount on site change so each tab resets its own range/loading state.- switch (activeTab) {- case 'pages': return <PagesTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'referrers': return <ReferrersTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'devices': return <DevicesTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'realtime': return <RealtimeTab key={selectedSiteId} siteId={selectedSiteId} />;- default: return <OverviewTab key={selectedSiteId} siteId={selectedSiteId} />;- }- };-- // Report tabs get a site picker in the topbar; the Sites tab manages its own.- const topbarActions = isReport && sites.length > 0 ? (- <select- className="analytics-site-select"- value={selectedSiteId ?? ''}- onChange={(e) => setSelectedSiteId(e.target.value)}- aria-label="Selected site"- >- {sites.map((s) => (- <option key={s.id} value={String(s.id)}>{s.name}</option>- ))}- </select>- ) : null;-- return (- <div className="analytics-page">- <PageTopbar- icon={<BarChart3 size={18} />}- title="Web Analytics"- actions={topbarActions}- />-- <nav className="analytics-tabs" aria-label="Web Analytics sections">- {TABS.map((t) => (- <NavLink- key={t.slug}- to={t.to}- end={t.end}- className={({ isActive }) => `analytics-tabs__tab${isActive ? ' is-active' : ''}`}- >- {t.icon}- {t.label}- </NavLink>- ))}- </nav>-- <div className="analytics-page__body">- {activeTab === 'sites'- ? <SitesTab sites={sites} loading={sitesLoading} reload={loadSites} />- : renderReportBody()}- </div>- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsx b/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsxdeleted file mode 100644index aa86c32a..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsx+++ /dev/null@@ -1,28 +0,0 @@-// Shared date-range picker for the report tabs. Rendered as a small segmented-// button group styled by our own `.analytics-range` rules (isolated SCSS).-const RANGES = [- { value: '1d', label: '24h' },- { value: '7d', label: '7d' },- { value: '14d', label: '14d' },- { value: '30d', label: '30d' },- { value: '90d', label: '90d' },-];--export default function RangePicker({ value, onChange }) {- return (- <div className="analytics-range" role="tablist" aria-label="Date range">- {RANGES.map((r) => (- <button- key={r.value}- type="button"- role="tab"- aria-selected={value === r.value}- className={`analytics-range__btn${value === r.value ? ' is-active' : ''}`}- onClick={() => onChange(r.value)}- >- {r.label}- </button>- ))}- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsxdeleted file mode 100644index 7bb48205..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsx+++ /dev/null@@ -1,73 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Monitor, Globe, Cpu, MapPin } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, labelOrDirect } from '../../utils/format.js';--const makeColumns = (header) => [- { key: 'value', header, className: 'analytics-col-grow', render: (r) => (- <span title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },-];--const SECTIONS = [- { key: 'device', label: 'Device class', icon: Monitor, columns: makeColumns('Device') },- { key: 'browser', label: 'Browser', icon: Globe, columns: makeColumns('Browser') },- { key: 'os', label: 'Operating system', icon: Cpu, columns: makeColumns('OS') },- { key: 'country', label: 'Country', icon: MapPin, columns: makeColumns('Country') },-];--export default function DevicesTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/devices?range=${range}`);- setData(res);- } catch (error) {- toast.error(`Could not load devices: ${error.message}`);- setData(null);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- {loading ? (- <EmptyState loading title="Loading devices…" />- ) : (- <div className="analytics-grid analytics-grid--devices">- {SECTIONS.map(({ key, label, icon: Icon, columns }) => (- <div className="analytics-panel" key={key}>- <div className="analytics-panel__head">- <Icon size={15} /> {label}- </div>- <DataTable- columns={columns}- data={data?.[key] || []}- keyField="value"- emptyTitle={`No ${label.toLowerCase()} data`}- emptyMessage="Nothing recorded in this range yet."- />- </div>- ))}- </div>- )}- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsxdeleted file mode 100644index 8bad763b..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsx+++ /dev/null@@ -1,160 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import {- ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,-} from 'recharts';-import { Users, Eye, TrendingDown, Zap, Radio, BarChart3 } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, formatMs, formatPct, formatDay, labelOrDirect } from '../../utils/format.js';--const KPIS = [- { key: 'visitors', label: 'Visitors', icon: Users, tone: 'accent', fmt: formatInt },- { key: 'pageviews', label: 'Pageviews', icon: Eye, tone: 'cyan', fmt: formatInt },- { key: 'bounce_rate', label: 'Bounce rate', icon: TrendingDown, tone: 'amber', fmt: formatPct },- { key: 'avg_load_ms', label: 'Avg load', icon: Zap, tone: 'violet', fmt: formatMs },-];--const pageColumns = [- { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },- { key: 'avg_load_ms', header: 'Avg load', render: (r) => formatMs(r.avg_load_ms) },-];--const referrerColumns = [- { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },-];--export default function OverviewTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/overview?range=${range}`);- setData(res);- } catch (error) {- toast.error(`Could not load overview: ${error.message}`);- setData(null);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- const totals = data?.totals || {};- const timeseries = data?.timeseries || [];- const realtime = data?.realtime || {};- const hasTraffic = (totals.pageviews || 0) > 0 || (totals.visitors || 0) > 0;-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- <span className="analytics-live" title="Active visitors in the last 30 minutes">- <Radio size={14} className="analytics-live__dot" />- {formatInt(realtime.active_visitors)} active now- </span>- </div>-- <div className="analytics-kpis">- {KPIS.map(({ key, label, icon: Icon, tone, fmt }) => (- <div className="analytics-kpi" key={key}>- <span className={`analytics-kpi__icon analytics-kpi__icon--${tone}`}>- <Icon size={16} />- </span>- <div className="analytics-kpi__val">{loading ? '—' : fmt(totals[key])}</div>- <div className="analytics-kpi__label">{label}</div>- </div>- ))}- </div>-- {loading ? (- <EmptyState loading title="Loading overview…" />- ) : !hasTraffic ? (- <div className="analytics-empty">- <EmptyState- icon={BarChart3}- title="No traffic in this range yet"- description="Once the tracking snippet is installed and visitors arrive, their pageviews show up here."- />- </div>- ) : (- <>- <div className="analytics-chart-card">- <div className="analytics-chart-card__head">Visitors & pageviews</div>- <ResponsiveContainer width="100%" height={260}>- <AreaChart data={timeseries} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>- <defs>- <linearGradient id="anVisitors" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />- </linearGradient>- <linearGradient id="anPageviews" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#22c7d6" stopOpacity={0.3} />- <stop offset="95%" stopColor="#22c7d6" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />- <XAxis- dataKey="date"- tickFormatter={formatDay}- tick={{ fontSize: 11, fill: '#888' }}- minTickGap={24}- axisLine={false}- tickLine={false}- />- <YAxis- allowDecimals={false}- tick={{ fontSize: 11, fill: '#888' }}- width={40}- axisLine={false}- tickLine={false}- />- <Tooltip labelFormatter={formatDay} />- <Area type="monotone" dataKey="visitors" name="Visitors" stroke="#8b93ff" fill="url(#anVisitors)" strokeWidth={2} />- <Area type="monotone" dataKey="pageviews" name="Pageviews" stroke="#22c7d6" fill="url(#anPageviews)" strokeWidth={2} />- </AreaChart>- </ResponsiveContainer>- </div>-- <div className="analytics-grid">- <div className="analytics-panel">- <div className="analytics-panel__head">Top pages</div>- <DataTable- columns={pageColumns}- data={data?.top_pages || []}- keyField="value"- emptyTitle="No pages yet"- emptyMessage="Pageviews will appear here once visitors browse the site."- />- </div>- <div className="analytics-panel">- <div className="analytics-panel__head">Top referrers</div>- <DataTable- columns={referrerColumns}- data={data?.top_referrers || []}- keyField="value"- emptyTitle="No referrers yet"- emptyMessage="Sources that send traffic to the site will appear here."- />- </div>- </div>- </>- )}- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsxdeleted file mode 100644index a4c70add..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsx+++ /dev/null@@ -1,56 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, formatMs, labelOrDirect } from '../../utils/format.js';--const columns = [- { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },- { key: 'avg_load_ms', header: 'Avg load', sortable: true, sortValue: (r) => r.avg_load_ms ?? -1, render: (r) => formatMs(r.avg_load_ms) },-];--export default function PagesTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [rows, setRows] = useState([]);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/pages?range=${range}`);- setRows(res?.rows || []);- } catch (error) {- toast.error(`Could not load pages: ${error.message}`);- setRows([]);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- <div className="analytics-panel">- <DataTable- columns={columns}- data={rows}- keyField="value"- loading={loading}- defaultSort={{ key: 'pageviews', direction: 'desc' }}- emptyTitle="No pages yet"- emptyMessage="Pageviews will appear here once visitors browse the site."- />- </div>- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsxdeleted file mode 100644index 6a8af6b2..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsx+++ /dev/null@@ -1,102 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Radio, Users, Eye } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import { formatInt, formatClock, labelOrDirect } from '../../utils/format.js';--const MINUTE_OPTIONS = [5, 15, 30, 60];-const POLL_MS = 15000;--const columns = [- { key: 'ts', header: 'Time', render: (r) => <span className="analytics-cell-mono">{formatClock(r.ts)}</span> },- { key: 'path', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.path}>{labelOrDirect(r.path)}</span>- ) },- { key: 'referrer_host', header: 'Referrer', render: (r) => labelOrDirect(r.referrer_host) },- { key: 'device_class', header: 'Device', render: (r) => r.device_class || '—' },- { key: 'country', header: 'Country', render: (r) => r.country || '—' },-];--export default function RealtimeTab({ siteId }) {- const toast = useToast();- const [minutes, setMinutes] = useState(30);- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- // `silent` polls skip the loading skeleton so the feed refreshes without flicker.- const load = useCallback(async (silent = false) => {- if (!silent) setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/realtime?minutes=${minutes}`);- setData(res);- } catch (error) {- if (!silent) {- toast.error(`Could not load realtime: ${error.message}`);- setData(null);- }- } finally {- if (!silent) setLoading(false);- }- }, [siteId, minutes, toast]);-- useEffect(() => {- load(false);- const id = setInterval(() => load(true), POLL_MS);- return () => clearInterval(id);- }, [load]);-- // Realtime events carry no id; synthesize a stable unique key per row so the- // table never collides two hits sharing a timestamp.- const recent = (data?.recent || []).map((r, i) => ({ ...r, _rid: `${r.ts || 'x'}-${i}` }));-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <div className="analytics-range" role="tablist" aria-label="Time window">- {MINUTE_OPTIONS.map((m) => (- <button- key={m}- type="button"- role="tab"- aria-selected={minutes === m}- className={`analytics-range__btn${minutes === m ? ' is-active' : ''}`}- onClick={() => setMinutes(m)}- >- {m}m- </button>- ))}- </div>- <span className="analytics-live" title="Auto-refreshing">- <Radio size={14} className="analytics-live__dot" />- Live · last {data?.minutes ?? minutes} min- </span>- </div>-- <div className="analytics-realtime">- <div className="analytics-realtime__stat">- <span className="analytics-realtime__icon analytics-realtime__icon--accent"><Users size={18} /></span>- <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.active_visitors)}</div>- <div className="analytics-realtime__label">Active visitors</div>- </div>- <div className="analytics-realtime__stat">- <span className="analytics-realtime__icon analytics-realtime__icon--cyan"><Eye size={18} /></span>- <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.pageviews)}</div>- <div className="analytics-realtime__label">Pageviews</div>- </div>- </div>-- <div className="analytics-panel">- <div className="analytics-panel__head">Recent activity</div>- <DataTable- columns={columns}- data={recent}- keyField="_rid"- loading={loading}- emptyTitle="No activity yet"- emptyMessage="Hits from the last few minutes will stream in here."- />- </div>- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsxdeleted file mode 100644index b86b093d..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsx+++ /dev/null@@ -1,55 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, labelOrDirect } from '../../utils/format.js';--const columns = [- { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },-];--export default function ReferrersTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [rows, setRows] = useState([]);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/referrers?range=${range}`);- setRows(res?.rows || []);- } catch (error) {- toast.error(`Could not load referrers: ${error.message}`);- setRows([]);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- <div className="analytics-panel">- <DataTable- columns={columns}- data={rows}- keyField="value"- loading={loading}- defaultSort={{ key: 'pageviews', direction: 'desc' }}- emptyTitle="No referrers yet"- emptyMessage="Sources that send traffic to the site will appear here."- />- </div>- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsxdeleted file mode 100644index 3aeaee43..00000000--- a/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsx+++ /dev/null@@ -1,318 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Plus, Trash2, RefreshCw, Copy, Check, Code2, Power, Globe } from 'lucide-react';-import api from '@/services/api';-import { DataTable, Pill } from '@/components/ds';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { useToast } from '@/contexts/ToastContext';-import { useClipboard } from '@/hooks/useClipboard';--const INITIAL_FORM = { name: '', hostnames: '', allowedOrigins: '', honorDnt: true, enabled: true };--// Split a textarea value on newlines/commas into a clean list of tokens.-const parseList = (raw) => (raw || '').split(/[\n,]/).map((s) => s.trim()).filter(Boolean);--export default function SitesTab({ sites, loading, reload }) {- const toast = useToast();- const { copy, copied } = useClipboard({ successMessage: 'Snippet copied' });-- const [busy, setBusy] = useState(false);- const [confirm, setConfirm] = useState(null);-- // Add-site modal- const [addOpen, setAddOpen] = useState(false);- const [form, setForm] = useState(INITIAL_FORM);-- // Snippet modal- const [snippetSite, setSnippetSite] = useState(null);- const [snippetData, setSnippetData] = useState(null);- const [snippetLoading, setSnippetLoading] = useState(false);- const [snippetOutlinks, setSnippetOutlinks] = useState(false);-- const fetchSnippet = useCallback(async (site, outlinks) => {- setSnippetLoading(true);- try {- const res = await api.request(`/analytics/sites/${site.id}/snippet?outlinks=${outlinks}`);- setSnippetData(res);- } catch (error) {- toast.error(`Could not load snippet: ${error.message}`);- setSnippetData(null);- } finally {- setSnippetLoading(false);- }- }, [toast]);-- useEffect(() => {- if (snippetSite) fetchSnippet(snippetSite, snippetOutlinks);- }, [snippetSite, snippetOutlinks, fetchSnippet]);-- const openAdd = () => { setForm(INITIAL_FORM); setAddOpen(true); };- const openSnippet = (site) => { setSnippetOutlinks(false); setSnippetSite(site); };- const closeSnippet = () => { setSnippetSite(null); setSnippetData(null); };-- const handleCreate = async () => {- const name = form.name.trim();- const hostnames = parseList(form.hostnames);- if (!name) { toast.error('Name is required.'); return; }- if (hostnames.length === 0) { toast.error('Add at least one hostname.'); return; }- setBusy(true);- try {- const site = await api.request('/analytics/sites', {- method: 'POST',- body: {- name,- hostnames,- allowed_origins: parseList(form.allowedOrigins),- honor_dnt: form.honorDnt,- enabled: form.enabled,- },- });- setAddOpen(false);- toast.success(`Site "${site.name}" created`);- await reload();- openSnippet(site);- } catch (error) {- toast.error(`Could not create site: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggle = async (site) => {- try {- await api.request(`/analytics/sites/${site.id}`, { method: 'PUT', body: { enabled: !site.enabled } });- await reload();- } catch (error) {- toast.error(`Could not update site: ${error.message}`);- }- };-- const handleRotate = (site) => setConfirm({- title: `Rotate key for ${site.name}?`,- message: 'A new site key is generated immediately. The old key stops accepting hits, so update the installed snippet afterward.',- confirmText: 'Rotate key',- variant: 'warning',- onConfirm: async () => {- setConfirm(null);- setBusy(true);- try {- await api.request(`/analytics/sites/${site.id}/rotate-key`, { method: 'POST' });- toast.success('Site key rotated');- await reload();- if (snippetSite && snippetSite.id === site.id) fetchSnippet(site, snippetOutlinks);- } catch (error) {- toast.error(`Could not rotate key: ${error.message}`);- } finally {- setBusy(false);- }- },- });-- const handleDelete = (site) => setConfirm({- title: `Delete ${site.name}?`,- message: 'This removes the site and all of its collected analytics. This cannot be undone.',- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- setConfirm(null);- setBusy(true);- try {- await api.request(`/analytics/sites/${site.id}`, { method: 'DELETE' });- toast.success('Site deleted');- if (snippetSite && snippetSite.id === site.id) closeSnippet();- await reload();- } catch (error) {- toast.error(`Could not delete site: ${error.message}`);- } finally {- setBusy(false);- }- },- });-- const columns = [- { key: 'name', header: 'Site', sortable: true, render: (s) => (- <div className="analytics-site-name">- <span className="analytics-site-name__title">{s.name}</span>- <span className="analytics-cell-mono analytics-site-name__key">{s.site_key}</span>- </div>- ) },- { key: 'hostnames', header: 'Hostnames', render: (s) => {- const list = (s.hostnames || []).join(', ');- return <span className="analytics-cell-mono" title={list}>{list || '—'}</span>;- } },- { key: 'enabled', header: 'Status', render: (s) => (- s.enabled ? <Pill kind="green">Enabled</Pill> : <Pill kind="gray">Disabled</Pill>- ) },- { key: 'actions', header: '', className: 'analytics-col-actions', render: (s) => (- <div className="analytics-row-actions">- <Button variant="secondary" size="sm" onClick={() => openSnippet(s)} title="Tracking snippet">- <Code2 size={14} />- </Button>- <Button variant="secondary" size="sm" onClick={() => handleToggle(s)} title={s.enabled ? 'Disable' : 'Enable'}>- <Power size={14} />- </Button>- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRotate(s)} title="Rotate key">- <RefreshCw size={14} />- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDelete(s)} title="Delete">- <Trash2 size={14} />- </Button>- </div>- ) },- ];-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar analytics-toolbar--between">- <span className="analytics-toolbar__hint">- {sites.length} site{sites.length === 1 ? '' : 's'} tracked- </span>- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add site- </Button>- </div>-- <div className="analytics-panel">- <DataTable- columns={columns}- data={sites}- keyField="id"- loading={loading}- emptyState={(- <EmptyState- icon={Globe}- title="No tracked sites yet"- description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."- action={(- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add site- </Button>- )}- />- )}- />- </div>-- {/* Add-site modal */}- <Modal- open={addOpen}- onClose={() => setAddOpen(false)}- title="Add a site"- size="lg"- footer={(- <>- <Button variant="outline" onClick={() => setAddOpen(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreate} disabled={busy || !form.name.trim()}>- <Plus size={14} /> Create site- </Button>- </>- )}- >- <div className="analytics-form">- <div className="form-group">- <Label>Name</Label>- <Input- value={form.name}- placeholder="My website"- autoFocus- onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Hostnames</Label>- <textarea- className="analytics-textarea"- value={form.hostnames}- placeholder={'example.com\nwww.example.com'}- spellCheck={false}- onChange={(e) => setForm((f) => ({ ...f, hostnames: e.target.value }))}- />- <p className="analytics-form__hint">One per line (or comma-separated). Hits are accepted from these hostnames.</p>- </div>- <div className="form-group">- <Label>Allowed origins (optional)</Label>- <textarea- className="analytics-textarea"- value={form.allowedOrigins}- placeholder={'https://example.com'}- spellCheck={false}- onChange={(e) => setForm((f) => ({ ...f, allowedOrigins: e.target.value }))}- />- <p className="analytics-form__hint">Restrict the collector to these CORS origins. Leave empty to allow any.</p>- </div>- <label className="analytics-check">- <input- type="checkbox"- checked={form.honorDnt}- onChange={(e) => setForm((f) => ({ ...f, honorDnt: e.target.checked }))}- />- <span>Honor the browser's Do Not Track signal</span>- </label>- <label className="analytics-check">- <input- type="checkbox"- checked={form.enabled}- onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}- />- <span>Start collecting immediately</span>- </label>- </div>- </Modal>-- {/* Tracking snippet modal */}- <Modal- open={!!snippetSite}- onClose={closeSnippet}- title={snippetSite ? `Tracking snippet · ${snippetSite.name}` : 'Tracking snippet'}- size="lg"- footer={<Button variant="outline" onClick={closeSnippet}>Close</Button>}- >- {snippetLoading ? (- <EmptyState loading title="Loading snippet…" />- ) : !snippetData ? (- <EmptyState title="Snippet unavailable" description="Could not load the tracking snippet for this site." />- ) : (- <div className="analytics-snippet-wrap">- <p className="analytics-form__hint">- Paste this into the <head> of every page you want to track. It is cookieless and under 4 KB.- </p>- <label className="analytics-check">- <input- type="checkbox"- checked={snippetOutlinks}- onChange={(e) => setSnippetOutlinks(e.target.checked)}- />- <span>Include outbound-link tracking</span>- </label>- <pre className="analytics-snippet"><code>{snippetData.snippet}</code></pre>- <div className="analytics-snippet__foot">- <span className="analytics-cell-mono analytics-snippet__key" title={snippetData.tracker_url}>- {snippetData.site_key}- </span>- <Button variant="default" size="sm" onClick={() => copy(snippetData.snippet)}>- {copied ? <Check size={14} /> : <Copy size={14} />}- {copied ? 'Copied' : 'Copy'}- </Button>- </div>- </div>- )}- </Modal>-- {confirm && (- <ConfirmDialog- isOpen- title={confirm.title}- message={confirm.message}- confirmText={confirm.confirmText}- variant={confirm.variant}- onConfirm={confirm.onConfirm}- onCancel={() => setConfirm(null)}- />- )}- </div>- );-}diff --git a/builtin-extensions/serverkit-analytics/frontend/index.jsx b/builtin-extensions/serverkit-analytics/frontend/index.jsxdeleted file mode 100644index 077ede6e..00000000--- a/builtin-extensions/serverkit-analytics/frontend/index.jsx+++ /dev/null@@ -1,10 +0,0 @@-// 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/frontend/styles/analytics.scss b/builtin-extensions/serverkit-analytics/frontend/styles/analytics.scssdeleted file mode 100644index 818fab99..00000000--- a/builtin-extensions/serverkit-analytics/frontend/styles/analytics.scss+++ /dev/null@@ -1,410 +0,0 @@-/* serverkit-analytics — isolated plugin styles.- Compiled in ISOLATION from the host: no SCSS $variables, no @import of host- partials. Colours come from the host theme via CSS custom properties- (var(--token, fallback)) plus neutral rgba(128,128,128,α) tints, so the- dashboard tracks light/dark automatically.-- Every in-page rule is namespaced under .analytics-page. The Modal /- ConfirmDialog primitives portal to <body> — OUTSIDE the .analytics-page- subtree — so the modal-content rules near the bottom of this file are- intentionally top-level (same idiom as the tramo extension). All of our- class names are `.analytics-*` prefixed, so the few top-level rules cannot- collide with the host or other plugins. */--.analytics-page {- display: flex;- flex-direction: column;- min-height: 0;-- &__body {- padding: 18px 24px 28px;- }-- /* ── Route-driven tab bar (replaces sidebar sub-menus) ── */- .analytics-tabs {- display: flex;- align-items: center;- gap: 4px;- padding: 0 24px;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.18));- overflow-x: auto;-- &__tab {- display: inline-flex;- align-items: center;- gap: 7px;- padding: 11px 14px;- font-size: 13.5px;- font-weight: 500;- color: var(--text-secondary, rgba(128, 128, 128, 0.9));- text-decoration: none;- border-bottom: 2px solid transparent;- white-space: nowrap;- transition: color 0.15s ease, border-color 0.15s ease;-- svg { opacity: 0.8; }-- &:hover { color: var(--text-primary, inherit); }-- &.is-active {- color: var(--accent-bright, #6366f1);- border-bottom-color: var(--accent-bright, #6366f1);- }- }- }-- /* Site picker in the topbar actions slot */- .analytics-site-select {- height: 32px;- max-width: 220px;- padding: 0 10px;- border-radius: 8px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.06));- color: inherit;- font-size: 13px;- cursor: pointer;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- }-- /* ── Tab body scaffolding ── */- .analytics-tabbody {- display: flex;- flex-direction: column;- gap: 16px;- }-- .analytics-toolbar {- display: flex;- align-items: center;- gap: 12px;- flex-wrap: wrap;-- &--between { justify-content: space-between; }-- &__hint {- font-size: 12.5px;- opacity: 0.65;- }- }-- .analytics-live {- display: inline-flex;- align-items: center;- gap: 6px;- margin-left: auto;- font-size: 12.5px;- font-weight: 500;- color: var(--green, #22c55e);-- &__dot {- color: var(--green, #22c55e);- animation: analytics-pulse 1.8s ease-in-out infinite;- }- }-- /* Range / minutes segmented control */- .analytics-range {- display: inline-flex;- gap: 2px;- padding: 3px;- border-radius: 9px;- background: rgba(128, 128, 128, 0.1);-- &__btn {- border: 0;- background: transparent;- color: var(--text-secondary, inherit);- font-size: 12.5px;- font-weight: 500;- padding: 5px 11px;- border-radius: 7px;- cursor: pointer;- transition: background 0.15s ease, color 0.15s ease;-- &:hover { color: var(--text-primary, inherit); }-- &.is-active {- background: var(--bg-card, rgba(128, 128, 128, 0.9));- color: var(--accent-bright, #6366f1);- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);- }- }- }-- /* ── KPI tiles ── */- .analytics-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));- gap: 12px;- }-- .analytics-kpi {- display: flex;- flex-direction: column;- gap: 6px;- padding: 16px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));-- &__icon {- width: 34px;- height: 34px;- border-radius: 9px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);- color: var(--accent-bright, #818cf8);-- &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }- &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }- &--amber { background: rgba(234, 179, 8, 0.16); color: #eab308; }- &--violet { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }- }-- &__val {- font-size: 24px;- font-weight: 700;- line-height: 1.1;- color: var(--text-primary, inherit);- }-- &__label {- font-size: 12.5px;- opacity: 0.65;- }- }-- /* ── Chart card ── */- .analytics-chart-card {- padding: 16px 16px 8px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));-- &__head {- font-size: 13px;- font-weight: 600;- margin-bottom: 12px;- opacity: 0.85;- }- }-- /* ── Grids of tables ── */- .analytics-grid {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 16px;-- &--devices {- grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));- }-- @media (max-width: 720px) {- grid-template-columns: 1fr;- }- }-- .analytics-panel {- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- overflow: hidden;-- &__head {- display: flex;- align-items: center;- gap: 7px;- padding: 12px 16px;- font-size: 13px;- font-weight: 600;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.12));- opacity: 0.9;-- svg { opacity: 0.7; }- }- }-- /* ── Realtime counters ── */- .analytics-realtime {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));- gap: 12px;-- &__stat {- display: flex;- flex-direction: column;- gap: 6px;- padding: 18px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- }-- &__icon {- width: 38px;- height: 38px;- border-radius: 10px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);-- &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }- &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }- }-- &__val {- font-size: 30px;- font-weight: 700;- line-height: 1;- color: var(--text-primary, inherit);- }-- &__label {- font-size: 12.5px;- opacity: 0.65;- }- }-- /* ── Sites table cells ── */- .analytics-site-name {- display: flex;- flex-direction: column;- gap: 2px;-- &__title { font-weight: 600; font-size: 13.5px; }- &__key { font-size: 11px; opacity: 0.55; }- }-- .analytics-row-actions {- display: flex;- gap: 6px;- justify-content: flex-end;- flex-wrap: wrap;- }-- .analytics-col-actions {- text-align: right;- white-space: nowrap;- }-- .analytics-col-grow {- min-width: 150px;- }-- /* In-page empty/dashed wrapper */- .analytics-empty {- border-radius: 12px;- border: 1px dashed var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- }-}--/* Shared monospace utility — used in-page (tables) AND inside the portaled- snippet modal, so it lives at top level to match both DOM locations. */-.analytics-cell-mono {- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12.5px;-}--@keyframes analytics-pulse {- 0%, 100% { opacity: 1; }- 50% { opacity: 0.35; }-}--@media (prefers-reduced-motion: reduce) {- .analytics-live__dot { animation: none; }-}--/* ── Portaled modal content (Modal / ConfirmDialog render into <body>, OUTSIDE- .analytics-page) — these MUST stay top-level or they never match. ── */-.analytics-form {- display: flex;- flex-direction: column;- gap: 14px;-- .form-group { margin: 0; }-- &__hint {- margin: 6px 0 0;- font-size: 12px;- line-height: 1.45;- opacity: 0.62;- }-}--.analytics-textarea {- width: 100%;- min-height: 78px;- resize: vertical;- padding: 10px 12px;- border-radius: 9px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.05));- color: inherit;- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 12.5px;- line-height: 1.5;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- &::placeholder { opacity: 0.4; }-}--.analytics-check {- display: flex;- align-items: center;- gap: 9px;- font-size: 13px;- cursor: pointer;-- input {- width: 15px;- height: 15px;- cursor: pointer;- accent-color: var(--accent-bright, #6366f1);- }-}--.analytics-snippet-wrap {- display: flex;- flex-direction: column;- gap: 12px;-}--.analytics-snippet {- margin: 0;- max-height: 260px;- overflow: auto;- padding: 14px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-elevated, rgba(128, 128, 128, 0.08));- color: var(--text-primary, inherit);- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12px;- line-height: 1.55;- white-space: pre-wrap;- word-break: break-all;-- code {- font: inherit;- color: inherit;- background: none;- }-- &__foot {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- }-- &__key {- opacity: 0.7;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-}diff --git a/builtin-extensions/serverkit-analytics/frontend/utils/format.js b/builtin-extensions/serverkit-analytics/frontend/utils/format.jsdeleted file mode 100644index 47bd7469..00000000--- a/builtin-extensions/serverkit-analytics/frontend/utils/format.js+++ /dev/null@@ -1,28 +0,0 @@-// Small, dependency-free formatting helpers for the analytics dashboard.-// Kept isolated (no host imports) so the plugin bundle stays self-contained.--export const formatInt = (n) => Number(n ?? 0).toLocaleString();--export const formatMs = (ms) => (ms == null ? '—' : `${Math.round(ms)} ms`);--export const formatPct = (n) => `${Number(n ?? 0).toFixed(1)}%`;--// A 'YYYY-MM-DD' rollup date → a short "Jul 18" label. Parsed as local midnight-// (append time) so the label never drifts a day across time zones.-export const formatDay = (iso) => {- if (!iso) return '';- const d = new Date(`${iso}T00:00:00`);- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleDateString([], { month: 'short', day: 'numeric' });-};--// An ISO timestamp → a wall-clock "14:03:21" label for the realtime feed.-export const formatClock = (iso) => {- if (!iso) return '—';- const d = new Date(iso);- if (Number.isNaN(d.getTime())) return '—';- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });-};--// Referrer/path dimension value → a readable label ("Direct / none" for empties).-export const labelOrDirect = (value) => (value && value.trim() ? value : 'Direct / none');diff --git a/builtin-extensions/serverkit-analytics/plugin.json b/builtin-extensions/serverkit-analytics/plugin.jsondeleted file mode 100644index c4deac93..00000000--- a/builtin-extensions/serverkit-analytics/plugin.json+++ /dev/null@@ -1,71 +0,0 @@-{- "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/builtin-extensions/serverkit-crowdsec/backend/__init__.py b/builtin-extensions/serverkit-crowdsec/backend/__init__.pydeleted file mode 100644index 9d503ce7..00000000--- a/builtin-extensions/serverkit-crowdsec/backend/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""ServerKit CrowdSec extension backend package."""diff --git a/builtin-extensions/serverkit-crowdsec/backend/crowdsec.py b/builtin-extensions/serverkit-crowdsec/backend/crowdsec.pydeleted file mode 100644index fbf82544..00000000--- a/builtin-extensions/serverkit-crowdsec/backend/crowdsec.py+++ /dev/null@@ -1,205 +0,0 @@-"""CrowdSec API endpoints (serverkit-crowdsec extension).--Mounted under ``/api/v1/crowdsec`` via the manifest's ``url_prefix``. Thin-routing layer over :class:`CrowdSecService` — all cscli work happens in the-service. Reads need viewer, mutations need admin (same split as the core-Fail2ban surface).-"""-from flask import Blueprint, jsonify, request--from app.middleware.rbac import admin_required, viewer_required-from .crowdsec_service import CrowdSecService--crowdsec_bp = Blueprint('crowdsec', __name__)--_NOT_INSTALLED = (- 'CrowdSec is not installed on this host. See the status endpoint for '- 'installation guidance.'-)---def _installed_or_error():- """Return an error response tuple when CrowdSec is absent, else None."""- if not CrowdSecService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503- return None---# ── Status ──--@crowdsec_bp.route('/status', methods=['GET'])-@viewer_required-def get_status():- """Installed / running / version / LAPI / allowlist-support summary."""- return jsonify(CrowdSecService.get_status()), 200---# ── Decisions ──--@crowdsec_bp.route('/decisions', methods=['GET'])-@viewer_required-def list_decisions():- """Active decisions, flattened. Filters: ?ip= &scope= &type=."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.list_decisions(- ip=request.args.get('ip'),- scope=request.args.get('scope'),- dtype=request.args.get('type'),- )- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to list decisions')}), 500- return jsonify({'decisions': result['decisions']}), 200---@crowdsec_bp.route('/decisions', methods=['POST'])-@admin_required-def add_decision():- """Ban an IP or range: {ip, duration?, reason?, type?}."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- ip = (data.get('ip') or '').strip()- if not ip:- return jsonify({'error': 'ip is required'}), 400- result = CrowdSecService.add_decision(- ip,- duration=data.get('duration') or '4h',- reason=data.get('reason') or 'Manual ban from ServerKit',- dtype=data.get('type') or 'ban',- )- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to add decision')}), 400- return jsonify(result), 201---@crowdsec_bp.route('/decisions/<path:ip>', methods=['DELETE'])-@admin_required-def delete_decision(ip):- """Remove all decisions for an IP (path converter allows CIDR ranges)."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.delete_decision(ip)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to delete decision')}), 400- return jsonify(result), 200---# ── Alerts ──--@crowdsec_bp.route('/alerts', methods=['GET'])-@viewer_required-def list_alerts():- """Recent alerts (?limit=, default 50)."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.list_alerts(limit=request.args.get('limit', 50))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to list alerts')}), 500- return jsonify({'alerts': result['alerts']}), 200---# ── Allowlists (feature-detected) ──--@crowdsec_bp.route('/allowlists', methods=['GET'])-@viewer_required-def list_allowlists():- """Allowlists, or {supported: false} when the cscli lacks the subcommand."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.list_allowlists()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to list allowlists')}), 500- return jsonify({- 'supported': result.get('supported', False),- 'allowlists': result.get('allowlists', []),- 'message': result.get('message'),- }), 200---@crowdsec_bp.route('/allowlists', methods=['POST'])-@admin_required-def create_allowlist():- """Create an allowlist: {name, description?}."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- name = (data.get('name') or '').strip()- if not name:- return jsonify({'error': 'name is required'}), 400- result = CrowdSecService.create_allowlist(name, data.get('description') or '')- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to create allowlist')}), 400- return jsonify(result), 201---@crowdsec_bp.route('/allowlists/<name>', methods=['GET'])-@viewer_required-def inspect_allowlist(name):- """Allowlist detail (items) via cscli allowlists inspect."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.inspect_allowlist(name)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to inspect allowlist')}), 400- return jsonify({'allowlist': result.get('allowlist')}), 200---@crowdsec_bp.route('/allowlists/<name>/items', methods=['POST'])-@admin_required-def add_allowlist_item(name):- """Add an entry: {value, expiration?, comment?}."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- value = (data.get('value') or '').strip()- if not value:- return jsonify({'error': 'value is required'}), 400- result = CrowdSecService.add_allowlist_entry(- name, value,- expiration=data.get('expiration'),- comment=data.get('comment'),- )- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to add allowlist entry')}), 400- return jsonify(result), 201---@crowdsec_bp.route('/allowlists/<name>/items', methods=['DELETE'])-@admin_required-def remove_allowlist_item(name):- """Remove an entry — value via ?value= or JSON body (CIDRs carry a '/')."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json(silent=True) or {}- value = (request.args.get('value') or data.get('value') or '').strip()- if not value:- return jsonify({'error': 'value is required'}), 400- result = CrowdSecService.remove_allowlist_entry(name, value)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to remove allowlist entry')}), 400- return jsonify(result), 200---# ── Metrics ──--@crowdsec_bp.route('/metrics', methods=['GET'])-@viewer_required-def get_metrics():- """Raw engine metrics, best-effort (shape varies across versions)."""- guard = _installed_or_error()- if guard:- return guard- result = CrowdSecService.get_metrics()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to fetch metrics')}), 500- return jsonify({'metrics': result.get('metrics')}), 200diff --git a/builtin-extensions/serverkit-crowdsec/backend/crowdsec_service.py b/builtin-extensions/serverkit-crowdsec/backend/crowdsec_service.pydeleted file mode 100644index e5e9ce08..00000000--- a/builtin-extensions/serverkit-crowdsec/backend/crowdsec_service.py+++ /dev/null@@ -1,343 +0,0 @@-"""CrowdSec integration service (serverkit-crowdsec extension).--Read/write integration with a host-installed CrowdSec security engine via its-``cscli`` CLI — the same pattern as the core Fail2ban integration, packaged as-an extension:--* **Single choke-point** — every invocation goes through :meth:`_cscli`,- which owns privilege escalation, timeouts, JSON parsing, and error shaping.-* **Best-effort, Linux-only** — on Windows (dev) or when ``cscli`` is absent,- calls return a clean error dict instead of raising; the UI degrades to an- install-guidance empty state. CrowdSec is never auto-installed.-* **Feature-detected allowlists** — the ``cscli allowlists`` subcommand only- exists in newer CrowdSec releases; when the installed version lacks it the- service reports ``supported: False`` and the UI shows an upgrade note.-"""-import ipaddress-import json-import logging-import os-import re-import subprocess--from app.utils.system import run_privileged, is_command_available, ServiceControl--logger = logging.getLogger(__name__)--CSCLI_TIMEOUT = 20-DOCS_URL = 'https://docs.crowdsec.net/docs/getting_started/install_crowdsec/'--# cscli-style durations: 4h, 30m, 1h30m, 7d ...-_DURATION_RE = re.compile(r'^(\d+[smhd])+$')-# Allowlist names stay argv/URL-safe.-_NAME_RE = re.compile(r'^[A-Za-z0-9_.-]+$')-# cobra's "no such subcommand" wording variants (feature detection).-_UNKNOWN_CMD_RE = re.compile(r'unknown (?:command|sub-?command)', re.IGNORECASE)---def _valid_ip_or_range(value):- """True when *value* parses as an IP address or CIDR range."""- if not value or not isinstance(value, str):- return False- try:- if '/' in value:- ipaddress.ip_network(value, strict=False)- else:- ipaddress.ip_address(value)- return True- except ValueError:- return False---class CrowdSecService:- """Stateless wrapper around ``cscli``. All methods return plain dicts."""-- # ---------- availability ------------ @classmethod- def is_installed(cls):- """True only on a Linux host where cscli is installed."""- if os.name == 'nt':- return False- return is_command_available('cscli')-- # ---------- choke-point ------------ @classmethod- def _cscli(cls, args, timeout=CSCLI_TIMEOUT, parse_json=False):- """Run ``cscli <args>`` and return a normalized result dict.-- Every cscli invocation in this service funnels through here so- privilege escalation, timeouts, JSON parsing, and error shaping- live in exactly one place.- """- if os.name == 'nt':- return {'success': False,- 'error': 'CrowdSec integration is not supported on Windows.'}- if not is_command_available('cscli'):- return {'success': False, 'not_installed': True,- 'error': 'CrowdSec (cscli) is not installed on this host.'}-- cmd = ['cscli'] + list(args)- try:- result = run_privileged(cmd, timeout=timeout)- except subprocess.TimeoutExpired:- return {'success': False,- 'error': f'cscli timed out after {timeout}s'}- except (OSError, subprocess.SubprocessError) as e:- return {'success': False, 'error': f'Failed to run cscli: {e}'}-- out = {- 'success': result.returncode == 0,- 'returncode': result.returncode,- 'stdout': result.stdout or '',- 'stderr': result.stderr or '',- }- if not out['success']:- out['error'] = (out['stderr'] or out['stdout'] or 'cscli failed').strip()- return out-- if parse_json:- raw = out['stdout'].strip()- # cscli prints the literal string "null" for empty result sets.- if raw in ('', 'null'):- out['data'] = None- else:- try:- out['data'] = json.loads(raw)- except ValueError:- out['success'] = False- out['error'] = 'cscli returned invalid JSON'- return out-- # ---------- status ------------ @classmethod- def get_status(cls):- """Installed / running / version / LAPI reachability, best-effort."""- status = {- 'installed': cls.is_installed(),- 'running': False,- 'version': None,- 'lapi_ok': False,- 'allowlists_supported': False,- 'docs_url': DOCS_URL,- }- if not status['installed']:- return status-- try:- status['running'] = ServiceControl.is_active('crowdsec')- except Exception: # systemctl absent (container) — stay best-effort- status['running'] = False-- # `cscli version` historically prints to stderr; scan both streams.- res = cls._cscli(['version'])- blob = (res.get('stdout', '') or '') + '\n' + (res.get('stderr', '') or '')- m = re.search(r'version:?\s*v?([0-9][\w.+~-]*)', blob, re.IGNORECASE)- if m:- status['version'] = m.group(1)-- # LAPI reachability: exit 0 == the engine can talk to its Local API.- lapi = cls._cscli(['lapi', 'status'])- status['lapi_ok'] = bool(lapi.get('success'))-- status['allowlists_supported'] = cls.allowlists_supported()- return status-- # ---------- decisions ------------ @classmethod- def list_decisions(cls, ip=None, scope=None, dtype=None):- """Flattened active decisions (cscli nests them under alerts)."""- args = ['decisions', 'list', '-o', 'json']- if ip:- args += ['--ip', ip]- if scope:- args += ['--scope', scope]- if dtype:- args += ['--type', dtype]- res = cls._cscli(args, parse_json=True)- if not res.get('success'):- return res-- decisions = []- for alert in res.get('data') or []:- source = alert.get('source') or {}- for d in alert.get('decisions') or []:- decisions.append({- 'id': d.get('id'),- 'value': d.get('value'),- 'scope': d.get('scope'),- 'type': d.get('type'),- 'origin': d.get('origin'),- 'duration': d.get('duration'),- 'until': d.get('until'),- 'reason': d.get('scenario') or alert.get('scenario'),- 'country': source.get('cn'),- 'as_name': source.get('as_name'),- 'created_at': alert.get('created_at'),- })- return {'success': True, 'decisions': decisions}-- @classmethod- def add_decision(cls, ip, duration='4h', reason='Manual ban from ServerKit',- dtype='ban'):- """Ban an IP or CIDR range (``cscli decisions add``)."""- if not _valid_ip_or_range(ip):- return {'success': False, 'error': f'Invalid IP address or range: {ip!r}'}- if not _DURATION_RE.match(duration or ''):- return {'success': False,- 'error': f'Invalid duration (use e.g. 4h, 30m, 7d): {duration!r}'}- target_flag = '--range' if '/' in ip else '--ip'- res = cls._cscli(['decisions', 'add', target_flag, ip,- '--duration', duration,- '--reason', str(reason or 'Manual ban from ServerKit'),- '--type', str(dtype or 'ban')])- if res.get('success'):- return {'success': True, 'message': f'Decision added for {ip}'}- return res-- @classmethod- def delete_decision(cls, ip):- """Remove all decisions for an IP or CIDR range."""- if not _valid_ip_or_range(ip):- return {'success': False, 'error': f'Invalid IP address or range: {ip!r}'}- target_flag = '--range' if '/' in ip else '--ip'- res = cls._cscli(['decisions', 'delete', target_flag, ip])- if res.get('success'):- return {'success': True, 'message': f'Decisions deleted for {ip}'}- return res-- # ---------- alerts ------------ @classmethod- def list_alerts(cls, limit=50):- """Recent alerts, normalized for the table UI."""- try:- limit = max(1, min(int(limit), 500))- except (TypeError, ValueError):- limit = 50- res = cls._cscli(['alerts', 'list', '-o', 'json', '--limit', str(limit)],- parse_json=True)- if not res.get('success'):- return res-- alerts = []- for a in res.get('data') or []:- source = a.get('source') or {}- alerts.append({- 'id': a.get('id'),- 'scenario': a.get('scenario'),- 'source': source.get('ip') or source.get('value'),- 'country': source.get('cn'),- 'as_name': source.get('as_name'),- 'events_count': a.get('events_count'),- 'decisions': len(a.get('decisions') or []),- 'created_at': a.get('created_at'),- })- return {'success': True, 'alerts': alerts}-- # ---------- allowlists (feature-detected) ------------ @classmethod- def _allowlists_probe(cls):- """Run the cheapest allowlists command and return (supported, result)."""- res = cls._cscli(['allowlists', 'list', '-o', 'json'], parse_json=True)- if res.get('success'):- return True, res- blob = ' '.join([res.get('error', '') or '',- res.get('stderr', '') or '',- res.get('stdout', '') or ''])- if _UNKNOWN_CMD_RE.search(blob):- return False, res- # Command exists but the call failed for another reason (LAPI down…).- return True, res-- @classmethod- def allowlists_supported(cls):- """True when the installed cscli knows the ``allowlists`` subcommand."""- supported, _ = cls._allowlists_probe()- return supported-- _ALLOWLISTS_UNSUPPORTED_MSG = (- 'The installed CrowdSec version does not support centralized '- 'allowlists (cscli allowlists). Upgrade CrowdSec to manage '- 'allowlists from the panel.'- )-- @classmethod- def list_allowlists(cls):- supported, res = cls._allowlists_probe()- if not supported:- return {'success': True, 'supported': False, 'allowlists': [],- 'message': cls._ALLOWLISTS_UNSUPPORTED_MSG}- if not res.get('success'):- return res- entries = res.get('data') or []- if not isinstance(entries, list):- entries = []- return {'success': True, 'supported': True, 'allowlists': entries}-- @classmethod- def inspect_allowlist(cls, name):- if not _NAME_RE.match(name or ''):- return {'success': False, 'error': f'Invalid allowlist name: {name!r}'}- res = cls._cscli(['allowlists', 'inspect', name, '-o', 'json'],- parse_json=True)- if not res.get('success'):- return res- return {'success': True, 'allowlist': res.get('data')}-- @classmethod- def create_allowlist(cls, name, description=''):- if not _NAME_RE.match(name or ''):- return {'success': False,- 'error': 'Allowlist name must be alphanumeric/dashes/underscores/dots.'}- res = cls._cscli(['allowlists', 'create', name,- '--description', str(description or 'Managed by ServerKit')])- if res.get('success'):- return {'success': True, 'message': f'Allowlist {name} created'}- return res-- @classmethod- def add_allowlist_entry(cls, name, value, expiration=None, comment=None):- if not _NAME_RE.match(name or ''):- return {'success': False, 'error': f'Invalid allowlist name: {name!r}'}- if not _valid_ip_or_range(value):- return {'success': False,- 'error': f'Invalid IP address or range: {value!r}'}- args = ['allowlists', 'add', name, value]- if expiration:- if not _DURATION_RE.match(str(expiration)):- return {'success': False,- 'error': f'Invalid expiration (use e.g. 24h, 7d): {expiration!r}'}- args += ['--expiration', str(expiration)]- if comment:- args += ['--comment', str(comment)]- res = cls._cscli(args)- if res.get('success'):- return {'success': True, 'message': f'Added {value} to {name}'}- return res-- @classmethod- def remove_allowlist_entry(cls, name, value):- if not _NAME_RE.match(name or ''):- return {'success': False, 'error': f'Invalid allowlist name: {name!r}'}- if not _valid_ip_or_range(value):- return {'success': False,- 'error': f'Invalid IP address or range: {value!r}'}- res = cls._cscli(['allowlists', 'remove', name, value])- if res.get('success'):- return {'success': True, 'message': f'Removed {value} from {name}'}- return res-- # ---------- metrics ------------ @classmethod- def get_metrics(cls):- """Raw engine metrics, best-effort (shape varies across versions)."""- res = cls._cscli(['metrics', '-o', 'json'], parse_json=True)- if not res.get('success'):- return res- return {'success': True, 'metrics': res.get('data')}diff --git a/builtin-extensions/serverkit-crowdsec/frontend/components/CrowdSecPage.jsx b/builtin-extensions/serverkit-crowdsec/frontend/components/CrowdSecPage.jsxdeleted file mode 100644index 3e0c9379..00000000--- a/builtin-extensions/serverkit-crowdsec/frontend/components/CrowdSecPage.jsx+++ /dev/null@@ -1,566 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { ShieldCheck, RefreshCw, Ban, ListChecks, Activity, Plus } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill, MetricCard } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--const DURATIONS = ['1h', '4h', '12h', '24h', '7d'];--const formatDate = (d) => (d ? new Date(d).toLocaleString() : '—');--// Best-effort: pull a headline number out of `cscli metrics -o json`, whose-// shape varies across CrowdSec versions. Null when nothing recognizable.-function parsedEventsTotal(metrics) {- try {- const acq = metrics?.acquisition;- if (!acq || typeof acq !== 'object') return null;- let total = 0;- for (const source of Object.values(acq)) {- const n = source?.parsed ?? source?.lines_parsed;- if (typeof n === 'number') total += n;- }- return total > 0 ? total : null;- } catch {- return null;- }-}--const CrowdSecPage = () => {- const toast = useToast();-- const [status, setStatus] = useState(null);- const [decisions, setDecisions] = useState([]);- const [alerts, setAlerts] = useState([]);- const [allowlists, setAllowlists] = useState({ supported: false, allowlists: [], message: null });- const [metrics, setMetrics] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Ban modal- const [showBanModal, setShowBanModal] = useState(false);- const [banForm, setBanForm] = useState({ ip: '', duration: '4h', reason: '' });-- // Allowlist manager- const [showListModal, setShowListModal] = useState(false);- const [listForm, setListForm] = useState({ name: '', description: '' });- const [selectedList, setSelectedList] = useState(null);- const [listItems, setListItems] = useState([]);- const [entryForm, setEntryForm] = useState({ value: '', comment: '' });-- const loadData = useCallback(async () => {- setLoading(true);- try {- const statusData = await api.request('/crowdsec/status');- setStatus(statusData);- if (statusData?.installed) {- const [d, a, al, m] = await Promise.all([- api.request('/crowdsec/decisions').catch(() => ({ decisions: [] })),- api.request('/crowdsec/alerts').catch(() => ({ alerts: [] })),- api.request('/crowdsec/allowlists').catch(() => ({ supported: false, allowlists: [] })),- api.request('/crowdsec/metrics').catch(() => null),- ]);- setDecisions(d.decisions || []);- setAlerts(a.alerts || []);- setAllowlists(al || { supported: false, allowlists: [] });- setMetrics(m?.metrics ?? null);- }- } catch (error) {- toast.error(`Failed to load CrowdSec data: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => {- loadData();- }, [loadData]);-- const handleBan = async () => {- if (!banForm.ip.trim()) return;- setActionLoading(true);- try {- await api.request('/crowdsec/decisions', {- method: 'POST',- body: {- ip: banForm.ip.trim(),- duration: banForm.duration,- reason: banForm.reason.trim() || undefined,- },- });- toast.success(`Decision added for ${banForm.ip}`);- setShowBanModal(false);- setBanForm({ ip: '', duration: '4h', reason: '' });- await loadData();- } catch (error) {- toast.error(`Failed to ban IP: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteDecision = (value) => {- setConfirmDialog({- title: 'Remove decision',- message: `Remove all active decisions for ${value}?`,- confirmText: 'Remove',- variant: 'warning',- onConfirm: async () => {- try {- await api.request(`/crowdsec/decisions/${encodeURIComponent(value)}`, { method: 'DELETE' });- toast.success(`Decisions removed for ${value}`);- await loadData();- } catch (error) {- toast.error(`Failed to remove decision: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleCreateList = async () => {- if (!listForm.name.trim()) return;- setActionLoading(true);- try {- await api.request('/crowdsec/allowlists', {- method: 'POST',- body: { name: listForm.name.trim(), description: listForm.description.trim() },- });- toast.success(`Allowlist ${listForm.name} created`);- setShowListModal(false);- setListForm({ name: '', description: '' });- await loadData();- } catch (error) {- toast.error(`Failed to create allowlist: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const openList = async (name) => {- setSelectedList(name);- setListItems([]);- try {- const res = await api.request(`/crowdsec/allowlists/${encodeURIComponent(name)}`);- setListItems(res?.allowlist?.items || []);- } catch (error) {- toast.error(`Failed to load allowlist: ${error.message}`);- }- };-- const handleAddEntry = async () => {- if (!selectedList || !entryForm.value.trim()) return;- setActionLoading(true);- try {- await api.request(`/crowdsec/allowlists/${encodeURIComponent(selectedList)}/items`, {- method: 'POST',- body: { value: entryForm.value.trim(), comment: entryForm.comment.trim() || undefined },- });- toast.success(`Added ${entryForm.value} to ${selectedList}`);- setEntryForm({ value: '', comment: '' });- await openList(selectedList);- } catch (error) {- toast.error(`Failed to add entry: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRemoveEntry = async (value) => {- try {- await api.request(- `/crowdsec/allowlists/${encodeURIComponent(selectedList)}/items?value=${encodeURIComponent(value)}`,- { method: 'DELETE' }- );- toast.success(`Removed ${value} from ${selectedList}`);- await openList(selectedList);- } catch (error) {- toast.error(`Failed to remove entry: ${error.message}`);- }- };-- if (loading) {- return (- <div className="page-container crowdsec-page">- <PageTopbar icon={<ShieldCheck size={18} />} title="CrowdSec" />- <EmptyState loading title="Loading CrowdSec status..." />- </div>- );- }-- // ── Not installed: guidance, never auto-install ──- if (!status?.installed) {- return (- <div className="page-container crowdsec-page">- <PageTopbar icon={<ShieldCheck size={18} />} title="CrowdSec" />- <div className="empty-state">- <ShieldCheck size={48} strokeWidth={1} />- <h3>CrowdSec Is Not Installed</h3>- <p>- CrowdSec is a collaborative security engine that detects attacks in your- logs and shares blocklists across its community. Install it on this host- and this page will surface its decisions, alerts, and allowlists.- </p>- <p>- ServerKit does not install it for you — follow the official guide, then- refresh this page.- </p>- <div className="cs-empty-actions">- <Button asChild variant="default">- <a href={status?.docs_url || 'https://docs.crowdsec.net/'} target="_blank" rel="noreferrer">- Installation Guide- </a>- </Button>- <Button variant="outline" onClick={loadData}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- );- }-- const parsedEvents = parsedEventsTotal(metrics);-- return (- <div className="page-container crowdsec-page">- <PageTopbar- icon={<ShieldCheck size={18} />}- title="CrowdSec"- actions={- <>- <Button variant="default" size="sm" onClick={() => setShowBanModal(true)}>- <Ban size={14} /> Ban an IP- </Button>- <Button variant="outline" size="sm" onClick={loadData}>- <RefreshCw size={14} /> Refresh- </Button>- </>- }- />-- {/* ── Status ── */}- <div className="card">- <div className="card-header">- <h3>Engine Status</h3>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Service</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Local API</span>- <Pill kind={status.lapi_ok ? 'green' : 'amber'}>- {status.lapi_ok ? 'Reachable' : 'Unreachable'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Version</span>- <span className="v">{status.version || 'Unknown'}</span>- </div>- <div className="sk-info-row">- <span className="k">Allowlists</span>- <span className="v">- {status.allowlists_supported- ? 'Supported'- : 'Not supported by this CrowdSec version'}- </span>- </div>- <div className="sk-info-row">- <span className="k">AppSec / WAF</span>- <span className="v">- In-line request filtering needs the CrowdSec AppSec component and a- bouncer on your reverse proxy — configured outside the panel.- </span>- </div>- </div>- </div>- </div>-- {/* ── Metric cards (best-effort) ── */}- <div className="cs-kpis">- <MetricCard icon={<Ban size={15} />} tone="red" value={decisions.length} label="Active decisions" />- <MetricCard icon={<Activity size={15} />} tone="amber" value={alerts.length} label="Recent alerts" />- <MetricCard- icon={<ListChecks size={15} />}- tone="green"- value={allowlists.supported ? (allowlists.allowlists || []).length : '—'}- label="Allowlists"- />- {parsedEvents != null && (- <MetricCard icon={<Activity size={15} />} tone="cyan" value={parsedEvents} label="Parsed log lines" />- )}- </div>-- {/* ── Decisions ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Decisions {decisions.length > 0 && <span className="sec-count">· {decisions.length}</span>}</h3>- </div>- {decisions.length === 0 ? (- <div className="card-body">- <p className="text-muted">No active decisions — nothing is currently banned.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Value</th>- <th>Scope</th>- <th>Type</th>- <th>Origin</th>- <th>Reason</th>- <th>Expires</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {decisions.map((d, i) => (- <tr key={d.id ?? i}>- <td className="sk-cell-mono">{d.value}</td>- <td><span className="sk-tag">{d.scope || '—'}</span></td>- <td>{d.type || '—'}</td>- <td>{d.origin || '—'}</td>- <td>{d.reason || '—'}</td>- <td>{d.until ? formatDate(d.until) : (d.duration || '—')}</td>- <td>- <Button variant="secondary" size="sm" onClick={() => handleDeleteDecision(d.value)}>- Delete- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Alerts ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Alerts {alerts.length > 0 && <span className="sec-count">· {alerts.length}</span>}</h3>- </div>- {alerts.length === 0 ? (- <div className="card-body">- <p className="text-muted">No recent alerts.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Scenario</th>- <th>Source</th>- <th>Country</th>- <th>Events</th>- <th>Decisions</th>- <th>Created</th>- </tr>- </thead>- <tbody>- {alerts.map((a, i) => (- <tr key={a.id ?? i}>- <td>{a.scenario || '—'}</td>- <td className="sk-cell-mono">{a.source || '—'}</td>- <td>{a.country || '—'}</td>- <td>{a.events_count ?? '—'}</td>- <td>{a.decisions ?? '—'}</td>- <td>{formatDate(a.created_at)}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Allowlists ── */}- <div className="card">- <div className="card-header">- <h3>Allowlists</h3>- {allowlists.supported && (- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowListModal(true)}>- <Plus size={14} /> New Allowlist- </Button>- </div>- )}- </div>- <div className="card-body">- {!allowlists.supported ? (- <p className="text-muted">- {allowlists.message- || 'The installed CrowdSec version does not support centralized allowlists. Upgrade CrowdSec to manage allowlists from the panel.'}- </p>- ) : (allowlists.allowlists || []).length === 0 ? (- <p className="text-muted">No allowlists yet. Create one to exempt trusted IPs from remediation.</p>- ) : (- <div className="cs-allowlists">- <div className="cs-allowlists__names">- {(allowlists.allowlists || []).map((l, i) => (- <button- key={l.name ?? i}- type="button"- className={`cs-allowlists__name${selectedList === l.name ? ' is-active' : ''}`}- onClick={() => openList(l.name)}- >- <span className="sk-tag">{l.name}</span>- {l.description && <span className="text-muted"> {l.description}</span>}- </button>- ))}- </div>- {selectedList && (- <div className="cs-allowlists__detail">- <h4>{selectedList}</h4>- {listItems.length === 0 ? (- <p className="text-muted">No entries in this allowlist.</p>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Value</th>- <th>Comment</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {listItems.map((it, i) => {- const value = typeof it === 'string' ? it : it.value;- return (- <tr key={value ?? i}>- <td className="sk-cell-mono">{value}</td>- <td>{(typeof it === 'object' && (it.description || it.comment)) || '—'}</td>- <td>- <Button variant="secondary" size="sm" onClick={() => handleRemoveEntry(value)}>- Remove- </Button>- </td>- </tr>- );- })}- </tbody>- </table>- )}- <div className="cs-entry-form">- <Input- type="text"- value={entryForm.value}- onChange={(e) => setEntryForm((f) => ({ ...f, value: e.target.value }))}- placeholder="IP or CIDR, e.g. 203.0.113.7 or 10.0.0.0/8"- />- <Input- type="text"- value={entryForm.comment}- onChange={(e) => setEntryForm((f) => ({ ...f, comment: e.target.value }))}- placeholder="Comment (optional)"- />- <Button- variant="default"- size="sm"- onClick={handleAddEntry}- disabled={actionLoading || !entryForm.value.trim()}- >- Add Entry- </Button>- </div>- </div>- )}- </div>- )}- </div>- </div>-- {/* ── Ban modal ── */}- <Modal open={showBanModal} onClose={() => setShowBanModal(false)} title="Ban an IP">- <div className="form-group">- <Label>IP address or CIDR range</Label>- <Input- type="text"- value={banForm.ip}- onChange={(e) => setBanForm((f) => ({ ...f, ip: e.target.value }))}- placeholder="203.0.113.7 or 203.0.113.0/24"- />- </div>- <div className="form-group">- <Label>Duration</Label>- <Select value={banForm.duration} onValueChange={(v) => setBanForm((f) => ({ ...f, duration: v }))}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {DURATIONS.map((d) => (- <SelectItem key={d} value={d}>{d}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="form-group">- <Label>Reason</Label>- <Input- type="text"- value={banForm.reason}- onChange={(e) => setBanForm((f) => ({ ...f, reason: e.target.value }))}- placeholder="Manual ban from ServerKit"- />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowBanModal(false)}>Cancel</Button>- <Button variant="destructive" onClick={handleBan} disabled={actionLoading || !banForm.ip.trim()}>- {actionLoading ? 'Banning...' : 'Ban IP'}- </Button>- </div>- </Modal>-- {/* ── New allowlist modal ── */}- <Modal open={showListModal} onClose={() => setShowListModal(false)} title="New Allowlist">- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={listForm.name}- onChange={(e) => setListForm((f) => ({ ...f, name: e.target.value }))}- placeholder="trusted-ips"- />- </div>- <div className="form-group">- <Label>Description</Label>- <Input- type="text"- value={listForm.description}- onChange={(e) => setListForm((f) => ({ ...f, description: e.target.value }))}- placeholder="Office and monitoring IPs"- />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowListModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreateList} disabled={actionLoading || !listForm.name.trim()}>- {actionLoading ? 'Creating...' : 'Create'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default CrowdSecPage;diff --git a/builtin-extensions/serverkit-crowdsec/frontend/index.jsx b/builtin-extensions/serverkit-crowdsec/frontend/index.jsxdeleted file mode 100644index 09905699..00000000--- a/builtin-extensions/serverkit-crowdsec/frontend/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// CrowdSec integration UI, contributed through the extension system. Unlike the-// re-export builtins (ftp/status/email…), this page is fully self-contained in-// the extension — no core page to wrap. After sync this folder lives at-// frontend/src/plugins/serverkit-crowdsec/, so '@/…' host aliases resolve.-export { default as CrowdSecPage } from './components/CrowdSecPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/builtin-extensions/serverkit-crowdsec/frontend/styles/crowdsec.css b/builtin-extensions/serverkit-crowdsec/frontend/styles/crowdsec.cssdeleted file mode 100644index 0d110e6c..00000000--- a/builtin-extensions/serverkit-crowdsec/frontend/styles/crowdsec.css+++ /dev/null@@ -1,53 +0,0 @@-/* CrowdSec extension — layout-only styles; colors/typography inherit from the- host design system (card, sk-dtable, sk-info-row, sk-kpi, empty-state…). */--.crowdsec-page .cs-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));- gap: 12px;- margin: 12px 0;-}--.crowdsec-page .cs-empty-actions {- display: flex;- gap: 8px;- justify-content: center;- margin-top: 12px;-}--.crowdsec-page .cs-allowlists {- display: flex;- flex-direction: column;- gap: 12px;-}--.crowdsec-page .cs-allowlists__names {- display: flex;- flex-wrap: wrap;- gap: 8px;-}--.crowdsec-page .cs-allowlists__name {- background: none;- border: none;- padding: 2px 4px;- cursor: pointer;- text-align: left;- border-radius: 6px;-}--.crowdsec-page .cs-allowlists__name.is-active {- outline: 1px solid currentColor;- outline-offset: 2px;-}--.crowdsec-page .cs-entry-form {- display: flex;- gap: 8px;- margin-top: 12px;- align-items: center;-}--.crowdsec-page .cs-entry-form input {- max-width: 320px;-}diff --git a/builtin-extensions/serverkit-crowdsec/plugin.json b/builtin-extensions/serverkit-crowdsec/plugin.jsondeleted file mode 100644index 2819e513..00000000--- a/builtin-extensions/serverkit-crowdsec/plugin.json+++ /dev/null@@ -1,40 +0,0 @@-{- "name": "serverkit-crowdsec",- "display_name": "CrowdSec",- "version": "1.0.0",- "description": "CrowdSec security engine integration. Surface active decisions and alerts, ban/unban IPs, and manage allowlists straight from the panel. Read/write via cscli on the host; shows install guidance when CrowdSec is absent (never auto-installs).",- "author": "ServerKit",- "license": "MIT",- "category": "security",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["shell"],- "min_panel_version": "1.7.0",- "entry_point": "crowdsec:crowdsec_bp",- "url_prefix": "/api/v1/crowdsec",- "icon": "<path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\"/><path d=\"m9 12 2 2 4-4\"/>",- "contributions": {- "nav": [- {- "id": "crowdsec",- "label": "CrowdSec",- "route": "/crowdsec",- "category": "operations",- "icon": "<path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\"/><path d=\"m9 12 2 2 4-4\"/>"- }- ],- "routes": [- { "path": "crowdsec", "component": "CrowdSecPage" }- ],- "page_titles": {- "/crowdsec": "CrowdSec"- },- "command_palette": [- {- "label": "CrowdSec",- "path": "/crowdsec",- "category": "Pages",- "keywords": "crowdsec decisions alerts bans ips allowlist security waf appsec"- }- ]- }-}diff --git a/builtin-extensions/serverkit-dns-server/backend/__init__.py b/builtin-extensions/serverkit-dns-server/backend/__init__.pydeleted file mode 100644index 041f76f3..00000000--- a/builtin-extensions/serverkit-dns-server/backend/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""ServerKit DNS Server extension backend package."""diff --git a/builtin-extensions/serverkit-dns-server/backend/dns_server.py b/builtin-extensions/serverkit-dns-server/backend/dns_server.pydeleted file mode 100644index e41d54ee..00000000--- a/builtin-extensions/serverkit-dns-server/backend/dns_server.py+++ /dev/null@@ -1,187 +0,0 @@-"""DNS Server API endpoints (serverkit-dns-server extension).--Mounted under ``/api/v1/dns-server`` via the manifest's ``url_prefix``. Thin-routing layer over :class:`DnsServerService` — all Docker and PowerDNS API-work happens in the service. Reads need viewer, mutations need admin (same-split as the serverkit-crowdsec extension).-"""-from flask import Blueprint, jsonify, request--from app.middleware.rbac import admin_required, viewer_required-from .dns_server_service import DnsServerService--dns_server_bp = Blueprint('dns_server', __name__)--_NOT_INSTALLED = (- 'The DNS server is not installed. Install it from the DNS Server page '- '(admin only).'-)---def _installed_or_error():- """Return an error response tuple when the container is absent, else None."""- if not DnsServerService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503- return None---# ── Status / lifecycle ──--@dns_server_bp.route('/status', methods=['GET'])-@viewer_required-def get_status():- """Installed / running / version / nameserver hostname summary."""- return jsonify(DnsServerService.get_status()), 200---@dns_server_bp.route('/install', methods=['POST'])-@admin_required-def install():- """Run the PowerDNS container: {ns_hostname, admin_email}."""- data = request.get_json() or {}- ns_hostname = (data.get('ns_hostname') or '').strip()- admin_email = (data.get('admin_email') or '').strip()- if not ns_hostname:- return jsonify({'error': 'ns_hostname is required'}), 400- if not admin_email:- return jsonify({'error': 'admin_email is required'}), 400- result = DnsServerService.install(ns_hostname, admin_email)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Install failed')}), 400- return jsonify(result), 201---@dns_server_bp.route('/install', methods=['DELETE'])-@admin_required-def uninstall():- """Remove the container (?keep_data=true keeps the SQLite zone data)."""- keep_data = (request.args.get('keep_data', 'true').lower()- not in ('false', '0', 'no'))- result = DnsServerService.uninstall(keep_data=keep_data)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Uninstall failed')}), 400- return jsonify(result), 200---# ── Zones ──--@dns_server_bp.route('/zones', methods=['GET'])-@viewer_required-def list_zones():- guard = _installed_or_error()- if guard:- return guard- result = DnsServerService.list_zones()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to list zones')}), 500- return jsonify({'zones': result['zones']}), 200---@dns_server_bp.route('/zones', methods=['POST'])-@admin_required-def create_zone():- """Create a zone: {name}. SOA/NS are bootstrapped from install params."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- name = (data.get('name') or '').strip()- if not name:- return jsonify({'error': 'name is required'}), 400- result = DnsServerService.create_zone(name)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to create zone')}), 400- return jsonify(result), 201---@dns_server_bp.route('/zones/<path:zone>', methods=['GET'])-@viewer_required-def get_zone(zone):- """Zone detail: rrsets + DNSSEC status (+DS) + delegation check."""- guard = _installed_or_error()- if guard:- return guard- result = DnsServerService.get_zone(zone)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to load zone')}), 404- payload = {'zone': result['zone']}- if result['zone'].get('dnssec'):- ds = DnsServerService.get_ds_records(zone)- payload['ds_records'] = ds.get('ds_records', []) if ds.get('success') else []- payload['delegation'] = DnsServerService.check_delegation(zone)- return jsonify(payload), 200---@dns_server_bp.route('/zones/<path:zone>', methods=['DELETE'])-@admin_required-def delete_zone(zone):- guard = _installed_or_error()- if guard:- return guard- result = DnsServerService.delete_zone(zone)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to delete zone')}), 400- return jsonify(result), 200---# ── Record sets ──--@dns_server_bp.route('/zones/<path:zone>/rrsets', methods=['POST'])-@admin_required-def upsert_rrset(zone):- """Create or replace a record set: {name, type, ttl, records: [...]}."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- rtype = (data.get('type') or '').strip()- if not rtype:- return jsonify({'error': 'type is required'}), 400- result = DnsServerService.upsert_rrset(- zone,- data.get('name'),- rtype,- data.get('ttl', 3600),- data.get('records') or [],- )- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to save record set')}), 400- return jsonify(result), 200---@dns_server_bp.route('/zones/<path:zone>/rrsets', methods=['DELETE'])-@admin_required-def delete_rrset(zone):- """Delete a record set — name/type via query params or JSON body."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json(silent=True) or {}- name = request.args.get('name', data.get('name'))- rtype = (request.args.get('type') or data.get('type') or '').strip()- if not rtype:- return jsonify({'error': 'type is required'}), 400- result = DnsServerService.delete_rrset(zone, name, rtype)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to delete record set')}), 400- return jsonify(result), 200---# ── DNSSEC ──--@dns_server_bp.route('/zones/<path:zone>/dnssec', methods=['POST'])-@admin_required-def set_dnssec(zone):- """Enable/disable DNSSEC: {action: 'enable'|'disable'}. Enable returns- the DS records to publish at the registrar."""- guard = _installed_or_error()- if guard:- return guard- data = request.get_json() or {}- action = (data.get('action') or '').strip().lower()- if action not in ('enable', 'disable'):- return jsonify({'error': "action must be 'enable' or 'disable'"}), 400- result = DnsServerService.set_dnssec(zone, action == 'enable')- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to update DNSSEC')}), 400- return jsonify(result), 200diff --git a/builtin-extensions/serverkit-dns-server/backend/dns_server_service.py b/builtin-extensions/serverkit-dns-server/backend/dns_server_service.pydeleted file mode 100644index a67fd003..00000000--- a/builtin-extensions/serverkit-dns-server/backend/dns_server_service.py+++ /dev/null@@ -1,634 +0,0 @@-"""Authoritative DNS hosting service (serverkit-dns-server extension).--Runs PowerDNS Authoritative Server (SQLite backend) in a managed Docker-container so a ServerKit box can BE the nameserver for its domains. Built-for homelab / air-gapped setups; it complements the provider-based DNS-integrations (Cloudflare etc.) and never replaces them.--Design notes, mirroring the serverkit-crowdsec extension:--* **Two choke-points** — every Docker invocation goes through- :meth:`_docker` (privilege escalation, timeouts, error shaping) and every- PowerDNS HTTP API call goes through :meth:`_api` (auth header, JSON,- error shaping). Nothing else shells out or talks HTTP.-* **Authoritative only** — ``pdns-auth`` does not recurse, by design. This- extension will never answer recursive queries for clients; it only serves- the zones the operator creates. Point resolvers elsewhere.-* **Best-effort, Linux-only** — on Windows (dev) or when Docker is absent,- calls return a clean error dict instead of raising.-* **State lives in PowerDNS** — zone data is PowerDNS's own SQLite file- under ``/var/serverkit/dns-server``; the extension's few settings- (generated API key, NS hostname, hostmaster email) live in the plugin- config store (``plugins_sdk.config``). No core models, no migrations.-"""-import json-import logging-import os-import re-import secrets-import socket-import struct-import subprocess--import requests--from app.utils.system import run_privileged, is_command_available--logger = logging.getLogger(__name__)--SLUG = 'serverkit-dns-server'--# Official PowerDNS Authoritative Server image, 4.9.x line.-IMAGE = 'powerdns/pdns-auth-49'-CONTAINER_NAME = 'serverkit-dns-server'-DATA_DIR = '/var/serverkit/dns-server'-# SQLite path *inside* the container (DATA_DIR is bind-mounted there).-CONTAINER_DB_DIR = '/var/lib/powerdns'--API_HOST = '127.0.0.1'-API_PORT = 8081-API_BASE = f'http://{API_HOST}:{API_PORT}/api/v1'-API_TIMEOUT = 10-DOCKER_TIMEOUT = 120--DOCS_URL = 'https://doc.powerdns.com/authoritative/'--# Record types the panel will read/write. Anything else is rejected.-ALLOWED_RECORD_TYPES = frozenset(- ('A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'CAA', 'PTR', 'SOA'))--# Hostname labels: letters/digits/hyphen, plus '_' (SRV/TXT conventions) and a-# lone '*' for wildcards. No leading/trailing hyphen.-_LABEL_RE = re.compile(r'^(?:\*|_?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)$')-_HOSTNAME_RE = re.compile(- r'^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'- r'(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+\.?$')-_EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')--# Public resolvers asked during the best-effort delegation check.-DELEGATION_RESOLVERS = ('1.1.1.1', '8.8.8.8')-_QTYPE_NS = 2-_QCLASS_IN = 1---def _canonical_zone(zone):- """Normalize a zone name to lowercase, dot-terminated. None if invalid."""- if not zone or not isinstance(zone, str):- return None- z = zone.strip().lower().rstrip('.')- if not z or not _HOSTNAME_RE.match(z + '.') or '*' in z:- return None- return z + '.'---def _valid_record_name(name):- """True when every label of *name* (dot-terminated FQDN) is well-formed."""- labels = name.rstrip('.').split('.')- return all(_LABEL_RE.match(lbl) for lbl in labels)---class DnsServerService:- """Stateless wrapper around Docker + the PowerDNS HTTP API."""-- # ---------- config (plugin config store) ------------ @classmethod- def _config(cls):- """Saved extension settings from the plugin config store."""- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)-- @classmethod- def _save_config(cls, updates):- """Merge *updates* into the plugin's stored config.-- The SDK ``config()`` helper is read-only (the panel owns writes), so- the generated API key is persisted through the InstalledPlugin row- directly. Returns False when the plugin row is absent (dev shells).- """- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- logger.warning('%s: no InstalledPlugin row; config not persisted', SLUG)- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True-- # ---------- docker choke-point ------------ @classmethod- def _docker(cls, args, timeout=DOCKER_TIMEOUT):- """Run ``docker <args>`` and return a normalized result dict."""- if os.name == 'nt':- return {'success': False,- 'error': 'The DNS server extension is not supported on Windows.'}- if not is_command_available('docker'):- return {'success': False, 'not_installed': True,- 'error': 'Docker is not installed on this host.'}- cmd = ['docker'] + list(args)- try:- result = run_privileged(cmd, timeout=timeout)- except subprocess.TimeoutExpired:- return {'success': False, 'error': f'docker timed out after {timeout}s'}- except (OSError, subprocess.SubprocessError) as e:- return {'success': False, 'error': f'Failed to run docker: {e}'}- out = {- 'success': result.returncode == 0,- 'returncode': result.returncode,- 'stdout': result.stdout or '',- 'stderr': result.stderr or '',- }- if not out['success']:- out['error'] = (out['stderr'] or out['stdout'] or 'docker failed').strip()- return out-- # ---------- PowerDNS API choke-point ------------ @classmethod- def _api(cls, method, path, payload=None):- """Call the container's PowerDNS HTTP API (loopback only).-- Returns ``{'success': True, 'data': <json-or-None>}`` or an error- dict. The web server is published on 127.0.0.1 exclusively, so this- never leaves the host.- """- api_key = cls._config().get('api_key')- if not api_key:- return {'success': False,- 'error': 'PowerDNS API key is not configured. Reinstall the DNS server.'}- try:- resp = requests.request(- method, API_BASE + path,- headers={'X-API-Key': api_key},- json=payload,- timeout=API_TIMEOUT,- )- except requests.RequestException as e:- return {'success': False,- 'error': f'PowerDNS API is unreachable: {e}'}- if resp.status_code >= 400:- try:- detail = resp.json().get('error') or resp.text- except ValueError:- detail = resp.text- return {'success': False,- 'error': f'PowerDNS API error ({resp.status_code}): {detail}'.strip()}- if not resp.content:- return {'success': True, 'data': None}- try:- return {'success': True, 'data': resp.json()}- except ValueError:- return {'success': False, 'error': 'PowerDNS API returned invalid JSON'}-- # ---------- container lifecycle ------------ @classmethod- def is_installed(cls):- """True when the managed container exists (running or not)."""- if os.name == 'nt':- return False- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- return bool(res.get('success'))-- @classmethod- def get_status(cls):- """Installed / running / version / config summary, best-effort."""- status = {- 'installed': False,- 'running': False,- 'version': None,- 'image': IMAGE,- 'container': CONTAINER_NAME,- 'ns_hostname': cls._config().get('ns_hostname') if os.name != 'nt' else None,- 'authoritative_only': True,- 'docs_url': DOCS_URL,- }- if os.name == 'nt':- return status- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- if not res.get('success'):- return status- status['installed'] = True- status['running'] = res.get('stdout', '').strip() == 'true'- if status['running']:- info = cls._api('GET', '/servers/localhost')- if info.get('success') and isinstance(info.get('data'), dict):- status['version'] = info['data'].get('version')- return status-- @classmethod- def install(cls, ns_hostname, admin_email):- """Create and start the PowerDNS container.-- * SQLite state bind-mounted at ``DATA_DIR`` (the official image- bootstraps the schema on first start).- * Port 53 published on tcp+udp (the box becomes a nameserver).- * HTTP API enabled with a generated key, web server published on- **127.0.0.1 only** — never reachable off-host.- """- if os.name == 'nt':- return {'success': False,- 'error': 'The DNS server extension is not supported on Windows.'}- ns_hostname = (ns_hostname or '').strip().lower().rstrip('.')- admin_email = (admin_email or '').strip()- if not ns_hostname or not _HOSTNAME_RE.match(ns_hostname):- return {'success': False,- 'error': f'Invalid nameserver hostname: {ns_hostname!r}'}- if not admin_email or not _EMAIL_RE.match(admin_email):- return {'success': False,- 'error': f'Invalid hostmaster email: {admin_email!r}'}- if cls.is_installed():- return {'success': False,- 'error': 'The DNS server container already exists. Uninstall it first.'}-- dir_res = run_privileged(['mkdir', '-p', DATA_DIR])- if getattr(dir_res, 'returncode', 1) != 0:- return {'success': False,- 'error': f'Could not create data directory {DATA_DIR}: '- f'{(dir_res.stderr or "").strip()}'}-- api_key = secrets.token_hex(24)- run_args = [- 'run', '-d',- '--name', CONTAINER_NAME,- '--restart', 'unless-stopped',- '-p', '53:53/udp',- '-p', '53:53/tcp',- '-p', f'{API_HOST}:{API_PORT}:{API_PORT}',- '-v', f'{DATA_DIR}:{CONTAINER_DB_DIR}',- IMAGE,- # pdns_server flags (the image forwards container args to pdns):- '--api=yes',- f'--api-key={api_key}',- '--webserver=yes',- '--webserver-address=0.0.0.0',- f'--webserver-port={API_PORT}',- '--webserver-allow-from=0.0.0.0/0',- '--launch=gsqlite3',- f'--gsqlite3-database={CONTAINER_DB_DIR}/pdns.sqlite3',- '--gsqlite3-dnssec=yes',- ]- res = cls._docker(run_args)- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to start the PowerDNS container')}-- persisted = cls._save_config({- 'api_key': api_key,- 'ns_hostname': ns_hostname,- 'admin_email': admin_email,- })- result = {'success': True,- 'message': 'PowerDNS authoritative server installed',- 'container': CONTAINER_NAME}- if not persisted:- result['warning'] = ('Container started but the API key could not be '- 'persisted to the plugin config store.')- return result-- @classmethod- def uninstall(cls, keep_data=True):- """Remove the container; optionally delete the SQLite zone data."""- if os.name == 'nt':- return {'success': False,- 'error': 'The DNS server extension is not supported on Windows.'}- res = cls._docker(['rm', '-f', CONTAINER_NAME])- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to remove the PowerDNS container')}- if not keep_data:- rm = run_privileged(['rm', '-rf', DATA_DIR])- if getattr(rm, 'returncode', 1) != 0:- return {'success': True,- 'warning': f'Container removed but zone data at {DATA_DIR} '- f'could not be deleted: {(rm.stderr or "").strip()}'}- cls._save_config({'api_key': None})- return {'success': True,- 'message': 'DNS server removed'- + ('' if keep_data else ' (zone data deleted)')}-- # ---------- zones ------------ @classmethod- def list_zones(cls):- res = cls._api('GET', '/servers/localhost/zones')- if not res.get('success'):- return res- zones = [{- 'name': z.get('name'),- 'kind': z.get('kind'),- 'serial': z.get('serial'),- 'dnssec': bool(z.get('dnssec')),- } for z in (res.get('data') or [])]- return {'success': True, 'zones': zones}-- @classmethod- def create_zone(cls, zone):- """Create a Native zone with a bootstrap SOA + NS from install params."""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- cfg = cls._config()- ns_hostname = (cfg.get('ns_hostname') or '').rstrip('.')- admin_email = cfg.get('admin_email') or ''- if not ns_hostname or not admin_email:- return {'success': False,- 'error': 'Nameserver hostname / hostmaster email are not '- 'configured. Reinstall the DNS server.'}- hostmaster = admin_email.replace('@', '.').rstrip('.') + '.'- soa_content = f'{ns_hostname}. {hostmaster} 1 10800 3600 604800 3600'- payload = {- 'name': canonical,- 'kind': 'Native',- 'rrsets': [- {- 'name': canonical, 'type': 'SOA', 'ttl': 3600,- 'changetype': 'REPLACE',- 'records': [{'content': soa_content, 'disabled': False}],- },- {- 'name': canonical, 'type': 'NS', 'ttl': 3600,- 'changetype': 'REPLACE',- 'records': [{'content': f'{ns_hostname}.', 'disabled': False}],- },- ],- }- res = cls._api('POST', '/servers/localhost/zones', payload)- if not res.get('success'):- return res- return {'success': True, 'zone': canonical,- 'message': f'Zone {canonical} created'}-- @classmethod- def delete_zone(cls, zone):- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- res = cls._api('DELETE', f'/servers/localhost/zones/{canonical}')- if not res.get('success'):- return res- return {'success': True, 'message': f'Zone {canonical} deleted'}-- @classmethod- def get_zone(cls, zone):- """Zone detail: normalized rrsets + dnssec flag."""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- res = cls._api('GET', f'/servers/localhost/zones/{canonical}')- if not res.get('success'):- return res- data = res.get('data') or {}- rrsets = [{- 'name': r.get('name'),- 'type': r.get('type'),- 'ttl': r.get('ttl'),- 'records': [rec.get('content') for rec in (r.get('records') or [])- if not rec.get('disabled')],- } for r in (data.get('rrsets') or [])]- return {'success': True, 'zone': {- 'name': data.get('name'),- 'kind': data.get('kind'),- 'serial': data.get('serial'),- 'dnssec': bool(data.get('dnssec')),- 'rrsets': rrsets,- }}-- # ---------- rrsets ------------ @classmethod- def _rrset_target(cls, zone, name, rtype):- """Validate + canonicalize an rrset target. Returns (zone, fqdn) or error dict."""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- rtype = (rtype or '').strip().upper()- if rtype not in ALLOWED_RECORD_TYPES:- allowed = ', '.join(sorted(ALLOWED_RECORD_TYPES))- return {'success': False,- 'error': f'Unsupported record type {rtype!r}. Allowed: {allowed}'}- raw = (name or '').strip().lower()- if raw in ('', '@', canonical.rstrip('.')):- fqdn = canonical- elif raw.endswith('.'):- fqdn = raw- else:- fqdn = f'{raw}.{canonical}'- if not (fqdn == canonical or fqdn.endswith('.' + canonical)):- return {'success': False,- 'error': f'{name!r} is not inside zone {canonical}'}- if not _valid_record_name(fqdn):- return {'success': False, 'error': f'Invalid record name: {name!r}'}- return canonical, fqdn, rtype-- @classmethod- def upsert_rrset(cls, zone, name, rtype, ttl, records):- target = cls._rrset_target(zone, name, rtype)- if isinstance(target, dict):- return target- canonical, fqdn, rtype = target- try:- ttl = int(ttl)- except (TypeError, ValueError):- return {'success': False, 'error': f'Invalid TTL: {ttl!r}'}- if not (1 <= ttl <= 604800):- return {'success': False, 'error': 'TTL must be between 1 and 604800'}- values = [str(r).strip() for r in (records or []) if str(r).strip()]- if not values:- return {'success': False, 'error': 'At least one record value is required'}- payload = {'rrsets': [{- 'name': fqdn, 'type': rtype, 'ttl': ttl, 'changetype': 'REPLACE',- 'records': [{'content': v, 'disabled': False} for v in values],- }]}- res = cls._api('PATCH', f'/servers/localhost/zones/{canonical}', payload)- if not res.get('success'):- return res- return {'success': True, 'message': f'{rtype} record set saved for {fqdn}'}-- @classmethod- def delete_rrset(cls, zone, name, rtype):- target = cls._rrset_target(zone, name, rtype)- if isinstance(target, dict):- return target- canonical, fqdn, rtype = target- if rtype == 'SOA':- return {'success': False,- 'error': 'The SOA record cannot be deleted (edit it instead).'}- payload = {'rrsets': [{- 'name': fqdn, 'type': rtype, 'changetype': 'DELETE', 'records': [],- }]}- res = cls._api('PATCH', f'/servers/localhost/zones/{canonical}', payload)- if not res.get('success'):- return res- return {'success': True, 'message': f'{rtype} record set deleted for {fqdn}'}-- # ---------- DNSSEC ------------ @classmethod- def get_ds_records(cls, zone):- """DS records (paste at the registrar/parent) from active cryptokeys."""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- res = cls._api('GET', f'/servers/localhost/zones/{canonical}/cryptokeys')- if not res.get('success'):- return res- ds = []- for key in res.get('data') or []:- if key.get('active'):- ds.extend(key.get('ds') or [])- return {'success': True, 'ds_records': ds}-- @classmethod- def set_dnssec(cls, zone, enabled):- """Enable/disable DNSSEC. PowerDNS generates the keys server-side;- enabling returns the DS records for the parent zone."""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}- payload = {'dnssec': bool(enabled)}- if enabled:- payload['api_rectify'] = True- res = cls._api('PUT', f'/servers/localhost/zones/{canonical}', payload)- if not res.get('success'):- return res- if not enabled:- return {'success': True, 'dnssec': False,- 'message': f'DNSSEC disabled for {canonical}. Remove the DS '- f'records at your registrar.'}- ds = cls.get_ds_records(canonical)- return {'success': True, 'dnssec': True,- 'ds_records': ds.get('ds_records', []) if ds.get('success') else [],- 'message': f'DNSSEC enabled for {canonical}. Publish the DS '- f'records at your registrar to complete the chain.'}-- # ---------- delegation check (minimal stdlib DNS client) ------------ @staticmethod- def _build_ns_query(zone, query_id):- """Build a DNS query packet asking for the NS records of *zone*."""- header = struct.pack('>HHHHHH', query_id, 0x0100, 1, 0, 0, 0)- question = b''- for label in zone.rstrip('.').split('.'):- encoded = label.encode('idna') if not label.isascii() else label.encode()- question += struct.pack('>B', len(encoded)) + encoded- question += b'\x00' + struct.pack('>HH', _QTYPE_NS, _QCLASS_IN)- return header + question-- @staticmethod- def _parse_name(data, offset):- """Decode a (possibly compressed) DNS name. Returns (name, next_offset)."""- labels = []- jumped = False- next_offset = offset- hops = 0- while True:- if offset >= len(data):- raise ValueError('truncated DNS name')- length = data[offset]- if length & 0xC0 == 0xC0: # compression pointer- if offset + 1 >= len(data):- raise ValueError('truncated compression pointer')- pointer = struct.unpack('>H', data[offset:offset + 2])[0] & 0x3FFF- if not jumped:- next_offset = offset + 2- jumped = True- offset = pointer- hops += 1- if hops > 32:- raise ValueError('compression loop')- continue- if length == 0:- if not jumped:- next_offset = offset + 1- break- offset += 1- labels.append(data[offset:offset + length].decode('ascii', 'replace'))- offset += length- return '.'.join(labels).lower(), next_offset-- @classmethod- def _parse_ns_response(cls, data, query_id):- """Extract NS names from a DNS response (answer + authority sections)."""- if len(data) < 12:- raise ValueError('truncated DNS header')- rid, flags, qdcount, ancount, nscount, _ = struct.unpack('>HHHHHH', data[:12])- if rid != query_id:- raise ValueError('DNS response id mismatch')- rcode = flags & 0x000F- if rcode not in (0, 3): # NOERROR or NXDOMAIN- raise ValueError(f'DNS query failed with rcode {rcode}')- offset = 12- for _ in range(qdcount):- _, offset = cls._parse_name(data, offset)- offset += 4 # qtype + qclass- ns_names = []- for _ in range(ancount + nscount):- _, offset = cls._parse_name(data, offset)- if offset + 10 > len(data):- raise ValueError('truncated resource record')- rtype, _, _, rdlength = struct.unpack('>HHIH', data[offset:offset + 10])- offset += 10- if rtype == _QTYPE_NS:- name, _ = cls._parse_name(data, offset)- ns_names.append(name)- offset += rdlength- return ns_names-- @classmethod- def _query_public_ns(cls, zone):- """Ask public resolvers for the NS set the world sees for *zone*."""- query_id = secrets.randbelow(0x10000)- packet = cls._build_ns_query(zone, query_id)- last_error = None- for resolver in DELEGATION_RESOLVERS:- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- try:- sock.settimeout(4)- sock.sendto(packet, (resolver, 53))- data, _ = sock.recvfrom(4096)- return cls._parse_ns_response(data, query_id)- except (OSError, ValueError) as e:- last_error = e- finally:- sock.close()- raise OSError(f'All resolvers failed: {last_error}')-- @classmethod- def check_delegation(cls, zone):- """Best-effort: does the public NS set for the zone match ours?"""- canonical = _canonical_zone(zone)- if not canonical:- return {'success': False, 'error': f'Invalid zone name: {zone!r}'}-- zone_ns = []- detail = cls.get_zone(canonical)- if detail.get('success'):- for rrset in detail['zone'].get('rrsets', []):- if rrset.get('type') == 'NS' and rrset.get('name') == canonical:- zone_ns = sorted(v.rstrip('.').lower() for v in rrset['records'])-- try:- public_ns = sorted(set(cls._query_public_ns(canonical)))- except (OSError, ValueError) as e:- return {'success': True, 'checked': False, 'zone_ns': zone_ns,- 'public_ns': [], 'delegated': None,- 'note': f'Could not query public resolvers: {e}'}-- delegated = bool(public_ns) and set(public_ns) == set(zone_ns)- note = None- if not public_ns:- note = ('No public NS records found — the domain is not delegated '- 'to any nameserver yet. Set the NS (glue) records at your '- 'registrar.')- elif not delegated:- note = ('The public NS set differs from this zone\'s NS records. '- 'Update the nameservers at your registrar.')- return {'success': True, 'checked': True, 'zone_ns': zone_ns,- 'public_ns': public_ns, 'delegated': delegated, 'note': note}diff --git a/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsx b/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsxdeleted file mode 100644index ef0a4caa..00000000--- a/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsx+++ /dev/null@@ -1,381 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Globe, RefreshCw, Plus, Trash2, Server } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import ZoneDetail from './ZoneDetail.jsx';--const DnsServerPage = () => {- const toast = useToast();-- const [status, setStatus] = useState(null);- const [zones, setZones] = useState([]);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);- const [selectedZone, setSelectedZone] = useState(null);-- // Install form- const [installForm, setInstallForm] = useState({ ns_hostname: '', admin_email: '' });-- // New zone modal- const [showZoneModal, setShowZoneModal] = useState(false);- const [zoneName, setZoneName] = useState('');-- const loadData = useCallback(async () => {- setLoading(true);- try {- const statusData = await api.request('/dns-server/status');- setStatus(statusData);- if (statusData?.installed) {- const z = await api.request('/dns-server/zones').catch(() => ({ zones: [] }));- setZones(z.zones || []);- }- } catch (error) {- toast.error(`Failed to load DNS server status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => {- loadData();- }, [loadData]);-- const handleInstall = async () => {- if (!installForm.ns_hostname.trim() || !installForm.admin_email.trim()) return;- setActionLoading(true);- try {- await api.request('/dns-server/install', {- method: 'POST',- body: {- ns_hostname: installForm.ns_hostname.trim(),- admin_email: installForm.admin_email.trim(),- },- });- toast.success('PowerDNS authoritative server installed');- await loadData();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove DNS server',- message: keepData- ? 'Remove the PowerDNS container? Zone data stays on disk and a reinstall picks it back up.'- : 'Remove the PowerDNS container AND delete all zone data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/dns-server/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('DNS server removed');- setSelectedZone(null);- await loadData();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleCreateZone = async () => {- if (!zoneName.trim()) return;- setActionLoading(true);- try {- await api.request('/dns-server/zones', {- method: 'POST',- body: { name: zoneName.trim() },- });- toast.success(`Zone ${zoneName} created`);- setShowZoneModal(false);- setZoneName('');- await loadData();- } catch (error) {- toast.error(`Failed to create zone: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteZone = (name) => {- setConfirmDialog({- title: 'Delete zone',- message: `Delete zone ${name} and all of its records?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/dns-server/zones/${encodeURIComponent(name)}`, { method: 'DELETE' });- toast.success(`Zone ${name} deleted`);- if (selectedZone === name) setSelectedZone(null);- await loadData();- } catch (error) {- toast.error(`Failed to delete zone: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- if (loading) {- return (- <div className="page-container dns-server-page">- <PageTopbar icon={<Globe size={18} />} title="DNS Server" />- <EmptyState loading title="Loading DNS server status..." />- </div>- );- }-- // ── Not installed: explainer + install form ──- if (!status?.installed) {- return (- <div className="page-container dns-server-page">- <PageTopbar icon={<Globe size={18} />} title="DNS Server" />- <div className="card">- <div className="card-header">- <h3>Host Your Own Nameserver</h3>- </div>- <div className="card-body">- <p>- Run PowerDNS (authoritative, SQLite backend) in a managed Docker- container so this box answers DNS for your domains directly —- handy for homelabs and air-gapped networks where a hosted DNS- provider is not an option.- </p>- <ul className="dns-explainer">- <li>- <strong>Authoritative only.</strong> This serves the zones you- create; it never resolves other names for clients. Keep using- your normal resolver.- </li>- <li>- <strong>Port 53 must be free</strong> on this host (tcp + udp).- systemd-resolved or another DNS service will conflict.- </li>- <li>- <strong>Delegation happens at your registrar.</strong> Point the- domain's NS (and glue) records at this box's nameserver- hostname so the world finds it.- </li>- <li>- This complements provider integrations (Cloudflare etc.) — it- does not replace them.- </li>- </ul>- <div className="dns-install-form">- <div className="form-group">- <Label>Nameserver hostname</Label>- <Input- type="text"- value={installForm.ns_hostname}- onChange={(e) => setInstallForm((f) => ({ ...f, ns_hostname: e.target.value }))}- placeholder="ns1.example.com"- />- <p className="text-muted">- The hostname other resolvers will use to reach this server.- It should resolve (via glue records) to this box's public IP.- </p>- </div>- <div className="form-group">- <Label>Hostmaster email</Label>- <Input- type="email"- value={installForm.admin_email}- onChange={(e) => setInstallForm((f) => ({ ...f, admin_email: e.target.value }))}- placeholder="[email protected]"- />- <p className="text-muted">Used in each zone's SOA record.</p>- </div>- <div className="dns-install-actions">- <Button- variant="default"- onClick={handleInstall}- disabled={actionLoading || !installForm.ns_hostname.trim() || !installForm.admin_email.trim()}- >- {actionLoading ? 'Installing...' : 'Install DNS Server'}- </Button>- <Button variant="outline" onClick={loadData}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- </div>- </div>- );- }-- return (- <div className="page-container dns-server-page">- <PageTopbar- icon={<Globe size={18} />}- title="DNS Server"- actions={- <>- <Button variant="default" size="sm" onClick={() => setShowZoneModal(true)}>- <Plus size={14} /> New Zone- </Button>- <Button variant="outline" size="sm" onClick={loadData}>- <RefreshCw size={14} /> Refresh- </Button>- </>- }- />-- {/* ── Status ── */}- <div className="card">- <div className="card-header">- <h3>Server Status</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)}>- <Trash2 size={14} /> Remove + data- </Button>- </div>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Container</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Engine</span>- <span className="v">- PowerDNS Authoritative {status.version ? `v${status.version}` : '(version unavailable)'}- </span>- </div>- <div className="sk-info-row">- <span className="k">Nameserver</span>- <span className="v sk-cell-mono">{status.ns_hostname || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Mode</span>- <span className="v">Authoritative only — no recursion, by design.</span>- </div>- </div>- </div>- </div>-- {/* ── Zones ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Zones {zones.length > 0 && <span className="sec-count">· {zones.length}</span>}</h3>- </div>- {zones.length === 0 ? (- <div className="card-body">- <p className="text-muted">- No zones yet. Create one, then point the domain's nameservers here- at your registrar.- </p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Zone</th>- <th>Kind</th>- <th>Serial</th>- <th>DNSSEC</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {zones.map((z) => (- <tr key={z.name}>- <td className="sk-cell-mono">- <button- type="button"- className="dns-zone-link"- onClick={() => setSelectedZone(z.name)}- >- {z.name}- </button>- </td>- <td>{z.kind || '—'}</td>- <td>{z.serial ?? '—'}</td>- <td>- <Pill kind={z.dnssec ? 'green' : 'gray'}>- {z.dnssec ? 'Signed' : 'Off'}- </Pill>- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => setSelectedZone(z.name)}>- <Server size={14} /> Manage- </Button>{' '}- <Button variant="secondary" size="sm" onClick={() => handleDeleteZone(z.name)}>- Delete- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Zone detail ── */}- {selectedZone && (- <ZoneDetail- zoneName={selectedZone}- onClose={() => setSelectedZone(null)}- onChanged={loadData}- />- )}-- {/* ── New zone modal ── */}- <Modal open={showZoneModal} onClose={() => setShowZoneModal(false)} title="New Zone">- <div className="form-group">- <Label>Zone name</Label>- <Input- type="text"- value={zoneName}- onChange={(e) => setZoneName(e.target.value)}- placeholder="example.com"- />- <p className="text-muted">- SOA and NS records are bootstrapped from the nameserver hostname and- hostmaster email you provided at install.- </p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowZoneModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreateZone} disabled={actionLoading || !zoneName.trim()}>- {actionLoading ? 'Creating...' : 'Create Zone'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default DnsServerPage;diff --git a/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsx b/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsxdeleted file mode 100644index 4d9a1fb3..00000000--- a/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsx+++ /dev/null@@ -1,333 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { RefreshCw, Plus, ShieldCheck, X } from 'lucide-react';-import api from '@/services/api';-import { Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import { useToast } from '@/contexts/ToastContext';--const RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'CAA', 'PTR'];-const EMPTY_FORM = { name: '', type: 'A', ttl: 3600, records: '' };--const ZoneDetail = ({ zoneName, onClose, onChanged }) => {- const toast = useToast();-- const [zone, setZone] = useState(null);- const [dsRecords, setDsRecords] = useState([]);- const [delegation, setDelegation] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Record editor modal (add or edit — edit pre-fills, save is an upsert)- const [showRecordModal, setShowRecordModal] = useState(false);- const [recordForm, setRecordForm] = useState(EMPTY_FORM);-- const loadZone = useCallback(async () => {- setLoading(true);- try {- const data = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}`);- setZone(data.zone || null);- setDsRecords(data.ds_records || []);- setDelegation(data.delegation || null);- } catch (error) {- toast.error(`Failed to load zone: ${error.message}`);- } finally {- setLoading(false);- }- }, [zoneName, toast]);-- useEffect(() => {- loadZone();- }, [loadZone]);-- const openAdd = () => {- setRecordForm(EMPTY_FORM);- setShowRecordModal(true);- };-- const openEdit = (rrset) => {- setRecordForm({- name: rrset.name,- type: rrset.type,- ttl: rrset.ttl ?? 3600,- records: (rrset.records || []).join('\n'),- });- setShowRecordModal(true);- };-- const handleSaveRecord = async () => {- const values = recordForm.records.split('\n').map((v) => v.trim()).filter(Boolean);- if (!values.length) return;- setActionLoading(true);- try {- await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets`, {- method: 'POST',- body: {- name: recordForm.name.trim(),- type: recordForm.type,- ttl: Number(recordForm.ttl) || 3600,- records: values,- },- });- toast.success(`${recordForm.type} record set saved`);- setShowRecordModal(false);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`Failed to save record set: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteRecord = (rrset) => {- setConfirmDialog({- title: 'Delete record set',- message: `Delete the ${rrset.type} record set for ${rrset.name}?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- const qs = `name=${encodeURIComponent(rrset.name)}&type=${encodeURIComponent(rrset.type)}`;- await api.request(- `/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets?${qs}`,- { method: 'DELETE' }- );- toast.success(`${rrset.type} record set deleted`);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`Failed to delete record set: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleDnssec = async (enable) => {- setActionLoading(true);- try {- const res = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/dnssec`, {- method: 'POST',- body: { action: enable ? 'enable' : 'disable' },- });- toast.success(res.message || `DNSSEC ${enable ? 'enabled' : 'disabled'}`);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`DNSSEC update failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- return (- <div className="card dns-zone-detail">- <div className="card-header">- <h3 className="sk-cell-mono">{zoneName}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add Record- </Button>- <Button variant="outline" size="sm" onClick={loadZone}>- <RefreshCw size={14} /> Refresh- </Button>- <Button variant="secondary" size="sm" onClick={onClose}>- <X size={14} /> Close- </Button>- </div>- </div>- <div className="card-body">- {loading ? (- <p className="text-muted">Loading zone...</p>- ) : !zone ? (- <p className="text-muted">Zone could not be loaded.</p>- ) : (- <>- {/* ── Delegation banner ── */}- {delegation && (- <div- className={`dns-delegation dns-delegation--${- delegation.checked === false ? 'unknown' : delegation.delegated ? 'ok' : 'warn'- }`}- >- {delegation.checked === false ? (- <span>Delegation check unavailable: {delegation.note}</span>- ) : delegation.delegated ? (- <span>- Delegation looks correct — the public NS set matches this- zone ({(delegation.public_ns || []).join(', ')}).- </span>- ) : (- <span>- {delegation.note}{' '}- {delegation.public_ns?.length > 0 && (- <>Public: {delegation.public_ns.join(', ')} · Zone:{' '}- {(delegation.zone_ns || []).join(', ') || 'none'}</>- )}- </span>- )}- </div>- )}-- {/* ── Records ── */}- <table className="sk-dtable">- <thead>- <tr>- <th>Name</th>- <th>Type</th>- <th>TTL</th>- <th>Values</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {(zone.rrsets || []).map((r) => (- <tr key={`${r.name}|${r.type}`}>- <td className="sk-cell-mono">{r.name}</td>- <td><span className="sk-tag">{r.type}</span></td>- <td>{r.ttl ?? '—'}</td>- <td className="sk-cell-mono dns-values">- {(r.records || []).map((v) => <div key={v}>{v}</div>)}- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => openEdit(r)}>- Edit- </Button>{' '}- {r.type !== 'SOA' && (- <Button variant="secondary" size="sm" onClick={() => handleDeleteRecord(r)}>- Delete- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>-- {/* ── DNSSEC ── */}- <div className="dns-dnssec">- <div className="dns-dnssec__head">- <h4><ShieldCheck size={16} /> DNSSEC</h4>- <Pill kind={zone.dnssec ? 'green' : 'gray'}>- {zone.dnssec ? 'Enabled' : 'Disabled'}- </Pill>- <Button- variant={zone.dnssec ? 'secondary' : 'default'}- size="sm"- disabled={actionLoading}- onClick={() => handleDnssec(!zone.dnssec)}- >- {zone.dnssec ? 'Disable' : 'Enable'}- </Button>- </div>- {zone.dnssec && (- dsRecords.length > 0 ? (- <div className="dns-ds">- <p className="text-muted">- Publish these DS records at your registrar (the parent- zone) to complete the chain of trust:- </p>- {dsRecords.map((ds) => (- <code key={ds} className="dns-ds__record">{ds}</code>- ))}- </div>- ) : (- <p className="text-muted">- DNSSEC is enabled but no DS records were returned yet —- refresh in a moment.- </p>- )- )}- </div>- </>- )}- </div>-- {/* ── Record editor ── */}- <Modal- open={showRecordModal}- onClose={() => setShowRecordModal(false)}- title={`${recordForm.name ? 'Edit' : 'Add'} Record Set`}- >- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={recordForm.name}- onChange={(e) => setRecordForm((f) => ({ ...f, name: e.target.value }))}- placeholder={`@ or www (relative to ${zoneName})`}- />- </div>- <div className="form-group">- <Label>Type</Label>- <Select- value={recordForm.type}- onValueChange={(v) => setRecordForm((f) => ({ ...f, type: v }))}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {RECORD_TYPES.map((t) => (- <SelectItem key={t} value={t}>{t}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="form-group">- <Label>TTL (seconds)</Label>- <Input- type="number"- min={1}- max={604800}- value={recordForm.ttl}- onChange={(e) => setRecordForm((f) => ({ ...f, ttl: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Values (one per line)</Label>- <textarea- className="dns-record-values"- rows={4}- value={recordForm.records}- onChange={(e) => setRecordForm((f) => ({ ...f, records: e.target.value }))}- placeholder={'203.0.113.7\n203.0.113.8'}- />- <p className="text-muted">- Saving replaces the whole record set for this name + type.- </p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowRecordModal(false)}>Cancel</Button>- <Button- variant="default"- onClick={handleSaveRecord}- disabled={actionLoading || !recordForm.records.trim()}- >- {actionLoading ? 'Saving...' : 'Save Record Set'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default ZoneDetail;diff --git a/builtin-extensions/serverkit-dns-server/frontend/index.jsx b/builtin-extensions/serverkit-dns-server/frontend/index.jsxdeleted file mode 100644index 8e9bc6b1..00000000--- a/builtin-extensions/serverkit-dns-server/frontend/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// Authoritative DNS hosting UI, contributed through the extension system.-// Fully self-contained in the extension — no core page to wrap. After sync-// this folder lives at frontend/src/plugins/serverkit-dns-server/, so '@/…'-// host aliases resolve.-export { default as DnsServerPage } from './components/DnsServerPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.css b/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.cssdeleted file mode 100644index 738c42fa..00000000--- a/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.css+++ /dev/null@@ -1,92 +0,0 @@-/* DNS Server extension — layout-only styles; colors/typography inherit from- the host design system (card, sk-dtable, sk-info-row, empty-state…). */--.dns-server-page .dns-explainer {- margin: 12px 0;- padding-left: 20px;- display: flex;- flex-direction: column;- gap: 6px;-}--.dns-server-page .dns-install-form {- max-width: 480px;- margin-top: 16px;-}--.dns-server-page .dns-install-actions {- display: flex;- gap: 8px;- margin-top: 12px;-}--.dns-server-page .dns-zone-link {- background: none;- border: none;- padding: 0;- cursor: pointer;- font: inherit;- color: inherit;- text-decoration: underline;-}--.dns-server-page .dns-delegation {- border-radius: 8px;- padding: 10px 12px;- margin-bottom: 12px;- border: 1px solid currentColor;-}--.dns-server-page .dns-delegation--ok { opacity: 0.9; }-.dns-server-page .dns-delegation--warn { font-weight: 500; }-.dns-server-page .dns-delegation--unknown { opacity: 0.7; }--.dns-server-page .dns-values div {- line-height: 1.5;- word-break: break-all;-}--.dns-server-page .dns-dnssec {- margin-top: 16px;- padding-top: 12px;- border-top: 1px solid rgba(128, 128, 128, 0.25);-}--.dns-server-page .dns-dnssec__head {- display: flex;- align-items: center;- gap: 10px;-}--.dns-server-page .dns-dnssec__head h4 {- display: flex;- align-items: center;- gap: 6px;- margin: 0;-}--.dns-server-page .dns-ds {- margin-top: 10px;- display: flex;- flex-direction: column;- gap: 6px;-}--.dns-server-page .dns-ds__record {- display: block;- padding: 6px 8px;- border-radius: 6px;- word-break: break-all;- background: rgba(128, 128, 128, 0.12);-}--.dns-server-page .dns-record-values {- width: 100%;- font-family: inherit;- border-radius: 6px;- padding: 8px;- resize: vertical;- background: transparent;- color: inherit;- border: 1px solid rgba(128, 128, 128, 0.35);-}diff --git a/builtin-extensions/serverkit-dns-server/plugin.json b/builtin-extensions/serverkit-dns-server/plugin.jsondeleted file mode 100644index 4eedd6ce..00000000--- a/builtin-extensions/serverkit-dns-server/plugin.json+++ /dev/null@@ -1,40 +0,0 @@-{- "name": "serverkit-dns-server",- "display_name": "DNS Server",- "version": "1.0.0",- "description": "Host authoritative DNS on this box with PowerDNS (SQLite backend) in a managed Docker container, covering zones, records, DNSSEC, and delegation checks from the panel. Authoritative only (no recursion); complements provider integrations like Cloudflare, never replaces them. Built for homelab and air-gapped setups.",- "author": "ServerKit",- "license": "MIT",- "category": "networking",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["shell", "docker"],- "min_panel_version": "1.7.0",- "entry_point": "dns_server:dns_server_bp",- "url_prefix": "/api/v1/dns-server",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>",- "contributions": {- "nav": [- {- "id": "dns-server",- "label": "DNS Server",- "route": "/dns-server",- "category": "operations",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>"- }- ],- "routes": [- { "path": "dns-server", "component": "DnsServerPage" }- ],- "page_titles": {- "/dns-server": "DNS Server"- },- "command_palette": [- {- "label": "DNS Server",- "path": "/dns-server",- "category": "Pages",- "keywords": "dns server powerdns authoritative nameserver zones records dnssec delegation hosting"- }- ]- }-}diff --git a/builtin-extensions/serverkit-gpu/README.md b/builtin-extensions/serverkit-gpu/README.mddeleted file mode 100644index eb74385f..00000000--- a/builtin-extensions/serverkit-gpu/README.md+++ /dev/null@@ -1,47 +0,0 @@-# serverkit-gpu--Live NVIDIA GPU metrics (utilization, VRAM, temperature, power, fan) for servers-with a GPU. The first **CORE_SLIM** slice (plan 32 #7): both halves now live in-this extension.--## Layout--```-serverkit-gpu/- plugin.json # entry_point gpu:gpu_bp, url_prefix /api/v1/gpu, sdk_version ^1.0.0- backend/- __init__.py- gpu.py # blueprint (gpu_bp) — thin routing over the service- gpu_service.py # nvidia-smi parsing (no app.* imports)- frontend/- index.jsx # exports GpuMonitorPage (matched by contributions.routes)- components/GpuMonitor.jsx # the page UI (SDK + @/ imports)-```--The backend loads in-place as `app.plugins.serverkit-gpu` (mirrors the-CrowdSec/WordPress extraction). The frontend ships **baked**: pre-bundled into-`frontend/src/plugins/serverkit-gpu/` by `scripts/sync-builtin-frontends.mjs`-(the CI `--check` drift gate keeps source ↔ artifact in sync).--## Shipping as a runtime-ESM bundle (deferred — plan 32 #9)--This slice is intentionally kept on the **baked** path for one release-(CORE_SLIM dual-path guardrail). To later ship it as an external, no-rebuild-runtime bundle (the loader plan 32 hardens), follow-[docs/EXTENSIONS_CI.md](../../docs/EXTENSIONS_CI.md):--1. Add a `frontend/vite.config.mjs` (via `scripts/new-extension.mjs --template- frontend-esm`) that externalizes `react`, `react-dom`, `react/jsx-runtime`,- `react-router-dom`, `serverkit-sdk` and emits `dist/index.mjs`.-2. **Blocker to resolve first:** `GpuMonitor.jsx` imports `EmptyState` and- `Button` from the host via the `@/` alias — these are NOT on the SDK surface,- so an externalized build can't resolve them. Either promote both into- `serverkit-sdk` (a deliberate SDK **minor** bump) or bundle equivalents into- the extension. `_gpu.scss` (core design-system SCSS) must likewise move into- the bundle's inlined CSS.-3. Set `frontend_entry: dist/index.mjs`, cut a release + `sha256`, and swap the- registry entry — the operator runbook- [docs/runbooks/extension-release-and-tamper-e2e.md](../../docs/runbooks/extension-release-and-tamper-e2e.md)- covers publishing + the tamper e2e.--Until then the baked path serves the page and the runtime loader is unaffected.diff --git a/builtin-extensions/serverkit-gpu/backend/__init__.py b/builtin-extensions/serverkit-gpu/backend/__init__.pydeleted file mode 100644index 8234c5c7..00000000--- a/builtin-extensions/serverkit-gpu/backend/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""ServerKit GPU Monitor extension backend package."""diff --git a/builtin-extensions/serverkit-gpu/backend/gpu.py b/builtin-extensions/serverkit-gpu/backend/gpu.pydeleted file mode 100644index 9b88e12d..00000000--- a/builtin-extensions/serverkit-gpu/backend/gpu.py+++ /dev/null@@ -1,20 +0,0 @@-"""GPU Monitor API endpoints (serverkit-gpu extension).--Mounted under ``/api/v1/gpu`` via the manifest's ``entry_point`` + ``url_prefix``-(the same prefix the core route used, so the frontend is unchanged — decision D9).-Thin routing layer over :class:`GpuService`; read-only metrics, JWT-protected.-"""-from flask import Blueprint, jsonify-from flask_jwt_extended import jwt_required--from .gpu_service import GpuService--gpu_bp = Blueprint('gpu', __name__)---@gpu_bp.route('/', methods=['GET'])-@jwt_required()-def gpu_info():- """Per-GPU stats (utilization, VRAM, temperature, power, fan, driver) plus- the GPU compute processes, with best-effort container resolution."""- return jsonify(GpuService.info())diff --git a/builtin-extensions/serverkit-gpu/backend/gpu_service.py b/builtin-extensions/serverkit-gpu/backend/gpu_service.pydeleted file mode 100644index 342417d3..00000000--- a/builtin-extensions/serverkit-gpu/backend/gpu_service.py+++ /dev/null@@ -1,130 +0,0 @@-"""NVIDIA GPU monitoring (serverkit-gpu extension).--Moved out of core as the first CORE_SLIM slice (plan 32 #7). Shells out to-``nvidia-smi`` (like the rest of the service layer) and degrades gracefully to-"no GPUs" when it isn't present, so the panel stays happy on GPU-less hosts.-"""-import logging-import re-import subprocess--logger = logging.getLogger(__name__)--# (key, caster) in the same order as GPU_QUERY below.-GPU_FIELDS = [- ('index', int),- ('name', str),- ('utilization_gpu', float), # %- ('memory_used', float), # MiB- ('memory_total', float), # MiB- ('temperature', float), # C- ('power_draw', float), # W- ('power_limit', float), # W- ('fan_speed', float), # %- ('driver_version', str),-]-GPU_QUERY = ('index,name,utilization.gpu,memory.used,memory.total,'- 'temperature.gpu,power.draw,power.limit,fan.speed,driver_version')--_NA = ('', '[N/A]', 'N/A', '[Not Supported]', '[Unknown Error]')---class GpuService:-- @staticmethod- def _run(args, timeout=10):- return subprocess.run(['nvidia-smi', *args], capture_output=True, text=True, timeout=timeout)-- @staticmethod- def _coerce(value, caster):- v = value.strip()- if v in _NA:- return None- try:- return caster(v)- except (ValueError, TypeError):- return v if caster is str else None-- @classmethod- def available(cls):- try:- return cls._run(['--query-gpu=index', '--format=csv,noheader']).returncode == 0- except Exception:- return False-- @classmethod- def list_gpus(cls):- try:- result = cls._run([f'--query-gpu={GPU_QUERY}', '--format=csv,noheader,nounits'])- if result.returncode != 0:- return []- except Exception:- return []-- gpus = []- for line in result.stdout.strip().splitlines():- if not line.strip():- continue- parts = [p.strip() for p in line.split(',')]- if len(parts) < len(GPU_FIELDS):- continue- gpu = {key: cls._coerce(raw, caster)- for (key, caster), raw in zip(GPU_FIELDS, parts)}- if gpu.get('memory_total'):- gpu['memory_percent'] = round(100.0 * (gpu.get('memory_used') or 0) / gpu['memory_total'], 1)- gpus.append(gpu)- return gpus-- @classmethod- def _container_for_pid(cls, pid):- """Best-effort: resolve a host PID to a Docker container name via its- cgroup. Returns None when it can't be determined (or off Linux)."""- if not pid:- return None- try:- with open(f'/proc/{pid}/cgroup', 'r') as fh:- match = re.search(r'docker[-/]([0-9a-f]{64})', fh.read())- if not match:- return None- cid = match.group(1)[:12]- out = subprocess.run(['docker', 'inspect', '-f', '{{.Name}}', cid],- capture_output=True, text=True, timeout=5)- return out.stdout.strip().lstrip('/') if out.returncode == 0 else cid- except Exception:- return None-- @classmethod- def processes(cls):- try:- result = cls._run(['--query-compute-apps=gpu_uuid,pid,process_name,used_memory',- '--format=csv,noheader,nounits'])- if result.returncode != 0:- return []- except Exception:- return []-- procs = []- for line in result.stdout.strip().splitlines():- if not line.strip():- continue- parts = [p.strip() for p in line.split(',')]- if len(parts) < 4:- continue- pid = cls._coerce(parts[1], int)- procs.append({- 'gpu_uuid': parts[0],- 'pid': pid,- 'process_name': parts[2],- 'used_memory': cls._coerce(parts[3], float),- 'container': cls._container_for_pid(pid),- })- return procs-- @classmethod- def info(cls):- gpus = cls.list_gpus()- return {- 'available': bool(gpus),- 'gpus': gpus,- 'processes': cls.processes() if gpus else [],- }diff --git a/builtin-extensions/serverkit-gpu/frontend/components/GpuMonitor.jsx b/builtin-extensions/serverkit-gpu/frontend/components/GpuMonitor.jsxdeleted file mode 100644index 1dca0948..00000000--- a/builtin-extensions/serverkit-gpu/frontend/components/GpuMonitor.jsx+++ /dev/null@@ -1,202 +0,0 @@-// GPU Monitor page — the serverkit-gpu extension's UI, moved out of core as the-// first CORE_SLIM slice (plan 32 #7). Imports come from the SDK (PageTopbar,-// KpiBand, api, useToast); EmptyState + Button are host components not yet on the-// SDK surface, so they resolve via the `@/` alias (fine for the baked path — a-// future runtime-ESM build would bundle them or promote them into the SDK).-import { useState, useEffect, useCallback } from 'react';-import { Cpu, RefreshCw, Thermometer, Zap, Fan } from 'lucide-react';-import { PageTopbar, KpiBand, api, useToast } from 'serverkit-sdk';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';--function clampPercent(value) {- const n = Number(value);- if (!Number.isFinite(n)) return 0;- return Math.min(100, Math.max(0, n));-}--function utilTone(percent) {- if (percent >= 85) return 'is-red';- if (percent >= 60) return 'is-amber';- return 'is-green';-}--function formatMib(value) {- const n = Number(value);- if (!Number.isFinite(n)) return '—';- if (n >= 1024) return `${(n / 1024).toFixed(1)} GiB`;- return `${Math.round(n)} MiB`;-}--const GpuCard = ({ gpu }) => {- const util = clampPercent(gpu.utilization_gpu);- const memPercent = clampPercent(- gpu.memory_percent != null- ? gpu.memory_percent- : (gpu.memory_total ? (gpu.memory_used / gpu.memory_total) * 100 : 0)- );-- return (- <div className="gpu-card">- <div className="gpu-card__head">- <div className="gpu-card__title">- <Cpu size={16} />- <span className="gpu-card__name">{gpu.name || `GPU ${gpu.index}`}</span>- </div>- <span className="gpu-card__index">#{gpu.index}</span>- </div>-- <div className="gpu-card__bars">- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">GPU Utilization</span>- <span className="gpu-bar__value">{util}%</span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(util)}`} style={{ width: `${util}%` }} />- </div>- </div>-- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">VRAM</span>- <span className="gpu-bar__value">- {formatMib(gpu.memory_used)} / {formatMib(gpu.memory_total)} ({Math.round(memPercent)}%)- </span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(memPercent)}`} style={{ width: `${memPercent}%` }} />- </div>- </div>- </div>-- <div className="gpu-stats">- <div className="gpu-stat">- <Thermometer size={14} />- <span className="gpu-stat__label">Temp</span>- <span className="gpu-stat__value">- {gpu.temperature != null ? `${gpu.temperature}°C` : '—'}- </span>- </div>- <div className="gpu-stat">- <Zap size={14} />- <span className="gpu-stat__label">Power</span>- <span className="gpu-stat__value">- {gpu.power_draw != null ? `${Math.round(gpu.power_draw)}W` : '—'}- {gpu.power_limit != null && (- <span className="gpu-stat__sub"> / {Math.round(gpu.power_limit)}W</span>- )}- </span>- </div>- <div className="gpu-stat">- <Fan size={14} />- <span className="gpu-stat__label">Fan</span>- <span className="gpu-stat__value">- {gpu.fan_speed != null ? `${gpu.fan_speed}%` : '—'}- </span>- </div>- <div className="gpu-stat">- <Cpu size={14} />- <span className="gpu-stat__label">Driver</span>- <span className="gpu-stat__value">{gpu.driver_version || '—'}</span>- </div>- </div>- </div>- );-};--const GpuMonitor = () => {- const toast = useToast();- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);-- const load = useCallback(async (isRefresh = false) => {- if (isRefresh) setRefreshing(true);- try {- const result = await api.getGpuInfo();- setData(result);- } catch (err) {- if (isRefresh) toast.error(err.message || 'Failed to load GPU info');- console.error('Failed to load GPU info:', err);- } finally {- setLoading(false);- setRefreshing(false);- }- }, [toast]);-- useEffect(() => { load(); }, [load]);-- const gpus = data?.gpus || [];- const processes = data?.processes || [];-- return (- <div className="page-container gpu-page">- <PageTopbar- icon={<Cpu size={18} />}- title="GPU Monitor"- meta={data?.available ? `${gpus.length} GPU${gpus.length !== 1 ? 's' : ''}` : undefined}- actions={- <Button variant="outline" size="sm" onClick={() => load(true)} disabled={refreshing}>- <RefreshCw size={15} />- {refreshing ? 'Refreshing…' : 'Refresh'}- </Button>- }- />-- {loading ? (- <EmptyState loading title="Loading GPU data" />- ) : !data?.available ? (- <EmptyState- icon={Cpu}- size="lg"- title="No NVIDIA GPU detected"- description="This host has no NVIDIA GPU, or the NVIDIA drivers / nvidia-smi are not available."- />- ) : (- <>- {/* Custom live-meter tiles kept per Plan 20 Decision 5 — band supplies grid/spacing only */}- <KpiBand max={5}>- {gpus.map((gpu) => (- <GpuCard key={gpu.index} gpu={gpu} />- ))}- </KpiBand>-- <div className="gpu-procs">- <div className="gpu-procs__head">- <h2>GPU Processes</h2>- <span className="text-muted">{processes.length} running</span>- </div>- <table className="sk-dtable gpu-procs__table">- <thead>- <tr>- <th>PID</th>- <th>Process</th>- <th>Container</th>- <th>VRAM</th>- </tr>- </thead>- <tbody>- {processes.map((proc, i) => (- <tr key={`${proc.pid}-${i}`}>- <td className="sk-cell-mono">{proc.pid}</td>- <td>{proc.process_name || '—'}</td>- <td>{proc.container || '—'}</td>- <td className="sk-cell-mono">{formatMib(proc.used_memory)}</td>- </tr>- ))}- {processes.length === 0 && (- <tr>- <td colSpan={4} className="text-center text-muted">No active GPU processes</td>- </tr>- )}- </tbody>- </table>- </div>- </>- )}- </div>- );-};--export default GpuMonitor;diff --git a/builtin-extensions/serverkit-gpu/frontend/index.jsx b/builtin-extensions/serverkit-gpu/frontend/index.jsxdeleted file mode 100644index 481f84aa..00000000--- a/builtin-extensions/serverkit-gpu/frontend/index.jsx+++ /dev/null@@ -1,11 +0,0 @@-// GPU Monitor, contributed through the extension system. As of the first-// CORE_SLIM slice (plan 32 #7) the page component lives INSIDE the extension-// (./components/GpuMonitor) and its /api/v1/gpu backend is bridged from-// builtin-extensions/serverkit-gpu/backend — the core page + core blueprint are-// gone. The extension owns the /gpu route + sidebar/palette entries via its-// manifest, and declares an sdk_version range for the runtime SDK gate.-import GpuMonitor from './components/GpuMonitor';--export function GpuMonitorPage() {- return <GpuMonitor />;-}diff --git a/builtin-extensions/serverkit-gpu/plugin.json b/builtin-extensions/serverkit-gpu/plugin.jsondeleted file mode 100644index 07e791cf..00000000--- a/builtin-extensions/serverkit-gpu/plugin.json+++ /dev/null@@ -1,44 +0,0 @@-{- "name": "serverkit-gpu",- "display_name": "GPU Monitor",- "version": "1.0.0",- "description": "Live NVIDIA GPU metrics covering utilization, memory, temperature, power and fan, for servers with a GPU.",- "author": "ServerKit",- "license": "MIT",- "category": "monitoring",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["shell"],- "min_panel_version": "1.7.0",- "featured": true,- "feature_score": 60,- "sdk_version": "^1.0.0",- "entry_point": "gpu:gpu_bp",- "url_prefix": "/api/v1/gpu",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>",- "contributions": {- "nav": [- {- "id": "gpu",- "label": "GPU Monitor",- "route": "/gpu",- "category": "system",- "requiresCondition": "gpuAvailable",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>"- }- ],- "routes": [- { "path": "gpu", "component": "GpuMonitorPage" }- ],- "page_titles": {- "/gpu": "GPU Monitor"- },- "command_palette": [- {- "label": "GPU Monitor",- "path": "/gpu",- "category": "Pages",- "keywords": "nvidia cuda metrics gpu"- }- ]- }-}diff --git a/builtin-extensions/serverkit-k8s/backend/__init__.py b/builtin-extensions/serverkit-k8s/backend/__init__.pydeleted file mode 100644index c7cb3d27..00000000--- a/builtin-extensions/serverkit-k8s/backend/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-"""ServerKit Kubernetes extension backend package (kubectl engine)."""-from .k8s import k8s_bp--__all__ = ['k8s_bp']diff --git a/builtin-extensions/serverkit-k8s/backend/cluster_service.py b/builtin-extensions/serverkit-k8s/backend/cluster_service.pydeleted file mode 100644index d2ba464f..00000000--- a/builtin-extensions/serverkit-k8s/backend/cluster_service.py+++ /dev/null@@ -1,365 +0,0 @@-"""High-level operations for the serverkit-k8s extension.--This is the layer the blueprint calls. It owns:--- CRUD for saved cluster connections (:class:`K8sCluster` rows), including the- single-default invariant.-- ``test_connection`` -- probe ``kubectl version`` and cache the result on the row.-- Read helpers (nodes, namespaces, workloads, pods, logs, services, ingresses,- overview) that run ``kubectl get ... -o json`` and **normalize** the verbose- Kubernetes objects down to the small flat dicts the UI actually consumes.-- Mutations (scale, restart, delete, apply) as thin ``kubectl`` wrappers.--Nothing here trusts the cluster to stay reachable: every read that hits the-cluster is wrapped by the blueprint and surfaces a clean error rather than a-stack trace.-"""-import json-import logging-from datetime import datetime--from app import db--from .models import K8sCluster-from . import kubectl_service-from .kubectl_service import KubectlError--logger = logging.getLogger(__name__)---# ---------------------------------------------------------------------------# CRUD-# ---------------------------------------------------------------------------def list_clusters():- return [c.to_dict() for c in K8sCluster.query.order_by(K8sCluster.name.asc()).all()]---def get_cluster(cluster_id):- return K8sCluster.query.get(cluster_id)---def get_default_cluster():- return (K8sCluster.query.filter_by(is_default=True).first()- or K8sCluster.query.order_by(K8sCluster.id.asc()).first())---def create_cluster(name, kubeconfig, context=None, make_default=False):- name = (name or '').strip()- if not name:- raise ValueError('A cluster name is required.')- if not (kubeconfig or '').strip():- raise ValueError('A kubeconfig is required.')- if K8sCluster.query.filter_by(name=name).first():- raise ValueError(f'A cluster named "{name}" already exists.')-- cluster = K8sCluster(name=name, context=(context or None) or None)- cluster.set_kubeconfig(kubeconfig)-- # First cluster is default automatically; otherwise honor the flag.- if make_default or K8sCluster.query.count() == 0:- _clear_default()- cluster.is_default = True-- db.session.add(cluster)- db.session.commit()- return cluster---def update_cluster(cluster_id, name=None, kubeconfig=None, context=None):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- if name is not None:- name = name.strip()- if not name:- raise ValueError('A cluster name is required.')- existing = K8sCluster.query.filter_by(name=name).first()- if existing and existing.id != cluster.id:- raise ValueError(f'A cluster named "{name}" already exists.')- cluster.name = name- if kubeconfig is not None and kubeconfig.strip():- cluster.set_kubeconfig(kubeconfig)- if context is not None:- cluster.context = context.strip() or None- db.session.commit()- return cluster---def delete_cluster(cluster_id):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- was_default = cluster.is_default- db.session.delete(cluster)- db.session.commit()- # Promote another cluster to default if we removed the default one.- if was_default:- nxt = K8sCluster.query.order_by(K8sCluster.id.asc()).first()- if nxt:- nxt.is_default = True- db.session.commit()- return True---def set_default(cluster_id):- cluster = get_cluster(cluster_id)- if not cluster:- raise ValueError('Cluster not found.')- _clear_default()- cluster.is_default = True- db.session.commit()- return cluster---def _clear_default():- for c in K8sCluster.query.filter_by(is_default=True).all():- c.is_default = False---# ---------------------------------------------------------------------------# Connectivity-# ---------------------------------------------------------------------------def test_connection(cluster):- """Probe the cluster and cache the result on the row. Never raises."""- result = {'ok': False, 'server_version': None, 'error': None}- try:- data = kubectl_service.run_json(cluster, ['version', '-o', 'json'], timeout=15)- server = (data or {}).get('serverVersion') or {}- version = server.get('gitVersion')- if not version:- raise KubectlError('cluster did not report a server version (unreachable?)')- result['ok'] = True- result['server_version'] = version- except KubectlError as e:- result['error'] = str(e)- except Exception as e: # noqa: BLE001 - defensive: never let a probe crash the request- result['error'] = str(e)-- cluster.last_reachable = result['ok']- cluster.last_status = json.dumps({'server_version': result['server_version'], 'error': result['error']})- cluster.last_checked_at = datetime.utcnow()- db.session.commit()- return result---# ---------------------------------------------------------------------------# Reads (normalized)-# ---------------------------------------------------------------------------def _items(cluster, args):- data = kubectl_service.run_json(cluster, args)- return (data or {}).get('items', []) or []---def _ns_args(namespace):- if namespace and namespace != 'all':- return ['-n', namespace]- return ['--all-namespaces']---def get_nodes(cluster):- out = []- for n in _items(cluster, ['get', 'nodes', '-o', 'json']):- meta = n.get('metadata', {})- status = n.get('status', {})- conditions = {c.get('type'): c.get('status') for c in status.get('conditions', [])}- ready = conditions.get('Ready') == 'True'- info = status.get('nodeInfo', {})- roles = [k.split('/', 1)[1] for k in meta.get('labels', {})- if k.startswith('node-role.kubernetes.io/')]- out.append({- 'name': meta.get('name'),- 'ready': ready,- 'roles': roles or ['worker'],- 'kubelet_version': info.get('kubeletVersion'),- 'os_image': info.get('osImage'),- 'kernel_version': info.get('kernelVersion'),- 'container_runtime': info.get('containerRuntimeVersion'),- 'cpu': status.get('capacity', {}).get('cpu'),- 'memory': status.get('capacity', {}).get('memory'),- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_namespaces(cluster):- out = []- for ns in _items(cluster, ['get', 'namespaces', '-o', 'json']):- meta = ns.get('metadata', {})- out.append({- 'name': meta.get('name'),- 'phase': ns.get('status', {}).get('phase'),- 'created_at': meta.get('creationTimestamp'),- })- return out---_WORKLOAD_KINDS = {- 'deployment': 'deployments',- 'statefulset': 'statefulsets',- 'daemonset': 'daemonsets',-}---def get_workloads(cluster, namespace='all', kind='deployment'):- resource = _WORKLOAD_KINDS.get(kind, 'deployments')- out = []- for w in _items(cluster, ['get', resource] + _ns_args(namespace) + ['-o', 'json']):- meta = w.get('metadata', {})- spec = w.get('spec', {})- status = w.get('status', {})- if resource == 'daemonsets':- desired = status.get('desiredNumberScheduled', 0)- ready = status.get('numberReady', 0)- else:- desired = spec.get('replicas', 0)- ready = status.get('readyReplicas', 0) or 0- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'kind': kind,- 'desired': desired,- 'ready': ready,- 'available': status.get('availableReplicas', ready) if resource != 'daemonsets' else status.get('numberAvailable', ready),- 'healthy': bool(desired) and ready == desired,- 'images': [c.get('image') for c in spec.get('template', {}).get('spec', {}).get('containers', [])],- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_pods(cluster, namespace='all'):- out = []- for p in _items(cluster, ['get', 'pods'] + _ns_args(namespace) + ['-o', 'json']):- meta = p.get('metadata', {})- status = p.get('status', {})- container_statuses = status.get('containerStatuses', []) or []- restarts = sum(cs.get('restartCount', 0) for cs in container_statuses)- ready_count = sum(1 for cs in container_statuses if cs.get('ready'))- total = len(container_statuses) or len(p.get('spec', {}).get('containers', []))- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'phase': status.get('phase'),- 'ready': f'{ready_count}/{total}',- 'restarts': restarts,- 'node': p.get('spec', {}).get('nodeName'),- 'pod_ip': status.get('podIP'),- 'containers': [c.get('name') for c in p.get('spec', {}).get('containers', [])],- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_pod_logs(cluster, namespace, pod, container=None, tail=200):- args = ['logs', pod, '-n', namespace, '--tail', str(int(tail))]- if container:- args += ['-c', container]- return kubectl_service.run(cluster, args, timeout=30)---def get_services(cluster, namespace='all'):- out = []- for s in _items(cluster, ['get', 'services'] + _ns_args(namespace) + ['-o', 'json']):- meta = s.get('metadata', {})- spec = s.get('spec', {})- ports = ['{}/{}'.format(p.get('port'), p.get('protocol', 'TCP')) for p in spec.get('ports', [])]- ingress = s.get('status', {}).get('loadBalancer', {}).get('ingress', []) or []- external = ', '.join(filter(None, [i.get('ip') or i.get('hostname') for i in ingress])) or None- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'type': spec.get('type'),- 'cluster_ip': spec.get('clusterIP'),- 'external_ip': external,- 'ports': ports,- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_ingresses(cluster, namespace='all'):- out = []- for ing in _items(cluster, ['get', 'ingresses'] + _ns_args(namespace) + ['-o', 'json']):- meta = ing.get('metadata', {})- spec = ing.get('spec', {})- hosts = [r.get('host') for r in spec.get('rules', []) if r.get('host')]- out.append({- 'name': meta.get('name'),- 'namespace': meta.get('namespace'),- 'class': spec.get('ingressClassName'),- 'hosts': hosts,- 'created_at': meta.get('creationTimestamp'),- })- return out---def get_overview(cluster):- """A compact dashboard payload. Best-effort; partial data on partial failure."""- overview = {- 'cluster': cluster.to_dict(),- 'reachable': False,- 'server_version': None,- 'counts': {'nodes': 0, 'nodes_ready': 0, 'namespaces': 0, 'pods': 0, 'pods_running': 0, 'deployments': 0},- 'error': None,- }- conn = test_connection(cluster)- overview['reachable'] = conn['ok']- overview['server_version'] = conn['server_version']- if not conn['ok']:- overview['error'] = conn['error']- return overview- try:- nodes = get_nodes(cluster)- namespaces = get_namespaces(cluster)- pods = get_pods(cluster, 'all')- deployments = get_workloads(cluster, 'all', 'deployment')- overview['counts'] = {- 'nodes': len(nodes),- 'nodes_ready': sum(1 for n in nodes if n['ready']),- 'namespaces': len(namespaces),- 'pods': len(pods),- 'pods_running': sum(1 for p in pods if p['phase'] == 'Running'),- 'deployments': len(deployments),- }- except KubectlError as e:- overview['error'] = str(e)- return overview---# ---------------------------------------------------------------------------# Mutations-# ---------------------------------------------------------------------------def scale_deployment(cluster, namespace, name, replicas):- replicas = int(replicas)- if replicas < 0:- raise ValueError('replicas must be >= 0')- kubectl_service.run(- cluster,- ['scale', 'deployment', name, '-n', namespace, f'--replicas={replicas}'],- )- return {'name': name, 'namespace': namespace, 'replicas': replicas}---def restart_deployment(cluster, namespace, name):- kubectl_service.run(cluster, ['rollout', 'restart', 'deployment', name, '-n', namespace])- return {'name': name, 'namespace': namespace, 'restarted': True}---_DELETABLE_KINDS = {'pod', 'deployment', 'statefulset', 'daemonset', 'service', 'ingress'}---def delete_resource(cluster, kind, name, namespace):- kind = (kind or '').lower()- if kind not in _DELETABLE_KINDS:- raise ValueError(f'Refusing to delete unsupported resource kind "{kind}".')- if not name or not namespace:- raise ValueError('name and namespace are required.')- kubectl_service.run(cluster, ['delete', kind, name, '-n', namespace])- return {'kind': kind, 'name': name, 'namespace': namespace, 'deleted': True}---def apply_manifest(cluster, manifest_text):- if not (manifest_text or '').strip():- raise ValueError('An empty manifest cannot be applied.')- out = kubectl_service.run(cluster, ['apply', '-f', '-'], input_text=manifest_text, timeout=60)- return {'output': out.strip()}diff --git a/builtin-extensions/serverkit-k8s/backend/k8s.py b/builtin-extensions/serverkit-k8s/backend/k8s.pydeleted file mode 100644index 7d67087d..00000000--- a/builtin-extensions/serverkit-k8s/backend/k8s.py+++ /dev/null@@ -1,277 +0,0 @@-"""Kubernetes API endpoints (serverkit-k8s extension).--Mounted under ``/api/v1/k8s`` via the manifest's ``url_prefix``. Thin routing-layer over :mod:`cluster_service` -- all kubectl work happens there. Reads need-viewer, mutations need admin (same split as the serverkit-mail and-serverkit-dns-server extensions).--Cluster CRUD works even when ``kubectl`` is absent so an operator can stage a-connection first; only routes that actually talk to a cluster are guarded by-``_kubectl_or_error`` (503 when the binary is missing).-"""-from flask import Blueprint, jsonify, request--from app.middleware.rbac import admin_required, viewer_required--from . import cluster_service-from . import kubectl_service-from .kubectl_service import KubectlError--k8s_bp = Blueprint('k8s', __name__)---def _kubectl_or_error():- if not kubectl_service.is_available():- return jsonify({- 'error': 'kubectl is not installed on the panel host. Install kubectl '- 'to talk to clusters.'- }), 503- return None---def _cluster_or_404(cluster_id):- return cluster_service.get_cluster(cluster_id)---def _kubectl_call(fn):- """Run a cluster read/mutation, converting KubectlError to a clean 502."""- try:- return jsonify(fn())- except KubectlError as e:- return jsonify({'error': str(e)}), 502- except ValueError as e:- return jsonify({'error': str(e)}), 400---# ---------------------------------------------------------------------------# Status + cluster CRUD (no kubectl required)-# ---------------------------------------------------------------------------@k8s_bp.route('/status', methods=['GET'])-@viewer_required-def status():- default = cluster_service.get_default_cluster()- return jsonify({- 'kubectl_available': kubectl_service.is_available(),- 'clusters': cluster_service.list_clusters(),- 'default_cluster_id': default.id if default else None,- })---@k8s_bp.route('/clusters', methods=['GET'])-@viewer_required-def list_clusters():- return jsonify({'clusters': cluster_service.list_clusters()})---@k8s_bp.route('/clusters', methods=['POST'])-@admin_required-def create_cluster():- data = request.get_json(silent=True) or {}- try:- cluster = cluster_service.create_cluster(- name=data.get('name'),- kubeconfig=data.get('kubeconfig'),- context=data.get('context'),- make_default=bool(data.get('make_default')),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(cluster.to_dict()), 201---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['GET'])-@viewer_required-def get_cluster(cluster_id):- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster.to_dict())---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['PUT'])-@admin_required-def update_cluster(cluster_id):- data = request.get_json(silent=True) or {}- try:- cluster = cluster_service.update_cluster(- cluster_id,- name=data.get('name'),- kubeconfig=data.get('kubeconfig'),- context=data.get('context'),- )- except ValueError as e:- code = 404 if 'not found' in str(e).lower() else 400- return jsonify({'error': str(e)}), code- return jsonify(cluster.to_dict())---@k8s_bp.route('/clusters/<int:cluster_id>', methods=['DELETE'])-@admin_required-def delete_cluster(cluster_id):- try:- cluster_service.delete_cluster(cluster_id)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify({'deleted': True})---@k8s_bp.route('/clusters/<int:cluster_id>/default', methods=['POST'])-@admin_required-def set_default(cluster_id):- try:- cluster = cluster_service.set_default(cluster_id)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify(cluster.to_dict())---# ---------------------------------------------------------------------------# Cluster-talking routes (kubectl required)-# ---------------------------------------------------------------------------@k8s_bp.route('/clusters/<int:cluster_id>/test', methods=['POST'])-@viewer_required-def test_connection(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster_service.test_connection(cluster))---@k8s_bp.route('/clusters/<int:cluster_id>/overview', methods=['GET'])-@viewer_required-def overview(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- return jsonify(cluster_service.get_overview(cluster))---def _read_route(cluster_id, fn_name):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- namespace = request.args.get('namespace', 'all')- fn = getattr(cluster_service, fn_name)- if fn_name in ('get_nodes', 'get_namespaces'):- return _kubectl_call(lambda: {'items': fn(cluster)})- return _kubectl_call(lambda: {'items': fn(cluster, namespace)})---@k8s_bp.route('/clusters/<int:cluster_id>/nodes', methods=['GET'])-@viewer_required-def nodes(cluster_id):- return _read_route(cluster_id, 'get_nodes')---@k8s_bp.route('/clusters/<int:cluster_id>/namespaces', methods=['GET'])-@viewer_required-def namespaces(cluster_id):- return _read_route(cluster_id, 'get_namespaces')---@k8s_bp.route('/clusters/<int:cluster_id>/pods', methods=['GET'])-@viewer_required-def pods(cluster_id):- return _read_route(cluster_id, 'get_pods')---@k8s_bp.route('/clusters/<int:cluster_id>/services', methods=['GET'])-@viewer_required-def services(cluster_id):- return _read_route(cluster_id, 'get_services')---@k8s_bp.route('/clusters/<int:cluster_id>/ingresses', methods=['GET'])-@viewer_required-def ingresses(cluster_id):- return _read_route(cluster_id, 'get_ingresses')---@k8s_bp.route('/clusters/<int:cluster_id>/workloads', methods=['GET'])-@viewer_required-def workloads(cluster_id):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- namespace = request.args.get('namespace', 'all')- kind = request.args.get('kind', 'deployment')- return _kubectl_call(lambda: {'items': cluster_service.get_workloads(cluster, namespace, kind)})---@k8s_bp.route('/clusters/<int:cluster_id>/pods/<namespace>/<pod>/logs', methods=['GET'])-@viewer_required-def pod_logs(cluster_id, namespace, pod):- guard = _kubectl_or_error()- if guard:- return guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return jsonify({'error': 'Cluster not found'}), 404- container = request.args.get('container')- tail = request.args.get('tail', 200)- return _kubectl_call(lambda: {'logs': cluster_service.get_pod_logs(cluster, namespace, pod, container, tail)})---# ---------------------------------------------------------------------------# Mutations (admin + kubectl required)-# ---------------------------------------------------------------------------def _mutation_setup(cluster_id):- guard = _kubectl_or_error()- if guard:- return None, guard- cluster = _cluster_or_404(cluster_id)- if not cluster:- return None, (jsonify({'error': 'Cluster not found'}), 404)- return cluster, None---@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/scale', methods=['POST'])-@admin_required-def scale(cluster_id, namespace, name):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.scale_deployment(cluster, namespace, name, data.get('replicas', 0)))---@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/restart', methods=['POST'])-@admin_required-def restart(cluster_id, namespace, name):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- return _kubectl_call(lambda: cluster_service.restart_deployment(cluster, namespace, name))---@k8s_bp.route('/clusters/<int:cluster_id>/delete-resource', methods=['POST'])-@admin_required-def delete_resource(cluster_id):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.delete_resource(- cluster, data.get('kind'), data.get('name'), data.get('namespace')))---@k8s_bp.route('/clusters/<int:cluster_id>/apply', methods=['POST'])-@admin_required-def apply(cluster_id):- cluster, err = _mutation_setup(cluster_id)- if err:- return err- data = request.get_json(silent=True) or {}- return _kubectl_call(lambda: cluster_service.apply_manifest(cluster, data.get('manifest')))diff --git a/builtin-extensions/serverkit-k8s/backend/kubectl_service.py b/builtin-extensions/serverkit-k8s/backend/kubectl_service.pydeleted file mode 100644index 5824a40e..00000000--- a/builtin-extensions/serverkit-k8s/backend/kubectl_service.py+++ /dev/null@@ -1,127 +0,0 @@-"""Low-level ``kubectl`` engine for the serverkit-k8s extension.--Every cluster operation runs the real ``kubectl`` binary against a per-cluster-kubeconfig that we materialize to a private temp file for the duration of one-call and delete immediately after (never left on disk between calls). This keeps-the panel host free of any standing cluster credentials.--Nothing here is Linux-specific -- ``kubectl`` runs on any OS -- so the extension-is not platform-gated. The temp-file ``chmod 0600`` is guarded with-``os.name != 'nt'`` per the repo's platform rule.-"""-import json-import logging-import os-import subprocess-import tempfile--logger = logging.getLogger(__name__)--KUBECTL_BIN = 'kubectl'-DEFAULT_TIMEOUT = 30---class KubectlError(RuntimeError):- """Raised when a kubectl invocation fails (non-zero exit)."""-- def __init__(self, message, returncode=None, stderr=None):- super().__init__(message)- self.returncode = returncode- self.stderr = stderr---def is_available():- """Return True if the ``kubectl`` binary is on the host."""- try:- from app.utils.system import is_command_available- return is_command_available(KUBECTL_BIN)- except Exception: # pragma: no cover - fall back to a direct probe- from shutil import which- return which(KUBECTL_BIN) is not None---def _write_kubeconfig(kubeconfig_text):- """Write *kubeconfig_text* to a private temp file and return its path."""- fd, path = tempfile.mkstemp(prefix='sk8s-', suffix='.yaml')- try:- with os.fdopen(fd, 'w', encoding='utf-8') as fh:- fh.write(kubeconfig_text or '')- if os.name != 'nt':- os.chmod(path, 0o600)- except Exception:- _safe_unlink(path)- raise- return path---def _safe_unlink(path):- try:- if path and os.path.exists(path):- os.unlink(path)- except OSError as e: # pragma: no cover - best effort cleanup- logger.warning('serverkit-k8s: could not remove temp kubeconfig %s: %s', path, e)---def build_argv(cluster, args):- """Return the full ``kubectl`` argv for *args* against *cluster*.-- Separated out so tests can assert on argv construction without running the- binary. The ``--kubeconfig`` path is appended by :func:`run` since it is only- known once the temp file is written.- """- argv = [KUBECTL_BIN]- if getattr(cluster, 'context', None):- argv += ['--context', cluster.context]- return argv + list(args)---def run(cluster, args, timeout=DEFAULT_TIMEOUT, input_text=None):- """Run ``kubectl <args>`` against *cluster* and return stdout as a string.-- Raises :class:`KubectlError` on a non-zero exit or missing binary.- """- if not is_available():- raise KubectlError('kubectl is not installed on the panel host.')-- kubeconfig_text = cluster.get_kubeconfig() if hasattr(cluster, 'get_kubeconfig') else cluster- path = _write_kubeconfig(kubeconfig_text)- try:- argv = build_argv(cluster, args)- argv += ['--kubeconfig', path]- try:- result = subprocess.run(- argv,- capture_output=True,- text=True,- timeout=timeout,- input=input_text,- )- except subprocess.TimeoutExpired as e:- raise KubectlError(f'kubectl timed out after {timeout}s') from e- except (OSError, subprocess.SubprocessError) as e:- raise KubectlError(f'kubectl could not be executed: {e}') from e-- if result.returncode != 0:- stderr = (result.stderr or '').strip()- raise KubectlError(- stderr or f'kubectl exited with code {result.returncode}',- returncode=result.returncode,- stderr=stderr,- )- return result.stdout or ''- finally:- _safe_unlink(path)---def run_json(cluster, args, timeout=DEFAULT_TIMEOUT):- """Run a kubectl command that emits JSON and return the parsed object.-- The caller is expected to include ``-o json`` (or a get with it) in *args*.- """- out = run(cluster, args, timeout=timeout)- if not out.strip():- return {}- try:- return json.loads(out)- except ValueError as e:- raise KubectlError(f'kubectl returned unparseable JSON: {e}') from ediff --git a/builtin-extensions/serverkit-k8s/backend/lifecycle.py b/builtin-extensions/serverkit-k8s/backend/lifecycle.pydeleted file mode 100644index c999df1d..00000000--- a/builtin-extensions/serverkit-k8s/backend/lifecycle.py+++ /dev/null@@ -1,32 +0,0 @@-"""Install / uninstall lifecycle hooks (serverkit-k8s extension).--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.--There is no engine to provision: the extension only talks to *remote* clusters-through kubectl, so install just registers a notification event and uninstall is-a no-op (the ``ext_serverkit_k8s_*`` table is dropped by the platform on-``--purge``).-"""-import logging--logger = logging.getLogger(__name__)---def on_install(plugin):- """Register the extension's notification events. Best-effort."""- try:- from app.plugins_sdk import notify- notify.register_event(- 'k8s.cluster_unreachable',- 'A Kubernetes cluster became unreachable',- template='generic', severity='warning', category='system')- logger.info('serverkit-k8s installed: notification events registered')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-k8s on_install hook error: %s', e)---def on_uninstall(plugin, purge=False):- """Nothing to tear down -- clusters are remote and hold no local resources."""- logger.info('serverkit-k8s on_uninstall (purge=%s): no local resources to remove', purge)diff --git a/builtin-extensions/serverkit-k8s/backend/models.py b/builtin-extensions/serverkit-k8s/backend/models.pydeleted file mode 100644index 80a7741a..00000000--- a/builtin-extensions/serverkit-k8s/backend/models.py+++ /dev/null@@ -1,101 +0,0 @@-"""Data models for the serverkit-k8s extension.--A :class:`K8sCluster` row is a saved *connection* to an external Kubernetes-cluster: a friendly name, the cluster's **kubeconfig** (stored encrypted with the-panel key), an optional context to select within that kubeconfig, a default flag,-and a small cache of the last reachability probe so the Overview can render-without blocking on a live ``kubectl`` call.--The panel host is never assumed to be a cluster member. All cluster access goes-through ``kubectl --kubeconfig <the decrypted blob>`` (see ``kubectl_service``),-so the only secret we hold is the kubeconfig, and it is **never** returned by-:meth:`K8sCluster.to_dict`.--Tables are namespaced ``ext_serverkit_k8s_*`` (dash -> underscore) per the-extension convention, so ``--purge`` on uninstall drops exactly these.--Registration: importing this module defines the table on the shared metadata as-a side effect; the manifest's ``models: "models:register"`` then calls-:func:`register` (a no-op passthrough) and the platform runs ``db.create_all()``.-"""-import json-from datetime import datetime--from app import db--try:- from app.utils.crypto import encrypt_secret, decrypt_secret_safe-except Exception: # pragma: no cover - crypto util should always be present- encrypt_secret = None- decrypt_secret_safe = None---class K8sCluster(db.Model):- __tablename__ = 'ext_serverkit_k8s_clusters'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), unique=True, nullable=False, index=True)-- # Encrypted kubeconfig YAML. Read/written only through the helpers below so- # the plaintext never lands in a column or a log line.- kubeconfig_encrypted = db.Column(db.Text, nullable=False)-- # Optional context to select inside the kubeconfig (kubectl --context).- context = db.Column(db.String(255), nullable=True)-- is_default = db.Column(db.Boolean, default=False, nullable=False)-- # Cached result of the last reachability probe (test_connection).- last_reachable = db.Column(db.Boolean, nullable=True)- last_status = db.Column(db.Text, nullable=True) # JSON: {server_version, error}- last_checked_at = db.Column(db.DateTime, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- # --- secret helpers -------------------------------------------------- def set_kubeconfig(self, plaintext):- """Encrypt and store a kubeconfig YAML string."""- if encrypt_secret is None:- # No key configured: store as-is so dev boxes still work. Encryption- # is expected in any real deployment.- self.kubeconfig_encrypted = plaintext or ''- else:- self.kubeconfig_encrypted = encrypt_secret(plaintext or '')-- def get_kubeconfig(self):- """Return the decrypted kubeconfig YAML string."""- if not self.kubeconfig_encrypted:- return ''- if decrypt_secret_safe is None:- return self.kubeconfig_encrypted- return decrypt_secret_safe(self.kubeconfig_encrypted)-- # --- serialization --------------------------------------------------- def to_dict(self):- status = None- if self.last_status:- try:- status = json.loads(self.last_status)- except (ValueError, TypeError):- status = None- return {- 'id': self.id,- 'name': self.name,- 'context': self.context,- 'is_default': self.is_default,- 'last_reachable': self.last_reachable,- 'status': status,- 'last_checked_at': self.last_checked_at.isoformat() if self.last_checked_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }---def register(db): # noqa: A002 - signature dictated by the platform (fn(db))- """No-op passthrough required by the manifest ``models: "models:register"``.-- Importing this module already defined the table on ``db.metadata``; the- platform creates it. Nothing else to do here.- """- return [K8sCluster]diff --git a/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsx b/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsxdeleted file mode 100644index 1f9ac198..00000000--- a/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsx+++ /dev/null@@ -1,696 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- ShipWheel, RefreshCw, Plus, Trash2, Server, Boxes, Network,- Layers, RotateCw, ScrollText, Star, Cable, FileCode, X,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/k8s.scss';--// Route-driven tabs (manifest maps /k8s and /k8s/:tab to this component).-const TABS = [- { slug: 'overview', to: '/k8s', label: 'Overview', end: true },- { slug: 'workloads', to: '/k8s/workloads', label: 'Workloads' },- { slug: 'pods', to: '/k8s/pods', label: 'Pods' },- { slug: 'services', to: '/k8s/services', label: 'Services' },- { slug: 'nodes', to: '/k8s/nodes', label: 'Nodes' },- { slug: 'apply', to: '/k8s/apply', label: 'Apply' },- { slug: 'clusters', to: '/k8s/clusters', label: 'Clusters' },-];-const VALID_TABS = TABS.map((t) => t.slug);--const phasePill = (phase) => {- const kind = phase === 'Running' || phase === 'Succeeded' || phase === 'Active'- ? 'green'- : phase === 'Pending' ? 'amber' : phase === 'Failed' ? 'red' : 'gray';- return <Pill kind={kind}>{phase || 'Unknown'}</Pill>;-};--const K8sPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [kubectlAvailable, setKubectlAvailable] = useState(true);- const [clusters, setClusters] = useState([]);- const [selectedId, setSelectedId] = useState(null);- const [loading, setLoading] = useState(true);- const [busy, setBusy] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Per-tab data- const [overview, setOverview] = useState(null);- const [namespace, setNamespace] = useState('all');- const [namespaces, setNamespaces] = useState([]);- const [workloadKind, setWorkloadKind] = useState('deployment');- const [rows, setRows] = useState([]);- const [dataLoading, setDataLoading] = useState(false);-- // Modals- const [addClusterOpen, setAddClusterOpen] = useState(false);- const [addForm, setAddForm] = useState({ name: '', context: '', kubeconfig: '', make_default: false });- const [logsModal, setLogsModal] = useState(null); // {pod, namespace, container, text, loading}- const [manifest, setManifest] = useState('');- const [applyOutput, setApplyOutput] = useState(null);-- const selected = useMemo(- () => clusters.find((c) => String(c.id) === String(selectedId)) || null,- [clusters, selectedId],- );-- // ── Cluster list ──- const loadStatus = useCallback(async () => {- setLoading(true);- try {- const data = await api.request('/k8s/status');- setKubectlAvailable(data.kubectl_available);- setClusters(data.clusters || []);- setSelectedId((prev) => {- if (prev && (data.clusters || []).some((c) => String(c.id) === String(prev))) return prev;- return data.default_cluster_id || (data.clusters?.[0]?.id ?? null);- });- } catch (error) {- toast.error(`Could not load Kubernetes status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => { loadStatus(); }, [loadStatus]);-- // ── Namespaces (for the namespace filter) ──- const loadNamespaces = useCallback(async () => {- if (!selected || !kubectlAvailable) return;- try {- const data = await api.request(`/k8s/clusters/${selected.id}/namespaces`);- setNamespaces((data.items || []).map((n) => n.name).filter(Boolean));- } catch { /* namespace filter is optional */ }- }, [selected, kubectlAvailable]);-- useEffect(() => { loadNamespaces(); }, [loadNamespaces]);-- // ── Tab data ──- const loadTab = useCallback(async () => {- if (!selected || !kubectlAvailable) { setRows([]); setOverview(null); return; }- setDataLoading(true);- try {- if (activeTab === 'overview') {- setOverview(await api.request(`/k8s/clusters/${selected.id}/overview`));- } else if (activeTab === 'workloads') {- const data = await api.request(`/k8s/clusters/${selected.id}/workloads?namespace=${namespace}&kind=${workloadKind}`);- setRows(data.items || []);- } else if (activeTab === 'pods') {- const data = await api.request(`/k8s/clusters/${selected.id}/pods?namespace=${namespace}`);- setRows(data.items || []);- } else if (activeTab === 'services') {- const data = await api.request(`/k8s/clusters/${selected.id}/services?namespace=${namespace}`);- setRows(data.items || []);- } else if (activeTab === 'nodes') {- const data = await api.request(`/k8s/clusters/${selected.id}/nodes`);- setRows(data.items || []);- }- } catch (error) {- toast.error(error.message);- setRows([]);- } finally {- setDataLoading(false);- }- }, [selected, kubectlAvailable, activeTab, namespace, workloadKind, toast]);-- useEffect(() => { loadTab(); }, [loadTab]);-- // ── Cluster actions ──- const handleAddCluster = async () => {- if (!addForm.name.trim() || !addForm.kubeconfig.trim()) {- toast.error('Name and kubeconfig are required.');- return;- }- setBusy(true);- try {- await api.request('/k8s/clusters', { method: 'POST', body: addForm });- toast.success(`Cluster "${addForm.name}" added`);- setAddClusterOpen(false);- setAddForm({ name: '', context: '', kubeconfig: '', make_default: false });- await loadStatus();- } catch (error) {- toast.error(`Could not add cluster: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleDeleteCluster = (cluster) => {- setConfirmDialog({- title: `Remove ${cluster.name}?`,- message: 'This deletes the stored connection and its kubeconfig from the panel. The cluster itself is not touched.',- confirmText: 'Remove',- variant: 'destructive',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/k8s/clusters/${cluster.id}`, { method: 'DELETE' });- toast.success('Cluster removed');- await loadStatus();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleSetDefault = async (cluster) => {- try {- await api.request(`/k8s/clusters/${cluster.id}/default`, { method: 'POST' });- await loadStatus();- } catch (error) {- toast.error(error.message);- }- };-- const handleTest = async (cluster) => {- setBusy(true);- try {- const res = await api.request(`/k8s/clusters/${cluster.id}/test`, { method: 'POST' });- if (res.ok) toast.success(`Reachable — ${res.server_version}`);- else toast.error(`Unreachable: ${res.error}`);- await loadStatus();- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- // ── Workload actions ──- const handleScale = (w, delta) => {- const next = Math.max(0, (w.desired || 0) + delta);- return doScale(w, next);- };-- const doScale = async (w, replicas) => {- setBusy(true);- try {- await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/scale`,- { method: 'POST', body: { replicas } });- toast.success(`Scaled ${w.name} to ${replicas}`);- await loadTab();- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- const handleRestart = async (w) => {- setBusy(true);- try {- await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/restart`,- { method: 'POST' });- toast.success(`Restart triggered for ${w.name}`);- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- const handleDeleteResource = (kind, row) => {- setConfirmDialog({- title: `Delete ${kind} ${row.name}?`,- message: `This removes ${row.name} from namespace ${row.namespace} on the live cluster.`,- confirmText: 'Delete',- variant: 'destructive',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/k8s/clusters/${selected.id}/delete-resource`,- { method: 'POST', body: { kind, name: row.name, namespace: row.namespace } });- toast.success(`${kind} ${row.name} deleted`);- await loadTab();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- // ── Pod logs ──- const openLogs = async (pod) => {- const container = pod.containers?.[0] || '';- setLogsModal({ pod: pod.name, namespace: pod.namespace, container, text: '', loading: true });- try {- const q = container ? `?container=${container}&tail=200` : '?tail=200';- const data = await api.request(`/k8s/clusters/${selected.id}/pods/${pod.namespace}/${pod.name}/logs${q}`);- setLogsModal((m) => m && ({ ...m, text: data.logs || '(no output)', loading: false }));- } catch (error) {- setLogsModal((m) => m && ({ ...m, text: `Error: ${error.message}`, loading: false }));- }- };-- // ── Apply ──- const handleApply = async () => {- if (!manifest.trim()) { toast.error('Paste a manifest first.'); return; }- setBusy(true);- setApplyOutput(null);- try {- const res = await api.request(`/k8s/clusters/${selected.id}/apply`, { method: 'POST', body: { manifest } });- setApplyOutput(res.output || '(applied)');- toast.success('Manifest applied');- } catch (error) {- setApplyOutput(`Error: ${error.message}`);- toast.error(error.message);- } finally {- setBusy(false);- }- };-- // ── Renderers ──- const NamespaceFilter = () => (- <div className="k8s-filter">- <Label>Namespace</Label>- <select className="k8s-select" value={namespace} onChange={(e) => setNamespace(e.target.value)}>- <option value="all">All namespaces</option>- {namespaces.map((n) => <option key={n} value={n}>{n}</option>)}- </select>- </div>- );-- const renderOverview = () => {- if (dataLoading && !overview) return <EmptyState loading title="Querying cluster..." />;- if (!overview) return <EmptyState icon={ShipWheel} title="No data" description="Select a reachable cluster." />;- if (!overview.reachable) {- return (- <div className="card">- <div className="card-body">- <EmptyState icon={Cable} title="Cluster unreachable"- description={overview.error || 'kubectl could not reach the API server with the stored kubeconfig.'} />- <div className="k8s-center">- <Button variant="outline" size="sm" onClick={() => handleTest(selected)}>- <RefreshCw size={14} /> Retry- </Button>- </div>- </div>- </div>- );- }- const c = overview.counts;- const cards = [- { label: 'Server', value: overview.server_version, icon: ShipWheel },- { label: 'Nodes ready', value: `${c.nodes_ready}/${c.nodes}`, icon: Server },- { label: 'Namespaces', value: c.namespaces, icon: Layers },- { label: 'Pods running', value: `${c.pods_running}/${c.pods}`, icon: Boxes },- { label: 'Deployments', value: c.deployments, icon: Network },- ];- return (- <div className="k8s-kpis">- {cards.map((k) => (- <div className="card k8s-kpi" key={k.label}>- <div className="card-body">- <div className="k8s-kpi__icon"><k.icon size={18} /></div>- <div className="k8s-kpi__val">{k.value ?? '—'}</div>- <div className="k8s-kpi__label">{k.label}</div>- </div>- </div>- ))}- </div>- );- };-- const renderWorkloads = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Workloads</h3>- <div className="card-actions k8s-toolbar">- <select className="k8s-select" value={workloadKind} onChange={(e) => setWorkloadKind(e.target.value)}>- <option value="deployment">Deployments</option>- <option value="statefulset">StatefulSets</option>- <option value="daemonset">DaemonSets</option>- </select>- <NamespaceFilter />- </div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading workloads..." />- : rows.length === 0 ? <EmptyState icon={Network} title="No workloads" description="Nothing found in this namespace." />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Replicas</th><th>Status</th><th>Image</th><th /></tr>- </thead>- <tbody>- {rows.map((w) => (- <tr key={`${w.namespace}/${w.name}`}>- <td className="sk-cell-mono">{w.name}</td>- <td>{w.namespace}</td>- <td>- {workloadKind === 'deployment' ? (- <span className="k8s-scale">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, -1)}>−</Button>- <span className="k8s-scale__n">{w.ready}/{w.desired}</span>- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, +1)}>+</Button>- </span>- ) : <span className="sk-cell-mono">{w.ready}/{w.desired}</span>}- </td>- <td><Pill kind={w.healthy ? 'green' : 'amber'}>{w.healthy ? 'healthy' : 'degraded'}</Pill></td>- <td className="sk-cell-mono k8s-truncate" title={(w.images || []).join(', ')}>{(w.images || [])[0] || '—'}</td>- <td className="k8s-row-actions">- {workloadKind === 'deployment' && (- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRestart(w)} title="Rolling restart">- <RotateCw size={14} />- </Button>- )}- <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource(workloadKind, w)}>- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderPods = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Pods</h3>- <div className="card-actions"><NamespaceFilter /></div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading pods..." />- : rows.length === 0 ? <EmptyState icon={Boxes} title="No pods" description="Nothing running in this namespace." />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Ready</th><th>Status</th><th>Restarts</th><th>Node</th><th /></tr>- </thead>- <tbody>- {rows.map((p) => (- <tr key={`${p.namespace}/${p.name}`}>- <td className="sk-cell-mono k8s-truncate" title={p.name}>{p.name}</td>- <td>{p.namespace}</td>- <td className="sk-cell-mono">{p.ready}</td>- <td>{phasePill(p.phase)}</td>- <td className="sk-cell-mono">{p.restarts > 0 ? <Pill kind="amber">{p.restarts}</Pill> : 0}</td>- <td className="sk-cell-mono k8s-truncate">{p.node || '—'}</td>- <td className="k8s-row-actions">- <Button variant="secondary" size="sm" onClick={() => openLogs(p)} title="Logs">- <ScrollText size={14} />- </Button>- <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource('pod', p)}>- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderServices = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Services</h3>- <div className="card-actions"><NamespaceFilter /></div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading services..." />- : rows.length === 0 ? <EmptyState icon={Cable} title="No services" />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Type</th><th>Cluster IP</th><th>External</th><th>Ports</th></tr>- </thead>- <tbody>- {rows.map((s) => (- <tr key={`${s.namespace}/${s.name}`}>- <td className="sk-cell-mono">{s.name}</td>- <td>{s.namespace}</td>- <td><Pill kind={s.type === 'LoadBalancer' ? 'green' : 'gray'}>{s.type}</Pill></td>- <td className="sk-cell-mono">{s.cluster_ip || '—'}</td>- <td className="sk-cell-mono">{s.external_ip || '—'}</td>- <td className="sk-cell-mono">{(s.ports || []).join(', ') || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderNodes = () => (- <div className="card sec-flush">- <div className="card-header"><h3>Nodes</h3></div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading nodes..." />- : rows.length === 0 ? <EmptyState icon={Server} title="No nodes" />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Status</th><th>Roles</th><th>Version</th><th>OS</th><th>CPU</th><th>Memory</th></tr>- </thead>- <tbody>- {rows.map((n) => (- <tr key={n.name}>- <td className="sk-cell-mono">{n.name}</td>- <td><Pill kind={n.ready ? 'green' : 'red'}>{n.ready ? 'Ready' : 'NotReady'}</Pill></td>- <td>{(n.roles || []).join(', ')}</td>- <td className="sk-cell-mono">{n.kubelet_version || '—'}</td>- <td className="k8s-truncate" title={n.os_image}>{n.os_image || '—'}</td>- <td className="sk-cell-mono">{n.cpu || '—'}</td>- <td className="sk-cell-mono">{n.memory || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderApply = () => (- <div className="card">- <div className="card-header"><h3>Apply manifest</h3></div>- <div className="card-body k8s-apply">- <p className="text-muted">- Paste a Kubernetes YAML or JSON manifest. It is sent to the selected cluster with- <code> kubectl apply -f -</code>. Admin only.- </p>- <textarea- className="k8s-textarea"- rows={16}- spellCheck={false}- placeholder={'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: demo'}- value={manifest}- onChange={(e) => setManifest(e.target.value)}- />- <div className="k8s-apply__actions">- <Button variant="default" size="sm" disabled={busy || !selected} onClick={handleApply}>- <FileCode size={14} /> Apply- </Button>- <Button variant="outline" size="sm" onClick={() => { setManifest(''); setApplyOutput(null); }}>Clear</Button>- </div>- {applyOutput != null && <pre className="k8s-output">{applyOutput}</pre>}- </div>- </div>- );-- const renderClusters = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Clusters</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setAddClusterOpen(true)}>- <Plus size={14} /> Add cluster- </Button>- </div>- </div>- <div className="card-body">- {clusters.length === 0 ? (- <EmptyState icon={ShipWheel} title="No clusters yet"- description="Add a cluster by pasting its kubeconfig to start managing workloads." />- ) : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Context</th><th>Reachable</th><th>Server</th><th>Last checked</th><th /></tr>- </thead>- <tbody>- {clusters.map((c) => (- <tr key={c.id}>- <td className="sk-cell-mono">- {c.is_default && <Star size={12} className="k8s-default-star" title="Default" />} {c.name}- </td>- <td className="sk-cell-mono">{c.context || '—'}</td>- <td>- {c.last_reachable == null- ? <Pill kind="gray">unknown</Pill>- : <Pill kind={c.last_reachable ? 'green' : 'red'}>{c.last_reachable ? 'yes' : 'no'}</Pill>}- </td>- <td className="sk-cell-mono">{c.status?.server_version || '—'}</td>- <td className="sk-cell-mono">{c.last_checked_at ? new Date(c.last_checked_at).toLocaleString() : '—'}</td>- <td className="k8s-row-actions">- <Button variant="secondary" size="sm" disabled={busy || !kubectlAvailable} onClick={() => handleTest(c)}>Test</Button>- {!c.is_default && <Button variant="secondary" size="sm" onClick={() => handleSetDefault(c)}>Set default</Button>}- <Button variant="destructive" size="sm" onClick={() => handleDeleteCluster(c)}><Trash2 size={14} /></Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- // ── Page shell ──- if (loading) {- return (- <div className="page-container page-container--full-bleed sk-tabgroup k8s-page">- <PageTopbar icon={<ShipWheel size={18} />} title="Kubernetes" />- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- <EmptyState loading title="Loading Kubernetes..." />- </div>- </div>- </div>- );- }-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));- const needsCluster = activeTab !== 'clusters' && clusters.length === 0;-- return (- <div className="page-container page-container--full-bleed sk-tabgroup k8s-page">- <PageTopbar- icon={<ShipWheel size={18} />}- title="Kubernetes"- tabs={topbarTabs}- actions={- <div className="k8s-topbar-actions">- {clusters.length > 0 && activeTab !== 'clusters' && (- <select className="k8s-select" value={selectedId ?? ''} onChange={(e) => setSelectedId(e.target.value)}>- {clusters.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}- </select>- )}- <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadTab(); }}>- <RefreshCw size={14} /> Refresh- </Button>- </div>- }- />-- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- {!kubectlAvailable && (- <div className="card k8s-warn">- <div className="card-body">- <strong>kubectl is not installed on the panel host.</strong> You can still add and- store cluster connections, but live cluster data and actions are unavailable until- <code> kubectl</code> is on the panel host PATH.- </div>- </div>- )}-- {needsCluster ? (- <div className="card">- <div className="card-body">- <EmptyState icon={ShipWheel} title="No clusters connected"- description="Add a cluster on the Clusters tab by pasting its kubeconfig." />- <div className="k8s-center">- <Button variant="default" size="sm" onClick={() => navigate('/k8s/clusters')}>- <Plus size={14} /> Go to Clusters- </Button>- </div>- </div>- </div>- ) : (- <>- {activeTab === 'overview' && renderOverview()}- {activeTab === 'workloads' && renderWorkloads()}- {activeTab === 'pods' && renderPods()}- {activeTab === 'services' && renderServices()}- {activeTab === 'nodes' && renderNodes()}- {activeTab === 'apply' && renderApply()}- {activeTab === 'clusters' && renderClusters()}- </>- )}- </div>- </div>-- {/* Add cluster modal */}- <Modal open={addClusterOpen} onClose={() => setAddClusterOpen(false)} title="Add Kubernetes cluster">- <div className="k8s-form">- <div className="form-group">- <Label>Name</Label>- <Input type="text" value={addForm.name} placeholder="prod-eu"- onChange={(e) => setAddForm((f) => ({ ...f, name: e.target.value }))} />- </div>- <div className="form-group">- <Label>Context (optional)</Label>- <Input type="text" value={addForm.context} placeholder="Leave blank for the kubeconfig's current-context"- onChange={(e) => setAddForm((f) => ({ ...f, context: e.target.value }))} />- </div>- <div className="form-group">- <Label>Kubeconfig</Label>- <textarea className="k8s-textarea" rows={10} spellCheck={false}- placeholder="Paste the full kubeconfig YAML here"- value={addForm.kubeconfig}- onChange={(e) => setAddForm((f) => ({ ...f, kubeconfig: e.target.value }))} />- <p className="text-muted">Stored encrypted with the panel key. Never shown again after saving.</p>- </div>- <label className="k8s-checkbox">- <input type="checkbox" checked={addForm.make_default}- onChange={(e) => setAddForm((f) => ({ ...f, make_default: e.target.checked }))} />- Make this the default cluster- </label>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setAddClusterOpen(false)}>Cancel</Button>- <Button variant="default" onClick={handleAddCluster} disabled={busy}>Add cluster</Button>- </div>- </Modal>-- {/* Logs modal */}- <Modal open={!!logsModal} onClose={() => setLogsModal(null)}- title={logsModal ? `Logs · ${logsModal.pod}` : 'Logs'}>- {logsModal?.loading- ? <EmptyState loading title="Fetching logs..." />- : <pre className="k8s-logs">{logsModal?.text}</pre>}- <div className="modal-footer">- <Button variant="outline" onClick={() => setLogsModal(null)}><X size={14} /> Close</Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default K8sPage;diff --git a/builtin-extensions/serverkit-k8s/frontend/index.jsx b/builtin-extensions/serverkit-k8s/frontend/index.jsxdeleted file mode 100644index bb282478..00000000--- a/builtin-extensions/serverkit-k8s/frontend/index.jsx+++ /dev/null@@ -1,7 +0,0 @@-// Kubernetes cluster management UI, contributed through the extension system.-// Fully self-contained in the extension. After sync this folder lives at-// frontend/src/plugins/serverkit-k8s/, so '@/…' host aliases resolve.-export { default as K8sPage } from './components/K8sPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scss b/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scssdeleted file mode 100644index 7c732390..00000000--- a/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scss+++ /dev/null@@ -1,177 +0,0 @@-/* Kubernetes extension — layout-only styles. Colors, typography, spacing and- controls all inherit from the host design system (card, sk-dtable, Pill,- empty-state, form controls). No hardcoded palette; surface tints lean on- currentColor / neutral rgba so they read in both themes. */--.k8s-page {- .k8s-topbar-actions {- display: flex;- align-items: center;- gap: 8px;- }-- .k8s-select {- height: 32px;- padding: 0 10px;- border-radius: 6px;- border: 1px solid rgba(128, 128, 128, 0.35);- background: transparent;- color: inherit;- font-size: 13px;- }-- .k8s-filter {- display: flex;- align-items: center;- gap: 8px;-- label {- margin: 0;- white-space: nowrap;- }- }-- .k8s-toolbar {- display: flex;- align-items: center;- gap: 12px;- flex-wrap: wrap;- }-- .k8s-warn {- margin-bottom: 16px;-- code {- padding: 1px 5px;- border-radius: 4px;- background: rgba(128, 128, 128, 0.15);- }- }-- .k8s-center {- display: flex;- justify-content: center;- margin-top: 12px;- }-- /* Overview KPI band */- .k8s-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));- gap: 12px;- }-- .k8s-kpi {- .card-body {- display: flex;- flex-direction: column;- gap: 4px;- }-- &__icon {- opacity: 0.6;- margin-bottom: 4px;- }-- &__val {- font-size: 20px;- font-weight: 600;- word-break: break-word;- }-- &__label {- font-size: 12px;- opacity: 0.7;- }- }-- /* Tables */- .k8s-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;- justify-content: flex-end;- }-- .k8s-truncate {- max-width: 240px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- .k8s-scale {- display: inline-flex;- align-items: center;- gap: 8px;-- &__n {- min-width: 44px;- text-align: center;- font-variant-numeric: tabular-nums;- }- }-- .k8s-default-star {- color: #eab308;- vertical-align: middle;- }-- /* Forms */- .k8s-form {- display: flex;- flex-direction: column;- gap: 12px;- }-- .k8s-textarea,- .k8s-logs,- .k8s-output {- width: 100%;- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12.5px;- border-radius: 8px;- border: 1px solid rgba(128, 128, 128, 0.3);- background: rgba(128, 128, 128, 0.06);- color: inherit;- padding: 12px;- box-sizing: border-box;- }-- .k8s-textarea {- resize: vertical;- }-- .k8s-checkbox {- display: flex;- align-items: center;- gap: 8px;- font-size: 13px;- cursor: pointer;- }-- /* Apply */- .k8s-apply {- display: flex;- flex-direction: column;- gap: 12px;-- &__actions {- display: flex;- gap: 8px;- }- }-- .k8s-logs,- .k8s-output {- max-height: 55vh;- overflow: auto;- white-space: pre-wrap;- word-break: break-word;- margin: 0;- }-- .k8s-output {- margin-top: 4px;- }-}diff --git a/builtin-extensions/serverkit-k8s/plugin.json b/builtin-extensions/serverkit-k8s/plugin.jsondeleted file mode 100644index 3359002d..00000000--- a/builtin-extensions/serverkit-k8s/plugin.json+++ /dev/null@@ -1,46 +0,0 @@-{- "name": "serverkit-k8s",- "display_name": "Kubernetes",- "version": "1.0.0",- "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["shell", "filesystem", "network"],- "min_panel_version": "1.7.0",- "entry_point": "k8s:k8s_bp",- "url_prefix": "/api/v1/k8s",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>",- "contributions": {- "nav": [- {- "id": "k8s",- "label": "Kubernetes",- "route": "/k8s",- "category": "infrastructure",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>"- }- ],- "routes": [- { "path": "k8s", "component": "K8sPage" },- { "path": "k8s/:tab", "component": "K8sPage" }- ],- "page_titles": {- "/k8s": "Kubernetes"- },- "command_palette": [- {- "label": "Kubernetes",- "path": "/k8s",- "category": "Pages",- "keywords": "k8s kubernetes kubectl cluster node namespace pod deployment workload statefulset daemonset service ingress scale restart apply kubeconfig"- }- ]- }-}diff --git a/builtin-extensions/serverkit-mail/backend/__init__.py b/builtin-extensions/serverkit-mail/backend/__init__.pydeleted file mode 100644index 4a3057cc..00000000--- a/builtin-extensions/serverkit-mail/backend/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-"""ServerKit Mail Server extension backend package (Stalwart engine)."""-from .mail import mail_bp--__all__ = ['mail_bp']diff --git a/builtin-extensions/serverkit-mail/backend/dns_mail_service.py b/builtin-extensions/serverkit-mail/backend/dns_mail_service.pydeleted file mode 100644index b3b2bede..00000000--- a/builtin-extensions/serverkit-mail/backend/dns_mail_service.py+++ /dev/null@@ -1,239 +0,0 @@-"""DKIM keygen + mail DNS record deployment (serverkit-mail extension).--Owns the DNS side of standing up a deliverable domain:--* :meth:`generate_dkim` — mint an RSA-2048 DKIM keypair (via ``cryptography``),- store the PEM private key + base64 DER public key on the :class:`MailDomain`- row, and expose the public half as a DKIM TXT value.-* :meth:`build_records` — the **pure, testable** record builder: given a domain- row + optional server IP, return the exact list of records- (MX/SPF/DKIM/DMARC/A) the domain needs. No side effects.-* :meth:`deploy_dns` — push those records through the core- :class:`DNSProviderService` (``source='mail'`` for the ownership ledger),- recording per-record results on the row. When no connected provider manages- the zone, degrade to manual instructions.-* :meth:`dns_instructions` — the record list for the UI, provider or not.-* :meth:`request_cert` — best-effort Let's Encrypt cert for the mail hostname.--Best-effort throughout; the provider/SSL layers are imported lazily so a missing-dependency never breaks import, and nothing here raises to the caller.-"""-import base64-import json-import logging-import os--logger = logging.getLogger(__name__)--DEFAULT_SELECTOR = 'serverkit'-DMARC_POLICY = 'quarantine'---class DkimDnsService:- """Stateless DKIM + mail-DNS orchestration."""-- # ---------- DKIM key generation ------------ @classmethod- def generate_dkim(cls, domain_row):- """Generate an RSA-2048 DKIM keypair and store it on *domain_row*.-- Returns ``{success, selector, dkim_value}`` (or an error dict). The- private key is stored as PEM, the public key as base64 DER, and the- DKIM TXT value ``v=DKIM1; k=rsa; p=<b64>`` is returned for display.- """- try:- from cryptography.hazmat.primitives import serialization- from cryptography.hazmat.primitives.asymmetric import rsa- except ImportError as e:- return {'success': False, 'error': f'cryptography is required for DKIM: {e}'}- try:- key = rsa.generate_private_key(public_exponent=65537, key_size=2048)- private_pem = key.private_bytes(- encoding=serialization.Encoding.PEM,- format=serialization.PrivateFormat.TraditionalOpenSSL,- encryption_algorithm=serialization.NoEncryption(),- ).decode('ascii')- public_der = key.public_key().public_bytes(- encoding=serialization.Encoding.DER,- format=serialization.PublicFormat.SubjectPublicKeyInfo,- )- public_b64 = base64.b64encode(public_der).decode('ascii')- except Exception as e: # noqa: BLE001- return {'success': False, 'error': f'DKIM key generation failed: {e}'}-- selector = domain_row.dkim_selector or DEFAULT_SELECTOR- try:- from app import db- domain_row.dkim_selector = selector- domain_row.dkim_private_key = private_pem- domain_row.dkim_public_key = public_b64- db.session.commit()- except Exception as e: # noqa: BLE001- try:- from app import db- db.session.rollback()- except Exception:- pass- return {'success': False, 'error': f'Could not store DKIM key: {e}'}-- return {- 'success': True,- 'selector': selector,- 'dkim_value': cls._dkim_txt_value(public_b64),- }-- @staticmethod- def _dkim_txt_value(public_b64):- return f'v=DKIM1; k=rsa; p={public_b64}'-- # ---------- pure record builder (testable) ------------ @classmethod- def build_records(cls, domain_row, server_ip=None):- """Return the list of DNS records *domain_row* needs. Pure, no I/O.-- Each record is ``{type, name, value}`` (plus ``priority`` for MX). The- DKIM record is included only once a key has been generated.- """- name = (domain_row.name or '').strip().lower().rstrip('.')- selector = domain_row.dkim_selector or DEFAULT_SELECTOR- mail_host = f'mail.{name}'- records = [- {'type': 'MX', 'name': name, 'value': f'10 {mail_host}', 'priority': 10},- {'type': 'TXT', 'name': name, 'value': 'v=spf1 mx a ~all'},- {'type': 'TXT', 'name': f'_dmarc.{name}',- 'value': f'v=DMARC1; p={DMARC_POLICY}; rua=mailto:postmaster@{name}'},- ]- if domain_row.dkim_public_key:- records.append({- 'type': 'TXT',- 'name': f'{selector}._domainkey.{name}',- 'value': cls._dkim_txt_value(domain_row.dkim_public_key),- })- if server_ip:- records.append({'type': 'A', 'name': mail_host, 'value': server_ip})- return records-- # ---------- DNS deployment ------------ @classmethod- def deploy_dns(cls, domain_id, server_ip=None):- """Deploy the domain's mail records through a connected DNS provider.-- Records the per-record result on ``MailDomain.dns_last_result`` and sets- ``dns_deployed``. When no connected provider manages the zone, returns- ``{success: True, deployed: False, manual: True, records: [...]}`` so the- caller can show manual instructions. Never raises.- """- try:- from app import db- from .models import MailDomain- except Exception as e: # noqa: BLE001- return {'success': False, 'error': f'Model import failed: {e}'}-- domain_row = MailDomain.query.get(domain_id)- if not domain_row:- return {'success': False, 'error': 'Domain not found'}-- records = cls.build_records(domain_row, server_ip=server_ip)-- try:- from app.services.dns_provider_service import DNSProviderService- except Exception as e: # noqa: BLE001- return {'success': True, 'deployed': False, 'manual': True,- 'records': records, 'note': f'DNS provider layer unavailable: {e}'}-- try:- config, zone = DNSProviderService.find_zone_for_domain(domain_row.name)- except Exception as e: # noqa: BLE001- return {'success': True, 'deployed': False, 'manual': True,- 'records': records, 'note': f'Provider lookup failed: {e}'}-- if not config or not zone:- return {'success': True, 'deployed': False, 'manual': True,- 'records': records,- 'note': f'No connected DNS provider manages {domain_row.name}.'}-- results = {}- all_ok = True- for rec in records:- key = f"{rec['type'].lower()}:{rec['name']}"- try:- res = DNSProviderService.set_record(- config.id, zone['id'], rec['type'], rec['name'], rec['value'],- priority=rec.get('priority'), source='mail')- except Exception as e: # noqa: BLE001- res = {'success': False, 'error': str(e)}- results[key] = {'success': bool(res.get('success')),- 'error': res.get('error'),- 'record': rec}- all_ok = all_ok and bool(res.get('success'))-- payload = {'provider': config.name, 'zone': zone.get('name'),- 'results': results, 'all_ok': all_ok}- try:- domain_row.dns_last_result = json.dumps(payload)- domain_row.dns_deployed = all_ok- db.session.commit()- except Exception as e: # noqa: BLE001- try:- db.session.rollback()- except Exception:- pass- logger.warning('Could not persist DNS deploy result: %s', e)-- cls._notify_deployed(domain_row.name, all_ok)- return {'success': all_ok, 'deployed': all_ok, 'manual': False,- 'provider': config.name, 'zone': zone.get('name'),- 'results': results, 'records': records}-- @staticmethod- def _notify_deployed(domain, all_ok):- try:- from app.plugins_sdk import notify- notify.send('mail.dns_deployed', to='admins',- data={'domain': domain, 'all_ok': all_ok}, category='system')- except Exception as e: # noqa: BLE001- logger.debug('mail.dns_deployed notify failed: %s', e)-- @classmethod- def dns_instructions(cls, domain_row, server_ip=None):- """Return the records the operator must publish (for the UI), plus the- current deployment status. Provider-independent."""- deployed = bool(getattr(domain_row, 'dns_deployed', False))- last_result = None- if getattr(domain_row, 'dns_last_result', None):- try:- last_result = json.loads(domain_row.dns_last_result)- except (ValueError, TypeError):- last_result = None- return {- 'domain': domain_row.name,- 'records': cls.build_records(domain_row, server_ip=server_ip),- 'dns_deployed': deployed,- 'dns_last_result': last_result,- 'dkim_configured': bool(getattr(domain_row, 'dkim_private_key', None)),- }-- # ---------- TLS certificate ------------ @classmethod- def request_cert(cls, hostname):- """Best-effort Let's Encrypt cert for ``mail.<hostname>``. Linux-only."""- if os.name == 'nt':- return {'success': False, 'skipped': True,- 'error': 'Certificate issuance is not supported on this OS.'}- hostname = (hostname or '').strip().lower().rstrip('.')- if not hostname:- return {'success': False, 'error': 'A hostname is required'}- try:- from app.services.ssl_service import SSLService- except Exception as e: # noqa: BLE001- return {'success': False, 'error': f'SSL service unavailable: {e}'}- email = f'postmaster@{hostname.split(".", 1)[-1]}' if '.' in hostname else f'postmaster@{hostname}'- try:- result = SSLService.obtain_certificate([hostname], email, use_nginx=True)- except Exception as e: # noqa: BLE001- return {'success': False, 'error': f'Certificate request failed: {e}'}- return resultdiff --git a/builtin-extensions/serverkit-mail/backend/jobs.py b/builtin-extensions/serverkit-mail/backend/jobs.pydeleted file mode 100644index c7df64f9..00000000--- a/builtin-extensions/serverkit-mail/backend/jobs.py+++ /dev/null@@ -1,70 +0,0 @@-"""Background job handlers (serverkit-mail 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).--* ``mail.preflight.run`` (:func:`run_preflight`) — re-check deliverability for the- configured hostname on a daily schedule; notify admins if it regressed to- failing.-* ``mail.queue.flush`` (:func:`flush_queue`) — ask Stalwart to retry its outbound- queue.-"""-import logging--logger = logging.getLogger(__name__)--SLUG = 'serverkit-mail'---def run_preflight(job):- """Re-run the deliverability preflight for the configured hostname.-- Reads the hostname from the plugin config store, re-runs preflight, and —- when the verdict regressed from passing to failing — notifies admins. Never- raises.- """- try:- from app.plugins_sdk import config as plugin_config- from .preflight_service import PreflightService-- cfg = plugin_config(SLUG)- hostname = cfg.get('hostname')- server_ip = cfg.get('server_ip')- if not hostname:- return {'skipped': True, 'reason': 'no hostname configured'}-- previous = PreflightService.latest()- was_passing = bool(previous and previous.get('passed'))-- result = PreflightService.run(hostname, server_ip=server_ip)- now_passing = bool(result and result.get('passed'))-- if was_passing and not now_passing:- _notify_regression(hostname, result)-- return {'hostname': hostname, 'passed': now_passing,- 'regressed': was_passing and not now_passing}- except Exception as e: # noqa: BLE001 — a maintenance job must not crash the loop- logger.warning('mail preflight job failed: %s', e)- return {'error': str(e)}---def _notify_regression(hostname, result):- try:- from app.plugins_sdk import notify- notify.send('mail.preflight_failed', to='admins',- data={'hostname': hostname, 'result': result},- category='system')- except Exception as e: # noqa: BLE001- logger.debug('mail.preflight_failed notify failed: %s', e)---def flush_queue(job):- """Best-effort flush of the Stalwart outbound queue. Never raises."""- try:- from .stalwart_service import StalwartService- return StalwartService.flush_queue()- except Exception as e: # noqa: BLE001- logger.warning('mail queue flush job failed: %s', e)- return {'error': str(e)}diff --git a/builtin-extensions/serverkit-mail/backend/lifecycle.py b/builtin-extensions/serverkit-mail/backend/lifecycle.pydeleted file mode 100644index ad423ec2..00000000--- a/builtin-extensions/serverkit-mail/backend/lifecycle.py+++ /dev/null@@ -1,43 +0,0 @@-"""Install / uninstall lifecycle hooks (serverkit-mail extension).--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.-"""-import logging--logger = logging.getLogger(__name__)---def on_install(plugin):- """Register the extension's notification events. Best-effort."""- try:- from app.plugins_sdk import notify- notify.register_event(- 'mail.preflight_failed',- 'Mail deliverability preflight failed',- template='generic', severity='warning', category='system')- notify.register_event(- 'mail.dns_deployed',- 'Mail DNS records deployed',- template='generic', severity='success', category='system')- logger.info('serverkit-mail installed: notification events registered')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-mail on_install hook error: %s', e)---def on_uninstall(plugin, purge=False):- """Best-effort stop/remove the Stalwart container on uninstall.-- On ``purge`` the mail data directory is deleted too; otherwise the container- is removed but the data is kept so a reinstall can pick it back up.- """- try:- from .stalwart_service import StalwartService- if StalwartService.is_installed():- result = StalwartService.uninstall(keep_data=not purge)- logger.info('serverkit-mail on_uninstall: %s', result)- else:- logger.info('serverkit-mail on_uninstall: container not present')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-mail on_uninstall hook error: %s', e)diff --git a/builtin-extensions/serverkit-mail/backend/mail.py b/builtin-extensions/serverkit-mail/backend/mail.pydeleted file mode 100644index e2200717..00000000--- a/builtin-extensions/serverkit-mail/backend/mail.py+++ /dev/null@@ -1,392 +0,0 @@-"""Mail Server API endpoints (serverkit-mail extension).--Mounted under ``/api/v1/mail`` via the manifest's ``url_prefix``. Thin routing-layer over the extension services — all Docker, Stalwart-API, DNS, and DKIM work-happens in the services. Reads need viewer, mutations need admin (same split as-the serverkit-dns-server extension).--``_installed_or_error`` guards only the routes that genuinely need a running-Stalwart engine (``/queue``, ``/service/<action>``). Domain/mailbox/forwarder-CRUD writes to *our* DB and reconciles to Stalwart best-effort, so it works even-before the engine is installed (operators can stage config first).-"""-from flask import Blueprint, jsonify, request--from app.middleware.rbac import admin_required, viewer_required--from .mail_service import MailService-from .stalwart_service import StalwartService-from .preflight_service import PreflightService-from .dns_mail_service import DkimDnsService--mail_bp = Blueprint('mail', __name__)--_NOT_INSTALLED = (- 'The mail server is not installed. Install it from the Mail Server page '- '(admin only).'-)---def _installed_or_error():- """Return an error response tuple when the engine is absent, else None."""- if not StalwartService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503- return None---def _server_ip(data=None):- """Resolve the server public IP: explicit body value, else system settings."""- if data and data.get('server_ip'):- return str(data['server_ip']).strip()- try:- from app.services.site_domain_service import SiteDomainService- return SiteDomainService.server_ip()- except Exception: # noqa: BLE001- return None---def _domain_or_404(domain_id):- from .models import MailDomain- return MailDomain.query.get(domain_id)---# ── Status / lifecycle ──--@mail_bp.route('/status', methods=['GET'])-@viewer_required-def get_status():- """Engine status + latest deliverability preflight."""- return jsonify(MailService.get_status()), 200---@mail_bp.route('/install', methods=['POST'])-@admin_required-def install():- """Start the Stalwart container: {hostname}."""- data = request.get_json() or {}- hostname = (data.get('hostname') or '').strip()- if not hostname:- return jsonify({'error': 'hostname is required'}), 400- result = StalwartService.install(hostname)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Install failed')}), 400- return jsonify(result), 201---@mail_bp.route('/install', methods=['DELETE'])-@admin_required-def uninstall():- """Remove the container (?keep_data=true keeps the mail data)."""- keep_data = (request.args.get('keep_data', 'true').lower()- not in ('false', '0', 'no'))- result = StalwartService.uninstall(keep_data=keep_data)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Uninstall failed')}), 400- return jsonify(result), 200---@mail_bp.route('/service/<action>', methods=['POST'])-@admin_required-def control_service(action):- """Start / stop / restart the engine container."""- guard = _installed_or_error()- if guard:- return guard- if action not in ('start', 'stop', 'restart'):- return jsonify({'error': "action must be start, stop or restart"}), 400- result = StalwartService.control(action)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Service control failed')}), 400- return jsonify(result), 200---# ── Preflight ──--@mail_bp.route('/preflight', methods=['GET'])-@viewer_required-def get_preflight():- """Latest persisted preflight result (or null)."""- return jsonify({'preflight': PreflightService.latest()}), 200---@mail_bp.route('/preflight', methods=['POST'])-@admin_required-def run_preflight():- """Run and persist a deliverability preflight: {hostname, server_ip?}."""- data = request.get_json() or {}- hostname = (data.get('hostname') or '').strip()- if not hostname:- return jsonify({'error': 'hostname is required'}), 400- server_ip = _server_ip(data)- result = PreflightService.run(hostname, server_ip=server_ip)- return jsonify(result), 200---# ── Domains ──--@mail_bp.route('/domains', methods=['GET'])-@viewer_required-def list_domains():- return jsonify({'domains': MailService.list_domains()}), 200---@mail_bp.route('/domains', methods=['POST'])-@admin_required-def add_domain():- """Add a mail domain: {name, catch_all_target?}."""- data = request.get_json() or {}- name = (data.get('name') or '').strip()- if not name:- return jsonify({'error': 'name is required'}), 400- result = MailService.add_domain(name, catch_all_target=data.get('catch_all_target'))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to add domain')}), 400- return jsonify(result), 201---@mail_bp.route('/domains/<int:domain_id>', methods=['GET'])-@viewer_required-def get_domain(domain_id):- domain = MailService.get_domain(domain_id)- if not domain:- return jsonify({'error': 'Domain not found'}), 404- return jsonify(domain), 200---@mail_bp.route('/domains/<int:domain_id>', methods=['PATCH'])-@admin_required-def update_domain(domain_id):- """Update a domain: {is_active?, catch_all_target?}. Activation is gated on a- passing preflight (or ?force=true)."""- data = request.get_json() or {}- force = (request.args.get('force', 'false').lower() in ('true', '1', 'yes')) \- or bool(data.get('force'))- is_active = data.get('is_active')- if is_active is not None:- result = MailService.set_domain_active(domain_id, bool(is_active), force=force)- else:- result = MailService.update_domain(- domain_id, catch_all_target=data.get('catch_all_target'))- if not result.get('success'):- code = 409 if result.get('code') == 'preflight_required' else 400- return jsonify({'error': result.get('error', 'Update failed'),- 'preflight': result.get('preflight')}), code- return jsonify(result), 200---@mail_bp.route('/domains/<int:domain_id>', methods=['DELETE'])-@admin_required-def remove_domain(domain_id):- result = MailService.remove_domain(domain_id)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to remove domain')}), 400- return jsonify(result), 200---# ── DKIM / DNS / cert ──--@mail_bp.route('/domains/<int:domain_id>/dkim', methods=['POST'])-@admin_required-def generate_dkim(domain_id):- domain = _domain_or_404(domain_id)- if not domain:- return jsonify({'error': 'Domain not found'}), 404- result = DkimDnsService.generate_dkim(domain)- if not result.get('success'):- return jsonify({'error': result.get('error', 'DKIM generation failed')}), 400- return jsonify(result), 200---@mail_bp.route('/domains/<int:domain_id>/dns', methods=['GET'])-@viewer_required-def dns_instructions(domain_id):- domain = _domain_or_404(domain_id)- if not domain:- return jsonify({'error': 'Domain not found'}), 404- return jsonify(DkimDnsService.dns_instructions(domain, server_ip=_server_ip())), 200---@mail_bp.route('/domains/<int:domain_id>/dns/deploy', methods=['POST'])-@admin_required-def deploy_dns(domain_id):- domain = _domain_or_404(domain_id)- if not domain:- return jsonify({'error': 'Domain not found'}), 404- data = request.get_json(silent=True) or {}- result = DkimDnsService.deploy_dns(domain_id, server_ip=_server_ip(data))- # A manual-instructions outcome is still a 200 (there's nothing to fix).- if not result.get('success') and not result.get('manual'):- return jsonify(result), 400- return jsonify(result), 200---@mail_bp.route('/domains/<int:domain_id>/cert', methods=['POST'])-@admin_required-def request_cert(domain_id):- domain = _domain_or_404(domain_id)- if not domain:- return jsonify({'error': 'Domain not found'}), 404- result = DkimDnsService.request_cert(f'mail.{domain.name}')- if not result.get('success'):- return jsonify(result), 200 if result.get('skipped') else 400- return jsonify(result), 200---# ── Mailboxes ──--@mail_bp.route('/domains/<int:domain_id>/mailboxes', methods=['GET'])-@viewer_required-def list_mailboxes(domain_id):- if not _domain_or_404(domain_id):- return jsonify({'error': 'Domain not found'}), 404- return jsonify({'mailboxes': MailService.list_mailboxes(domain_id)}), 200---@mail_bp.route('/domains/<int:domain_id>/mailboxes', methods=['POST'])-@admin_required-def add_mailbox(domain_id):- """Create a mailbox: {local_part, password, quota_mb?, display_name?}."""- data = request.get_json() or {}- local_part = (data.get('local_part') or '').strip()- password = data.get('password')- if not local_part:- return jsonify({'error': 'local_part is required'}), 400- if not password:- return jsonify({'error': 'password is required'}), 400- result = MailService.add_mailbox(- domain_id, local_part, password,- quota_mb=data.get('quota_mb', 0),- display_name=data.get('display_name'))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to create mailbox')}), 400- return jsonify(result), 201---@mail_bp.route('/mailboxes/<int:mailbox_id>', methods=['PATCH'])-@admin_required-def update_mailbox(mailbox_id):- """Update a mailbox: {quota_mb?, is_active?, display_name?}."""- data = request.get_json() or {}- result = MailService.update_mailbox(- mailbox_id,- quota_mb=data.get('quota_mb'),- is_active=data.get('is_active'),- display_name=data.get('display_name'))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to update mailbox')}), 400- return jsonify(result), 200---@mail_bp.route('/mailboxes/<int:mailbox_id>/password', methods=['POST'])-@admin_required-def set_mailbox_password(mailbox_id):- """Set a mailbox password: {password}."""- data = request.get_json() or {}- password = data.get('password')- if not password:- return jsonify({'error': 'password is required'}), 400- result = MailService.set_mailbox_password(mailbox_id, password)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to set password')}), 400- return jsonify(result), 200---@mail_bp.route('/mailboxes/<int:mailbox_id>', methods=['DELETE'])-@admin_required-def remove_mailbox(mailbox_id):- result = MailService.remove_mailbox(mailbox_id)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to remove mailbox')}), 400- return jsonify(result), 200---# ── Autoresponder ──--@mail_bp.route('/mailboxes/<int:mailbox_id>/autoresponder', methods=['GET'])-@viewer_required-def get_autoresponder(mailbox_id):- result = MailService.get_autoresponder(mailbox_id)- if result is None:- return jsonify({'error': 'Mailbox not found'}), 404- return jsonify({'autoresponder': result}), 200---@mail_bp.route('/mailboxes/<int:mailbox_id>/autoresponder', methods=['PUT'])-@admin_required-def set_autoresponder(mailbox_id):- """Set the autoresponder: {enabled, subject, body, start_at?, end_at?}."""- data = request.get_json() or {}- result = MailService.set_autoresponder(- mailbox_id,- enabled=data.get('enabled'),- subject=data.get('subject'),- body=data.get('body'),- start_at=data.get('start_at'),- end_at=data.get('end_at'))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to save autoresponder')}), 400- return jsonify(result), 200---# ── Forwarders ──--@mail_bp.route('/domains/<int:domain_id>/forwarders', methods=['GET'])-@viewer_required-def list_forwarders(domain_id):- if not _domain_or_404(domain_id):- return jsonify({'error': 'Domain not found'}), 404- return jsonify({'forwarders': MailService.list_forwarders(domain_id)}), 200---@mail_bp.route('/domains/<int:domain_id>/forwarders', methods=['POST'])-@admin_required-def add_forwarder(domain_id):- """Create a forwarder: {source_local_part, destination, keep_copy?}."""- data = request.get_json() or {}- source = (data.get('source_local_part') or '').strip()- destination = (data.get('destination') or '').strip()- if not source:- return jsonify({'error': 'source_local_part is required'}), 400- if not destination:- return jsonify({'error': 'destination is required'}), 400- result = MailService.add_forwarder(- domain_id, source, destination, keep_copy=bool(data.get('keep_copy')))- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to create forwarder')}), 400- return jsonify(result), 201---@mail_bp.route('/forwarders/<int:forwarder_id>', methods=['DELETE'])-@admin_required-def remove_forwarder(forwarder_id):- result = MailService.remove_forwarder(forwarder_id)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Failed to remove forwarder')}), 400- return jsonify(result), 200---# ── Queue ──--@mail_bp.route('/queue', methods=['GET'])-@viewer_required-def get_queue():- """Outbound queue messages from the Stalwart admin API (best-effort)."""- guard = _installed_or_error()- if guard:- return guard- result = StalwartService.list_queue()- return jsonify({'messages': result.get('messages', []),- 'note': result.get('note')}), 200---@mail_bp.route('/queue/flush', methods=['POST'])-@admin_required-def flush_queue():- """Ask Stalwart to retry/flush the outbound queue (best-effort)."""- guard = _installed_or_error()- if guard:- return guard- result = StalwartService.flush_queue()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Queue flush failed')}), 400- return jsonify(result), 200diff --git a/builtin-extensions/serverkit-mail/backend/mail_backup.py b/builtin-extensions/serverkit-mail/backend/mail_backup.pydeleted file mode 100644index 73cc0bdb..00000000--- a/builtin-extensions/serverkit-mail/backend/mail_backup.py+++ /dev/null@@ -1,58 +0,0 @@-"""Register the mail data directory as a backup policy (serverkit-mail extension).--Thin, best-effort binder over the core :class:`BackupPolicyService`: a mail-domain's maildir lives under the Stalwart data dir, so we register that path as a-``files`` backup target with a daily schedule. Everything is wrapped so a missing-BackupPolicyService (or a dev shell without the job bus) is non-fatal.-"""-import logging--from .stalwart_service import DATA_DIR--logger = logging.getLogger(__name__)---def register_backup_policy(domain_row):- """Register/enable a daily files backup of the mail data dir for *domain_row*.-- Best-effort: returns ``{success, ...}`` and never raises.- """- try:- from app.services.backup_policy_service import BackupPolicyService- except Exception as e: # noqa: BLE001- logger.debug('BackupPolicyService unavailable, skipping mail backup: %s', e)- return {'success': False, 'skipped': True, 'error': str(e)}- try:- policy = BackupPolicyService.get_or_create_policy(- target_type='files',- target_id=domain_row.id,- target_subtype='pathlist',- target_meta={'label': f'mail:{domain_row.name}', 'paths': [DATA_DIR]},- )- BackupPolicyService.update_policy(policy, {- 'enabled': True,- 'schedule_cron': '0 3 * * *', # daily at 03:00- })- return {'success': True, 'policy_id': policy.id}- except Exception as e: # noqa: BLE001- logger.warning('Could not register mail backup policy for %s: %s',- getattr(domain_row, 'name', '?'), e)- return {'success': False, 'error': str(e)}---def unregister_backup_policy(domain_row):- """Disable the mail backup policy for *domain_row*. Best-effort; never raises.-- The policy row (and its history) is intentionally left in place — only the- schedule is disabled — so a re-added domain keeps its backup lineage.- """- try:- from app.services.backup_policy_service import BackupPolicyService- policy = BackupPolicyService.get_policy('files', domain_row.id)- if not policy:- return {'success': True, 'skipped': True}- BackupPolicyService.update_policy(policy, {'enabled': False})- return {'success': True, 'policy_id': policy.id}- except Exception as e: # noqa: BLE001- logger.debug('Could not unregister mail backup policy: %s', e)- return {'success': False, 'error': str(e)}diff --git a/builtin-extensions/serverkit-mail/backend/mail_jail_service.py b/builtin-extensions/serverkit-mail/backend/mail_jail_service.pydeleted file mode 100644index 84b43c5a..00000000--- a/builtin-extensions/serverkit-mail/backend/mail_jail_service.py+++ /dev/null@@ -1,165 +0,0 @@-"""Fail2ban brute-force jails for the mail server (serverkit-mail extension).--Mirrors the core :class:`Fail2banJailService` write-half pattern: ServerKit-owned-``serverkit-mail-*`` jail files under ``/etc/fail2ban/jail.d``, written with-privilege (``sudo tee``), reloaded via ``fail2ban-client reload``.--The auth jail watches the mail auth log for repeated SMTP/IMAP login failures and-bans the offending IP. Best-effort and Linux-only: on Windows (dev) or when-fail2ban is absent, every mutating call returns a ``skipped`` descriptor instead-of raising, so mail setup degrades gracefully.-"""-import logging-import os--from app.utils.system import run_privileged, is_command_available, ServiceControl--logger = logging.getLogger(__name__)---class MailJailService:- JAIL_DIR = '/etc/fail2ban/jail.d'- JAIL_PREFIX = 'serverkit-mail-'- AUTH_JAIL = 'serverkit-mail-auth'-- # 5 auth failures within 10 min -> 1 hour ban.- MAXRETRY = 5- FINDTIME = 600- BANTIME = 3600-- # Stalwart writes its log inside the container data dir bind-mounted to the- # host; fall back to the common dovecot/postfix filters if present. The jail- # uses the stock filters so it works without a custom filter file.- LOG_PATH = '/var/serverkit/mail/logs/stalwart.log'-- JAIL_TEMPLATE = '''# ServerKit-managed mail brute-force jail.-# Generated by MailJailService - do not edit by hand (regenerated on change).-[{jail}]-enabled = true-filter = {filter}-port = smtp,submission,smtps,imap,imaps,pop3,pop3s-logpath = {logpath}-maxretry = {maxretry}-findtime = {findtime}-bantime = {bantime}-'''-- # ---------- availability ------------ @classmethod- def available(cls):- """True only on a Linux host where the fail2ban client is installed."""- if os.name == 'nt':- return False- return is_command_available('fail2ban-client')-- @staticmethod- def _unavailable():- return {- 'success': True, 'skipped': True, 'available': False, 'reason': 'unavailable',- 'message': 'fail2ban is not available on this host; mail brute-force '- 'protection is inactive.',- }-- # ---------- file helpers ------------ @classmethod- def _jail_path(cls):- filename = f'{cls.AUTH_JAIL}.conf'- if (not filename.startswith(cls.JAIL_PREFIX)- or '/' in filename or '\\' in filename or '..' in filename):- raise ValueError(f'refusing to target non-ServerKit jail file: {filename!r}')- return os.path.join(cls.JAIL_DIR, filename)-- @staticmethod- def _write_file(path, content):- """Write *content* to *path* with privilege (sudo tee)."""- try:- proc = run_privileged(['tee', path], input=content)- if getattr(proc, 'returncode', 1) != 0:- return {'success': False, 'error': (getattr(proc, 'stderr', '') or 'write failed').strip()}- return {'success': True, 'path': path}- except Exception as e: # noqa: BLE001- return {'success': False, 'error': str(e)}-- @classmethod- def _render_jail(cls):- return cls.JAIL_TEMPLATE.format(- jail=cls.AUTH_JAIL,- filter='postfix-sasl', # stock filter; broadly present on Debian/RHEL- logpath=cls.LOG_PATH,- maxretry=cls.MAXRETRY,- findtime=cls.FINDTIME,- bantime=cls.BANTIME,- )-- # ---------- jail lifecycle ------------ @classmethod- def enable_auth_jail(cls):- """Create/refresh the mail auth brute-force jail and reload fail2ban."""- if not cls.available():- return cls._unavailable()- try:- path = cls._jail_path()- except ValueError as e:- return {'success': False, 'error': str(e)}- written = cls._write_file(path, cls._render_jail())- if not written.get('success'):- return written- reloaded = cls.reload()- return {'success': True, 'enabled': True, 'jail': cls.AUTH_JAIL,- 'path': path, 'reloaded': reloaded.get('success')}-- @classmethod- def disable_auth_jail(cls):- """Remove the mail auth jail file and reload fail2ban. No-op when absent."""- if not cls.available():- return cls._unavailable()- try:- path = cls._jail_path()- except ValueError as e:- return {'success': False, 'error': str(e)}- if not os.path.exists(path):- return {'success': True, 'removed': False, 'message': 'no jail to remove'}- try:- proc = run_privileged(['rm', '-f', path])- if getattr(proc, 'returncode', 1) != 0:- return {'success': False, 'error': (getattr(proc, 'stderr', '') or 'remove failed').strip()}- except Exception as e: # noqa: BLE001- return {'success': False, 'error': str(e)}- reloaded = cls.reload()- return {'success': True, 'removed': True, 'jail': cls.AUTH_JAIL,- 'reloaded': reloaded.get('success')}-- @classmethod- def reload(cls):- """``fail2ban-client reload`` (keeps existing bans), falling back to a- service restart if the client call fails. Never raises."""- if not cls.available():- return cls._unavailable()- try:- proc = run_privileged(['fail2ban-client', 'reload'], timeout=30)- if getattr(proc, 'returncode', 1) == 0:- return {'success': True, 'message': 'fail2ban reloaded'}- except Exception:- pass- try:- res = ServiceControl.restart('fail2ban', timeout=30)- return {'success': getattr(res, 'returncode', 1) == 0,- 'message': 'fail2ban restarted' if getattr(res, 'returncode', 1) == 0- else (getattr(res, 'stderr', '') or 'reload failed')}- except Exception as e: # noqa: BLE001- return {'success': False, 'error': str(e)}-- @classmethod- def status(cls):- """Availability + whether the auth jail file exists."""- info = {'available': cls.available(), 'enabled': False, 'jail': cls.AUTH_JAIL}- if not cls.available():- return info- try:- info['enabled'] = os.path.exists(cls._jail_path())- except ValueError:- info['enabled'] = False- return infodiff --git a/builtin-extensions/serverkit-mail/backend/mail_service.py b/builtin-extensions/serverkit-mail/backend/mail_service.pydeleted file mode 100644index dc0bc4a7..00000000--- a/builtin-extensions/serverkit-mail/backend/mail_service.py+++ /dev/null@@ -1,442 +0,0 @@-"""DB <-> Stalwart orchestration (serverkit-mail extension).--The panel's tables (:mod:`.models`) are the source of truth for what mail objects-*should* exist; this service is the reconcile layer. Every mutation:--1. Writes the panel DB (this always succeeds, or returns a clean 400).-2. Best-effort reconciles the change to Stalwart via :class:`StalwartService`.-3. Records the outcome on the row's ``sync_state`` / ``sync_error``.--A Stalwart failure therefore never loses panel state: the row exists with-``sync_state='error'`` and the call returns ``{success: True, sync_state:-'error', ...}`` so the panel can surface and later re-sync the drift. Everything-is wrapped so a missing Stalwart/Docker (dev) never raises.--Activation gate: :meth:`set_domain_active` refuses to activate a domain (which-enables outbound sending) unless the latest :class:`PreflightResult` passed, or an-explicit ``force=True`` override is passed (which is audit-logged).-"""-import logging--logger = logging.getLogger(__name__)---class MailService:- """Stateless DB/Stalwart reconcile orchestration."""-- # ---------- helpers ------------ @staticmethod- def _db():- from app import db- return db-- @staticmethod- def _models():- from . import models- return models-- @staticmethod- def _stalwart():- from .stalwart_service import StalwartService- return StalwartService-- @classmethod- def _apply_sync(cls, row, result):- """Fold a StalwartService reconcile *result* into a row's sync state."""- if result.get('success'):- row.sync_state = 'synced'- row.sync_error = None- else:- row.sync_state = 'error'- row.sync_error = result.get('error') or 'Stalwart sync failed'- return row-- @staticmethod- def _norm(value):- return (value or '').strip().lower().rstrip('.')-- # ---------- status ------------ @classmethod- def get_status(cls):- """Engine status merged with the latest deliverability preflight."""- status = cls._stalwart().get_status()- try:- from .preflight_service import PreflightService- status['preflight'] = PreflightService.latest()- except Exception as e: # noqa: BLE001- logger.debug('preflight latest failed: %s', e)- status['preflight'] = None- try:- from .models import MailDomain- status['domains_count'] = MailDomain.query.count()- except Exception: # noqa: BLE001- status['domains_count'] = 0- return status-- # ---------- domains ------------ @classmethod- def list_domains(cls):- MailDomain = cls._models().MailDomain- return [d.to_dict() for d in MailDomain.query.order_by(MailDomain.name).all()]-- @classmethod- def get_domain(cls, domain_id):- MailDomain = cls._models().MailDomain- row = MailDomain.query.get(domain_id)- return row.to_dict() if row else None-- @classmethod- def add_domain(cls, name, catch_all_target=None):- db = cls._db()- MailDomain = cls._models().MailDomain- name = cls._norm(name)- if not name or '.' not in name:- return {'success': False, 'error': f'Invalid domain name: {name!r}'}- if MailDomain.query.filter_by(name=name).first():- return {'success': False, 'error': f'Domain {name} already exists'}- row = MailDomain(name=name,- catch_all_target=(catch_all_target or '').strip() or None,- is_active=False, sync_state='pending')- try:- db.session.add(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}-- result = cls._safe(lambda: cls._stalwart().upsert_domain(name))- cls._apply_sync(row, result)- db.session.commit()- return {'success': True, 'domain': row.to_dict(),- 'sync_state': row.sync_state, 'sync_error': row.sync_error}-- @classmethod- def update_domain(cls, domain_id, is_active=None, catch_all_target=None):- """Update mutable domain fields (catch-all + activation).-- Activation is delegated to :meth:`set_domain_active` so the preflight- gate cannot be bypassed here.- """- db = cls._db()- MailDomain = cls._models().MailDomain- row = MailDomain.query.get(domain_id)- if not row:- return {'success': False, 'error': 'Domain not found'}-- if catch_all_target is not None:- row.catch_all_target = (catch_all_target or '').strip() or None- db.session.commit()-- if is_active is not None:- return cls.set_domain_active(domain_id, bool(is_active))-- return {'success': True, 'domain': row.to_dict()}-- @classmethod- def set_domain_active(cls, domain_id, active, force=False):- """Activate/deactivate a domain. Activation enables outbound sending and- is **gated** on the latest preflight passing, unless ``force=True`` (which- is audit-logged)."""- db = cls._db()- MailDomain = cls._models().MailDomain- row = MailDomain.query.get(domain_id)- if not row:- return {'success': False, 'error': 'Domain not found'}-- if active:- from .preflight_service import PreflightService- latest = None- try:- latest = PreflightService.latest()- except Exception as e: # noqa: BLE001- logger.debug('preflight check failed during activation: %s', e)- passed = bool(latest and latest.get('passed'))- if not passed and not force:- return {'success': False, 'code': 'preflight_required',- 'error': 'Deliverability preflight has not passed. Run '- 'preflight and resolve any failures, or activate '- 'with force to override.',- 'preflight': latest}- if not passed and force:- cls._audit('mail.domain.activate_forced', row.id, {- 'domain': row.name,- 'preflight_passed': passed,- })-- row.is_active = bool(active)- db.session.commit()-- # Reconcile: ensure the domain principal exists when activating.- if active:- result = cls._safe(lambda: cls._stalwart().upsert_domain(row.name))- cls._apply_sync(row, result)- db.session.commit()-- return {'success': True, 'domain': row.to_dict(),- 'sync_state': row.sync_state, 'sync_error': row.sync_error}-- @classmethod- def remove_domain(cls, domain_id):- db = cls._db()- MailDomain = cls._models().MailDomain- row = MailDomain.query.get(domain_id)- if not row:- return {'success': False, 'error': 'Domain not found'}- name = row.name- # Best-effort Stalwart cleanup before the DB delete (cascade removes- # mailboxes/forwarders/autoresponders panel-side).- cls._safe(lambda: cls._stalwart().delete_domain(name))- try:- from .mail_backup import unregister_backup_policy- unregister_backup_policy(row)- except Exception as e: # noqa: BLE001- logger.debug('backup unregister failed: %s', e)- try:- db.session.delete(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}- return {'success': True, 'message': f'Domain {name} removed'}-- # ---------- mailboxes ------------ @classmethod- def list_mailboxes(cls, domain_id):- Mailbox = cls._models().Mailbox- rows = Mailbox.query.filter_by(domain_id=domain_id).order_by(Mailbox.local_part).all()- return [m.to_dict() for m in rows]-- @classmethod- def get_mailbox(cls, mailbox_id):- Mailbox = cls._models().Mailbox- row = Mailbox.query.get(mailbox_id)- return row.to_dict() if row else None-- @classmethod- def add_mailbox(cls, domain_id, local_part, password, quota_mb=0, display_name=None):- """Create a mailbox. ``password`` is required (set on Stalwart only) and is- NEVER persisted panel-side."""- db = cls._db()- models = cls._models()- MailDomain, Mailbox = models.MailDomain, models.Mailbox- domain = MailDomain.query.get(domain_id)- if not domain:- return {'success': False, 'error': 'Domain not found'}- local_part = (local_part or '').strip().lower()- if not local_part or '@' in local_part:- return {'success': False, 'error': f'Invalid local part: {local_part!r}'}- if not password:- return {'success': False, 'error': 'A password is required'}- if Mailbox.query.filter_by(domain_id=domain_id, local_part=local_part).first():- return {'success': False,- 'error': f'Mailbox {local_part}@{domain.name} already exists'}-- row = Mailbox(domain_id=domain_id, local_part=local_part,- quota_mb=int(quota_mb or 0),- display_name=(display_name or '').strip() or None,- is_active=True, sync_state='pending')- try:- db.session.add(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}-- email = f'{local_part}@{domain.name}'- result = cls._safe(lambda: cls._stalwart().upsert_account(- email, password=password, quota_mb=row.quota_mb, display_name=row.display_name))- cls._apply_sync(row, result)- db.session.commit()- # password intentionally discarded here — never stored.- return {'success': True, 'mailbox': row.to_dict(),- 'sync_state': row.sync_state, 'sync_error': row.sync_error}-- @classmethod- def update_mailbox(cls, mailbox_id, quota_mb=None, is_active=None, display_name=None):- db = cls._db()- Mailbox = cls._models().Mailbox- row = Mailbox.query.get(mailbox_id)- if not row:- return {'success': False, 'error': 'Mailbox not found'}- if quota_mb is not None:- row.quota_mb = int(quota_mb)- if display_name is not None:- row.display_name = (display_name or '').strip() or None- if is_active is not None:- row.is_active = bool(is_active)- db.session.commit()-- result = cls._safe(lambda: cls._stalwart().upsert_account(- row.email, quota_mb=row.quota_mb, display_name=row.display_name))- cls._apply_sync(row, result)- db.session.commit()- return {'success': True, 'mailbox': row.to_dict(),- 'sync_state': row.sync_state, 'sync_error': row.sync_error}-- @classmethod- def set_mailbox_password(cls, mailbox_id, password):- db = cls._db()- Mailbox = cls._models().Mailbox- row = Mailbox.query.get(mailbox_id)- if not row:- return {'success': False, 'error': 'Mailbox not found'}- if not password:- return {'success': False, 'error': 'A password is required'}- result = cls._safe(lambda: cls._stalwart().set_password(row.email, password))- cls._apply_sync(row, result)- db.session.commit()- return {'success': True, 'sync_state': row.sync_state,- 'sync_error': row.sync_error}-- @classmethod- def remove_mailbox(cls, mailbox_id):- db = cls._db()- Mailbox = cls._models().Mailbox- row = Mailbox.query.get(mailbox_id)- if not row:- return {'success': False, 'error': 'Mailbox not found'}- email = row.email- cls._safe(lambda: cls._stalwart().delete_account(email))- try:- db.session.delete(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}- return {'success': True, 'message': f'Mailbox {email} removed'}-- # ---------- autoresponder ------------ @classmethod- def get_autoresponder(cls, mailbox_id):- models = cls._models()- Mailbox, Autoresponder = models.Mailbox, models.Autoresponder- if not Mailbox.query.get(mailbox_id):- return None- row = Autoresponder.query.filter_by(mailbox_id=mailbox_id).first()- if row:- return row.to_dict()- # A not-yet-configured autoresponder reads as a disabled shell.- return {'mailbox_id': mailbox_id, 'enabled': False, 'subject': None,- 'body': None, 'start_at': None, 'end_at': None}-- @classmethod- def set_autoresponder(cls, mailbox_id, enabled=None, subject=None, body=None,- start_at=None, end_at=None):- db = cls._db()- models = cls._models()- Mailbox, Autoresponder = models.Mailbox, models.Autoresponder- if not Mailbox.query.get(mailbox_id):- return {'success': False, 'error': 'Mailbox not found'}- row = Autoresponder.query.filter_by(mailbox_id=mailbox_id).first()- if not row:- row = Autoresponder(mailbox_id=mailbox_id)- db.session.add(row)- if enabled is not None:- row.enabled = bool(enabled)- if subject is not None:- row.subject = subject- if body is not None:- row.body = body- if start_at is not None:- row.start_at = cls._parse_dt(start_at)- if end_at is not None:- row.end_at = cls._parse_dt(end_at)- try:- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}- return {'success': True, 'autoresponder': row.to_dict()}-- @staticmethod- def _parse_dt(value):- if not value:- return None- if hasattr(value, 'isoformat'):- return value- from datetime import datetime- try:- return datetime.fromisoformat(str(value).replace('Z', '+00:00'))- except (ValueError, TypeError):- return None-- # ---------- forwarders ------------ @classmethod- def list_forwarders(cls, domain_id):- Forwarder = cls._models().Forwarder- rows = Forwarder.query.filter_by(domain_id=domain_id).order_by(- Forwarder.source_local_part).all()- return [f.to_dict() for f in rows]-- @classmethod- def add_forwarder(cls, domain_id, source_local_part, destination, keep_copy=False):- db = cls._db()- models = cls._models()- MailDomain, Forwarder = models.MailDomain, models.Forwarder- domain = MailDomain.query.get(domain_id)- if not domain:- return {'success': False, 'error': 'Domain not found'}- source_local_part = (source_local_part or '').strip().lower()- destination = (destination or '').strip()- if not source_local_part or '@' in source_local_part:- return {'success': False, 'error': f'Invalid source: {source_local_part!r}'}- if not destination:- return {'success': False, 'error': 'A destination is required'}- row = Forwarder(domain_id=domain_id, source_local_part=source_local_part,- destination=destination, keep_copy=bool(keep_copy),- is_active=True, sync_state='pending')- try:- db.session.add(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}-- # Forwarders map to an aliased principal on Stalwart; reconcile best-effort.- email = f'{source_local_part}@{domain.name}'- result = cls._safe(lambda: cls._stalwart().upsert_account(email))- cls._apply_sync(row, result)- db.session.commit()- return {'success': True, 'forwarder': row.to_dict(),- 'sync_state': row.sync_state, 'sync_error': row.sync_error}-- @classmethod- def remove_forwarder(cls, forwarder_id):- db = cls._db()- Forwarder = cls._models().Forwarder- row = Forwarder.query.get(forwarder_id)- if not row:- return {'success': False, 'error': 'Forwarder not found'}- try:- db.session.delete(row)- db.session.commit()- except Exception as e: # noqa: BLE001- db.session.rollback()- return {'success': False, 'error': str(e)}- return {'success': True, 'message': 'Forwarder removed'}-- # ---------- internals ------------ @staticmethod- def _safe(fn):- """Run a best-effort Stalwart reconcile call; never raise."""- try:- result = fn()- return result if isinstance(result, dict) else {'success': bool(result)}- except Exception as e: # noqa: BLE001- logger.debug('Stalwart reconcile call failed: %s', e)- return {'success': False, 'error': str(e)}-- @staticmethod- def _audit(action, target_id, details):- try:- from app.plugins_sdk import audit- audit(action, 'mail_domain', target_id=target_id, details=details)- except Exception as e: # noqa: BLE001- logger.debug('audit %s failed: %s', action, e)diff --git a/builtin-extensions/serverkit-mail/backend/models.py b/builtin-extensions/serverkit-mail/backend/models.pydeleted file mode 100644index f03cbb87..00000000--- a/builtin-extensions/serverkit-mail/backend/models.py+++ /dev/null@@ -1,269 +0,0 @@-"""Data models for the serverkit-mail extension.--These tables are the panel-side **source of truth** for what mail objects-*should* exist; :class:`StalwartService` reconciles them to the running Stalwart-engine best-effort and each row records its own ``sync_state`` / ``sync_error``-so a Stalwart API failure never corrupts panel state (the row simply reports-drift).--Tables are namespaced ``ext_serverkit_mail_*`` (dash → underscore) per the-extension convention, so ``purge_models`` on uninstall drops exactly these.--Registration: importing this module defines the tables on the shared metadata as-a side effect; the manifest's ``models: "models:register"`` then calls-:func:`register` (a no-op passthrough) and the platform runs ``db.create_all()``.--Security: mailbox passwords are **never** persisted here — they live only on the-Stalwart engine. There is no password column on :class:`Mailbox`.-"""-from datetime import datetime--from app import db---class MailDomain(db.Model):- __tablename__ = 'ext_serverkit_mail_domains'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), unique=True, nullable=False, index=True)- is_active = db.Column(db.Boolean, default=False)- catch_all_target = db.Column(db.String(255), nullable=True)-- # DKIM- dkim_selector = db.Column(db.String(63), default='serverkit')- dkim_private_key = db.Column(db.Text, nullable=True)- dkim_public_key = db.Column(db.Text, nullable=True)-- # DNS deployment ledger- dns_deployed = db.Column(db.Boolean, default=False)- dns_last_result = db.Column(db.Text, nullable=True) # JSON string-- # Reconcile state against the Stalwart engine- sync_state = db.Column(db.String(20), default='pending') # pending|synced|error- sync_error = db.Column(db.Text, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- mailboxes = db.relationship('Mailbox', backref='domain', lazy=True,- cascade='all, delete-orphan')- forwarders = db.relationship('Forwarder', backref='domain', lazy=True,- cascade='all, delete-orphan')-- def to_dict(self):- import json- dns_result = None- if self.dns_last_result:- try:- dns_result = json.loads(self.dns_last_result)- except (ValueError, TypeError):- dns_result = None- return {- 'id': self.id,- 'name': self.name,- 'is_active': bool(self.is_active),- 'catch_all_target': self.catch_all_target,- 'dkim_selector': self.dkim_selector,- 'dkim_public_key': self.dkim_public_key,- 'dkim_configured': bool(self.dkim_private_key),- 'dns_deployed': bool(self.dns_deployed),- 'dns_last_result': dns_result,- 'sync_state': self.sync_state,- 'sync_error': self.sync_error,- 'mailboxes_count': len(self.mailboxes) if self.mailboxes else 0,- 'forwarders_count': len(self.forwarders) if self.forwarders else 0,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }-- def __repr__(self):- return f'<MailDomain {self.name}>'---class Mailbox(db.Model):- __tablename__ = 'ext_serverkit_mail_mailboxes'- __table_args__ = (- db.UniqueConstraint('domain_id', 'local_part', name='uq_mail_mailbox_local'),- )-- id = db.Column(db.Integer, primary_key=True)- domain_id = db.Column(db.Integer,- db.ForeignKey('ext_serverkit_mail_domains.id'),- nullable=False, index=True)- local_part = db.Column(db.String(255), nullable=False)- quota_mb = db.Column(db.Integer, default=0) # 0 == unlimited- is_active = db.Column(db.Boolean, default=True)- display_name = db.Column(db.String(255), nullable=True)-- # NO password column — passwords live only on Stalwart, never persisted.- sync_state = db.Column(db.String(20), default='pending')- sync_error = db.Column(db.Text, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- autoresponder = db.relationship('Autoresponder', backref='mailbox', uselist=False,- lazy=True, cascade='all, delete-orphan')-- @property- def email(self):- return f'{self.local_part}@{self.domain.name}' if self.domain else self.local_part-- def to_dict(self):- return {- 'id': self.id,- 'domain_id': self.domain_id,- 'domain_name': self.domain.name if self.domain else None,- 'local_part': self.local_part,- 'email': self.email,- 'quota_mb': self.quota_mb,- 'is_active': bool(self.is_active),- 'display_name': self.display_name,- 'sync_state': self.sync_state,- 'sync_error': self.sync_error,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }-- def __repr__(self):- return f'<Mailbox {self.email}>'---class Forwarder(db.Model):- __tablename__ = 'ext_serverkit_mail_forwarders'-- id = db.Column(db.Integer, primary_key=True)- domain_id = db.Column(db.Integer,- db.ForeignKey('ext_serverkit_mail_domains.id'),- nullable=False, index=True)- source_local_part = db.Column(db.String(255), nullable=False)- destination = db.Column(db.Text, nullable=False) # may be an external address- keep_copy = db.Column(db.Boolean, default=False)- is_active = db.Column(db.Boolean, default=True)-- sync_state = db.Column(db.String(20), default='pending')- sync_error = db.Column(db.Text, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- @property- def source(self):- return f'{self.source_local_part}@{self.domain.name}' if self.domain else self.source_local_part-- def to_dict(self):- return {- 'id': self.id,- 'domain_id': self.domain_id,- 'domain_name': self.domain.name if self.domain else None,- 'source_local_part': self.source_local_part,- 'source': self.source,- 'destination': self.destination,- 'keep_copy': bool(self.keep_copy),- 'is_active': bool(self.is_active),- 'sync_state': self.sync_state,- 'sync_error': self.sync_error,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }-- def __repr__(self):- return f'<Forwarder {self.source} -> {self.destination}>'---class Autoresponder(db.Model):- __tablename__ = 'ext_serverkit_mail_autoresponders'-- id = db.Column(db.Integer, primary_key=True)- mailbox_id = db.Column(db.Integer,- db.ForeignKey('ext_serverkit_mail_mailboxes.id'),- nullable=False, unique=True, index=True)- enabled = db.Column(db.Boolean, default=False)- subject = db.Column(db.String(500), nullable=True)- body = db.Column(db.Text, nullable=True)- start_at = db.Column(db.DateTime, nullable=True)- end_at = db.Column(db.DateTime, nullable=True)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- def to_dict(self):- return {- 'id': self.id,- 'mailbox_id': self.mailbox_id,- 'enabled': bool(self.enabled),- 'subject': self.subject,- 'body': self.body,- 'start_at': self.start_at.isoformat() if self.start_at else None,- 'end_at': self.end_at.isoformat() if self.end_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }-- def __repr__(self):- return f'<Autoresponder mailbox={self.mailbox_id} enabled={self.enabled}>'---class PreflightResult(db.Model):- __tablename__ = 'ext_serverkit_mail_preflight'-- id = db.Column(db.Integer, primary_key=True)- hostname = db.Column(db.String(255), nullable=True, index=True)- server_ip = db.Column(db.String(64), nullable=True)-- ptr_ok = db.Column(db.Boolean, default=False)- ptr_value = db.Column(db.String(255), nullable=True)- port25_ok = db.Column(db.Boolean, default=False)- rbl_ok = db.Column(db.Boolean, default=False)- rbl_hits = db.Column(db.Text, nullable=True) # JSON list- ports_ok = db.Column(db.Boolean, default=False)-- passed = db.Column(db.Boolean, default=False)- detail = db.Column(db.Text, nullable=True) # JSON object-- checked_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)-- def to_dict(self):- import json- rbl_hits = []- if self.rbl_hits:- try:- rbl_hits = json.loads(self.rbl_hits)- except (ValueError, TypeError):- rbl_hits = []- detail = None- if self.detail:- try:- detail = json.loads(self.detail)- except (ValueError, TypeError):- detail = None- return {- 'id': self.id,- 'hostname': self.hostname,- 'server_ip': self.server_ip,- 'ptr_ok': bool(self.ptr_ok),- 'ptr_value': self.ptr_value,- 'port25_ok': bool(self.port25_ok),- 'rbl_ok': bool(self.rbl_ok),- 'rbl_hits': rbl_hits,- 'ports_ok': bool(self.ports_ok),- 'passed': bool(self.passed),- 'detail': detail,- 'checked_at': self.checked_at.isoformat() if self.checked_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- }-- def __repr__(self):- return f'<PreflightResult {self.hostname} passed={self.passed}>'---def register(db): # noqa: A002 — signature dictated by the platform (fn(db))- """No-op passthrough required by the manifest ``models: "models:register"``.-- Importing this module already registered the tables on the metadata; the- platform calls this then runs ``db.create_all()``. Returns ``None``.- """- return Nonediff --git a/builtin-extensions/serverkit-mail/backend/preflight_service.py b/builtin-extensions/serverkit-mail/backend/preflight_service.pydeleted file mode 100644index 037cd23e..00000000--- a/builtin-extensions/serverkit-mail/backend/preflight_service.py+++ /dev/null@@ -1,236 +0,0 @@-"""Deliverability preflight checks (serverkit-mail extension).--Running a mail server that the world will *accept* mail from has hard host-prerequisites that a panel cannot fix for you. This service checks them and-persists the verdict; :class:`MailService` refuses to activate outbound sending-for a domain until the latest preflight ``passed`` (or an explicit force-override is logged).--Checks (all best-effort, individually monkeypatchable for tests):--* **PTR / reverse DNS** — the server IP's PTR record must resolve back to the- mail hostname (``socket.gethostbyaddr``). Mismatched PTR is the #1 reason big- providers reject mail.-* **Port-25 egress** — many VPS providers block outbound TCP :25. We try to open- a connection to a public MX on :25 with a short timeout.-* **RBL / DNSBL** — query a couple of well-known blocklists for the reversed- server IP; any hit means the IP is listed.-* **Local listening ports** — best-effort check that the mail ports are open- locally.--On Windows / dev, every host-dependent check returns ``skipped`` and the overall-verdict is ``passed=False`` with a clear note. Nothing here ever raises.-"""-import json-import logging-import os-import socket--logger = logging.getLogger(__name__)--# A public MX we can dial on :25 to prove outbound egress is not blocked.-PORT25_PROBE_HOST = 'gmail-smtp-in.l.google.com'-PORT25_PROBE_PORT = 25-PORT25_TIMEOUT = 6--# DNSBLs queried for the reversed server IP.-RBL_ZONES = ('zen.spamhaus.org', 'bl.spamcop.net')--# Mail ports we expect to be listening locally once Stalwart is up.-LOCAL_PORTS = (25, 465, 587, 993)---class PreflightService:- """Stateless deliverability preflight runner."""-- # ---------- individual checks (monkeypatchable) ------------ @staticmethod- def _check_ptr(hostname, server_ip):- """Reverse-DNS: does the server IP's PTR match *hostname*?-- Returns ``(ok, ptr_value, note)``.- """- if os.name == 'nt':- return None, None, 'skipped (not supported on this OS)'- if not server_ip:- return None, None, 'skipped (no server IP provided)'- try:- ptr_value = socket.gethostbyaddr(server_ip)[0]- except (OSError, socket.herror) as e:- return False, None, f'PTR lookup failed: {e}'- ptr_norm = (ptr_value or '').strip().lower().rstrip('.')- host_norm = (hostname or '').strip().lower().rstrip('.')- ok = bool(host_norm) and ptr_norm == host_norm- note = None if ok else f'PTR {ptr_norm!r} does not match hostname {host_norm!r}'- return ok, ptr_value, note-- @staticmethod- def _check_port25():- """Outbound TCP :25 egress test against a public MX.-- Returns ``(ok, note)``.- """- if os.name == 'nt':- return None, 'skipped (not supported on this OS)'- try:- conn = socket.create_connection(- (PORT25_PROBE_HOST, PORT25_PROBE_PORT), timeout=PORT25_TIMEOUT)- conn.close()- return True, None- except OSError as e:- return False, (f'Could not open outbound :25 to {PORT25_PROBE_HOST} '- f'({e}) — your provider likely blocks port 25.')-- @staticmethod- def _reverse_ip(server_ip):- """Return the reversed dotted-quad of an IPv4 address, or None."""- parts = (server_ip or '').split('.')- if len(parts) != 4 or not all(p.isdigit() and 0 <= int(p) <= 255 for p in parts):- return None- return '.'.join(reversed(parts))-- @classmethod- def _check_rbl(cls, server_ip):- """Query the DNSBLs for the reversed server IP.-- Returns ``(ok, hits, note)`` — ``ok`` is True when the IP is on no list.- """- if os.name == 'nt':- return None, [], 'skipped (not supported on this OS)'- if not server_ip:- return None, [], 'skipped (no server IP provided)'- reversed_ip = cls._reverse_ip(server_ip)- if not reversed_ip:- return None, [], 'skipped (non-IPv4 address)'- hits = []- checked = 0- for zone in RBL_ZONES:- query = f'{reversed_ip}.{zone}'- try:- socket.gethostbyname(query)- hits.append(zone) # a resolvable A record == listed- checked += 1- except socket.gaierror:- checked += 1 # NXDOMAIN == not listed (the good case)- except OSError:- continue # transient resolver error — don't count it- if checked == 0:- return None, [], 'skipped (RBL resolvers unreachable)'- ok = not hits- note = None if ok else f'Listed on: {", ".join(hits)}'- return ok, hits, note-- @staticmethod- def _check_local_ports():- """Best-effort: are the mail ports listening on localhost?-- Returns ``(ok, note)``. This is advisory only — a fresh install may not- be running yet — so it never drives the pass/fail verdict on its own.- """- if os.name == 'nt':- return None, 'skipped (not supported on this OS)'- open_ports = []- for port in LOCAL_PORTS:- try:- conn = socket.create_connection(('127.0.0.1', port), timeout=2)- conn.close()- open_ports.append(port)- except OSError:- continue- ok = bool(open_ports)- note = None if ok else 'No mail ports are listening locally yet.'- return ok, note-- # ---------- orchestration ------------ @classmethod- def run(cls, hostname, server_ip=None):- """Run all checks, persist a :class:`PreflightResult`, and return its dict.-- ``passed`` requires the *critical* checks (PTR, port-25 egress, RBL) to- pass. Skipped checks (Windows/dev, missing IP) count as not-passed so a- dev box never green-lights sending. Never raises.- """- hostname = (hostname or '').strip().lower().rstrip('.')-- ptr_ok, ptr_value, ptr_note = cls._check_ptr(hostname, server_ip)- port25_ok, port25_note = cls._check_port25()- rbl_ok, rbl_hits, rbl_note = cls._check_rbl(server_ip)- ports_ok, ports_note = cls._check_local_ports()-- # Critical checks must be explicitly True (None/skipped => not passed).- critical = [ptr_ok, port25_ok, rbl_ok]- passed = all(c is True for c in critical)-- detail = {- 'ptr': {'ok': ptr_ok, 'value': ptr_value, 'note': ptr_note},- 'port25': {'ok': port25_ok, 'note': port25_note},- 'rbl': {'ok': rbl_ok, 'hits': rbl_hits, 'note': rbl_note},- 'ports': {'ok': ports_ok, 'note': ports_note},- 'critical_checks': ['ptr', 'port25', 'rbl'],- }- if os.name == 'nt':- detail['dev_note'] = ('Host-dependent checks are skipped on this OS; '- 'run preflight on the target server before sending.')-- result = {- 'hostname': hostname,- 'server_ip': server_ip,- 'ptr_ok': bool(ptr_ok),- 'ptr_value': ptr_value,- 'port25_ok': bool(port25_ok),- 'rbl_ok': bool(rbl_ok),- 'rbl_hits': rbl_hits,- 'ports_ok': bool(ports_ok),- 'passed': passed,- 'detail': detail,- }- cls._persist(result)- # Return the freshly persisted row's dict (falls back to the raw result).- latest = cls.latest()- return latest or {**result, 'rbl_hits': rbl_hits, 'detail': detail}-- @classmethod- def _persist(cls, result):- """Store a PreflightResult row. Best-effort; never raises."""- try:- from app import db- from .models import PreflightResult- row = PreflightResult(- hostname=result.get('hostname'),- server_ip=result.get('server_ip'),- ptr_ok=result.get('ptr_ok'),- ptr_value=result.get('ptr_value'),- port25_ok=result.get('port25_ok'),- rbl_ok=result.get('rbl_ok'),- rbl_hits=json.dumps(result.get('rbl_hits') or []),- ports_ok=result.get('ports_ok'),- passed=result.get('passed'),- detail=json.dumps(result.get('detail') or {}),- )- db.session.add(row)- db.session.commit()- return row- except Exception as e: # noqa: BLE001 — persistence is best-effort- logger.warning('Preflight result could not be persisted: %s', e)- try:- from app import db- db.session.rollback()- except Exception:- pass- return None-- @classmethod- def latest(cls):- """Most recent PreflightResult as a dict, or None."""- try:- from .models import PreflightResult- row = (PreflightResult.query- .order_by(PreflightResult.checked_at.desc(),- PreflightResult.id.desc())- .first())- return row.to_dict() if row else None- except Exception as e: # noqa: BLE001- logger.debug('Could not load latest preflight: %s', e)- return Nonediff --git a/builtin-extensions/serverkit-mail/backend/stalwart_service.py b/builtin-extensions/serverkit-mail/backend/stalwart_service.pydeleted file mode 100644index 2339aa65..00000000--- a/builtin-extensions/serverkit-mail/backend/stalwart_service.py+++ /dev/null@@ -1,459 +0,0 @@-"""Stalwart mail-server engine service (serverkit-mail extension).--Runs the Stalwart all-in-one mail server (SMTP/IMAP/JMAP/Sieve) in a managed-Docker container so a ServerKit box can host mailboxes for its domains. Driven-entirely through Stalwart's HTTP **admin API**, published on loopback only.--Design mirrors the serverkit-dns-server extension exactly:--* **Two choke-points** — every Docker invocation goes through :meth:`_docker`- (privilege escalation, timeouts, error shaping) and every admin-API call goes- through :meth:`_api` (HTTP Basic auth, JSON, error shaping). Nothing else- shells out or talks HTTP.-* **Best-effort, Linux-only** — on Windows (dev) or when Docker is absent, calls- return a clean error dict instead of raising.-* **Panel DB is the source of truth** — our tables describe what *should* exist;- the thin reconcile methods (:meth:`upsert_account`, :meth:`upsert_domain`, …)- push best-effort to Stalwart and **degrade gracefully**: a 404 / shape change- in the version-sensitive admin API returns ``{success: False, error}`` and- never raises, so :class:`MailService` can still record a row with- ``sync_state='error'``.-* **Secrets in the config store** — the generated admin password lives in the- plugin config store (``plugins_sdk.config`` + the ``_save_config`` pattern),- used as HTTP Basic auth to the admin API.--Version note: the Stalwart admin API is version-sensitive. All endpoint paths are-centralized as module constants below and each reconcile call is wrapped so a-future API change degrades to a reported drift rather than a crash.-"""-import logging-import os-import secrets-import subprocess--import requests--from app.utils.system import run_privileged, is_command_available--logger = logging.getLogger(__name__)--SLUG = 'serverkit-mail'--# Official Stalwart all-in-one mail server image. NOTE: the image is-# ``stalwartlabs/stalwart`` — the older ``stalwartlabs/mail-server`` name no-# longer resolves on Docker Hub (verified against a live pull, v0.16.11).-IMAGE = 'stalwartlabs/stalwart:latest'-CONTAINER_NAME = 'serverkit-mail'-DATA_DIR = '/var/serverkit/mail'-# Stalwart splits config from data inside the container (its CMD is-# ``--config /etc/stalwart/config.json``). We bind two host sub-dirs so both-# survive a container recreate: the local bootstrap config and the data store.-CONTAINER_CONFIG_DIR = '/etc/stalwart' # holds config.json (written at setup)-CONTAINER_DATA_DIR = '/opt/stalwart' # holds the data/blob/fts store-HOST_CONFIG_DIR = f'{DATA_DIR}/etc'-HOST_DATA_DIR = f'{DATA_DIR}/data'--# Admin HTTP API — published on 127.0.0.1 only, never reachable off-host.-API_HOST = '127.0.0.1'-API_PORT = 8080-API_BASE = f'http://{API_HOST}:{API_PORT}/api'-API_TIMEOUT = 10-DOCKER_TIMEOUT = 180--# Default admin account Stalwart provisions on first start. The recovery/admin-# credential is pinned via a single ``STALWART_RECOVERY_ADMIN=user:secret`` env-# var (verified from the container's first-boot log, v0.16.11).-ADMIN_USER = 'admin'--# The web setup + admin SPA the recovery listener serves on the API port. On a-# fresh container Stalwart boots into *bootstrap mode*: only this UI + a recovery-# listener are up, and the whole ``/api/*`` management surface 404s until the-# one-time initial setup is completed here.-#-# Live findings (Stalwart 0.16.11, real box): in bootstrap ``GET /api/account``-# returns 200 with ``{"permissions": ["sysBootstrapGet", "sysBootstrapUpdate"]}``-# — i.e. the setup CAN be completed programmatically via that bootstrap grant, so-# a future iteration could auto-finish setup instead of asking the operator to-# use the web wizard. The management vocabulary (``principal``, ``dkim``,-# ``queue``, ``mailbox``, ``domain``) was confirmed against the server's own-# config schema, so the EP_* nouns below are correct; only their exact-# post-setup routing stays best-effort until confirmed on a fully-initialized box.-ADMIN_UI = '/account'--# Mail ports published on the host (SMTP / submission / IMAP / Sieve).-MAIL_PORTS = ('25', '465', '587', '993', '143', '4190')--DOCS_URL = 'https://stalw.art/docs/'--# ── Admin-API endpoint paths (version-sensitive; centralized on purpose) ──-# Each reconcile method wraps these so a 404 / shape change degrades gracefully.-# These management paths only exist once initial setup is complete (see-# ``get_status`` bootstrap detection); before that every ``/api/*`` is a 404.-EP_PRINCIPAL = '/principal' # accounts / mailboxes / domains (CRUD)-EP_DKIM = '/dkim' # DKIM signature management-EP_QUEUE = '/queue/messages' # outbound queue introspection-EP_RECONFIG = '/reload' # ask Stalwart to reload config-EP_SESSION = '/session' # logged-in principal probe (readiness/bootstrap)---class StalwartService:- """Stateless wrapper around Docker + the Stalwart admin HTTP API."""-- # ---------- config (plugin config store) ------------ @classmethod- def _config(cls):- """Saved extension settings from the plugin config store."""- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)-- @classmethod- def _save_config(cls, updates):- """Merge *updates* into the plugin's stored config.-- The SDK ``config()`` helper is read-only (the panel owns writes), so the- generated admin password is persisted through the InstalledPlugin row- directly. Returns False when the plugin row is absent (dev shells).- """- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- logger.warning('%s: no InstalledPlugin row; config not persisted', SLUG)- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True-- # ---------- docker choke-point ------------ @classmethod- def _docker(cls, args, timeout=DOCKER_TIMEOUT):- """Run ``docker <args>`` and return a normalized result dict."""- if os.name == 'nt':- return {'success': False,- 'error': 'The mail server extension is not supported on Windows.'}- if not is_command_available('docker'):- return {'success': False, 'not_installed': True,- 'error': 'Docker is not installed on this host.'}- cmd = ['docker'] + list(args)- try:- result = run_privileged(cmd, timeout=timeout)- except subprocess.TimeoutExpired:- return {'success': False, 'error': f'docker timed out after {timeout}s'}- except (OSError, subprocess.SubprocessError) as e:- return {'success': False, 'error': f'Failed to run docker: {e}'}- out = {- 'success': result.returncode == 0,- 'returncode': result.returncode,- 'stdout': result.stdout or '',- 'stderr': result.stderr or '',- }- if not out['success']:- out['error'] = (out['stderr'] or out['stdout'] or 'docker failed').strip()- return out-- # ---------- Stalwart admin-API choke-point ------------ @classmethod- def _api(cls, method, path, payload=None):- """Call the container's Stalwart admin HTTP API (loopback only).-- Returns ``{'success': True, 'data': <json-or-None>}`` or an error dict.- Auth is HTTP Basic with the generated admin password. The API is- published on 127.0.0.1 exclusively, so this never leaves the host.- Never raises.- """- if os.name == 'nt':- return {'success': False,- 'error': 'The mail server extension is not supported on Windows.'}- password = cls._config().get('admin_password')- if not password:- return {'success': False,- 'error': 'Stalwart admin password is not configured. Reinstall the mail server.'}- try:- resp = requests.request(- method, API_BASE + path,- auth=(ADMIN_USER, password),- json=payload,- timeout=API_TIMEOUT,- )- except requests.RequestException as e:- return {'success': False,- 'error': f'Stalwart admin API is unreachable: {e}'}- if resp.status_code >= 400:- # Stalwart returns RFC-7807 problem+json: {type,status,title,detail}.- try:- body = resp.json()- detail = (body.get('detail') or body.get('title')- or body.get('error') or resp.text)- except ValueError:- detail = resp.text- return {'success': False, 'status_code': resp.status_code,- 'error': f'Stalwart admin API error ({resp.status_code}): {detail}'.strip()}- if not resp.content:- return {'success': True, 'data': None}- try:- return {'success': True, 'data': resp.json()}- except ValueError:- return {'success': True, 'data': resp.text}-- # ---------- container lifecycle ------------ @classmethod- def is_installed(cls):- """True when the managed container exists (running or not)."""- if os.name == 'nt':- return False- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- return bool(res.get('success'))-- @classmethod- def get_status(cls):- """Installed / running / version / ports summary, best-effort."""- status = {- 'installed': False,- 'running': False,- 'needs_setup': None, # True until Stalwart's one-time setup is done- 'setup_url': None,- 'version': None,- 'engine': 'stalwart',- 'image': IMAGE,- 'container': CONTAINER_NAME,- 'ports': list(MAIL_PORTS),- 'admin_api': f'{API_HOST}:{API_PORT}',- 'hostname': cls._config().get('hostname') if os.name != 'nt' else None,- 'docs_url': DOCS_URL,- }- if os.name == 'nt':- return status- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- if not res.get('success'):- return status- status['installed'] = True- status['running'] = res.get('stdout', '').strip() == 'true'- if status['running']:- # A fresh container boots into bootstrap mode: only the recovery- # setup UI is up and every /api/* is a 404 until initial setup is- # completed. Detect that so the panel can guide the operator instead- # of firing management calls that will all fail.- probe = cls._api('GET', EP_SESSION)- if probe.get('status_code') == 404:- status['needs_setup'] = True- status['setup_url'] = f'http://{API_HOST}:{API_PORT}{ADMIN_UI}'- elif probe.get('success'):- status['needs_setup'] = False- data = probe.get('data')- if isinstance(data, dict):- status['version'] = data.get('version') or status['version']- # Any other error (unreachable, still starting): leave needs_setup- # None so the UI shows "checking…" rather than a false ready state.- return status-- @classmethod- def install(cls, hostname):- """Create and start the Stalwart container.-- * Data + config bind-mounted at ``DATA_DIR`` (Stalwart bootstraps on- first start).- * Mail ports published on the host so the box can send/receive mail.- * Admin HTTP API published on **127.0.0.1 only** with a generated- password persisted to the plugin config store.- """- if os.name == 'nt':- return {'success': False,- 'error': 'The mail server extension is not supported on Windows.'}- hostname = (hostname or '').strip().lower().rstrip('.')- if not hostname:- return {'success': False, 'error': 'A mail server hostname is required'}- if cls.is_installed():- return {'success': False,- 'error': 'The mail server container already exists. Uninstall it first.'}-- dir_res = run_privileged(['mkdir', '-p', HOST_CONFIG_DIR, HOST_DATA_DIR])- if getattr(dir_res, 'returncode', 1) != 0:- return {'success': False,- 'error': f'Could not create data directory {DATA_DIR}: '- f'{(getattr(dir_res, "stderr", "") or "").strip()}'}-- admin_password = secrets.token_urlsafe(24)- run_args = [- 'run', '-d',- '--name', CONTAINER_NAME,- '--restart', 'unless-stopped',- '--hostname', hostname,- ]- for port in MAIL_PORTS:- run_args += ['-p', f'{port}:{port}']- # Admin API bound to loopback on the host — never reachable off-box.- run_args += ['-p', f'{API_HOST}:{API_PORT}:{API_PORT}']- # Config and data on separate host dirs (see the module constants).- run_args += [- '-v', f'{HOST_CONFIG_DIR}:{CONTAINER_CONFIG_DIR}',- '-v', f'{HOST_DATA_DIR}:{CONTAINER_DATA_DIR}',- ]- # Pin the recovery/admin credential Stalwart reads on first boot — a- # single ``user:secret`` env var. Without this Stalwart prints a random- # one-time password to the container log that we could never recover.- run_args += [- '-e', f'STALWART_RECOVERY_ADMIN={ADMIN_USER}:{admin_password}',- IMAGE,- ]- res = cls._docker(run_args)- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to start the Stalwart container')}-- persisted = cls._save_config({- 'admin_password': admin_password,- 'hostname': hostname,- })- result = {'success': True,- 'message': 'Stalwart mail server installed — complete the one-time '- 'setup to activate the admin API',- 'container': CONTAINER_NAME,- 'hostname': hostname,- 'needs_setup': True,- 'setup_url': f'http://{API_HOST}:{API_PORT}{ADMIN_UI}'}- if not persisted:- result['warning'] = ('Container started but the admin password could not '- 'be persisted to the plugin config store.')- return result-- @classmethod- def uninstall(cls, keep_data=True):- """Remove the container; optionally delete the mail data directory."""- if os.name == 'nt':- return {'success': False,- 'error': 'The mail server extension is not supported on Windows.'}- res = cls._docker(['rm', '-f', CONTAINER_NAME])- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to remove the Stalwart container')}- if not keep_data:- rm = run_privileged(['rm', '-rf', DATA_DIR])- if getattr(rm, 'returncode', 1) != 0:- return {'success': True,- 'warning': f'Container removed but mail data at {DATA_DIR} '- f'could not be deleted: {(getattr(rm, "stderr", "") or "").strip()}'}- cls._save_config({'admin_password': None})- return {'success': True,- 'message': 'Mail server removed'- + ('' if keep_data else ' (mail data deleted)')}-- @classmethod- def control(cls, action):- """Start / stop / restart the managed container."""- if action not in ('start', 'stop', 'restart'):- return {'success': False, 'error': f'Invalid action: {action!r}'}- if not cls.is_installed():- return {'success': False, 'error': 'The mail server is not installed.'}- res = cls._docker([action, CONTAINER_NAME], timeout=60)- if not res.get('success'):- return {'success': False, 'error': res.get('error', f'docker {action} failed')}- return {'success': True, 'message': f'Mail server {action}ed', 'action': action}-- # ---------- thin reconcile methods (best-effort, never raise) ----------- #- # Each of these pushes the panel's intent to Stalwart via the version-- # sensitive admin API and returns {success, ...}. On any error they report- # {success: False, error} so MailService can flag the row's sync_state.-- @classmethod- def _principal_payload(cls, ptype, name, **extra):- payload = {'type': ptype, 'name': name}- payload.update({k: v for k, v in extra.items() if v is not None})- return payload-- @classmethod- def upsert_account(cls, email, password=None, quota_mb=0, display_name=None):- """Create/update a mailbox account principal on Stalwart. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- extra = {}- if password:- extra['secrets'] = [password]- if display_name:- extra['description'] = display_name- if quota_mb:- extra['quota'] = int(quota_mb) * 1024 * 1024 # bytes- payload = cls._principal_payload('individual', email, **extra)- res = cls._api('POST', EP_PRINCIPAL, payload)- if res.get('success'):- return {'success': True, 'email': email}- return {'success': False, 'error': res.get('error', 'Stalwart account upsert failed')}-- @classmethod- def delete_account(cls, email):- """Delete a mailbox account principal on Stalwart. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- res = cls._api('DELETE', f'{EP_PRINCIPAL}/{email}')- if res.get('success') or res.get('status_code') == 404:- return {'success': True, 'email': email}- return {'success': False, 'error': res.get('error', 'Stalwart account delete failed')}-- @classmethod- def set_password(cls, email, password):- """Set a mailbox account's password on Stalwart. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- if not password:- return {'success': False, 'error': 'A password is required'}- res = cls._api('PATCH', f'{EP_PRINCIPAL}/{email}', {'secrets': [password]})- if res.get('success'):- return {'success': True, 'email': email}- # Fall back to a full upsert if PATCH is unsupported in this version.- return cls.upsert_account(email, password=password)-- @classmethod- def upsert_domain(cls, name):- """Register a domain principal on Stalwart. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- payload = cls._principal_payload('domain', name)- res = cls._api('POST', EP_PRINCIPAL, payload)- if res.get('success'):- return {'success': True, 'domain': name}- return {'success': False, 'error': res.get('error', 'Stalwart domain upsert failed')}-- @classmethod- def delete_domain(cls, name):- """Remove a domain principal from Stalwart. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- res = cls._api('DELETE', f'{EP_PRINCIPAL}/{name}')- if res.get('success') or res.get('status_code') == 404:- return {'success': True, 'domain': name}- return {'success': False, 'error': res.get('error', 'Stalwart domain delete failed')}-- @classmethod- def list_queue(cls):- """List outbound queue messages from the admin API. ``[]`` when down."""- if not cls.is_installed():- return {'success': True, 'messages': []}- res = cls._api('GET', EP_QUEUE)- if not res.get('success'):- return {'success': True, 'messages': [], 'note': res.get('error')}- data = res.get('data')- if isinstance(data, list):- messages = data- elif isinstance(data, dict):- messages = data.get('items', [])- else:- messages = []- return {'success': True, 'messages': messages}-- @classmethod- def flush_queue(cls):- """Ask Stalwart to retry/flush the outbound queue. Best-effort."""- if not cls.is_installed():- return {'success': False, 'error': 'Mail server not installed', 'skipped': True}- res = cls._api('PATCH', EP_QUEUE, {'action': 'retry'})- if res.get('success'):- return {'success': True, 'message': 'Queue flush requested'}- return {'success': False, 'error': res.get('error', 'Queue flush failed')}diff --git a/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx b/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsxdeleted file mode 100644index 490fdf4b..00000000--- a/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx+++ /dev/null@@ -1,1383 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- Mail, RefreshCw, Plus, Trash2, ShieldCheck, ShieldAlert,- Globe, AtSign, Forward, KeyRound, Inbox, Copy, Power, Send,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--// Route-driven tabs (manifest maps /mail and /mail/:tab to this component).-const TABS = [- { slug: 'overview', to: '/mail', label: 'Overview', end: true },- { slug: 'domains', to: '/mail/domains', label: 'Domains' },- { slug: 'mailboxes', to: '/mail/mailboxes', label: 'Mailboxes' },- { slug: 'forwarders', to: '/mail/forwarders', label: 'Forwarders' },- { slug: 'dns', to: '/mail/dns', label: 'DNS & DKIM' },- { slug: 'queue', to: '/mail/queue', label: 'Queue' },-];-const VALID_TABS = TABS.map((t) => t.slug);--// A preflight check either passed, failed, or was skipped (e.g. on a dev box).-function checkPill(ok, skipped) {- if (skipped) return <Pill kind="gray">skipped</Pill>;- return ok ? <Pill kind="green">pass</Pill> : <Pill kind="red">fail</Pill>;-}--const MailPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [status, setStatus] = useState(null);- const [preflight, setPreflight] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Overview / install- const [installHostname, setInstallHostname] = useState('');-- // Domains- const [domains, setDomains] = useState([]);- const [showDomainForm, setShowDomainForm] = useState(false);- const [newDomain, setNewDomain] = useState({ name: '', catch_all_target: '' });- const [catchAllModal, setCatchAllModal] = useState(null); // { id, name, value }-- // Selected domain (shared by mailboxes / forwarders / dns)- const [selectedDomainId, setSelectedDomainId] = useState('');-- // Mailboxes- const [mailboxes, setMailboxes] = useState([]);- const [showMailboxForm, setShowMailboxForm] = useState(false);- const [newMailbox, setNewMailbox] = useState({ local_part: '', password: '', quota_mb: 0, display_name: '' });- const [passwordModal, setPasswordModal] = useState(null); // { id, address }- const [newPassword, setNewPassword] = useState('');- const [autoModal, setAutoModal] = useState(null); // { id, address }- const [autoResponder, setAutoResponder] = useState({ enabled: false, subject: '', body: '', start_at: '', end_at: '' });-- // Forwarders- const [forwarders, setForwarders] = useState([]);- const [showForwarderForm, setShowForwarderForm] = useState(false);- const [newForwarder, setNewForwarder] = useState({ source_local_part: '', destination: '', keep_copy: true });-- // DNS & DKIM- const [dnsInfo, setDnsInfo] = useState(null);-- // Queue- const [queue, setQueue] = useState({ messages: [], note: null });-- // ── Loaders ──-- const loadStatus = useCallback(async () => {- setLoading(true);- try {- const data = await api.request('/mail/status');- setStatus(data);- setPreflight(data?.preflight ?? null);- } catch (error) {- toast.error(`Failed to load mail server status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- const loadDomains = useCallback(async () => {- try {- const data = await api.request('/mail/domains');- setDomains(data.domains || []);- } catch (error) {- toast.error(`Failed to load domains: ${error.message}`);- }- }, [toast]);-- const loadMailboxes = useCallback(async (domainId) => {- if (!domainId) { setMailboxes([]); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/mailboxes`);- setMailboxes(data.mailboxes || []);- } catch (error) {- toast.error(`Failed to load mailboxes: ${error.message}`);- }- }, [toast]);-- const loadForwarders = useCallback(async (domainId) => {- if (!domainId) { setForwarders([]); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/forwarders`);- setForwarders(data.forwarders || []);- } catch (error) {- toast.error(`Failed to load forwarders: ${error.message}`);- }- }, [toast]);-- const loadDns = useCallback(async (domainId) => {- if (!domainId) { setDnsInfo(null); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/dns`);- setDnsInfo(data);- } catch (error) {- toast.error(`Failed to load DNS records: ${error.message}`);- setDnsInfo(null);- }- }, [toast]);-- const loadQueue = useCallback(async () => {- try {- const data = await api.request('/mail/queue');- setQueue({ messages: data.messages || [], note: data.note || null });- } catch (error) {- // 503 before install, or the admin API is unreachable — degrade gracefully.- setQueue({ messages: [], note: error.message });- }- }, []);-- useEffect(() => { loadStatus(); }, [loadStatus]);-- // Domains feed the selector on the mailboxes/forwarders/dns tabs too.- useEffect(() => {- if (['domains', 'mailboxes', 'forwarders', 'dns'].includes(activeTab)) loadDomains();- }, [activeTab, loadDomains]);-- useEffect(() => {- if (activeTab === 'mailboxes') loadMailboxes(selectedDomainId);- }, [activeTab, selectedDomainId, loadMailboxes]);-- useEffect(() => {- if (activeTab === 'forwarders') loadForwarders(selectedDomainId);- }, [activeTab, selectedDomainId, loadForwarders]);-- useEffect(() => {- if (activeTab === 'dns') loadDns(selectedDomainId);- }, [activeTab, selectedDomainId, loadDns]);-- useEffect(() => {- if (activeTab === 'queue') loadQueue();- }, [activeTab, loadQueue]);-- // ── Overview actions ──-- const handleInstall = async () => {- if (!installHostname.trim()) return;- setActionLoading(true);- try {- await api.request('/mail/install', {- method: 'POST',- body: { hostname: installHostname.trim() },- });- toast.success('Mail server installed');- setInstallHostname('');- await loadStatus();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove mail server',- message: keepData- ? 'Remove the Stalwart container? Mail data stays on disk and a reinstall picks it back up.'- : 'Remove the Stalwart container AND delete all mail data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('Mail server removed');- await loadStatus();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleService = async (action) => {- setActionLoading(true);- try {- await api.request(`/mail/service/${action}`, { method: 'POST' });- toast.success(`Mail server ${action} successful`);- await loadStatus();- } catch (error) {- toast.error(`Failed to ${action} mail server: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRunPreflight = async () => {- const hostname = status?.hostname || installHostname.trim() || preflight?.hostname || '';- if (!hostname) {- toast.error('Install the mail server (or set a hostname) before running preflight.');- return;- }- setActionLoading(true);- try {- const result = await api.request('/mail/preflight', {- method: 'POST',- body: { hostname },- });- setPreflight(result);- if (result?.passed) toast.success('Deliverability preflight passed');- else toast.error('Preflight found blocking issues — see the checks below');- } catch (error) {- toast.error(`Preflight failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Domain actions ──-- const handleAddDomain = async (e) => {- e.preventDefault();- if (!newDomain.name.trim()) return;- setActionLoading(true);- try {- await api.request('/mail/domains', {- method: 'POST',- body: {- name: newDomain.name.trim(),- catch_all_target: newDomain.catch_all_target.trim() || undefined,- },- });- toast.success(`Domain ${newDomain.name} added`);- setShowDomainForm(false);- setNewDomain({ name: '', catch_all_target: '' });- await loadDomains();- } catch (error) {- toast.error(`Failed to add domain: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleToggleDomain = async (domain) => {- try {- await api.request(`/mail/domains/${domain.id}`, {- method: 'PATCH',- body: { is_active: !domain.is_active },- });- toast.success(`Domain ${domain.is_active ? 'deactivated' : 'activated'}`);- await loadDomains();- } catch (error) {- // Preflight gate returns 409 — surface the guidance clearly.- toast.error(`Could not change domain state: ${error.message}`);- }- };-- const handleSaveCatchAll = async () => {- if (!catchAllModal) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${catchAllModal.id}`, {- method: 'PATCH',- body: { catch_all_target: catchAllModal.value.trim() },- });- toast.success('Catch-all updated');- setCatchAllModal(null);- await loadDomains();- } catch (error) {- toast.error(`Failed to update catch-all: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteDomain = (domain) => {- setConfirmDialog({- title: 'Delete domain',- message: `Delete ${domain.name} and all of its mailboxes and forwarders?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/domains/${domain.id}`, { method: 'DELETE' });- toast.success(`Domain ${domain.name} deleted`);- await loadDomains();- } catch (error) {- toast.error(`Failed to delete domain: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const openDnsForDomain = (domainId) => {- setSelectedDomainId(String(domainId));- navigate('/mail/dns');- };-- // ── Mailbox actions ──-- const handleAddMailbox = async (e) => {- e.preventDefault();- if (!selectedDomainId || !newMailbox.local_part.trim() || !newMailbox.password) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/mailboxes`, {- method: 'POST',- body: {- local_part: newMailbox.local_part.trim(),- password: newMailbox.password,- quota_mb: Number(newMailbox.quota_mb) || 0,- display_name: newMailbox.display_name.trim() || undefined,- },- });- toast.success('Mailbox created');- setShowMailboxForm(false);- setNewMailbox({ local_part: '', password: '', quota_mb: 0, display_name: '' });- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to create mailbox: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleToggleMailbox = async (mailbox) => {- try {- await api.request(`/mail/mailboxes/${mailbox.id}`, {- method: 'PATCH',- body: { is_active: !mailbox.is_active },- });- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to update mailbox: ${error.message}`);- }- };-- const handleChangePassword = async () => {- if (!passwordModal || !newPassword) return;- setActionLoading(true);- try {- await api.request(`/mail/mailboxes/${passwordModal.id}/password`, {- method: 'POST',- body: { password: newPassword },- });- toast.success('Password changed');- setPasswordModal(null);- setNewPassword('');- } catch (error) {- toast.error(`Failed to change password: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteMailbox = (mailbox) => {- setConfirmDialog({- title: 'Delete mailbox',- message: `Delete ${mailbox.address || mailbox.local_part}? The mailbox and its mail are removed.`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/mailboxes/${mailbox.id}`, { method: 'DELETE' });- toast.success('Mailbox deleted');- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to delete mailbox: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const openAutoResponder = async (mailbox) => {- setAutoModal({ id: mailbox.id, address: mailbox.address || mailbox.local_part });- setAutoResponder({ enabled: false, subject: '', body: '', start_at: '', end_at: '' });- try {- const data = await api.request(`/mail/mailboxes/${mailbox.id}/autoresponder`);- const ar = data.autoresponder || {};- setAutoResponder({- enabled: !!ar.enabled,- subject: ar.subject || '',- body: ar.body || '',- start_at: ar.start_at || '',- end_at: ar.end_at || '',- });- } catch (error) {- toast.error(`Failed to load autoresponder: ${error.message}`);- }- };-- const handleSaveAutoResponder = async () => {- if (!autoModal) return;- setActionLoading(true);- try {- await api.request(`/mail/mailboxes/${autoModal.id}/autoresponder`, {- method: 'PUT',- body: {- enabled: autoResponder.enabled,- subject: autoResponder.subject,- body: autoResponder.body,- start_at: autoResponder.start_at || null,- end_at: autoResponder.end_at || null,- },- });- toast.success('Autoresponder saved');- setAutoModal(null);- } catch (error) {- toast.error(`Failed to save autoresponder: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Forwarder actions ──-- const handleAddForwarder = async (e) => {- e.preventDefault();- if (!selectedDomainId || !newForwarder.source_local_part.trim() || !newForwarder.destination.trim()) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/forwarders`, {- method: 'POST',- body: {- source_local_part: newForwarder.source_local_part.trim(),- destination: newForwarder.destination.trim(),- keep_copy: newForwarder.keep_copy,- },- });- toast.success('Forwarder created');- setShowForwarderForm(false);- setNewForwarder({ source_local_part: '', destination: '', keep_copy: true });- await loadForwarders(selectedDomainId);- } catch (error) {- toast.error(`Failed to create forwarder: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteForwarder = (forwarder) => {- setConfirmDialog({- title: 'Delete forwarder',- message: `Delete the forwarder for ${forwarder.source || forwarder.source_local_part}?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/forwarders/${forwarder.id}`, { method: 'DELETE' });- toast.success('Forwarder deleted');- await loadForwarders(selectedDomainId);- } catch (error) {- toast.error(`Failed to delete forwarder: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- // ── DNS & DKIM actions ──-- const handleGenerateDkim = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/dkim`, { method: 'POST' });- toast.success('DKIM key generated');- await loadDns(selectedDomainId);- await loadDomains();- } catch (error) {- toast.error(`DKIM generation failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeployDns = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- const result = await api.request(`/mail/domains/${selectedDomainId}/dns/deploy`, { method: 'POST' });- if (result?.manual) toast.error('No DNS provider connected — publish the records manually');- else toast.success('DNS records deployed');- await loadDns(selectedDomainId);- } catch (error) {- toast.error(`DNS deploy failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRequestCert = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- const result = await api.request(`/mail/domains/${selectedDomainId}/cert`, { method: 'POST' });- if (result?.skipped) toast.error(result.error || 'Certificate request skipped');- else toast.success('Certificate requested');- } catch (error) {- toast.error(`Certificate request failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const copyValue = async (value) => {- try {- await navigator.clipboard.writeText(value);- toast.success('Copied to clipboard');- } catch {- toast.error('Could not copy to clipboard');- }- };-- // ── Queue actions ──-- const handleFlushQueue = async () => {- setActionLoading(true);- try {- await api.request('/mail/queue/flush', { method: 'POST' });- toast.success('Queue flush requested');- await loadQueue();- } catch (error) {- toast.error(`Failed to flush queue: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Render helpers ──-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));- const installed = !!status?.installed;- const selectedDomain = domains.find((d) => String(d.id) === String(selectedDomainId));-- const DomainSelector = () => (- <div className="mail-domain-picker">- <Label>Domain</Label>- <select- value={selectedDomainId}- onChange={(e) => setSelectedDomainId(e.target.value)}- className="mail-select"- >- <option value="">— Select a domain —</option>- {domains.map((d) => (- <option key={d.id} value={d.id}>{d.name}</option>- ))}- </select>- </div>- );-- const renderPreflightBanner = () => {- const passed = !!preflight?.passed;- return (- <div className={`card mail-preflight mail-preflight--${passed ? 'ok' : 'warn'}`}>- <div className="card-header">- <h3>- {passed- ? <><ShieldCheck size={16} /> Deliverability preflight passed</>- : <><ShieldAlert size={16} /> Sending is blocked until preflight passes</>}- </h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={handleRunPreflight} disabled={actionLoading}>- <RefreshCw size={14} /> Run preflight- </Button>- </div>- </div>- <div className="card-body">- {!preflight ? (- <p className="text-muted">- No preflight has run yet. Outbound mail stays disabled until PTR, port-25- egress and RBL checks pass — run a preflight to see where this host stands.- </p>- ) : (- <>- <div className="mail-preflight__checks">- <div className="mail-check">- <div className="mail-check__head">- <span className="k">PTR / reverse DNS</span>- {checkPill(preflight.ptr_ok, preflight.ptr_ok === null)}- </div>- <p className="text-muted">- {preflight.ptr_value- ? `Resolves to ${preflight.ptr_value}.`- : 'The public IP must resolve back to your mail hostname or receivers reject you.'}- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">Port 25 egress</span>- {checkPill(preflight.port25_ok, preflight.port25_ok === null)}- </div>- <p className="text-muted">- Many providers block outbound port 25. Without it this host cannot deliver mail directly.- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">RBL / blocklists</span>- {checkPill(preflight.rbl_ok, preflight.rbl_ok === null)}- </div>- <p className="text-muted">- {(preflight.rbl_hits && preflight.rbl_hits.length)- ? `Listed on: ${preflight.rbl_hits.join(', ')}`- : 'The IP is not on the blocklists we check.'}- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">Listening ports</span>- {checkPill(preflight.ports_ok, preflight.ports_ok === null)}- </div>- <p className="text-muted">- SMTP/submission/IMAPS ports (25/465/587/993) should be reachable on this host.- </p>- </div>- </div>- {preflight.checked_at && (- <p className="text-muted mail-preflight__ts">- Last checked {new Date(preflight.checked_at).toLocaleString()}- {' · '}- {passed- ? 'sending is allowed.'- : 'fix the failing checks (or force-activate a domain knowingly) before relying on delivery.'}- </p>- )}- </>- )}- </div>- </div>- );- };-- // ── Tab bodies ──-- const renderOverview = () => {- if (!installed) {- return (- <>- {renderPreflightBanner()}- <div className="card">- <div className="card-header"><h3>Mail Server Not Installed</h3></div>- <div className="card-body">- <p className="text-muted">- Run Stalwart (SMTP + IMAP + admin API) in a managed Docker container so this- box hosts mail for your domains — mailboxes, forwarders, autoresponders, and- automatic DKIM/SPF/DMARC/MX records.- </p>- <div className="mail-install-form">- <div className="form-group">- <Label>Mail hostname</Label>- <Input- type="text"- value={installHostname}- onChange={(e) => setInstallHostname(e.target.value)}- placeholder="mail.example.com"- />- <p className="text-muted">- The public hostname clients connect to. It should resolve to this box's- public IP and have a matching PTR record.- </p>- </div>- <div className="mail-install-actions">- <Button- variant="default"- onClick={handleInstall}- disabled={actionLoading || !installHostname.trim()}- >- {actionLoading ? 'Installing...' : 'Install Mail Server'}- </Button>- <Button variant="outline" onClick={loadStatus}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- </div>- </>- );- }-- return (- <>- {renderPreflightBanner()}- {status?.needs_setup === true && (- <div className="card mail-preflight mail-preflight--warn">- <div className="mail-preflight__head">- <span className="mail-preflight__title">- <ShieldAlert size={16} /> Finish the one-time Stalwart setup- </span>- </div>- <p className="text-muted">- The container is running in bootstrap mode — its admin API stays- offline until you complete the initial setup wizard, which creates- the permanent administrator. For safety the setup UI is bound to the- server's loopback only ({status.setup_url || 'http://127.0.0.1:8080/account'});- reach it over an SSH tunnel, then re-check.- </p>- <div className="mail-install-actions">- <Button variant="outline" size="sm" onClick={loadStatus}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- )}- <div className="card">- <div className="card-header">- <h3>Server Status</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)}>- <Trash2 size={14} /> Remove + data- </Button>- </div>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Container</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Engine</span>- <span className="v">- {status.engine || 'Stalwart'} {status.version ? `v${status.version}` : ''}- </span>- </div>- {status.hostname && (- <div className="sk-info-row">- <span className="k">Hostname</span>- <span className="v sk-cell-mono">{status.hostname}</span>- </div>- )}- {status.ports && (- <div className="sk-info-row">- <span className="k">Ports</span>- <span className="v sk-cell-mono">- {Array.isArray(status.ports) ? status.ports.join(', ') : String(status.ports)}- </span>- </div>- )}- </div>- <div className="mail-service-actions">- <Button variant="outline" size="sm" onClick={() => handleService('restart')} disabled={actionLoading}>- <RefreshCw size={14} /> Restart- </Button>- {status.running ? (- <Button variant="outline" size="sm" onClick={() => handleService('stop')} disabled={actionLoading}>- <Power size={14} /> Stop- </Button>- ) : (- <Button variant="default" size="sm" onClick={() => handleService('start')} disabled={actionLoading}>- <Power size={14} /> Start- </Button>- )}- </div>- </div>- </div>- </>- );- };-- const renderDomains = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Domains {domains.length > 0 && <span className="sec-count">· {domains.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowDomainForm((v) => !v)}>- <Plus size={14} /> {showDomainForm ? 'Cancel' : 'Add Domain'}- </Button>- </div>- </div>- {showDomainForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddDomain}>- <div className="form-group">- <Label>Domain name</Label>- <Input- type="text"- value={newDomain.name}- onChange={(e) => setNewDomain((f) => ({ ...f, name: e.target.value }))}- placeholder="example.com"- />- </div>- <div className="form-group">- <Label>Catch-all target (optional)</Label>- <Input- type="text"- value={newDomain.catch_all_target}- onChange={(e) => setNewDomain((f) => ({ ...f, catch_all_target: e.target.value }))}- placeholder="[email protected]"- />- </div>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newDomain.name.trim()}>- Add Domain- </Button>- </div>- </form>- </div>- )}- {domains.length === 0 ? (- <div className="card-body">- <p className="text-muted">No mail domains yet. Add one, then generate DKIM and publish its DNS records.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Domain</th>- <th>Catch-all</th>- <th>Sync</th>- <th>Status</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {domains.map((d) => (- <tr key={d.id}>- <td className="sk-cell-name">- <span className="mail-fav"><Globe size={14} /></span>- <span className="sk-cell-mono">{d.name}</span>- </td>- <td className="sk-cell-mono">{d.catch_all_target || '—'}</td>- <td>- {d.sync_state === 'error'- ? <Pill kind="amber" title={d.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={d.sync_state === 'synced' ? 'green' : 'gray'}>{d.sync_state || 'pending'}</Pill>}- </td>- <td>- <Pill kind={d.is_active ? 'green' : 'gray'}>{d.is_active ? 'active' : 'inactive'}</Pill>- </td>- <td>- <div className="mail-row-actions">- <Button variant="secondary" size="sm" onClick={() => handleToggleDomain(d)}>- {d.is_active ? 'Deactivate' : 'Activate'}- </Button>- <Button variant="secondary" size="sm" onClick={() => setCatchAllModal({ id: d.id, name: d.name, value: d.catch_all_target || '' })}>- Catch-all- </Button>- <Button variant="secondary" size="sm" onClick={() => openDnsForDomain(d.id)}>- <KeyRound size={14} /> DNS- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteDomain(d)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- );-- const renderMailboxes = () => (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>Mailboxes {mailboxes.length > 0 && <span className="sec-count">· {mailboxes.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowMailboxForm((v) => !v)}>- <Plus size={14} /> {showMailboxForm ? 'Cancel' : 'Add Mailbox'}- </Button>- </div>- </div>- {showMailboxForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddMailbox}>- <div className="form-grid">- <div className="form-group">- <Label>Local part</Label>- <Input- type="text"- value={newMailbox.local_part}- onChange={(e) => setNewMailbox((f) => ({ ...f, local_part: e.target.value }))}- placeholder="alice"- />- </div>- <div className="form-group">- <Label>Display name (optional)</Label>- <Input- type="text"- value={newMailbox.display_name}- onChange={(e) => setNewMailbox((f) => ({ ...f, display_name: e.target.value }))}- placeholder="Alice Doe"- />- </div>- <div className="form-group">- <Label>Password</Label>- <Input- type="password"- value={newMailbox.password}- onChange={(e) => setNewMailbox((f) => ({ ...f, password: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Quota (MB, 0 = unlimited)</Label>- <Input- type="number"- min="0"- value={newMailbox.quota_mb}- onChange={(e) => setNewMailbox((f) => ({ ...f, quota_mb: e.target.value }))}- />- </div>- </div>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newMailbox.local_part.trim() || !newMailbox.password}>- Create Mailbox- </Button>- </div>- </form>- </div>- )}- {mailboxes.length === 0 ? (- <div className="card-body">- <p className="text-muted">No mailboxes for {selectedDomain?.name} yet.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Address</th>- <th>Quota</th>- <th>Sync</th>- <th>Status</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {mailboxes.map((m) => (- <tr key={m.id}>- <td className="sk-cell-name">- <span className="mail-fav mail-fav--cyan"><AtSign size={14} /></span>- <span className="sk-cell-mono">{m.address || `${m.local_part}@${selectedDomain?.name || ''}`}</span>- </td>- <td className="sk-cell-mono">{m.quota_mb ? `${m.quota_mb} MB` : 'unlimited'}</td>- <td>- {m.sync_state === 'error'- ? <Pill kind="amber" title={m.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={m.sync_state === 'synced' ? 'green' : 'gray'}>{m.sync_state || 'pending'}</Pill>}- </td>- <td>- <Pill kind={m.is_active ? 'green' : 'gray'}>{m.is_active ? 'active' : 'disabled'}</Pill>- </td>- <td>- <div className="mail-row-actions">- <Button variant="secondary" size="sm" onClick={() => handleToggleMailbox(m)}>- {m.is_active ? 'Disable' : 'Enable'}- </Button>- <Button variant="secondary" size="sm" onClick={() => { setPasswordModal({ id: m.id, address: m.address || m.local_part }); setNewPassword(''); }}>- Password- </Button>- <Button variant="secondary" size="sm" onClick={() => openAutoResponder(m)}>- Autoreply- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteMailbox(m)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}- </>- );-- const renderForwarders = () => (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>Forwarders {forwarders.length > 0 && <span className="sec-count">· {forwarders.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowForwarderForm((v) => !v)}>- <Plus size={14} /> {showForwarderForm ? 'Cancel' : 'Add Forwarder'}- </Button>- </div>- </div>- {showForwarderForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddForwarder}>- <div className="form-grid">- <div className="form-group">- <Label>Source local part</Label>- <Input- type="text"- value={newForwarder.source_local_part}- onChange={(e) => setNewForwarder((f) => ({ ...f, source_local_part: e.target.value }))}- placeholder="sales"- />- </div>- <div className="form-group">- <Label>Destination</Label>- <Input- type="text"- value={newForwarder.destination}- onChange={(e) => setNewForwarder((f) => ({ ...f, destination: e.target.value }))}- placeholder="[email protected]"- />- </div>- </div>- <label className="mail-check-label">- <input- type="checkbox"- checked={newForwarder.keep_copy}- onChange={(e) => setNewForwarder((f) => ({ ...f, keep_copy: e.target.checked }))}- />- {' '}Keep a copy in the local mailbox- </label>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newForwarder.source_local_part.trim() || !newForwarder.destination.trim()}>- Add Forwarder- </Button>- </div>- </form>- </div>- )}- {forwarders.length === 0 ? (- <div className="card-body">- <p className="text-muted">No forwarders for {selectedDomain?.name} yet.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Source</th>- <th />- <th>Destination</th>- <th>Copy</th>- <th>Sync</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {forwarders.map((f) => (- <tr key={f.id}>- <td className="sk-cell-mono">{f.source || `${f.source_local_part}@${selectedDomain?.name || ''}`}</td>- <td className="mail-arrow"><Forward size={14} /></td>- <td className="sk-cell-mono">{f.destination}</td>- <td><Pill kind={f.keep_copy ? 'cyan' : 'gray'}>{f.keep_copy ? 'keeps copy' : 'no copy'}</Pill></td>- <td>- {f.sync_state === 'error'- ? <Pill kind="amber" title={f.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={f.sync_state === 'synced' ? 'green' : 'gray'}>{f.sync_state || 'pending'}</Pill>}- </td>- <td>- <div className="mail-row-actions">- <Button variant="destructive" size="sm" onClick={() => handleDeleteForwarder(f)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}- </>- );-- const renderDns = () => {- const records = dnsInfo?.records || [];- return (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>DNS & DKIM {selectedDomain ? `· ${selectedDomain.name}` : ''}</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={handleGenerateDkim} disabled={actionLoading}>- <KeyRound size={14} /> Generate DKIM- </Button>- <Button variant="default" size="sm" onClick={handleDeployDns} disabled={actionLoading}>- Push to provider- </Button>- <Button variant="secondary" size="sm" onClick={handleRequestCert} disabled={actionLoading}>- Request cert- </Button>- </div>- </div>- <div className="card-body">- <div className="sk-info-row">- <span className="k">Deploy status</span>- {dnsInfo?.deployed- ? <Pill kind="green">deployed</Pill>- : <Pill kind="amber">{dnsInfo?.manual ? 'manual publish needed' : 'not deployed'}</Pill>}- </div>- {dnsInfo?.provider && (- <div className="sk-info-row">- <span className="k">Provider</span>- <span className="v">{dnsInfo.provider}</span>- </div>- )}- <p className="text-muted mail-dns-hint">- Publish these records at your DNS provider (or push them automatically if a- provider is connected). MX + SPF + DKIM + DMARC are what receivers check to- trust your mail.- </p>- </div>- {records.length === 0 ? (- <div className="card-body">- <p className="text-muted">- No records yet. Generate a DKIM key to produce the full record set for {selectedDomain?.name}.- </p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Type</th>- <th>Name</th>- <th>Value</th>- <th>State</th>- <th />- </tr>- </thead>- <tbody>- {records.map((r, i) => {- const value = r.priority != null ? `${r.priority} ${r.value}` : r.value;- return (- <tr key={`${r.type}-${r.name}-${i}`}>- <td><span className="sk-tag">{r.type}</span></td>- <td className="sk-cell-mono">{r.name}</td>- <td className="sk-cell-mono mail-dns-value">{value}</td>- <td>- {(r.deployed ?? r.status === 'deployed')- ? <Pill kind="green">set</Pill>- : <Pill kind="gray">pending</Pill>}- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => copyValue(value)}>- <Copy size={14} /> Copy- </Button>- </td>- </tr>- );- })}- </tbody>- </table>- )}- </div>- )}- </>- );- };-- const renderQueue = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Outbound Queue {queue.messages.length > 0 && <span className="sec-count">· {queue.messages.length}</span>}</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={loadQueue} disabled={actionLoading}>- <RefreshCw size={14} /> Refresh- </Button>- <Button variant="default" size="sm" onClick={handleFlushQueue} disabled={actionLoading}>- <Send size={14} /> Flush queue- </Button>- </div>- </div>- {queue.messages.length === 0 ? (- <div className="card-body">- <EmptyState- icon={Inbox}- title="Queue is empty"- description={queue.note || 'No messages are waiting to be delivered.'}- />- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>ID</th>- <th>From</th>- <th>Recipients</th>- <th>Status</th>- <th>Queued</th>- </tr>- </thead>- <tbody>- {queue.messages.map((m, i) => (- <tr key={m.id ?? m.queue_id ?? i}>- <td className="sk-cell-mono">{m.id ?? m.queue_id ?? '—'}</td>- <td className="sk-cell-mono">{m.from || m.sender || '—'}</td>- <td className="sk-cell-mono">- {Array.isArray(m.recipients) ? m.recipients.join(', ') : (m.to || m.recipients || '—')}- </td>- <td>{m.status || m.state || '—'}</td>- <td className="sk-cell-mono">{m.created || m.arrival_time || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- );-- // ── Page shell ──-- if (loading) {- return (- <div className="page-container mail-page">- <PageTopbar icon={<Mail size={18} />} title="Mail Server" />- <EmptyState loading title="Loading mail server status..." />- </div>- );- }-- return (- <div className="page-container mail-page">- <PageTopbar- icon={<Mail size={18} />}- title="Mail Server"- meta={<>Stalwart · SMTP · IMAP · DKIM</>}- tabs={topbarTabs}- actions={- <Button variant="outline" size="sm" onClick={loadStatus}>- <RefreshCw size={14} /> Refresh- </Button>- }- />-- {activeTab === 'overview' && renderOverview()}- {activeTab === 'domains' && renderDomains()}- {activeTab === 'mailboxes' && renderMailboxes()}- {activeTab === 'forwarders' && renderForwarders()}- {activeTab === 'dns' && renderDns()}- {activeTab === 'queue' && renderQueue()}-- {/* ── Catch-all modal ── */}- <Modal open={!!catchAllModal} onClose={() => setCatchAllModal(null)} title={`Catch-all · ${catchAllModal?.name || ''}`}>- <div className="form-group">- <Label>Catch-all target</Label>- <Input- type="text"- value={catchAllModal?.value || ''}- onChange={(e) => setCatchAllModal((m) => ({ ...m, value: e.target.value }))}- placeholder="[email protected]"- />- <p className="text-muted">Leave empty to disable catch-all delivery for this domain.</p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setCatchAllModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleSaveCatchAll} disabled={actionLoading}>Save</Button>- </div>- </Modal>-- {/* ── Password modal ── */}- <Modal open={!!passwordModal} onClose={() => setPasswordModal(null)} title={`Change password · ${passwordModal?.address || ''}`}>- <div className="form-group">- <Label>New password</Label>- <Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setPasswordModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleChangePassword} disabled={actionLoading || !newPassword}>Change</Button>- </div>- </Modal>-- {/* ── Autoresponder modal ── */}- <Modal open={!!autoModal} onClose={() => setAutoModal(null)} title={`Autoresponder · ${autoModal?.address || ''}`}>- <label className="mail-check-label">- <input- type="checkbox"- checked={autoResponder.enabled}- onChange={(e) => setAutoResponder((a) => ({ ...a, enabled: e.target.checked }))}- />- {' '}Enabled- </label>- <div className="form-group">- <Label>Subject</Label>- <Input- type="text"- value={autoResponder.subject}- onChange={(e) => setAutoResponder((a) => ({ ...a, subject: e.target.value }))}- placeholder="Out of office"- />- </div>- <div className="form-group">- <Label>Body</Label>- <textarea- className="mail-textarea"- rows={5}- value={autoResponder.body}- onChange={(e) => setAutoResponder((a) => ({ ...a, body: e.target.value }))}- placeholder="I'm away until..."- />- </div>- <div className="form-grid">- <div className="form-group">- <Label>Start (optional)</Label>- <Input- type="datetime-local"- value={autoResponder.start_at || ''}- onChange={(e) => setAutoResponder((a) => ({ ...a, start_at: e.target.value }))}- />- </div>- <div className="form-group">- <Label>End (optional)</Label>- <Input- type="datetime-local"- value={autoResponder.end_at || ''}- onChange={(e) => setAutoResponder((a) => ({ ...a, end_at: e.target.value }))}- />- </div>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setAutoModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleSaveAutoResponder} disabled={actionLoading}>Save</Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default MailPage;diff --git a/builtin-extensions/serverkit-mail/frontend/index.jsx b/builtin-extensions/serverkit-mail/frontend/index.jsxdeleted file mode 100644index 3fc7e623..00000000--- a/builtin-extensions/serverkit-mail/frontend/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// Self-hosted mail server UI (Stalwart engine), contributed through the-// extension system. Fully self-contained in the extension — no core page to-// wrap. After sync this folder lives at frontend/src/plugins/serverkit-mail/,-// so '@/…' host aliases resolve.-export { default as MailPage } from './components/MailPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/builtin-extensions/serverkit-mail/frontend/styles/mail.scss b/builtin-extensions/serverkit-mail/frontend/styles/mail.scssdeleted file mode 100644index f2b89802..00000000--- a/builtin-extensions/serverkit-mail/frontend/styles/mail.scss+++ /dev/null@@ -1,156 +0,0 @@-/* Mail Server extension — layout-only styles. Colors, typography, spacing and- controls all inherit from the host design system (card, sk-dtable,- sk-info-row, Pill, empty-state…). No hardcoded palette; the few surface tints- below lean on currentColor / neutral rgba so they read in both themes. */--.mail-page .mail-install-form {- max-width: 480px;- margin-top: 16px;-}--.mail-page .mail-install-actions {- display: flex;- gap: 8px;- margin-top: 12px;-}--.mail-page .mail-service-actions {- display: flex;- gap: 8px;- margin-top: 16px;-}--.mail-page .mail-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;-}--.mail-page .mail-form {- display: flex;- flex-direction: column;- gap: 12px;- max-width: 640px;-}--.mail-page .form-grid {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 12px;-}--@media (max-width: 640px) {- .mail-page .form-grid {- grid-template-columns: 1fr;- }-}--.mail-page .mail-domain-picker {- display: flex;- flex-direction: column;- gap: 6px;- max-width: 360px;-}--.mail-page .mail-select {- width: 100%;- padding: 8px 10px;- border-radius: 6px;- font: inherit;- color: inherit;- background: transparent;- border: 1px solid rgba(128, 128, 128, 0.35);-}--.mail-page .mail-fav {- display: inline-flex;- align-items: center;- justify-content: center;- margin-right: 8px;- opacity: 0.75;-}--.mail-page .mail-arrow {- text-align: center;- opacity: 0.6;-}--.mail-page .mail-check-label {- display: inline-flex;- align-items: center;- gap: 6px;- cursor: pointer;-}--.mail-page .mail-textarea {- width: 100%;- font: inherit;- color: inherit;- background: transparent;- border: 1px solid rgba(128, 128, 128, 0.35);- border-radius: 6px;- padding: 8px;- resize: vertical;-}--.mail-page .mail-dns-hint {- margin-top: 10px;-}--.mail-page .mail-dns-value {- word-break: break-all;- max-width: 420px;-}--/* ── Preflight banner (the deliverability gate) ── */--.mail-page .mail-preflight .card-header h3 {- display: flex;- align-items: center;- gap: 8px;-}--.mail-page .mail-preflight--warn {- border-color: rgba(214, 158, 46, 0.55);-}--.mail-page .mail-preflight__checks {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 14px;- margin-top: 4px;-}--@media (max-width: 720px) {- .mail-page .mail-preflight__checks {- grid-template-columns: 1fr;- }-}--.mail-page .mail-check {- padding: 10px 12px;- border-radius: 8px;- border: 1px solid rgba(128, 128, 128, 0.25);-}--.mail-page .mail-check__head {- display: flex;- align-items: center;- justify-content: space-between;- gap: 8px;- margin-bottom: 4px;-}--.mail-page .mail-check__head .k {- font-weight: 500;-}--.mail-page .mail-check p {- margin: 0;- font-size: 0.85em;-}--.mail-page .mail-preflight__ts {- margin-top: 12px;- font-size: 0.85em;-}diff --git a/builtin-extensions/serverkit-mail/plugin.json b/builtin-extensions/serverkit-mail/plugin.jsondeleted file mode 100644index 7d5b8345..00000000--- a/builtin-extensions/serverkit-mail/plugin.json+++ /dev/null@@ -1,53 +0,0 @@-{- "name": "serverkit-mail",- "display_name": "Mail Server",- "version": "1.0.0",- "description": "Self-hosted mail server powered by Stalwart in a managed Docker container, providing domains, mailboxes, forwarders, and autoresponders, with automatic DKIM/SPF/DMARC/MX record deployment, a deliverability preflight (PTR, port-25 egress, RBL) that gates outbound sending, brute-force jails, and maildir backups. Most panels never run a mail server, so it ships as an opt-in extension.",- "author": "ServerKit",- "license": "MIT",- "category": "integration",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["shell", "filesystem", "network", "docker"],- "min_panel_version": "1.7.0",- "entry_point": "mail:mail_bp",- "url_prefix": "/api/v1/mail",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "jobs": [- { "kind": "mail.preflight.run", "handler": "jobs:run_preflight" },- { "kind": "mail.queue.flush", "handler": "jobs:flush_queue" }- ],- "schedules": [- { "name": "mail-preflight-daily", "kind": "mail.preflight.run", "cron": "0 6 * * *" }- ],- "icon": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"/><path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\"/>",- "contributions": {- "nav": [- {- "id": "mail",- "label": "Mail Server",- "route": "/mail",- "category": "operations",- "icon": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"/><path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\"/>"- }- ],- "routes": [- { "path": "mail", "component": "MailPage" },- { "path": "mail/:tab", "component": "MailPage" }- ],- "page_titles": {- "/mail": "Mail Server"- },- "command_palette": [- {- "label": "Mail Server",- "path": "/mail",- "category": "Pages",- "keywords": "mail smtp imap stalwart mailbox domain dkim spf dmarc mx deliverability forwarder autoresponder queue"- }- ]- }-}diff --git a/builtin-extensions/serverkit-tramo/backend/__init__.py b/builtin-extensions/serverkit-tramo/backend/__init__.pydeleted file mode 100644index b86d1323..00000000--- a/builtin-extensions/serverkit-tramo/backend/__init__.py+++ /dev/null@@ -1,10 +0,0 @@-"""ServerKit Automations extension backend package (tramo engine).--Embeds tramo (github.com/jhd3197/tramo) as the panel's workflow-automation-surface. The panel is the system of record for workflow docs; a managed-``@tramo/server`` Docker container on the panel host is the executor. See-docs/plans/45_TRAMO_AUTOMATIONS_EXTENSION_PLAN.md.-"""-from .tramo import tramo_bp--__all__ = ['tramo_bp']diff --git a/builtin-extensions/serverkit-tramo/backend/events_bridge.py b/builtin-extensions/serverkit-tramo/backend/events_bridge.pydeleted file mode 100644index 1bb35df2..00000000--- a/builtin-extensions/serverkit-tramo/backend/events_bridge.py+++ /dev/null@@ -1,166 +0,0 @@-"""Panel <-> tramo wiring (serverkit-tramo / Automations extension, plan 45 Phase 3).--Two integrations that let panel automations reach the outside world and act back-on the panel:--* **Events bridge** — one managed :class:`EventSubscription` whose ``url`` points- at the container's ``serverkit:event`` webhook trigger (``/sk/events`` via the- hooks passthrough). Subscribing to ``["*"]`` means every panel event is POSTed- to tramo; workflows filter with ``if``/``switch`` on ``trigger.body.event``.- Toggled on/off from the Settings tab; its id is remembered in plugin config.--* **Call-back key** — a scoped :class:`ApiKey` named ``serverkit-tramo`` issued- on engine install and injected into the container as ``SERVERKIT_API_KEY`` so- the ``@tramo/serverkit`` pack can start/stop/deploy apps, run backups, and send- notifications. Revoked on uninstall.--All helpers are best-effort and never raise into install/uninstall.-"""-import logging--from app import db--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Scopes the call-back key is granted. Matches the @tramo/serverkit pack actions:-# app-control/deploy (apps:*), backup-run (backups:write), list/get (read).-CALLBACK_KEY_NAME = 'serverkit-tramo'-CALLBACK_SCOPES = ['read', 'apps:read', 'apps:write', 'apps:deploy', 'backups:write']--# The path (under the hooks passthrough) the managed subscription targets, and-# which the container maps to a serverkit:event webhook-trigger node.-EVENTS_TRIGGER_PATH = 'sk/events'---def _config():- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)---def _save_config(updates):- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True---def _admin_user_id():- """Owner for the managed ApiKey / EventSubscription (first admin, else any)."""- from app.models.user import User- admin = User.query.filter_by(role=User.ROLE_ADMIN).order_by(User.id).first()- if admin:- return admin.id- any_user = User.query.order_by(User.id).first()- return any_user.id if any_user else None---# --------------------------------------------------------------------------- #-# Call-back key-# --------------------------------------------------------------------------- #--def issue_callback_key():- """Issue (or reissue) the scoped ``serverkit-tramo`` ApiKey.-- Returns the RAW key string (only available at creation) or None on failure.- The key id is stored in plugin config for later revocation.- """- from app.models.api_key import ApiKey-- user_id = _admin_user_id()- if not user_id:- logger.warning('tramo: no user to own the call-back API key')- return None-- # Revoke any previous managed key first (rotate).- revoke_callback_key()-- raw, prefix, key_hash = ApiKey.generate_key()- key = ApiKey(- user_id=user_id,- name=CALLBACK_KEY_NAME,- key_prefix=prefix,- key_hash=key_hash,- )- key.set_scopes(CALLBACK_SCOPES)- db.session.add(key)- db.session.commit()- _save_config({'callback_key_id': key.id})- return raw---def revoke_callback_key():- """Revoke the managed call-back ApiKey (best-effort)."""- from datetime import datetime- from app.models.api_key import ApiKey-- key_id = _config().get('callback_key_id')- if not key_id:- return False- key = ApiKey.query.get(key_id)- if key:- key.is_active = False- key.revoked_at = datetime.utcnow()- db.session.commit()- _save_config({'callback_key_id': None})- return True---# --------------------------------------------------------------------------- #-# Events bridge-# --------------------------------------------------------------------------- #--def is_events_bridge_enabled():- return bool(_config().get('events_subscription_id'))---def enable_events_bridge():- """Create the managed EventSubscription (idempotent). Returns its id or None."""- from app.models.event_subscription import EventSubscription-- existing_id = _config().get('events_subscription_id')- if existing_id and EventSubscription.query.get(existing_id):- return existing_id-- user_id = _admin_user_id()- if not user_id:- logger.warning('tramo: no user to own the events subscription')- return None-- from .host_service import TramoHostService- port = TramoHostService.host_port()- secret = EventSubscription.generate_secret()-- sub = EventSubscription(- user_id=user_id,- name='Automations (tramo) events bridge',- url=f'http://127.0.0.1:{port}/{EVENTS_TRIGGER_PATH}',- secret=secret,- is_active=True,- )- sub.set_events(['*'])- db.session.add(sub)- db.session.commit()- _save_config({'events_subscription_id': sub.id, 'events_secret': secret})- return sub.id---def disable_events_bridge():- """Delete the managed EventSubscription (best-effort). Returns True if removed."""- from app.models.event_subscription import EventSubscription-- sub_id = _config().get('events_subscription_id')- if not sub_id:- return False- sub = EventSubscription.query.get(sub_id)- if sub:- db.session.delete(sub)- db.session.commit()- _save_config({'events_subscription_id': None, 'events_secret': None})- return Truediff --git a/builtin-extensions/serverkit-tramo/backend/host_service.py b/builtin-extensions/serverkit-tramo/backend/host_service.pydeleted file mode 100644index a1f38e66..00000000--- a/builtin-extensions/serverkit-tramo/backend/host_service.py+++ /dev/null@@ -1,423 +0,0 @@-"""tramo engine host service (serverkit-tramo / Automations extension).--Runs ``@tramo/server`` (the headless tramo workflow host) in a managed Docker-container so the panel host can execute automation workflows: webhooks, cron,-run history, approvals. Driven through tramo's HTTP API, published on loopback-only.--Design mirrors serverkit-mail's :class:`StalwartService` exactly:--* **Two choke-points** — every Docker invocation goes through :meth:`_docker`- (privilege escalation, timeouts, error shaping) and every tramo-API call goes- through :meth:`_api` (Bearer auth, JSON, error shaping). Nothing else shells- out or talks HTTP.-* **Best-effort, Linux-only** — on Windows (dev) or when Docker is absent, calls- return a clean error dict instead of raising.-* **Panel DB is the source of truth** — workflow docs live in- ``ext_serverkit_tramo_*``; :mod:`workflow_store` materializes enabled docs into- the bind-mounted workflows dir and this service restarts the container.-* **Secrets in the config store** — the generated Bearer API key, the container- ``host_port``, an encrypted map of pack credentials (TELEGRAM_BOT_TOKEN, ...),- and the scoped panel call-back key all live in the plugin config store- (``plugins_sdk.config`` + the ``_save_config`` pattern), encrypted at rest.--The container is a *stateless executor*: it reads workflow ``.json`` files once-at boot (no server-side editing) and keeps run history in an in-memory ring, so-the panel harvests runs (see jobs) and re-deploys by restarting the container.-"""-import logging-import os-import secrets-import subprocess--import requests--from app.utils.system import run_privileged, is_command_available--try:- from app.utils.crypto import encrypt_secret, decrypt_secret_safe-except Exception: # pragma: no cover - crypto util should always be present- encrypt_secret = None- decrypt_secret_safe = None--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Pinned tramo-server image (GHCR, full-pack entry). Bumped deliberately like the-# Stalwart image, not floated. Published by the tramo repo's docker CI (plan 45-# Phase 0); until that ships this tag will not pull on a real box.-IMAGE = 'ghcr.io/jhd3197/tramo-server:0.1.1'-CONTAINER_NAME = 'serverkit-tramo'--# Host data dirs (bind-mounted). workflows/ holds the materialized <slug>.json-# docs; state/ is tramo's durable checkpoint store (suspend/resume survives a-# restart, so re-deploy = restart is safe).-DATA_DIR = '/var/serverkit/tramo'-HOST_WORKFLOWS_DIR = f'{DATA_DIR}/workflows'-HOST_STATE_DIR = f'{DATA_DIR}/state'-CONTAINER_WORKFLOWS_DIR = '/workflows'-CONTAINER_STATE_DIR = '/state'-CONTAINER_PORT = 3000--# tramo HTTP API — published on 127.0.0.1 only, never reachable off-host.-API_HOST = '127.0.0.1'-DEFAULT_HOST_PORT = 8377-API_TIMEOUT = 15-RUN_TIMEOUT = 120-DOCKER_TIMEOUT = 180--DOCS_URL = 'https://github.com/jhd3197/tramo'---class TramoHostService:- """Stateless wrapper around Docker + the tramo-server HTTP API."""-- # ---------- config (plugin config store) ------------ @classmethod- def _config(cls):- """Saved extension settings from the plugin config store."""- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)-- @classmethod- def _save_config(cls, updates):- """Merge *updates* into the plugin's stored config.-- The SDK ``config()`` helper is read-only (the panel owns writes), so- generated secrets are persisted through the InstalledPlugin row directly.- Returns False when the plugin row is absent (dev shells / tests without a- row).- """- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- logger.warning('%s: no InstalledPlugin row; config not persisted', SLUG)- return False- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()- return True-- # ---------- secret helpers ------------ @classmethod- def _encrypt(cls, plaintext):- if not plaintext:- return plaintext- if encrypt_secret is None:- return plaintext- return encrypt_secret(plaintext)-- @classmethod- def _decrypt(cls, value):- if not value:- return value- if decrypt_secret_safe is None:- return value- return decrypt_secret_safe(value)-- @classmethod- def _is_windows(cls):- """Windows (dev) has no Docker engine for us. Single testable seam so- tests can force either platform without touching the global ``os.name``- (which would break ``pathlib``)."""- return os.name == 'nt'-- @classmethod- def host_port(cls):- """Loopback host port the container's API is published on."""- try:- return int(cls._config().get('host_port') or DEFAULT_HOST_PORT)- except (TypeError, ValueError):- return DEFAULT_HOST_PORT-- @classmethod- def api_base(cls):- return f'http://{API_HOST}:{cls.host_port()}/api'-- @classmethod- def api_key(cls):- """Decrypted Bearer API key (empty string when not installed)."""- return cls._decrypt(cls._config().get('api_key')) or ''-- @classmethod- def get_pack_secrets(cls):- """Decrypted {ENV_NAME: value} map of pack credentials."""- stored = cls._config().get('pack_secrets') or {}- out = {}- for k, v in stored.items():- out[k] = cls._decrypt(v)- return out-- @classmethod- def set_pack_secrets(cls, secrets_map):- """Encrypt and persist a {ENV_NAME: value} map. Empty value deletes a key.-- Returns the new set of configured env-var names (values never returned).- """- current = dict(cls._config().get('pack_secrets') or {})- for name, value in (secrets_map or {}).items():- name = (name or '').strip()- if not name:- continue- if value in (None, ''):- current.pop(name, None)- else:- current[name] = cls._encrypt(str(value))- cls._save_config({'pack_secrets': current})- return sorted(current.keys())-- # ---------- docker choke-point ------------ @classmethod- def _docker(cls, args, timeout=DOCKER_TIMEOUT):- """Run ``docker <args>`` and return a normalized result dict. Never raises."""- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- if not is_command_available('docker'):- return {'success': False, 'not_installed': True,- 'error': 'Docker is not installed on this host.'}- cmd = ['docker'] + list(args)- try:- result = run_privileged(cmd, timeout=timeout)- except subprocess.TimeoutExpired:- return {'success': False, 'error': f'docker timed out after {timeout}s'}- except (OSError, subprocess.SubprocessError) as e:- return {'success': False, 'error': f'Failed to run docker: {e}'}- out = {- 'success': result.returncode == 0,- 'returncode': result.returncode,- 'stdout': result.stdout or '',- 'stderr': result.stderr or '',- }- if not out['success']:- out['error'] = (out['stderr'] or out['stdout'] or 'docker failed').strip()- return out-- # ---------- tramo API choke-point ------------ @classmethod- def _api(cls, method, path, payload=None, timeout=API_TIMEOUT):- """Call the container's tramo HTTP API (loopback only).-- Returns ``{'success': True, 'data': <json-or-None>, 'status_code': int}``- or an error dict. Auth is Bearer with the generated API key. Never raises.- """- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- key = cls.api_key()- if not key:- return {'success': False,- 'error': 'tramo API key is not configured. Reinstall the engine.'}- headers = {'Authorization': f'Bearer {key}'}- try:- resp = requests.request(- method, cls.api_base() + path,- headers=headers, json=payload, timeout=timeout,- )- except requests.RequestException as e:- return {'success': False,- 'error': f'tramo API is unreachable: {e}'}- result = {'success': resp.status_code < 400, 'status_code': resp.status_code}- if resp.status_code >= 400:- try:- body = resp.json()- detail = (body.get('error') or body.get('message')- or body.get('detail') or resp.text)- except ValueError:- detail = resp.text- result['error'] = f'tramo API error ({resp.status_code}): {detail}'.strip()- return result- if not resp.content:- result['data'] = None- return result- try:- result['data'] = resp.json()- except ValueError:- result['data'] = resp.text- return result-- # ---------- container lifecycle ------------ @classmethod- def is_installed(cls):- """True when the managed container exists (running or not)."""- if cls._is_windows():- return False- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- return bool(res.get('success'))-- @classmethod- def _panel_port(cls):- """Port the panel API listens on (for the container's call-back URL)."""- return str(cls._config().get('panel_port')- or os.environ.get('PORT') or '5000')-- @classmethod- def get_status(cls):- """Installed / running / health summary, best-effort."""- status = {- 'installed': False,- 'running': False,- 'healthy': None,- 'state': 'not_installed', # not_installed|stopped|unhealthy|ready- 'engine': 'tramo',- 'image': IMAGE,- 'container': CONTAINER_NAME,- 'host_port': cls.host_port(),- 'api': f'{API_HOST}:{cls.host_port()}',- 'docs_url': DOCS_URL,- }- if cls._is_windows():- status['error'] = 'The Automations extension is not supported on Windows.'- return status- res = cls._docker(['inspect', '--format', '{{.State.Running}}',- CONTAINER_NAME], timeout=20)- if not res.get('success'):- return status- status['installed'] = True- running = res.get('stdout', '').strip() == 'true'- status['running'] = running- if not running:- status['state'] = 'stopped'- return status- # Running: probe health to distinguish ready from starting/unhealthy.- probe = cls._api('GET', '/health', timeout=8)- if probe.get('success'):- status['healthy'] = True- status['state'] = 'ready'- data = probe.get('data')- if isinstance(data, dict):- status['version'] = data.get('version')- else:- status['healthy'] = False- status['state'] = 'unhealthy'- status['health_error'] = probe.get('error')- return status-- @classmethod- def health(cls):- """Raw health probe (GET /api/health). Best-effort dict."""- if not cls.is_installed():- return {'success': False, 'error': 'The Automations engine is not installed.'}- return cls._api('GET', '/health', timeout=8)-- @classmethod- def install(cls, host_port=None, callback_url=None, callback_api_key=None):- """Create and start the tramo-server container.-- * Workflows + checkpoint state bind-mounted under ``DATA_DIR``.- * HTTP API published on **127.0.0.1 only** with a generated Bearer key.- * Pack credentials + the scoped panel call-back key (SERVERKIT_URL /- SERVERKIT_API_KEY) injected as container env.- """- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- if cls.is_installed():- return {'success': False,- 'error': 'The Automations container already exists. Uninstall it first.'}-- port = int(host_port or cls.host_port())-- dir_res = run_privileged(['mkdir', '-p', HOST_WORKFLOWS_DIR, HOST_STATE_DIR])- if getattr(dir_res, 'returncode', 1) != 0:- return {'success': False,- 'error': f'Could not create data directory {DATA_DIR}: '- f'{(getattr(dir_res, "stderr", "") or "").strip()}'}-- api_key = secrets.token_urlsafe(32)-- run_args = cls._build_run_args(port, api_key, callback_url, callback_api_key)- res = cls._docker(run_args)- if not res.get('success'):- return {'success': False,- 'error': res.get('error', 'Failed to start the tramo container')}-- persisted = cls._save_config({- 'api_key': cls._encrypt(api_key),- 'host_port': port,- 'panel_port': cls._panel_port(),- })- result = {'success': True,- 'message': 'Automations engine installed',- 'container': CONTAINER_NAME,- 'host_port': port,- 'state': 'ready'}- if not persisted:- result['warning'] = ('Container started but the API key could not be '- 'persisted to the plugin config store.')- return result-- @classmethod- def _build_run_args(cls, port, api_key, callback_url=None, callback_api_key=None):- """Assemble the ``docker run`` argv. Split out so tests can assert it."""- run_args = [- 'run', '-d',- '--name', CONTAINER_NAME,- '--restart', 'unless-stopped',- # Let workflows call back to the panel on the host loopback.- '--add-host', 'host.docker.internal:host-gateway',- ]- # API published on 127.0.0.1 only.- run_args += ['-p', f'{API_HOST}:{port}:{CONTAINER_PORT}']- run_args += [- '-v', f'{HOST_WORKFLOWS_DIR}:{CONTAINER_WORKFLOWS_DIR}',- '-v', f'{HOST_STATE_DIR}:{CONTAINER_STATE_DIR}',- ]- # Bearer auth + load all first-party integration packs (full-pack entry).- run_args += ['-e', f'TRAMO_API_KEY={api_key}']- run_args += ['-e', 'TRAMO_PACKS=all']- # Panel call-back (SERVERKIT_URL/SERVERKIT_API_KEY consumed by the- # @tramo/serverkit pack via env fallback).- url = callback_url or f'http://host.docker.internal:{cls._panel_port()}'- run_args += ['-e', f'SERVERKIT_URL={url}']- if callback_api_key:- run_args += ['-e', f'SERVERKIT_API_KEY={callback_api_key}']- # Pack credentials (decrypted from the config store).- for name, value in cls.get_pack_secrets().items():- run_args += ['-e', f'{name}={value}']- run_args += [IMAGE]- return run_args-- @classmethod- def uninstall(cls, keep_data=True):- """Remove the container; optionally delete the data directory."""- if cls._is_windows():- return {'success': False,- 'error': 'The Automations extension is not supported on Windows.'}- res = cls._docker(['rm', '-f', CONTAINER_NAME])- if not res.get('success'):- # A missing container is not an error for uninstall.- if 'No such container' not in (res.get('error') or ''):- return {'success': False,- 'error': res.get('error', 'Failed to remove the tramo container')}- if not keep_data:- rm = run_privileged(['rm', '-rf', DATA_DIR])- if getattr(rm, 'returncode', 1) != 0:- return {'success': True,- 'warning': f'Container removed but data at {DATA_DIR} could '- f'not be deleted: {(getattr(rm, "stderr", "") or "").strip()}'}- cls._save_config({'api_key': None})- return {'success': True,- 'message': 'Automations engine removed'- + ('' if keep_data else ' (data deleted)')}-- @classmethod- def control(cls, action):- """Start / stop / restart the managed container."""- if action not in ('start', 'stop', 'restart'):- return {'success': False, 'error': f'Invalid action: {action!r}'}- if not cls.is_installed():- return {'success': False, 'error': 'The Automations engine is not installed.'}- res = cls._docker([action, CONTAINER_NAME], timeout=60)- if not res.get('success'):- return {'success': False, 'error': res.get('error', f'docker {action} failed')}- return {'success': True, 'message': f'Automations engine {action}ed', 'action': action}diff --git a/builtin-extensions/serverkit-tramo/backend/jobs.py b/builtin-extensions/serverkit-tramo/backend/jobs.pydeleted file mode 100644index cd152d5d..00000000--- a/builtin-extensions/serverkit-tramo/backend/jobs.py+++ /dev/null@@ -1,126 +0,0 @@-"""Background job handlers (serverkit-tramo / Automations 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).--* ``tramo.harvest_runs`` (:func:`harvest_runs`) -- pull recent runs from the- engine and upsert them into ``ext_serverkit_tramo_runs`` before the container's- in-memory ring evicts them; notify admins once per newly-seen failed run.-* ``tramo.health_check`` (:func:`health_check`) -- probe ``GET /api/health`` and- notify ``tramo.host_unreachable`` after repeated failures.-"""-import logging--logger = logging.getLogger(__name__)--SLUG = 'serverkit-tramo'--# Consecutive health failures before we notify (avoids flapping on a restart).-_HEALTH_FAIL_THRESHOLD = 2---def harvest_runs(job):- """Harvest recent runs from the engine into the DB. Never raises."""- try:- from .host_service import TramoHostService- from .run_sync import upsert_run-- if not TramoHostService.is_installed():- return {'skipped': True, 'reason': 'engine not installed'}-- res = TramoHostService._api('GET', '/runs?limit=200')- if not res.get('success'):- return {'skipped': True, 'reason': res.get('error', 'runs fetch failed')}-- data = res.get('data')- runs = data if isinstance(data, list) else (data or {}).get('runs') \- or (data or {}).get('items') or []-- harvested = 0- new_failures = 0- for run_json in runs:- row, is_new = upsert_run(run_json)- if row is None:- continue- harvested += 1- if is_new and (row.status or '').lower() in ('failed', 'error'):- _notify_run_failed(row)- new_failures += 1-- return {'harvested': harvested, 'new_failures': new_failures}- except Exception as e: # noqa: BLE001 -- a maintenance job must not crash the loop- logger.warning('tramo harvest_runs job failed: %s', e)- return {'error': str(e)}---def _notify_run_failed(row):- try:- from app.plugins_sdk import notify- notify.send('tramo.run_failed', to='admins',- data={'run_id': row.run_id,- 'workflow': row.workflow_slug,- 'error': row.error},- category='system')- except Exception as e: # noqa: BLE001- logger.debug('tramo.run_failed notify failed: %s', e)---def health_check(job):- """Probe engine health; notify after repeated failure. Never raises."""- try:- from .host_service import TramoHostService-- if not TramoHostService.is_installed():- _reset_health_streak()- return {'skipped': True, 'reason': 'engine not installed'}-- res = TramoHostService.health()- if res.get('success'):- _reset_health_streak()- return {'healthy': True}-- streak = _bump_health_streak()- if streak == _HEALTH_FAIL_THRESHOLD:- _notify_unreachable(res.get('error'))- return {'healthy': False, 'streak': streak}- except Exception as e: # noqa: BLE001- logger.warning('tramo health_check job failed: %s', e)- return {'error': str(e)}---def _health_config():- from app.plugins_sdk import config as plugin_config- return plugin_config(SLUG)---def _save_health(updates):- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug=SLUG).first()- if not row:- return- merged = dict(row.config or {})- merged.update(updates)- row.config = merged- db.session.commit()---def _bump_health_streak():- streak = int(_health_config().get('health_fail_streak') or 0) + 1- _save_health({'health_fail_streak': streak})- return streak---def _reset_health_streak():- if _health_config().get('health_fail_streak'):- _save_health({'health_fail_streak': 0})---def _notify_unreachable(error):- try:- from app.plugins_sdk import notify- notify.send('tramo.host_unreachable', to='admins',- data={'error': error}, category='system')- except Exception as e: # noqa: BLE001- logger.debug('tramo.host_unreachable notify failed: %s', e)diff --git a/builtin-extensions/serverkit-tramo/backend/lifecycle.py b/builtin-extensions/serverkit-tramo/backend/lifecycle.pydeleted file mode 100644index aedd4fd1..00000000--- a/builtin-extensions/serverkit-tramo/backend/lifecycle.py+++ /dev/null@@ -1,78 +0,0 @@-"""Install / uninstall lifecycle hooks (serverkit-tramo / Automations extension).--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`` registers the extension's notification events and retires any-ghost ``serverkit-workflows`` row left over from the builder this extension-replaces (plan 45 Phase 4). It does NOT start the container -- the operator does-that from the Automations Settings tab (mail pattern).--``on_uninstall`` tears down everything provisioned by the engine: the container,-the scoped call-back ApiKey, and the managed events-bridge subscription. Data-dirs are deleted only on ``--purge``.-"""-import logging--logger = logging.getLogger(__name__)---def on_install(plugin):- """Register notification events; retire the replaced Workflow Builder row."""- try:- from app.plugins_sdk import notify- notify.register_event(- 'tramo.host_unreachable',- 'The Automations engine became unreachable',- template='generic', severity='warning', category='system')- notify.register_event(- 'tramo.run_failed',- 'An automation run failed',- template='generic', severity='warning', category='system')- logger.info('serverkit-tramo installed: notification events registered')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_install notify hook error: %s', e)-- _retire_workflow_builder_row()---def _retire_workflow_builder_row():- """Remove any lingering serverkit-workflows InstalledPlugin row.-- The Workflow Builder extension is deleted from disk in plan 45 Phase 4, so- its backend/frontend no longer load, but an old InstalledPlugin row would- otherwise haunt the Marketplace as a broken entry (uninstall deletes the- row, so we mirror that). Best-effort.- """- try:- from app import db- from app.models.plugin import InstalledPlugin- row = InstalledPlugin.query.filter_by(slug='serverkit-workflows').first()- if row:- db.session.delete(row)- db.session.commit()- logger.info('serverkit-tramo: retired ghost serverkit-workflows row')- except Exception as e: # noqa: BLE001- logger.debug('serverkit-tramo: could not retire workflows row: %s', e)---def on_uninstall(plugin, purge=False):- """Stop/remove the container, revoke the call-back key, drop the events sub."""- try:- from .host_service import TramoHostService- if TramoHostService.is_installed():- result = TramoHostService.uninstall(keep_data=not purge)- logger.info('serverkit-tramo on_uninstall container: %s', result)- else:- logger.info('serverkit-tramo on_uninstall: container not present')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_uninstall container error: %s', e)-- try:- from . import events_bridge- events_bridge.revoke_callback_key()- events_bridge.disable_events_bridge()- logger.info('serverkit-tramo on_uninstall: call-back key + events bridge removed')- except Exception as e: # noqa: BLE001- logger.warning('serverkit-tramo on_uninstall bridge error: %s', e)diff --git a/builtin-extensions/serverkit-tramo/backend/models.py b/builtin-extensions/serverkit-tramo/backend/models.pydeleted file mode 100644index 9b508030..00000000--- a/builtin-extensions/serverkit-tramo/backend/models.py+++ /dev/null@@ -1,146 +0,0 @@-"""Data models for the serverkit-tramo (Automations) extension.--Two tables, both namespaced ``ext_serverkit_tramo_*`` (dash -> underscore) so-``--purge`` on uninstall drops exactly these:--* :class:`TramoWorkflow` — a workflow *document* the panel owns. The ``doc``- column holds a tramo ``WorkflowDoc`` (plain JSON) edited in the browser; the- ``slug`` doubles as the server-side workflow id and the ``<slug>.json``- filename materialized into the container's bind-mounted workflows dir.-* :class:`TramoRun` — a persisted summary of one execution, harvested from the- container's in-memory run ring (which evicts after 1000 runs) so run history- survives a restart.--Registration mirrors the serverkit-k8s pattern: importing this module defines-the tables on the shared metadata as a side effect; the manifest's-``models: "models:register"`` then calls :func:`register` (a no-op passthrough)-and the platform runs ``db.create_all()``.-"""-import json-from datetime import datetime--from app import db---class TramoWorkflow(db.Model):- __tablename__ = 'ext_serverkit_tramo_workflows'-- id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), nullable=False)- # Server-side workflow id + <slug>.json filename. Unique, URL-safe.- slug = db.Column(db.String(255), unique=True, nullable=False, index=True)-- # tramo WorkflowDoc JSON (edited by the embedded editor).- doc = db.Column(db.Text, nullable=True)-- enabled = db.Column(db.Boolean, default=True, nullable=False)- # Bumped on every doc save so the editor/UI can detect stale state.- doc_version = db.Column(db.Integer, default=1, nullable=False)-- created_at = db.Column(db.DateTime, default=datetime.utcnow)- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)- # Stamped when this workflow was last materialized + deployed to the engine.- deployed_at = db.Column(db.DateTime, nullable=True)- # doc_version captured at the last deploy. Dirty detection compares this to- # the live doc_version -- a version counter, not a timestamp, so the deploy- # commit's own updated_at bump can't make a just-deployed row look dirty.- deployed_version = db.Column(db.Integer, nullable=True)-- def get_doc(self):- """Return the parsed WorkflowDoc (empty dict if unset/invalid)."""- if not self.doc:- return {}- try:- return json.loads(self.doc)- except (ValueError, TypeError):- return {}-- def set_doc(self, doc):- """Store a WorkflowDoc (dict or JSON string)."""- if doc is None:- self.doc = None- elif isinstance(doc, str):- self.doc = doc- else:- self.doc = json.dumps(doc)-- def is_dirty(self):- """True when an enabled workflow needs a (re)deploy.-- Dirty when it has never been deployed or its doc changed since the last- deploy (``doc_version`` moved past ``deployed_version``). Disabled- workflows are never dirty -- they materialize to nothing.- """- if not self.enabled:- return False- if not self.deployed_at:- return True- return (self.doc_version or 1) > (self.deployed_version or 0)-- def to_dict(self, include_doc=False):- out = {- 'id': self.id,- 'name': self.name,- 'slug': self.slug,- 'enabled': self.enabled,- 'doc_version': self.doc_version,- 'dirty': self.is_dirty(),- 'created_at': self.created_at.isoformat() if self.created_at else None,- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,- 'deployed_at': self.deployed_at.isoformat() if self.deployed_at else None,- }- if include_doc:- out['doc'] = self.get_doc()- return out---class TramoRun(db.Model):- __tablename__ = 'ext_serverkit_tramo_runs'-- id = db.Column(db.Integer, primary_key=True)- # tramo's own run id (from GET /api/runs). Unique so harvest upserts.- run_id = db.Column(db.String(255), unique=True, nullable=False, index=True)- workflow_slug = db.Column(db.String(255), nullable=True, index=True)- status = db.Column(db.String(32), nullable=True) # running|success|failed|suspended...- source = db.Column(db.String(32), nullable=True) # api|webhook|cron|replay- error = db.Column(db.Text, nullable=True)-- usage = db.Column(db.Text, nullable=True) # JSON token/cost usage- pending_approvals = db.Column(db.Text, nullable=True) # JSON list- raw = db.Column(db.Text, nullable=True) # full run JSON as returned-- started_at = db.Column(db.DateTime, nullable=True)- finished_at = db.Column(db.DateTime, nullable=True)- created_at = db.Column(db.DateTime, default=datetime.utcnow)-- def _json(self, value):- if not value:- return None- try:- return json.loads(value)- except (ValueError, TypeError):- return None-- def to_dict(self):- return {- 'id': self.id,- 'run_id': self.run_id,- 'workflow_slug': self.workflow_slug,- 'status': self.status,- 'source': self.source,- 'error': self.error,- 'usage': self._json(self.usage),- 'pending_approvals': self._json(self.pending_approvals) or [],- 'started_at': self.started_at.isoformat() if self.started_at else None,- 'finished_at': self.finished_at.isoformat() if self.finished_at else None,- 'created_at': self.created_at.isoformat() if self.created_at else None,- }---def register(db): # noqa: A002 - signature dictated by the platform (fn(db))- """No-op passthrough required by the manifest ``models: "models:register"``.-- Importing this module already defined the tables on ``db.metadata``; the- platform runs ``db.create_all()``. Nothing else to do here.- """- return [TramoWorkflow, TramoRun]diff --git a/builtin-extensions/serverkit-tramo/backend/run_sync.py b/builtin-extensions/serverkit-tramo/backend/run_sync.pydeleted file mode 100644index dc3effa7..00000000--- a/builtin-extensions/serverkit-tramo/backend/run_sync.py+++ /dev/null@@ -1,94 +0,0 @@-"""Run persistence helpers (serverkit-tramo / Automations extension).--``@tramo/server`` keeps run history in an in-memory ring of 1000 (it evicts old-runs and loses everything on restart), so the panel harvests run summaries into-:class:`TramoRun`. Both the harvest job and the manual-run proxy funnel through-:func:`upsert_run` (keyed on the tramo run id) so a run is never duplicated.--tramo's run JSON field names are not frozen, so :func:`parse_run` reads a few-aliases defensively and keeps the untouched original in ``raw``.-"""-import json-import logging-from datetime import datetime--from app import db--from .models import TramoRun--logger = logging.getLogger(__name__)---def _first(d, *keys):- for k in keys:- if isinstance(d, dict) and d.get(k) not in (None, ''):- return d.get(k)- return None---def _parse_dt(value):- if not value:- return None- if isinstance(value, (int, float)):- try:- return datetime.utcfromtimestamp(value / 1000 if value > 1e12 else value)- except (ValueError, OSError):- return None- try:- return datetime.fromisoformat(str(value).replace('Z', '+00:00')).replace(tzinfo=None)- except (ValueError, TypeError):- return None---def _json_dump(value):- if value is None:- return None- if isinstance(value, str):- return value- try:- return json.dumps(value)- except (TypeError, ValueError):- return None---def parse_run(run_json):- """Map a tramo run object to TramoRun column values (dict)."""- run_id = _first(run_json, 'id', 'runId', 'run_id')- return {- 'run_id': str(run_id) if run_id is not None else None,- 'workflow_slug': _first(run_json, 'workflowId', 'workflow_id',- 'workflowSlug', 'workflow_slug', 'workflow'),- 'status': _first(run_json, 'status', 'state'),- 'source': _first(run_json, 'source', 'trigger', 'triggerType', 'trigger_type'),- 'error': _first(run_json, 'error', 'errorMessage', 'error_message'),- 'usage': _json_dump(_first(run_json, 'usage', 'cost', 'tokens')),- 'pending_approvals': _json_dump(_first(run_json, 'pendingApprovals',- 'pending_approvals', 'approvals')),- 'started_at': _parse_dt(_first(run_json, 'startedAt', 'started_at', 'startTime')),- 'finished_at': _parse_dt(_first(run_json, 'finishedAt', 'finished_at',- 'endTime', 'completedAt')),- 'raw': _json_dump(run_json),- }---def upsert_run(run_json):- """Insert or update a TramoRun from a tramo run object.-- Returns ``(row, is_new)``. ``is_new`` is True only when the row did not exist- before, so callers can fire a one-shot notification on first sight.- """- fields = parse_run(run_json)- if not fields.get('run_id'):- return None, False-- row = TramoRun.query.filter_by(run_id=fields['run_id']).first()- is_new = row is None- if is_new:- row = TramoRun(run_id=fields['run_id'])- db.session.add(row)- for key, value in fields.items():- if key == 'run_id':- continue- setattr(row, key, value)- db.session.commit()- return row, is_newdiff --git a/builtin-extensions/serverkit-tramo/backend/templates.py b/builtin-extensions/serverkit-tramo/backend/templates.pydeleted file mode 100644index e8cfcc78..00000000--- a/builtin-extensions/serverkit-tramo/backend/templates.py+++ /dev/null@@ -1,97 +0,0 @@-"""Starter workflow templates (serverkit-tramo / Automations extension, Phase 3).--A small set of seed :class:`WorkflowDoc` fixtures the Workflows tab offers as-"New from template", so a fresh install has something runnable to start from.-These are node-vocabulary sketches for the embedded editor -- the operator fills-in credentials (pack secrets) and adjusts nodes before deploying.--Kept as plain Python dicts (not files) so they ship with the backend package and-need no bundling. Each template's ``doc`` is a minimal tramo WorkflowDoc.-"""--STARTER_TEMPLATES = [- {- 'id': 'backup-failed-telegram',- 'name': 'Backup failed -> Telegram',- 'description': 'When a panel backup fails, send a Telegram message.',- 'doc': {- 'name': 'Backup failed -> Telegram',- 'nodes': [- {'id': 'trigger', 'type': 'webhook-trigger:serverkit:event',- 'position': {'x': 80, 'y': 120},- 'config': {'path': '/sk/events'}},- {'id': 'filter', 'type': 'if',- 'position': {'x': 360, 'y': 120},- 'config': {'expression': "{{trigger.body.event}} == 'backup.restored'"}},- {'id': 'notify', 'type': 'telegram:send-message',- 'position': {'x': 640, 'y': 120},- 'config': {'text': 'A ServerKit backup event fired: {{trigger.body.event}}'}},- ],- 'edges': [- {'id': 'e1', 'source': 'trigger', 'target': 'filter'},- {'id': 'e2', 'source': 'filter', 'target': 'notify'},- ],- },- },- {- 'id': 'nightly-health-github',- 'name': 'Nightly health ping -> GitHub issue',- 'description': 'On a nightly cron, check something and open a GitHub issue on failure.',- 'doc': {- 'name': 'Nightly health ping -> GitHub issue',- 'nodes': [- {'id': 'cron', 'type': 'cron-trigger',- 'position': {'x': 80, 'y': 120},- 'config': {'cron': '0 3 * * *'}},- {'id': 'ping', 'type': 'http-request',- 'position': {'x': 360, 'y': 120},- 'config': {'method': 'GET', 'url': 'https://example.com/health'}},- {'id': 'issue', 'type': 'github:create-issue',- 'position': {'x': 640, 'y': 120},- 'config': {'title': 'Nightly health check failed',- 'body': 'The nightly health ping did not pass.'}},- ],- 'edges': [- {'id': 'e1', 'source': 'cron', 'target': 'ping'},- {'id': 'e2', 'source': 'ping', 'target': 'issue'},- ],- },- },- {- 'id': 'panel-event-discord',- 'name': 'Panel event -> Discord webhook',- 'description': 'Relay any panel event to a Discord channel via webhook.',- 'doc': {- 'name': 'Panel event -> Discord webhook',- 'nodes': [- {'id': 'trigger', 'type': 'webhook-trigger:serverkit:event',- 'position': {'x': 80, 'y': 120},- 'config': {'path': '/sk/events'}},- {'id': 'discord', 'type': 'discord:send-message',- 'position': {'x': 400, 'y': 120},- 'config': {'content': 'ServerKit event: {{trigger.body.event}}'}},- ],- 'edges': [- {'id': 'e1', 'source': 'trigger', 'target': 'discord'},- ],- },- },-]---def list_templates(include_doc=False):- """Template summaries (or full docs when include_doc)."""- out = []- for t in STARTER_TEMPLATES:- entry = {'id': t['id'], 'name': t['name'], 'description': t['description']}- if include_doc:- entry['doc'] = t['doc']- out.append(entry)- return out---def get_template(template_id):- for t in STARTER_TEMPLATES:- if t['id'] == template_id:- return t- return Nonediff --git a/builtin-extensions/serverkit-tramo/backend/tramo.py b/builtin-extensions/serverkit-tramo/backend/tramo.pydeleted file mode 100644index fefaed6c..00000000--- a/builtin-extensions/serverkit-tramo/backend/tramo.py+++ /dev/null@@ -1,387 +0,0 @@-"""Automations API endpoints (serverkit-tramo extension, tramo engine).--Mounted under ``/api/v1/tramo`` via the manifest's ``url_prefix``. Thin routing-layer over the extension services -- all Docker, tramo-API, and DB work happens-in :mod:`host_service`, :mod:`workflow_store`, :mod:`run_sync`, and-:mod:`events_bridge`.--Auth split (same as serverkit-mail / serverkit-k8s): reads need viewer, mutations-need admin. The ONE exception is the inbound-webhook passthrough-(``/hooks/<path>``) which is intentionally auth-exempt so external services can-POST to a workflow's ``webhook-trigger`` node through the panel's public domain;-per-trigger HMAC (tramo native) covers spoofing and the container stays-loopback-only. The plugin-disabled 503 guard (attached by plugin_service) still-runs on every route including the passthrough.-"""-import logging--import requests-from flask import Blueprint, jsonify, request, Response--from app.middleware.rbac import admin_required, viewer_required--from .host_service import TramoHostService, RUN_TIMEOUT-from .workflow_store import WorkflowStore-from . import events_bridge-from .run_sync import upsert_run-from .models import TramoRun--logger = logging.getLogger(__name__)--tramo_bp = Blueprint('tramo', __name__)--_NOT_INSTALLED = ('The Automations engine is not installed. Install it from the '- 'Automations Settings tab (admin only).')--# Response/hop headers we must not blindly relay when proxying.-_HOP_HEADERS = {'content-length', 'transfer-encoding', 'connection',- 'content-encoding', 'host'}---def _installed_or_error():- if not TramoHostService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503- return None---# ── Workflows CRUD ──--@tramo_bp.route('/workflows', methods=['GET'])-@viewer_required-def list_workflows():- return jsonify({'workflows': WorkflowStore.list_workflows()}), 200---@tramo_bp.route('/workflows/<slug>', methods=['GET'])-@viewer_required-def get_workflow(slug):- wf = WorkflowStore.get(slug)- if not wf:- return jsonify({'error': 'Workflow not found'}), 404- return jsonify(wf.to_dict(include_doc=True)), 200---@tramo_bp.route('/workflows', methods=['POST'])-@admin_required-def create_workflow():- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.create(- name=data.get('name'),- doc=data.get('doc'),- enabled=data.get('enabled', True),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(wf.to_dict(include_doc=True)), 201---@tramo_bp.route('/workflows/<slug>', methods=['PUT'])-@admin_required-def update_workflow(slug):- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.update(- slug,- name=data.get('name'),- doc=data.get('doc'),- enabled=data.get('enabled'),- )- except ValueError as e:- code = 404 if 'not found' in str(e).lower() else 400- return jsonify({'error': str(e)}), code- return jsonify(wf.to_dict(include_doc=True)), 200---@tramo_bp.route('/workflows/<slug>', methods=['DELETE'])-@admin_required-def delete_workflow(slug):- try:- WorkflowStore.delete(slug)- except ValueError as e:- return jsonify({'error': str(e)}), 404- return jsonify({'deleted': True}), 200---@tramo_bp.route('/deploy', methods=['POST'])-@admin_required-def deploy():- result = WorkflowStore.deploy()- if not result.get('success'):- code = 503 if 'not installed' in (result.get('error') or '') else 400- return jsonify({'error': result.get('error', 'Deploy failed'),- 'materialized': result.get('materialized')}), code- return jsonify(result), 200---# ── Starter templates ──--@tramo_bp.route('/templates', methods=['GET'])-@viewer_required-def list_starter_templates():- from .templates import list_templates- return jsonify({'templates': list_templates()}), 200---@tramo_bp.route('/workflows/from-template/<template_id>', methods=['POST'])-@admin_required-def create_from_template(template_id):- from .templates import get_template- tpl = get_template(template_id)- if not tpl:- return jsonify({'error': 'Template not found'}), 404- data = request.get_json(silent=True) or {}- try:- wf = WorkflowStore.create(- name=data.get('name') or tpl['name'],- doc=tpl['doc'],- enabled=data.get('enabled', True),- )- except ValueError as e:- return jsonify({'error': str(e)}), 400- return jsonify(wf.to_dict(include_doc=True)), 201---# ── Runs / approvals (proxied to the engine) ──--@tramo_bp.route('/workflows/<slug>/run', methods=['POST'])-@admin_required-def run_workflow(slug):- guard = _installed_or_error()- if guard:- return guard- wf = WorkflowStore.get(slug)- if not wf:- return jsonify({'error': 'Workflow not found'}), 404- payload = request.get_json(silent=True) or {}- res = TramoHostService._api('POST', f'/workflows/{slug}/run', payload,- timeout=RUN_TIMEOUT)- if not res.get('success'):- return jsonify({'error': res.get('error', 'Run failed')}), 502- summary = res.get('data') or {}- try:- row, _ = upsert_run(summary if isinstance(summary, dict) else {})- run_dict = row.to_dict() if row else None- except Exception as e: # noqa: BLE001- logger.warning('tramo: failed to persist run summary: %s', e)- run_dict = None- return jsonify({'run': run_dict, 'result': summary}), 200---@tramo_bp.route('/runs', methods=['GET'])-@viewer_required-def list_runs():- q = TramoRun.query- slug = request.args.get('workflow')- status = request.args.get('status')- if slug:- q = q.filter_by(workflow_slug=slug)- if status:- q = q.filter_by(status=status)- try:- limit = min(int(request.args.get('limit', 100)), 500)- except (TypeError, ValueError):- limit = 100- rows = q.order_by(TramoRun.id.desc()).limit(limit).all()- return jsonify({'runs': [r.to_dict() for r in rows]}), 200---@tramo_bp.route('/runs/<run_id>', methods=['GET'])-@viewer_required-def get_run(run_id):- row = TramoRun.query.filter_by(run_id=run_id).first()- if not row:- return jsonify({'error': 'Run not found'}), 404- return jsonify(row.to_dict()), 200---@tramo_bp.route('/runs/<run_id>/replay', methods=['POST'])-@admin_required-def replay_run(run_id):- guard = _installed_or_error()- if guard:- return guard- res = TramoHostService._api('POST', f'/runs/{run_id}/replay')- if not res.get('success'):- return jsonify({'error': res.get('error', 'Replay failed')}), 502- try:- if isinstance(res.get('data'), dict):- upsert_run(res['data'])- except Exception as e: # noqa: BLE001- logger.debug('replay upsert failed: %s', e)- return jsonify(res.get('data') or {'replayed': True}), 200---@tramo_bp.route('/approvals', methods=['GET'])-@viewer_required-def list_approvals():- guard = _installed_or_error()- if guard:- return guard- res = TramoHostService._api('GET', '/approvals')- if not res.get('success'):- return jsonify({'approvals': [], 'note': res.get('error')}), 200- data = res.get('data')- approvals = data if isinstance(data, list) else (data or {}).get('approvals', [])- return jsonify({'approvals': approvals}), 200---@tramo_bp.route('/runs/<run_id>/approve', methods=['POST'])-@admin_required-def approve_run(run_id):- guard = _installed_or_error()- if guard:- return guard- payload = request.get_json(silent=True) or {}- res = TramoHostService._api('POST', f'/runs/{run_id}/approve', payload)- if not res.get('success'):- return jsonify({'error': res.get('error', 'Approve failed')}), 502- return jsonify(res.get('data') or {'approved': True}), 200---# ── Host (engine) lifecycle ──--@tramo_bp.route('/host/status', methods=['GET'])-@viewer_required-def host_status():- return jsonify(TramoHostService.get_status()), 200---@tramo_bp.route('/host/install', methods=['POST'])-@admin_required-def host_install():- data = request.get_json(silent=True) or {}- # Issue the scoped call-back key so workflows can act back on the panel.- callback_key = events_bridge.issue_callback_key()- result = TramoHostService.install(- host_port=data.get('host_port'),- callback_api_key=callback_key,- )- if not result.get('success'):- # Roll back the key we just issued if the container didn't start.- events_bridge.revoke_callback_key()- return jsonify({'error': result.get('error', 'Install failed')}), 400- return jsonify(result), 201---@tramo_bp.route('/host/install', methods=['DELETE'])-@admin_required-def host_uninstall():- keep_data = (request.args.get('keep_data', 'true').lower()- not in ('false', '0', 'no'))- result = TramoHostService.uninstall(keep_data=keep_data)- events_bridge.revoke_callback_key()- if not result.get('success'):- return jsonify({'error': result.get('error', 'Uninstall failed')}), 400- return jsonify(result), 200---@tramo_bp.route('/host/control/<action>', methods=['POST'])-@admin_required-def host_control(action):- guard = _installed_or_error()- if guard:- return guard- result = TramoHostService.control(action)- if not result.get('success'):- return jsonify({'error': result.get('error', 'Control failed')}), 400- return jsonify(result), 200---# ── Settings ──--@tramo_bp.route('/settings', methods=['GET'])-@viewer_required-def get_settings():- return jsonify({- 'host_port': TramoHostService.host_port(),- 'events_bridge_enabled': events_bridge.is_events_bridge_enabled(),- # Names only -- secret values are never returned.- 'pack_secret_names': sorted(TramoHostService.get_pack_secrets().keys()),- }), 200---@tramo_bp.route('/settings', methods=['PUT'])-@admin_required-def update_settings():- data = request.get_json(silent=True) or {}- out = {}-- if 'pack_secrets' in data and isinstance(data['pack_secrets'], dict):- out['pack_secret_names'] = TramoHostService.set_pack_secrets(data['pack_secrets'])-- if 'host_port' in data:- try:- port = int(data['host_port'])- if not (1024 <= port <= 65535):- raise ValueError- TramoHostService._save_config({'host_port': port})- out['host_port'] = port- except (TypeError, ValueError):- return jsonify({'error': 'host_port must be an integer 1024-65535'}), 400-- if 'events_bridge_enabled' in data:- if data['events_bridge_enabled']:- events_bridge.enable_events_bridge()- else:- events_bridge.disable_events_bridge()- out['events_bridge_enabled'] = events_bridge.is_events_bridge_enabled()-- return jsonify(out), 200---# ── Legacy Workflow Builder export (read-only, admin) ──--@tramo_bp.route('/legacy-workflows', methods=['GET'])-@admin_required-def legacy_workflows():- """Read-only dump of the retired Workflow Builder's rows (plan 45 Phase 4).-- The old ``workflows`` tables are kept (no data loss); this lets an operator- rebuild those flows by hand in tramo. Never fails if the model is gone.- """- try:- from app.models.workflow import Workflow- except Exception: # noqa: BLE001- return jsonify({'workflows': [], 'note': 'legacy workflow model not present'}), 200- try:- rows = Workflow.query.all()- out = [w.to_dict() if hasattr(w, 'to_dict') else {'id': w.id, 'name': getattr(w, 'name', None)}- for w in rows]- except Exception as e: # noqa: BLE001- return jsonify({'workflows': [], 'note': f'could not read legacy workflows: {e}'}), 200- return jsonify({'workflows': out}), 200---# ── Inbound webhook passthrough (AUTH-EXEMPT) ──--@tramo_bp.route('/hooks/<path:subpath>',- methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])-def hooks_passthrough(subpath):- """Forward an external webhook to the engine's trigger dispatcher.-- Intentionally has NO auth decorator: external services POST here through the- panel's public domain to fire a ``webhook-trigger`` node. The container is- loopback-only, so this is the only way in; per-trigger HMAC (configured on- the node) authenticates the payload.- """- if not TramoHostService.is_installed():- return jsonify({'error': _NOT_INSTALLED}), 503-- target = f'http://127.0.0.1:{TramoHostService.host_port()}/hooks/{subpath}'- fwd_headers = {k: v for k, v in request.headers- if k.lower() not in _HOP_HEADERS}- try:- upstream = requests.request(- request.method, target,- params=request.args,- data=request.get_data(),- headers=fwd_headers,- timeout=30,- )- except requests.RequestException as e:- return jsonify({'error': f'Automations engine unreachable: {e}'}), 502-- resp_headers = [(k, v) for k, v in upstream.headers.items()- if k.lower() not in _HOP_HEADERS]- return Response(upstream.content, status=upstream.status_code, headers=resp_headers)diff --git a/builtin-extensions/serverkit-tramo/backend/workflow_store.py b/builtin-extensions/serverkit-tramo/backend/workflow_store.pydeleted file mode 100644index aeccc709..00000000--- a/builtin-extensions/serverkit-tramo/backend/workflow_store.py+++ /dev/null@@ -1,212 +0,0 @@-"""Workflow document store (serverkit-tramo / Automations extension).--CRUD over :class:`TramoWorkflow` rows plus the two engine-facing operations:--* :meth:`WorkflowStore.materialize` — write every *enabled* workflow's doc as- ``<slug>.json`` into the container's bind-mounted workflows dir and prune the- files of disabled/deleted workflows.-* :meth:`WorkflowStore.deploy` — materialize, then restart the container so- ``@tramo/server`` re-reads the dir (it loads workflows once at boot), then- stamp ``deployed_at`` on the enabled rows.--File I/O goes through small choke-point classmethods (``_write_file`` /-``_remove_file`` / ``_list_files``) so it stays privileged (the data dir is-root-owned) and mockable in tests.-"""-import json-import logging-import os-import re-import tempfile--from app import db--from .models import TramoWorkflow-from .host_service import TramoHostService, HOST_WORKFLOWS_DIR--logger = logging.getLogger(__name__)--_SLUG_RE = re.compile(r'[^a-z0-9]+')---def slugify(value):- """Lowercase, hyphenated, URL/filename-safe slug."""- base = _SLUG_RE.sub('-', (value or '').strip().lower()).strip('-')- return base or 'workflow'---class WorkflowStore:- """DB CRUD + engine materialization for automation workflows."""-- # ---------- CRUD ------------ @classmethod- def list_workflows(cls):- rows = TramoWorkflow.query.order_by(TramoWorkflow.updated_at.desc()).all()- return [w.to_dict() for w in rows]-- @classmethod- def get(cls, slug):- return TramoWorkflow.query.filter_by(slug=slug).first()-- @classmethod- def _unique_slug(cls, name, ignore_id=None):- base = slugify(name)- candidate = base- n = 2- while True:- existing = TramoWorkflow.query.filter_by(slug=candidate).first()- if not existing or existing.id == ignore_id:- return candidate- candidate = f'{base}-{n}'- n += 1-- @classmethod- def create(cls, name, doc=None, enabled=True):- name = (name or '').strip()- if not name:- raise ValueError('A workflow name is required')- wf = TramoWorkflow(- name=name,- slug=cls._unique_slug(name),- enabled=bool(enabled),- doc_version=1,- )- wf.set_doc(doc if doc is not None else cls._empty_doc(wf.slug, name))- db.session.add(wf)- db.session.commit()- return wf-- @classmethod- def update(cls, slug, name=None, doc=None, enabled=None):- wf = cls.get(slug)- if not wf:- raise ValueError('Workflow not found')- if name is not None:- name = name.strip()- if not name:- raise ValueError('A workflow name is required')- wf.name = name- if enabled is not None:- wf.enabled = bool(enabled)- if doc is not None:- wf.set_doc(doc)- wf.doc_version = (wf.doc_version or 1) + 1- db.session.commit()- return wf-- @classmethod- def delete(cls, slug):- wf = cls.get(slug)- if not wf:- raise ValueError('Workflow not found')- db.session.delete(wf)- db.session.commit()- # Best-effort prune the materialized file.- try:- cls._remove_file(slug)- except Exception as e: # noqa: BLE001- logger.debug('could not remove workflow file for %s: %s', slug, e)- return True-- @staticmethod- def _empty_doc(slug, name):- """A minimal valid tramo WorkflowDoc so a new workflow opens cleanly.-- Mirrors tramo's own ``emptyDoc()`` — ``version`` and ``meta`` must be- present, since the editor's Canvas reads ``doc.meta.mcpServers``- unconditionally and crashes on a doc without ``meta``.- """- return {- 'version': 1,- 'id': slug,- 'name': name,- 'nodes': [],- 'edges': [],- 'meta': {},- }-- # ---------- engine materialization ------------ @classmethod- def _write_file(cls, slug, doc):- """Write ``<slug>.json`` into the workflows dir (privileged). Linux-only."""- if os.name == 'nt':- return- payload = json.dumps(doc, indent=2)- dest = f'{HOST_WORKFLOWS_DIR}/{slug}.json'- from app.utils.system import run_privileged- run_privileged(['mkdir', '-p', HOST_WORKFLOWS_DIR])- with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as tmp:- tmp.write(payload)- tmp_path = tmp.name- try:- run_privileged(['cp', tmp_path, dest])- finally:- try:- os.unlink(tmp_path)- except OSError:- pass-- @classmethod- def _remove_file(cls, slug):- if os.name == 'nt':- return- from app.utils.system import run_privileged- run_privileged(['rm', '-f', f'{HOST_WORKFLOWS_DIR}/{slug}.json'])-- @classmethod- def _list_files(cls):- """Slugs currently materialized in the workflows dir."""- if os.name == 'nt':- return []- from app.utils.system import run_privileged- res = run_privileged(['ls', '-1', HOST_WORKFLOWS_DIR])- if getattr(res, 'returncode', 1) != 0:- return []- out = getattr(res, 'stdout', '') or ''- return [line[:-5] for line in out.splitlines()- if line.strip().endswith('.json')]-- @classmethod- def materialize(cls):- """Write enabled docs, prune the rest. Returns a summary dict."""- enabled = TramoWorkflow.query.filter_by(enabled=True).all()- enabled_slugs = {w.slug for w in enabled}- written = []- for wf in enabled:- cls._write_file(wf.slug, wf.get_doc())- written.append(wf.slug)- pruned = []- for slug in cls._list_files():- if slug not in enabled_slugs:- cls._remove_file(slug)- pruned.append(slug)- return {'written': written, 'pruned': pruned}-- @classmethod- def deploy(cls):- """Materialize + restart the engine + stamp ``deployed_at``.-- Restart is required because ``@tramo/server`` reads the workflows dir- only at boot (no reload endpoint yet). The checkpoint store preserves any- suspended runs across the restart.- """- from datetime import datetime-- if not TramoHostService.is_installed():- return {'success': False,- 'error': 'The Automations engine is not installed. Install it '- 'from the Automations Settings tab first.'}- summary = cls.materialize()- restart = TramoHostService.control('restart')- if not restart.get('success'):- return {'success': False,- 'error': restart.get('error', 'Failed to restart the engine'),- 'materialized': summary}- now = datetime.utcnow()- for wf in TramoWorkflow.query.filter_by(enabled=True).all():- wf.deployed_at = now- wf.deployed_version = wf.doc_version- db.session.commit()- return {'success': True, 'message': 'Automations deployed', 'materialized': summary}diff --git a/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsx b/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsxdeleted file mode 100644index ca7bdd27..00000000--- a/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsx+++ /dev/null@@ -1,120 +0,0 @@-import { Suspense, lazy, useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import { ArrowLeft, Play, Rocket, Check, AlertCircle, Loader2 } from 'lucide-react';-import api from '@/services/api';-import { Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/tramo-automations.scss';--// The tramo editor is the heavy chunk (canvas engine + 21 integration packs +-// tramo/styles.css). Lazy-load it so it never lands in the panel entry bundle.-const TramoEditor = lazy(() => import('./TramoEditor.jsx'));--// Map the editor's save lifecycle to a small header indicator.-const SaveIndicator = ({ state }) => {- const status = state?.status || 'idle';- if (status === 'saving' || status === 'pending') {- return <span className="tramo-save tramo-save--busy"><Loader2 size={13} className="tramo-spin" /> Saving…</span>;- }- if (status === 'saved') {- return <span className="tramo-save tramo-save--ok"><Check size={13} /> Saved</span>;- }- if (status === 'error') {- return <span className="tramo-save tramo-save--err"><AlertCircle size={13} /> {state?.error || 'Save failed'}</span>;- }- return <span className="tramo-save tramo-save--idle">All changes saved</span>;-};--const AutomationEditorPage = () => {- const { slug } = useParams();- const navigate = useNavigate();- const toast = useToast();-- const [workflow, setWorkflow] = useState(null);- const [saveState, setSaveState] = useState(null);- const [busy, setBusy] = useState(false);-- // Header metadata (name, enabled) — the doc itself is owned by the editor.- useEffect(() => {- let cancelled = false;- (async () => {- try {- const data = await api.request(`/tramo/workflows/${slug}`);- if (!cancelled) setWorkflow(data);- } catch (error) {- if (!cancelled) toast.error(`Could not load workflow: ${error.message}`);- }- })();- return () => { cancelled = true; };- }, [slug, toast]);-- const onSaveStateChange = useCallback((s) => setSaveState(s), []);-- const handleRun = async () => {- setBusy(true);- try {- const res = await api.request(`/tramo/workflows/${slug}/run`, { method: 'POST', body: {} });- const status = res?.run?.status || res?.result?.status || 'started';- toast.success(`Run ${status} — see Runs for details`, {- action: { label: 'View runs', onClick: () => navigate('/automations/runs') },- });- } catch (error) {- toast.error(`Run failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleDeploy = async () => {- setBusy(true);- try {- const res = await api.request('/tramo/deploy', { method: 'POST' });- toast.success(res?.message || 'Deployed to the tramo engine');- } catch (error) {- toast.error(`Deploy failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- return (- <div className="tramo-editor-page">- <div className="tramo-editor-page__bar">- <div className="tramo-editor-page__left">- <Button variant="ghost" size="sm" onClick={() => navigate('/automations')} title="Back to Automations">- <ArrowLeft size={16} />- </Button>- <div className="tramo-editor-page__title">- <span className="tramo-editor-page__name">{workflow?.name || slug}</span>- {workflow && (- <Pill kind={workflow.enabled ? 'green' : 'gray'}>- {workflow.enabled ? 'enabled' : 'disabled'}- </Pill>- )}- </div>- <SaveIndicator state={saveState} />- </div>- <div className="tramo-editor-page__actions">- <Button variant="secondary" size="sm" onClick={handleRun} disabled={busy}>- <Play size={14} /> Run- </Button>- <Button variant="default" size="sm" onClick={handleDeploy} disabled={busy}>- <Rocket size={14} /> Deploy- </Button>- </div>- </div>-- <div className="tramo-editor-page__body">- <Suspense fallback={<EmptyState loading title="Loading editor..." />}>- <TramoEditor slug={slug} onSaveStateChange={onSaveStateChange} />- </Suspense>- </div>- </div>- );-};--export { AutomationEditorPage };-export default AutomationEditorPage;diff --git a/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsx b/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsxdeleted file mode 100644index 9a3ceb2b..00000000--- a/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsx+++ /dev/null@@ -1,1076 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- Workflow, RefreshCw, Plus, Trash2, Rocket, Pencil, Play, LayoutTemplate,- Server, Power, KeyRound, CheckCircle2, X, Send, Github, MessageSquare,- Zap, MousePointerClick, Clock, Webhook, Check, Search, Star,- Upload, FileJson,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/tramo-automations.scss';--// Route-driven tabs (manifest maps /automations and /automations/:tab here).-const TABS = [- { slug: 'workflows', to: '/automations', label: 'Workflows', end: true },- { slug: 'templates', to: '/automations/templates', label: 'Templates' },- { slug: 'runs', to: '/automations/runs', label: 'Runs' },- { slug: 'settings', to: '/automations/settings', label: 'Settings' },-];-const VALID_TABS = TABS.map((t) => t.slug);--// Favorited template ids live in the browser for now (per-device). A server-side-// favorites store can replace this later without touching the card UI.-const FAVORITES_KEY = 'tramo:favorite-templates';-const readFavorites = () => {- try {- const raw = JSON.parse(localStorage.getItem(FAVORITES_KEY) || '[]');- return new Set(Array.isArray(raw) ? raw : []);- } catch {- return new Set();- }-};--// Presentation for the starter templates (icon + accent + tags). Keyed by the-// backend template id; unknown ids fall back to a neutral card so new templates-// still render cleanly.-const TEMPLATE_META = {- 'backup-failed-telegram': { Icon: Send, brand: 'telegram', tags: ['Backups', 'Telegram'] },- 'nightly-health-github': { Icon: Github, brand: 'github', tags: ['Schedule', 'GitHub'] },- 'panel-event-discord': { Icon: MessageSquare, brand: 'discord', tags: ['Events', 'Discord'] },-};-const DEFAULT_TEMPLATE_META = { Icon: Zap, brand: 'default', tags: [] };--// Trigger choices for a new workflow. Each seeds a valid builtin tramo trigger-// node so the editor opens with the trigger already placed. Panel events arrive-// at a webhook-trigger on the /sk/events path (the events bridge posts there),-// so no custom node type is needed.-const TRIGGERS = [- {- id: 'manual', Icon: MousePointerClick, title: 'Manually trigger',- subtitle: 'Run it on demand from the Automations page',- node: () => ({ id: 'trigger', type: 'manual-trigger', position: { x: 80, y: 120 }, config: {} }),- },- {- id: 'schedule', Icon: Clock, title: 'On a schedule',- subtitle: 'Run on a cron schedule, e.g. every night',- node: () => ({ id: 'trigger', type: 'cron-trigger', position: { x: 80, y: 120 }, config: { expression: '0 3 * * *' } }),- },- {- id: 'event', Icon: Zap, title: 'On a panel event',- subtitle: 'React to app, backup, health, or security events',- node: () => ({ id: 'trigger', type: 'webhook-trigger', position: { x: 80, y: 120 }, config: { path: '/sk/events', method: 'POST' } }),- },- {- id: 'webhook', Icon: Webhook, title: 'Incoming webhook',- subtitle: 'Trigger from an external HTTP request',- node: () => ({ id: 'trigger', type: 'webhook-trigger', position: { x: 80, y: 120 }, config: { path: '/hooks/my-hook', method: 'POST' } }),- },-];--// Run status → Pill colour.-const runPill = (status) => {- const kind = status === 'succeeded' || status === 'success' ? 'green'- : status === 'running' || status === 'pending' ? 'amber'- : status === 'failed' || status === 'error' ? 'red'- : status === 'awaiting_approval' ? 'cyan' : 'gray';- return <Pill kind={kind}>{status || 'unknown'}</Pill>;-};--// Host lifecycle state → Pill colour.-const hostPill = (state) => {- const kind = state === 'ready' ? 'green'- : state === 'unhealthy' ? 'amber'- : state === 'stopped' ? 'gray' : 'red';- return <Pill kind={kind}>{state || 'not_installed'}</Pill>;-};--const formatDuration = (start, finish) => {- if (!start || !finish) return '—';- const ms = new Date(finish).getTime() - new Date(start).getTime();- if (Number.isNaN(ms) || ms < 0) return '—';- if (ms < 1000) return `${ms}ms`;- return `${(ms / 1000).toFixed(1)}s`;-};--const AutomationsPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'workflows';-- const [busy, setBusy] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Workflows tab- const [workflows, setWorkflows] = useState([]);- const [wfLoading, setWfLoading] = useState(false);- const [newModal, setNewModal] = useState(false);- const [newName, setNewName] = useState('');- const [newTrigger, setNewTrigger] = useState('manual');- const [templates, setTemplates] = useState([]);- const [templatesLoading, setTemplatesLoading] = useState(false);- const [templateSearch, setTemplateSearch] = useState('');- const [favorites, setFavorites] = useState(readFavorites);- const [importModal, setImportModal] = useState(false);- const [importName, setImportName] = useState('');- const [importText, setImportText] = useState('');-- // Runs tab- const [runs, setRuns] = useState([]);- const [approvals, setApprovals] = useState([]);- const [runsLoading, setRunsLoading] = useState(false);-- // Settings tab- const [host, setHost] = useState(null);- const [settings, setSettings] = useState(null);- const [settingsLoading, setSettingsLoading] = useState(false);- const [settingsSection, setSettingsSection] = useState('engine');- const [installPort, setInstallPort] = useState('');- const [newSecret, setNewSecret] = useState({ name: '', value: '' });- const [hostPortDraft, setHostPortDraft] = useState('');-- // ── Loaders ──- const loadWorkflows = useCallback(async () => {- setWfLoading(true);- try {- const data = await api.request('/tramo/workflows');- setWorkflows(data.workflows || []);- } catch (error) {- toast.error(`Could not load workflows: ${error.message}`);- } finally {- setWfLoading(false);- }- }, [toast]);-- const loadRuns = useCallback(async () => {- setRunsLoading(true);- try {- const [runData, apprData] = await Promise.all([- api.request('/tramo/runs?limit=100'),- api.request('/tramo/approvals'),- ]);- setRuns(runData.runs || []);- setApprovals(apprData.approvals || []);- } catch (error) {- toast.error(`Could not load runs: ${error.message}`);- } finally {- setRunsLoading(false);- }- }, [toast]);-- const loadSettings = useCallback(async () => {- setSettingsLoading(true);- try {- const [statusData, settingsData] = await Promise.all([- api.request('/tramo/host/status'),- api.request('/tramo/settings'),- ]);- setHost(statusData);- setSettings(settingsData);- setHostPortDraft(String(settingsData.host_port ?? statusData.host_port ?? ''));- } catch (error) {- toast.error(`Could not load settings: ${error.message}`);- } finally {- setSettingsLoading(false);- }- }, [toast]);-- const loadTemplates = useCallback(async () => {- setTemplatesLoading(true);- try {- const data = await api.request('/tramo/templates');- setTemplates(data.templates || []);- } catch (error) {- toast.error(`Could not load templates: ${error.message}`);- } finally {- setTemplatesLoading(false);- }- }, [toast]);-- useEffect(() => {- if (activeTab === 'workflows') loadWorkflows();- else if (activeTab === 'templates') loadTemplates();- else if (activeTab === 'runs') loadRuns();- else if (activeTab === 'settings') loadSettings();- }, [activeTab, loadWorkflows, loadTemplates, loadRuns, loadSettings]);-- const toggleFavorite = (id) => {- setFavorites((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id); else next.add(id);- try { localStorage.setItem(FAVORITES_KEY, JSON.stringify([...next])); } catch { /* ignore */ }- return next;- });- };-- // ── Workflow actions ──- const openNewModal = () => {- setNewName('');- setNewTrigger('manual');- setNewModal(true);- };-- const handleCreate = async () => {- if (!newName.trim()) { toast.error('Name is required.'); return; }- const trigger = TRIGGERS.find((t) => t.id === newTrigger) || TRIGGERS[0];- const doc = { name: newName.trim(), nodes: [trigger.node()], edges: [] };- setBusy(true);- try {- const wf = await api.request('/tramo/workflows', {- method: 'POST', body: { name: newName.trim(), doc },- });- setNewModal(false);- setNewName('');- toast.success(`Workflow "${wf.name}" created`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not create workflow: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleFromTemplate = async (template) => {- setBusy(true);- try {- const wf = await api.request(`/tramo/workflows/from-template/${template.id}`, { method: 'POST', body: {} });- toast.success(`Created "${wf.name}" from ${template.name}`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not create from template: ${error.message}`);- } finally {- setBusy(false);- }- };-- const openImportModal = () => {- setImportName('');- setImportText('');- setImportModal(true);- };-- const handleImportFile = async (e) => {- const file = e.target.files?.[0];- if (!file) return;- try {- setImportText(await file.text());- if (!importName.trim()) setImportName(file.name.replace(/\.json$/i, ''));- } catch {- toast.error('Could not read that file.');- }- e.target.value = '';- };-- const handleImport = async () => {- let doc;- try {- doc = JSON.parse(importText);- } catch {- toast.error('That is not valid JSON. Paste a tramo workflow document.');- return;- }- if (!doc || typeof doc !== 'object' || !Array.isArray(doc.nodes)) {- toast.error('That JSON does not look like a workflow (missing a nodes array).');- return;- }- const name = importName.trim() || doc.name || 'Imported automation';- setBusy(true);- try {- const wf = await api.request('/tramo/workflows', {- method: 'POST', body: { name, doc: { ...doc, name } },- });- setImportModal(false);- toast.success(`Imported "${wf.name}"`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not import: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggleEnabled = async (wf) => {- try {- await api.request(`/tramo/workflows/${wf.slug}`, { method: 'PUT', body: { enabled: !wf.enabled } });- await loadWorkflows();- } catch (error) {- toast.error(`Could not update workflow: ${error.message}`);- }- };-- const handleDeleteWorkflow = (wf) => {- setConfirmDialog({- title: `Delete ${wf.name}?`,- message: 'This removes the workflow and its stored document. Deployed runs already recorded are kept.',- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/tramo/workflows/${wf.slug}`, { method: 'DELETE' });- toast.success('Workflow deleted');- await loadWorkflows();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleDeploy = async () => {- setBusy(true);- try {- const res = await api.request('/tramo/deploy', { method: 'POST' });- toast.success(res?.message || 'Deployed to the tramo engine');- await loadWorkflows();- } catch (error) {- toast.error(`Deploy failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleRunWorkflow = async (wf) => {- setBusy(true);- try {- const res = await api.request(`/tramo/workflows/${wf.slug}/run`, { method: 'POST', body: {} });- const status = res?.run?.status || res?.result?.status || 'started';- toast.success(`Run ${status} — see the Runs tab`);- } catch (error) {- toast.error(`Run failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Run actions ──- const handleApprove = async (runId) => {- setBusy(true);- try {- await api.request(`/tramo/runs/${runId}/approve`, { method: 'POST', body: {} });- toast.success('Approved');- await loadRuns();- } catch (error) {- toast.error(`Approve failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleReplay = async (runId) => {- setBusy(true);- try {- await api.request(`/tramo/runs/${runId}/replay`, { method: 'POST' });- toast.success('Replay queued');- await loadRuns();- } catch (error) {- toast.error(`Replay failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Host / settings actions ──- const handleInstall = async () => {- setBusy(true);- try {- const body = installPort ? { host_port: Number(installPort) } : {};- await api.request('/tramo/host/install', { method: 'POST', body });- toast.success('tramo engine installed');- setInstallPort('');- await loadSettings();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove tramo engine',- message: keepData- ? 'Remove the tramo container? Workflow data stays on disk and a reinstall picks it back up.'- : 'Remove the tramo container AND delete all engine data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/tramo/host/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('tramo engine removed');- await loadSettings();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleControl = async (action) => {- setBusy(true);- try {- await api.request(`/tramo/host/control/${action}`, { method: 'POST' });- toast.success(`Engine ${action} requested`);- await loadSettings();- } catch (error) {- toast.error(`Could not ${action} engine: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleAddSecret = async () => {- if (!newSecret.name.trim() || !newSecret.value) { toast.error('Name and value are required.'); return; }- setBusy(true);- try {- await api.request('/tramo/settings', {- method: 'PUT',- body: { pack_secrets: { [newSecret.name.trim()]: newSecret.value } },- });- toast.success(`Secret ${newSecret.name.trim()} saved`);- setNewSecret({ name: '', value: '' });- await loadSettings();- } catch (error) {- toast.error(`Could not save secret: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggleBridge = async () => {- setBusy(true);- try {- await api.request('/tramo/settings', {- method: 'PUT',- body: { events_bridge_enabled: !settings?.events_bridge_enabled },- });- await loadSettings();- } catch (error) {- toast.error(`Could not update events bridge: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleSaveHostPort = async () => {- const port = Number(hostPortDraft);- if (!port) { toast.error('Enter a valid port.'); return; }- setBusy(true);- try {- await api.request('/tramo/settings', { method: 'PUT', body: { host_port: port } });- toast.success('Host port updated');- await loadSettings();- } catch (error) {- toast.error(`Could not update host port: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Renderers ──- const renderTemplates = () => {- const q = templateSearch.trim().toLowerCase();- const filtered = templates.filter((t) => !q- || t.name.toLowerCase().includes(q)- || (t.description || '').toLowerCase().includes(q));- // Favorites float to the top; otherwise preserve the incoming order.- const sorted = [...filtered].sort(- (a, b) => (favorites.has(a.id) ? 0 : 1) - (favorites.has(b.id) ? 0 : 1));- return (- <div className="tramo-templates">- <div className="tramo-templates__bar">- <div className="tramo-search">- <Search size={15} />- <input- type="text"- placeholder="Search templates..."- value={templateSearch}- onChange={(e) => setTemplateSearch(e.target.value)}- />- </div>- <span className="tramo-templates__count">- {filtered.length} template{filtered.length === 1 ? '' : 's'}- </span>- </div>- {templatesLoading ? (- <EmptyState loading title="Loading templates..." />- ) : sorted.length === 0 ? (- <EmptyState- icon={LayoutTemplate}- title={q ? 'No templates match your search' : 'No templates yet'}- description={q ? 'Try a different search.' : 'Import your own to get started.'}- />- ) : (- <div className="tramo-tpl-grid">- {sorted.map((t) => {- const meta = TEMPLATE_META[t.id] || DEFAULT_TEMPLATE_META;- const { Icon } = meta;- const fav = favorites.has(t.id);- return (- <div className="tramo-card" key={t.id}>- <div className="tramo-card__top">- <span className={`tramo-card__icon tramo-card__icon--${meta.brand}`}>- <Icon size={20} />- </span>- <button- type="button"- className={`tramo-card__fav${fav ? ' is-fav' : ''}`}- onClick={() => toggleFavorite(t.id)}- title={fav ? 'Remove from favorites' : 'Add to favorites'}- aria-pressed={fav}- >- <Star size={16} />- </button>- </div>- <h4 className="tramo-card__name">{t.name}</h4>- {t.description && <p className="tramo-card__desc">{t.description}</p>}- {meta.tags.length > 0 && (- <div className="tramo-card__tags">- {meta.tags.map((tag) => (- <span className="tramo-card__tag" key={tag}>{tag}</span>- ))}- </div>- )}- <div className="tramo-card__foot">- <Button variant="default" size="sm" disabled={busy} onClick={() => handleFromTemplate(t)}>- <Plus size={14} /> Use template- </Button>- </div>- </div>- );- })}- </div>- )}- </div>- );- };-- const renderWorkflows = () => (- <div className="card">- <div className="card-body">- {wfLoading ? <EmptyState loading title="Loading workflows..." />- : workflows.length === 0 ? (- <EmptyState- icon={Workflow}- title="No automations yet"- description="Create a workflow on the visual canvas, or start from a template. Enable it and deploy to run it headless on the tramo engine."- />- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Name</th><th>Enabled</th><th>State</th><th>Version</th><th>Updated</th><th /></tr>- </thead>- <tbody>- {workflows.map((wf) => (- <tr key={wf.id ?? wf.slug}>- <td className="sk-cell-mono">{wf.name}</td>- <td>- <button- type="button"- className={`tramo-toggle${wf.enabled ? ' tramo-toggle--on' : ''}`}- onClick={() => handleToggleEnabled(wf)}- aria-pressed={wf.enabled}- title={wf.enabled ? 'Disable' : 'Enable'}- >- <span className="tramo-toggle__knob" />- </button>- </td>- <td>- {wf.dirty- ? <Pill kind="amber" title="Edited since last deploy">undeployed</Pill>- : <Pill kind="green">deployed</Pill>}- </td>- <td className="sk-cell-mono">{wf.doc_version ?? '—'}</td>- <td className="sk-cell-mono">{wf.updated_at ? new Date(wf.updated_at).toLocaleString() : '—'}</td>- <td className="tramo-row-actions">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRunWorkflow(wf)} title="Run now">- <Play size={14} />- </Button>- <Button variant="secondary" size="sm" onClick={() => navigate(`/automations/edit/${wf.slug}`)} title="Edit">- <Pencil size={14} />- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteWorkflow(wf)} title="Delete">- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderRuns = () => (- <>- {approvals.length > 0 && (- <div className="card tramo-approvals">- <div className="card-header">- <h3>Pending approvals <span className="sec-count">· {approvals.length}</span></h3>- </div>- <div className="card-body">- {approvals.map((a) => (- <div className="tramo-approval" key={a.run_id}>- <div className="tramo-approval__info">- <span className="sk-cell-mono">{a.workflow_slug || a.workflow || '—'}</span>- <span className="text-muted">{a.node || a.message || 'Awaiting approval'}</span>- </div>- <Button variant="default" size="sm" disabled={busy} onClick={() => handleApprove(a.run_id)}>- <CheckCircle2 size={14} /> Approve- </Button>- </div>- ))}- </div>- </div>- )}- <div className="card">- <div className="card-body">- {runsLoading ? <EmptyState loading title="Loading runs..." />- : runs.length === 0 ? (- <EmptyState icon={Play} title="No runs yet" description="Deploy an enabled workflow, then trigger it or wait for a matching event." />- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Status</th><th>Workflow</th><th>Source</th><th>Duration</th><th>Tokens</th><th>Error</th><th /></tr>- </thead>- <tbody>- {runs.map((r) => (- <tr key={r.run_id}>- <td>{runPill(r.status)}</td>- <td className="sk-cell-mono">{r.workflow_slug || '—'}</td>- <td><Pill kind="gray">{r.source || 'manual'}</Pill></td>- <td className="sk-cell-mono">{formatDuration(r.started_at, r.finished_at)}</td>- <td className="sk-cell-mono">{r.usage?.total_tokens ?? r.usage?.tokens ?? '—'}</td>- <td className="sk-cell-mono tramo-truncate" title={r.error || ''}>{r.error || '—'}</td>- <td className="tramo-row-actions">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleReplay(r.run_id)} title="Replay">- <RefreshCw size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- </>- );-- const SETTINGS_SECTIONS = [- { id: 'engine', label: 'Engine', Icon: Server },- { id: 'general', label: 'Events & port', Icon: Zap },- { id: 'secrets', label: 'Pack secrets', Icon: KeyRound },- ];-- const renderSettings = () => {- const state = host?.state || 'not_installed';- const installed = !!host?.installed;- const notSupported = !installed && !!host?.error;-- const engineCard = (- <div className="card">- <div className="card-header">- <h3><Server size={16} /> Automation engine</h3>- </div>- <div className="card-body">- {settingsLoading && !host ? <EmptyState loading title="Loading engine status..." /> : (- <>- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Status</span>- {hostPill(state)}- </div>- <div className="sk-info-row">- <span className="k">Container</span>- <span className="v sk-cell-mono">{host?.container || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Image</span>- <span className="v sk-cell-mono">{host?.image || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Host port</span>- <span className="v sk-cell-mono">{host?.host_port ?? '—'}</span>- </div>- {host?.version && (- <div className="sk-info-row">- <span className="k">Version</span>- <span className="v sk-cell-mono">{host.version}</span>- </div>- )}- </div>-- {notSupported && (- <div className="tramo-note">- Docker is required to run the tramo engine, and it is not available on this- host (the engine does not run on Windows dev boxes). You can still design- workflows; deploying and running them needs a Linux host with Docker.- <div className="tramo-note__detail">{host.error}</div>- </div>- )}-- <div className="tramo-host-actions">- {!installed ? (- <div className="tramo-install">- <div className="form-group">- <Label>Host port (optional)</Label>- <Input- type="number"- value={installPort}- placeholder={String(host?.host_port ?? 3737)}- onChange={(e) => setInstallPort(e.target.value)}- />- </div>- <Button variant="default" size="sm" onClick={handleInstall} disabled={busy}>- <Power size={14} /> Install engine- </Button>- </div>- ) : (- <>- <Button variant="outline" size="sm" onClick={() => handleControl('restart')} disabled={busy}>- <RefreshCw size={14} /> Restart- </Button>- {host?.running ? (- <Button variant="outline" size="sm" onClick={() => handleControl('stop')} disabled={busy}>- <Power size={14} /> Stop- </Button>- ) : (- <Button variant="default" size="sm" onClick={() => handleControl('start')} disabled={busy}>- <Power size={14} /> Start- </Button>- )}- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)} disabled={busy}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)} disabled={busy}>- <Trash2 size={14} /> Remove + data- </Button>- </>- )}- </div>- </>- )}- </div>- </div>- );-- const generalCard = (- <div className="card">- <div className="card-header"><h3><Zap size={16} /> Events & port</h3></div>- <div className="card-body tramo-settings">- <div className="tramo-field">- <div className="tramo-field__label">- <Label>Events bridge</Label>- <p className="text-muted">Forward panel events to tramo so workflows can react to them.</p>- </div>- <button- type="button"- className={`tramo-toggle${settings?.events_bridge_enabled ? ' tramo-toggle--on' : ''}`}- onClick={handleToggleBridge}- disabled={busy}- aria-pressed={!!settings?.events_bridge_enabled}- >- <span className="tramo-toggle__knob" />- </button>- </div>- <div className="tramo-field tramo-field--inline">- <div className="tramo-field__label">- <Label>Host port</Label>- <p className="text-muted">Port the tramo container is published on.</p>- </div>- <div className="tramo-field__control">- <Input type="number" value={hostPortDraft} onChange={(e) => setHostPortDraft(e.target.value)} />- <Button variant="secondary" size="sm" onClick={handleSaveHostPort} disabled={busy}>Save</Button>- </div>- </div>- </div>- </div>- );-- const secretsCard = (- <div className="card sec-flush">- <div className="card-header">- <h3><KeyRound size={16} /> Pack secrets</h3>- </div>- <div className="card-body">- <p className="text-muted">- Credentials integration packs need (API keys, tokens). Values are write-only — they are- stored encrypted and never shown again after saving.- </p>- {(settings?.pack_secret_names?.length ?? 0) === 0 ? (- <p className="text-muted">No pack secrets set yet.</p>- ) : (- <div className="tramo-secret-list">- {settings.pack_secret_names.map((name) => (- <div className="tramo-secret" key={name}>- <span className="sk-cell-mono">{name}</span>- <Pill kind="green">set</Pill>- </div>- ))}- </div>- )}- <div className="tramo-secret-add">- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={newSecret.name}- placeholder="TELEGRAM_BOT_TOKEN"- onChange={(e) => setNewSecret((s) => ({ ...s, name: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Value</Label>- <Input- type="password"- value={newSecret.value}- onChange={(e) => setNewSecret((s) => ({ ...s, value: e.target.value }))}- />- </div>- <Button variant="default" size="sm" onClick={handleAddSecret} disabled={busy}>- <Plus size={14} /> Add secret- </Button>- </div>- </div>- </div>- );-- return (- <div className="settings-layout tramo-settings-layout">- <nav className="settings-nav">- {SETTINGS_SECTIONS.map(({ id, label, Icon }) => (- <Button- key={id}- variant="ghost"- className={`settings-nav-item ${settingsSection === id ? 'active' : ''}`}- onClick={() => setSettingsSection(id)}- >- <Icon size={18} /> {label}- </Button>- ))}- </nav>- <div className="settings-content">- {settingsSection === 'engine' && engineCard}- {settingsSection === 'general' && generalCard}- {settingsSection === 'secrets' && secretsCard}- </div>- </div>- );- };-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));-- // Actions live in the topbar (like Domains / WordPress) and are contextual- // to the active tab, so the content area carries no second header row.- let topbarActions = null;- if (activeTab === 'workflows') {- topbarActions = (- <>- <Button variant="outline" size="sm" onClick={handleDeploy} disabled={busy}>- <Rocket size={14} /> Deploy- </Button>- <Button variant="default" size="sm" onClick={openNewModal}>- <Plus size={14} /> New workflow- </Button>- </>- );- } else if (activeTab === 'templates') {- topbarActions = (- <Button variant="default" size="sm" onClick={openImportModal}>- <Upload size={14} /> Import template- </Button>- );- } else if (activeTab === 'runs') {- topbarActions = (- <Button variant="outline" size="sm" onClick={loadRuns} disabled={runsLoading}>- <RefreshCw size={14} /> Refresh- </Button>- );- } else if (activeTab === 'settings') {- topbarActions = (- <Button variant="outline" size="sm" onClick={loadSettings} disabled={settingsLoading}>- <RefreshCw size={14} /> Refresh- </Button>- );- }-- return (- <div className="page-container page-container--full-bleed sk-tabgroup tramo-page">- <PageTopbar- icon={<Workflow size={18} />}- title="Automations"- tabs={topbarTabs}- actions={topbarActions}- />-- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- {activeTab === 'workflows' && renderWorkflows()}- {activeTab === 'templates' && renderTemplates()}- {activeTab === 'runs' && renderRuns()}- {activeTab === 'settings' && renderSettings()}- </div>- </div>-- {/* New workflow modal — two-column: explainer + name/trigger picker */}- <Modal- open={newModal}- onClose={() => setNewModal(false)}- title="Create an automation"- size="2xl"- className="tramo-newflow-modal"- footer={(- <>- <Button variant="outline" onClick={() => setNewModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreate} disabled={busy || !newName.trim()}>- <Plus size={14} /> Create- </Button>- </>- )}- >- <div className="tramo-newflow">- <aside className="tramo-newflow__hero">- <span className="tramo-newflow__hero-badge"><Workflow size={26} /></span>- <div className="tramo-newflow__hero-diagram" aria-hidden="true">- <span className="tramo-newflow__hero-node"><Zap size={15} /></span>- <span className="tramo-newflow__hero-line" />- <span className="tramo-newflow__hero-node"><Workflow size={15} /></span>- <span className="tramo-newflow__hero-line" />- <span className="tramo-newflow__hero-node"><Send size={15} /></span>- </div>- <h3 className="tramo-newflow__hero-title">Automate the boring parts</h3>- <p className="tramo-newflow__hero-text">- Chain triggers and actions on a visual canvas that runs headless- on the tramo engine. Pick a starting trigger below, then design- the rest in the editor.- </p>- <ul className="tramo-newflow__hero-list">- <li>Message yourself on Telegram when a backup fails</li>- <li>Open a GitHub issue on a nightly health check</li>- <li>Relay any panel event to a Discord channel</li>- </ul>- </aside>-- <div className="tramo-newflow__form">- <div className="form-group">- <Label>Automation name</Label>- <Input- type="text"- value={newName}- autoFocus- placeholder="Notify me when a backup fails"- onChange={(e) => setNewName(e.target.value)}- onKeyDown={(e) => { if (e.key === 'Enter' && newName.trim()) handleCreate(); }}- />- </div>-- <div className="tramo-newflow__triggers">- <span className="tramo-newflow__triggers-label">How should it start?</span>- <div className="tramo-trigger-list" role="radiogroup" aria-label="Trigger">- {TRIGGERS.map((tr) => {- const { Icon } = tr;- const selected = newTrigger === tr.id;- return (- <button- type="button"- key={tr.id}- role="radio"- aria-checked={selected}- className={`tramo-trigger${selected ? ' is-selected' : ''}`}- onClick={() => setNewTrigger(tr.id)}- >- <span className="tramo-trigger__icon"><Icon size={18} /></span>- <span className="tramo-trigger__body">- <span className="tramo-trigger__title">{tr.title}</span>- <span className="tramo-trigger__sub">{tr.subtitle}</span>- </span>- <span className="tramo-trigger__check">- {selected && <Check size={15} />}- </span>- </button>- );- })}- </div>- </div>- </div>- </div>- </Modal>-- {/* Import template / workflow modal */}- <Modal- open={importModal}- onClose={() => setImportModal(false)}- title="Import a template"- size="lg"- footer={(- <>- <Button variant="outline" onClick={() => setImportModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleImport} disabled={busy || !importText.trim()}>- <Upload size={14} /> Import- </Button>- </>- )}- >- <p className="tramo-tpl-intro">- Paste a tramo workflow document (JSON), or load one from a file. It is- created as a new automation you can edit and deploy.- </p>- <div className="form-group">- <Label>Name (optional)</Label>- <Input- type="text"- value={importName}- placeholder="My imported automation"- onChange={(e) => setImportName(e.target.value)}- />- </div>- <div className="form-group">- <div className="tramo-import__labelrow">- <Label>Workflow JSON</Label>- <label className="tramo-import__file">- <FileJson size={14} /> Load file- <input type="file" accept="application/json,.json" onChange={handleImportFile} hidden />- </label>- </div>- <textarea- className="tramo-import__text"- value={importText}- placeholder={'{\n "name": "My flow",\n "nodes": [],\n "edges": []\n}'}- onChange={(e) => setImportText(e.target.value)}- spellCheck={false}- />- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export { AutomationsPage };-export default AutomationsPage;diff --git a/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsx b/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsxdeleted file mode 100644index 3801d659..00000000--- a/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsx+++ /dev/null@@ -1,67 +0,0 @@-// TramoEditor — the heavy editor chunk.-//-// Everything tramo-visual lives behind this module so it code-splits away from-// the panel entry bundle. AutomationEditorPage React.lazy()-imports it; nothing-// on the entry path may import this file (or tramo/react / tramo/styles.css)-// statically, or the split collapses.-import { useEffect } from 'react';-import { Canvas, RightRail, useWorkflow } from 'tramo/react';-import api from '@/services/api';-import EmptyState from '@/components/EmptyState';-import { registry } from '../registry.js';--// tramo's own canvas + inspector CSS. Imported here (inside the lazy chunk) so-// it ships with the editor, not the entry bundle.-import 'tramo/styles.css';--const TramoEditor = ({ slug, onSaveStateChange }) => {- const handle = useWorkflow({- registry,- key: slug,- loadDoc: async () => {- const data = await api.request(`/tramo/workflows/${slug}`);- const doc = data.doc || { version: 1, id: slug, name: slug, nodes: [], edges: [], meta: {} };- // The editor's Canvas reads `doc.meta.mcpServers` unconditionally, so a- // doc without `meta` crashes it. Guarantee `meta` for brand-new- // workflows and any doc persisted by an older version.- if (!doc.meta) doc.meta = {};- return doc;- },- saveDoc: async (doc) => {- await api.request(`/tramo/workflows/${slug}`, { method: 'PUT', body: { doc } });- },- });-- // Surface the debounced save lifecycle up to the page's top strip.- useEffect(() => {- if (onSaveStateChange) onSaveStateChange(handle.saveState);- }, [handle.saveState, onSaveStateChange]);-- if (!handle.ready) {- return (- <div className="tramo-editor__loading">- <EmptyState loading title="Loading workflow..." />- </div>- );- }-- return (- <div className="tramo-editor">- <div className="tramo-editor__canvas">- <Canvas workflow={handle} />- </div>- <div className="tramo-editor__rail">- <RightRail- selection={handle.selection}- registry={handle.registry}- onApply={handle.applyPatch}- onClose={handle.clearSelection}- saveState={handle.saveState}- doc={handle.doc}- />- </div>- </div>- );-};--export default TramoEditor;diff --git a/builtin-extensions/serverkit-tramo/frontend/index.jsx b/builtin-extensions/serverkit-tramo/frontend/index.jsxdeleted file mode 100644index 12933af4..00000000--- a/builtin-extensions/serverkit-tramo/frontend/index.jsx+++ /dev/null@@ -1,12 +0,0 @@-// Automations (tramo) UI, contributed through the extension system. Fully-// self-contained in the extension. After sync this folder lives at-// frontend/src/plugins/serverkit-tramo/, so '@/…' host aliases resolve.-//-// plugin.json declares two route components — AutomationsPage (the tabbed-// list/runs/settings surface) and AutomationEditorPage (the full-bleed canvas).-// Both are resolved by name from these exports.-export { AutomationsPage } from './components/AutomationsPage.jsx';-export { AutomationEditorPage } from './components/AutomationEditorPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contributions resolve the NAMED exports.diff --git a/builtin-extensions/serverkit-tramo/frontend/registry.js b/builtin-extensions/serverkit-tramo/frontend/registry.jsdeleted file mode 100644index 3a6cc291..00000000--- a/builtin-extensions/serverkit-tramo/frontend/registry.js+++ /dev/null@@ -1,69 +0,0 @@-// Node registry for the tramo editor.-//-// tramo ships its node definitions as "packs": the built-in pack plus one pack-// per brand integration. `combinePacks` merges them into a single registry of-// editor-side node definitions (`.nodes`) and runtime executors (`.executors`).-// The editor only needs `.nodes` — executors run server-side inside the managed-// tramo container, never in the browser.-//-// This module is imported by TramoEditor.jsx (the lazy chunk) so all of these-// integration packs code-split into the editor bundle and never reach the-// panel's entry bundle.-import { combinePacks, BUILTIN_PACK } from 'tramo/runtime';--import gmail from 'tramo/integrations/gmail';-import github from 'tramo/integrations/github';-import telegram from 'tramo/integrations/telegram';-import discord from 'tramo/integrations/discord';-import notion from 'tramo/integrations/notion';-import openai from 'tramo/integrations/openai';-import anthropic from 'tramo/integrations/anthropic';-import linear from 'tramo/integrations/linear';-import airtable from 'tramo/integrations/airtable';-import stripe from 'tramo/integrations/stripe';-import cloudflare from 'tramo/integrations/cloudflare';-import googleDrive from 'tramo/integrations/google-drive';-import googleSheets from 'tramo/integrations/google-sheets';-import googleTasks from 'tramo/integrations/google-tasks';-import outlook from 'tramo/integrations/outlook';-import postgres from 'tramo/integrations/postgres';-import twilio from 'tramo/integrations/twilio';-import youtube from 'tramo/integrations/youtube';-import x from 'tramo/integrations/x';-import trello from 'tramo/integrations/trello';-import box from 'tramo/integrations/box';--// TODO(plan45): add SERVERKIT_PACK once @tramo/serverkit is published. Its-// executors run server-side; the editor only needs its node definitions here.--// Order matters only for the palette; combinePacks throws on id collisions, so-// the brand packs are all distinct by construction.-export const combined = combinePacks([- BUILTIN_PACK,- gmail,- github,- telegram,- discord,- notion,- openai,- anthropic,- linear,- airtable,- stripe,- cloudflare,- googleDrive,- googleSheets,- googleTasks,- outlook,- postgres,- twilio,- youtube,- x,- trello,- box,-]);--// The editor-side registry of node definitions. Pass straight to useWorkflow.-export const registry = combined.nodes;--export default registry;diff --git a/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scss b/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scssdeleted file mode 100644index d3def94e..00000000--- a/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scss+++ /dev/null@@ -1,747 +0,0 @@-/* Automations (tramo) extension — layout-only styles. Colours, typography,- spacing and controls all inherit from the host design system (card,- sk-dtable, sk-info-row, Pill, empty-state, form controls). Plugin SCSS is- compiled in isolation, so we lean on CSS custom properties (var(--…)) and- neutral rgba tints — never SCSS $variables, which aren't in scope here.- We never restyle tramo's own .tr-* classes; the editor owns those. */--.tramo-page {- .tramo-toolbar {- display: flex;- align-items: center;- gap: 8px;- flex-wrap: wrap;- }-- .tramo-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;- justify-content: flex-end;- }-- .tramo-truncate {- max-width: 280px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- /* Pending-approval strip */- .tramo-approvals {- margin-bottom: 16px;- }-- .tramo-approval {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 10px 0;- border-bottom: 1px solid rgba(128, 128, 128, 0.16);-- &:last-child {- border-bottom: 0;- }-- &__info {- display: flex;- flex-direction: column;- gap: 2px;- min-width: 0;- }- }-- /* Unsupported / Docker-required note */- .tramo-note {- margin-top: 14px;- padding: 12px 14px;- border-radius: var(--radius, 8px);- border: 1px solid rgba(234, 179, 8, 0.35);- background: rgba(234, 179, 8, 0.08);- font-size: 13px;- line-height: 1.5;-- &__detail {- margin-top: 8px;- font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12px;- opacity: 0.75;- word-break: break-word;- }- }-- /* Engine host actions */- .tramo-host-actions {- display: flex;- align-items: flex-end;- flex-wrap: wrap;- gap: 8px;- margin-top: 16px;- }-- .tramo-install {- display: flex;- align-items: flex-end;- gap: 8px;-- .form-group {- margin: 0;- min-width: 180px;- }- }-- /* Settings fields */- .tramo-settings {- display: flex;- flex-direction: column;- gap: 4px;- }-- .tramo-field {- display: flex;- align-items: center;- justify-content: space-between;- gap: 16px;- padding: 12px 0;- border-bottom: 1px solid rgba(128, 128, 128, 0.14);-- &:last-child {- border-bottom: 0;- }-- &__label {- min-width: 0;-- p {- margin: 2px 0 0;- }- }-- &__control {- display: flex;- align-items: center;- gap: 8px;-- input {- width: 140px;- }- }- }-- /* Pack secrets */- .tramo-secret-list {- display: flex;- flex-direction: column;- gap: 6px;- margin: 12px 0;- }-- .tramo-secret {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 8px 12px;- border-radius: var(--radius-sm, 6px);- background: rgba(128, 128, 128, 0.06);- }-- .tramo-secret-add {- display: flex;- align-items: flex-end;- gap: 8px;- flex-wrap: wrap;- margin-top: 12px;- padding-top: 12px;- border-top: 1px solid rgba(128, 128, 128, 0.14);-- .form-group {- margin: 0;- min-width: 200px;- flex: 1;- }- }-- /* Enable toggle (also used in the settings events-bridge field) */- .tramo-toggle {- --tramo-toggle-w: 38px;- --tramo-toggle-h: 22px;- position: relative;- width: var(--tramo-toggle-w);- height: var(--tramo-toggle-h);- border-radius: 999px;- border: 0;- cursor: pointer;- padding: 0;- background: rgba(128, 128, 128, 0.35);- transition: background 0.15s ease;-- &__knob {- position: absolute;- top: 2px;- left: 2px;- width: calc(var(--tramo-toggle-h) - 4px);- height: calc(var(--tramo-toggle-h) - 4px);- border-radius: 50%;- background: #fff;- transition: transform 0.15s ease;- }-- &--on {- background: var(--accent-bright, #3b82f6);-- .tramo-toggle__knob {- transform: translateX(calc(var(--tramo-toggle-w) - var(--tramo-toggle-h)));- }- }-- &:disabled {- opacity: 0.5;- cursor: not-allowed;- }- }--}--/* Template picker lives inside a <Modal>, which portals to <body> -- OUTSIDE the- .tramo-page subtree -- so these rules must be top-level, not nested under- .tramo-page, or they never match the portaled DOM. */-.tramo-tpl-intro {- margin: 0 0 14px;- font-size: 13px;- line-height: 1.5;- opacity: 0.7;-}--/* Templates marketplace tab (page content) + Import modal (portaled). Kept at- top level so the portaled Import modal picks these up too. */-.tramo-templates {- display: flex;- flex-direction: column;- gap: 16px;-- &__bar {- display: flex;- align-items: center;- gap: 12px;- }-- &__count {- font-size: 12px;- opacity: 0.6;- white-space: nowrap;- }-}--.tramo-search {- display: flex;- align-items: center;- gap: 8px;- flex: 1;- max-width: 340px;- padding: 8px 12px;- border-radius: 9px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-elevated, rgba(128, 128, 128, 0.04));-- svg { flex-shrink: 0; opacity: 0.55; }-- input {- flex: 1;- min-width: 0;- border: 0;- outline: 0;- background: transparent;- color: inherit;- font-size: 13px;-- &::placeholder { opacity: 0.5; }- }-}--.tramo-tpl-grid {- display: grid;- grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));- gap: 14px;-}--.tramo-card {- display: flex;- flex-direction: column;- gap: 10px;- padding: 16px;- border-radius: 14px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.22));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- transition: border-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;-- &:hover {- border-color: rgba(99, 102, 241, 0.4);- transform: translateY(-2px);- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);- }-- &__top {- display: flex;- align-items: flex-start;- justify-content: space-between;- }-- &__icon {- width: 42px;- height: 42px;- border-radius: 11px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.16);- color: var(--accent-bright, #818cf8);-- &--telegram { background: rgba(42, 171, 238, 0.16); color: #2aabee; }- &--github { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }- &--discord { background: rgba(88, 101, 242, 0.16); color: #7c86f5; }- }-- &__fav {- display: grid;- place-items: center;- width: 30px;- height: 30px;- border-radius: 8px;- border: 0;- background: transparent;- color: inherit;- opacity: 0.4;- cursor: pointer;- transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease;-- &:hover { opacity: 0.85; background: rgba(128, 128, 128, 0.12); }-- &.is-fav {- opacity: 1;- color: #f5b301;-- svg { fill: #f5b301; }- }- }-- &__name {- margin: 0;- font-size: 14px;- font-weight: 600;- line-height: 1.3;- }-- &__desc {- margin: 0;- flex: 1;- font-size: 12.5px;- line-height: 1.45;- opacity: 0.68;- }-- &__tags {- display: flex;- flex-wrap: wrap;- gap: 6px;- }-- &__tag {- font-size: 11px;- font-weight: 500;- padding: 2px 9px;- border-radius: 999px;- background: rgba(128, 128, 128, 0.16);- opacity: 0.9;- }-- &__foot {- display: flex;- margin-top: auto;- padding-top: 4px;-- > button { width: 100%; justify-content: center; }- }-}--/* Import modal */-.tramo-import__labelrow {- display: flex;- align-items: center;- justify-content: space-between;- margin-bottom: 6px;-}--.tramo-import__file {- display: inline-flex;- align-items: center;- gap: 6px;- font-size: 12px;- padding: 4px 10px;- border-radius: 7px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- cursor: pointer;- opacity: 0.85;-- &:hover { opacity: 1; border-color: var(--accent-bright, #6366f1); }-}--.tramo-import__text {- width: 100%;- min-height: 200px;- resize: vertical;- padding: 12px 14px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.05));- color: inherit;- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 12.5px;- line-height: 1.5;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- &::placeholder { opacity: 0.4; }-}--/* New-automation two-column modal (portaled -> top-level scope). Kill the modal- body padding so the hero panel can bleed to the dialog edges. */-.tramo-newflow-modal .sk-modal__body { padding: 0; }--.tramo-newflow {- display: grid;- grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr);- min-height: 430px;-}--.tramo-newflow__hero {- padding: 28px 26px;- display: flex;- flex-direction: column;- gap: 14px;- background: linear-gradient(160deg, rgba(99, 102, 241, 0.12), rgba(99, 102, 241, 0.02));- border-right: 1px solid var(--border, rgba(128, 128, 128, 0.18));-- &-badge {- width: 52px;- height: 52px;- border-radius: 14px;- display: grid;- place-items: center;- background: rgba(99, 102, 241, 0.16);- color: var(--accent-bright, #818cf8);- }-- &-diagram {- display: flex;- align-items: center;- gap: 6px;- margin: 2px 0 4px;- }-- &-node {- flex-shrink: 0;- width: 30px;- height: 30px;- border-radius: 8px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.16);- color: var(--accent-bright, #818cf8);- }-- &-line {- flex: 1;- max-width: 24px;- height: 2px;- border-radius: 2px;- background: rgba(128, 128, 128, 0.35);- }-- &-title {- margin: 0;- font-size: 15px;- font-weight: 600;- }-- &-text {- margin: 0;- font-size: 12.5px;- line-height: 1.5;- opacity: 0.72;- }-- &-list {- margin: 6px 0 0;- padding: 0;- list-style: none;- display: flex;- flex-direction: column;- gap: 9px;-- li {- position: relative;- padding-left: 20px;- font-size: 12px;- line-height: 1.4;- opacity: 0.78;-- &::before {- content: '';- position: absolute;- left: 4px;- top: 6px;- width: 6px;- height: 6px;- border-radius: 50%;- background: var(--accent-bright, #818cf8);- }- }- }-}--.tramo-newflow__form {- padding: 24px 26px;- display: flex;- flex-direction: column;- gap: 18px;-}--.tramo-newflow__triggers {- display: flex;- flex-direction: column;- gap: 10px;-- &-label {- font-size: 11px;- font-weight: 600;- letter-spacing: 0.04em;- text-transform: uppercase;- opacity: 0.6;- }-}--.tramo-trigger-list {- display: flex;- flex-direction: column;- gap: 8px;-}--.tramo-trigger {- display: flex;- align-items: center;- gap: 12px;- width: 100%;- text-align: left;- padding: 11px 13px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: transparent;- color: inherit;- cursor: pointer;- transition: border-color 0.15s ease, background 0.15s ease;-- &:hover {- border-color: rgba(99, 102, 241, 0.5);- background: rgba(99, 102, 241, 0.04);- }-- &.is-selected {- border-color: var(--accent-bright, #6366f1);- background: rgba(99, 102, 241, 0.09);- }-- &__icon {- flex-shrink: 0;- width: 34px;- height: 34px;- border-radius: 9px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);- color: var(--accent-bright, #818cf8);- }-- &__body {- flex: 1;- min-width: 0;- display: flex;- flex-direction: column;- gap: 2px;- }-- &__title {- font-weight: 600;- font-size: 13.5px;- }-- &__sub {- font-size: 12px;- line-height: 1.35;- opacity: 0.65;- }-- &__check {- flex-shrink: 0;- width: 20px;- height: 20px;- border-radius: 50%;- display: grid;- place-items: center;- border: 1.5px solid var(--border, rgba(128, 128, 128, 0.45));- color: #fff;- }-- &.is-selected &__check {- background: var(--accent-bright, #6366f1);- border-color: var(--accent-bright, #6366f1);- }-}--@media (max-width: 640px) {- .tramo-newflow {- grid-template-columns: 1fr;- min-height: 0;- }-- .tramo-newflow__hero {- display: none;- }-}--/* ── Full-bleed editor page (route automations/edit/:slug, layout "full") ── */-.tramo-editor-page {- height: 100%;- min-height: 0;- display: flex;- flex-direction: column;- background: var(--bg-body, transparent);-- &__bar {- flex-shrink: 0;- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 10px 16px;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-card, transparent);- }-- &__left {- display: flex;- align-items: center;- gap: 12px;- min-width: 0;- }-- &__title {- display: flex;- align-items: center;- gap: 8px;- min-width: 0;- }-- &__name {- font-weight: 600;- font-size: 15px;- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;- max-width: 320px;- }-- &__actions {- display: flex;- align-items: center;- gap: 8px;- flex-shrink: 0;- }-- &__body {- flex: 1;- min-height: 0;- position: relative;- }-}--/* Save-state indicator in the editor top strip */-.tramo-save {- display: inline-flex;- align-items: center;- gap: 5px;- font-size: 12.5px;-- &--busy { color: var(--text-dim, #9aa0a6); }- &--ok { color: var(--green, #22c55e); }- &--err { color: var(--red, #ef4444); }- &--idle { color: var(--text-dim, #9aa0a6); opacity: 0.7; }-}--.tramo-spin {- animation: tramo-spin 0.9s linear infinite;-}--@keyframes tramo-spin {- to { transform: rotate(360deg); }-}--@media (prefers-reduced-motion: reduce) {- .tramo-spin { animation: none; }-}--/* ── Editor composition: canvas fills, inspector rail is fixed-width ── */-.tramo-editor {- position: absolute;- inset: 0;- display: flex;- min-height: 0;-- /* Theme bridge — tramo's editor ships only a light `:root` palette- (--tr-*). We don't restyle its .tr-* classes; we feed its documented- colour variables from the host design tokens instead. Because custom- properties inherit down the DOM, defining them here (an ancestor of the- whole editor subtree) overrides tramo's :root values without any- specificity battle — and since the host tokens flip with data-theme,- the canvas + inspector track dark/light automatically. */- --tr-bg: var(--bg-body);- --tr-surface: var(--bg-card);- --tr-surface-alt: var(--bg-hover);- --tr-border: var(--border-default);- --tr-border-strong: var(--border-strong);- --tr-text: var(--text-primary);- --tr-text-muted: var(--text-secondary);- --tr-edge: var(--border-strong);- --tr-plus: var(--text-tertiary);- --tr-accent: var(--accent);- --tr-accent-soft: var(--accent-bg);- --tr-shadow: 0 1px 2px rgba(0, 0, 0, 0.28), 0 4px 12px rgba(0, 0, 0, 0.22);-- &__canvas {- position: relative;- flex: 1;- min-width: 0;- min-height: 0;- overflow: hidden;- }-- &__rail {- flex-shrink: 0;- width: 340px;- min-height: 0;- overflow-y: auto;- border-left: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-card, transparent);- }-- &__loading {- position: absolute;- inset: 0;- display: flex;- align-items: center;- justify-content: center;- }-- @media (max-width: 768px) {- &__rail { width: 260px; }- }-}diff --git a/builtin-extensions/serverkit-tramo/plugin.json b/builtin-extensions/serverkit-tramo/plugin.jsondeleted file mode 100644index 6375c90b..00000000--- a/builtin-extensions/serverkit-tramo/plugin.json+++ /dev/null@@ -1,57 +0,0 @@-{- "name": "serverkit-tramo",- "display_name": "Automations",- "version": "1.0.0",- "description": "Node-based automation builder powered by tramo. Design workflows on a visual canvas (triggers, actions, branches, loops, approval gates) that react to panel events or run on a schedule, with 21 brand integration packs (Telegram, GitHub, Gmail, Discord, Notion, Stripe, Cloudflare, Postgres, Twilio and more). Enabled workflows deploy to a managed tramo container on the panel host that runs them headless, with run history, approvals, and inbound webhooks proxied through the panel. This replaces the older drag-and-drop Workflow Builder.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "featured": true,- "feature_score": 90,- "permissions": ["docker", "shell", "filesystem", "network"],- "min_panel_version": "1.7.0",- "entry_point": "tramo:tramo_bp",- "url_prefix": "/api/v1/tramo",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "jobs": [- { "kind": "tramo.harvest_runs", "handler": "jobs:harvest_runs" },- { "kind": "tramo.health_check", "handler": "jobs:health_check" }- ],- "schedules": [- { "name": "tramo-harvest-runs", "kind": "tramo.harvest_runs", "interval_seconds": 120 },- { "name": "tramo-health-check", "kind": "tramo.health_check", "interval_seconds": 300 }- ],- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>",- "contributions": {- "nav": [- {- "id": "automations",- "label": "Automations",- "route": "/automations",- "category": "operations",- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>"- }- ],- "routes": [- { "path": "automations", "component": "AutomationsPage" },- { "path": "automations/:tab", "component": "AutomationsPage" },- { "path": "automations/edit/:slug", "component": "AutomationEditorPage", "layout": "full" }- ],- "page_titles": {- "/automations": "Automations"- },- "command_palette": [- {- "label": "Automations",- "path": "/automations",- "category": "Pages",- "keywords": "automation workflow tramo trigger action schedule webhook telegram github integration pipeline event"- }- ]- }-}diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 3180cc55..5790917e 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -1,12 +1,12 @@-# Web Analytics (`serverkit-analytics`)+# Analytics (`serverkit-analytics`)Native, privacy-first web analytics for the sites this panel manages. It is abuilt-in **extension** (opt-in) — install it from **Marketplace → Built-in →-Web Analytics**, or `POST /api/v1/plugins/builtin/serverkit-analytics/install`.+Analytics**, or `POST /api/v1/plugins/builtin/serverkit-analytics/install`.> **Two things share the name `serverkit-analytics`.** This document is about the> **panel extension** (the dashboard + collector). A separate **WordPress-> companion plugin** of the same name (plan 50) auto-injects this extension's+> companion plugin** of the same name (plan 51) auto-injects this extension's> tracker into WordPress sites. Until that ships, the panel injects a small> mu-plugin itself (see [WordPress](#wordpress)).@@ -113,7 +113,7 @@ and UA churn make visitor counts close **approximations**, not exact identities.## Configuration-Marketplace → Installed → Web Analytics → **Configure**:+Marketplace → Installed → Analytics → **Configure**:| Setting | Default | Purpose ||---|---|---|diff --git a/frontend/package.json b/frontend/package.jsonindex 3e897459..ef11b398 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -45,8 +45,7 @@"react-router-dom": "^7.18.1","recharts": "^2.12.3","socket.io-client": "^4.7.2",- "sonner": "^2.0.7",- "tramo": "^0.1.0"+ "sonner": "^2.0.7"},"devDependencies": {"@types/react": "^18.3.3",diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 4fff768a..3a536d93 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -423,7 +423,7 @@ function AppRoutes() {{groupRoutes.monitoring}</Route><Route path="observability" element={<Navigate to="/monitoring" replace />} />- {/* /gpu is now the serverkit-gpu builtin extension. */}+ {/* /gpu is contributed by the standalone serverkit-gpu extension. */}<Route element={<TabGroupLayout tabs={BACKUP_TABS} />}><Route path="backups" element={<Backups />} /><Route path="backups/:tab" element={<Backups />} />diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex dc52e308..2f4afe7f 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -89,8 +89,9 @@ export const SIDEBAR_ITEMS = [// WordPress is now the serverkit-wordpress builtin extension (Phase 5 #38);// its sidebar item is contributed by the extension manifest (nav), so it// disappears cleanly when the extension is uninstalled.- // Automations (tramo) is a builtin extension (serverkit-tramo) that replaced- // the old Workflow Builder; its sidebar item comes from the extension manifest.+ // Automations (tramo) is the standalone serverkit-tramo extension (own repo,+ // registry-installed) that replaced the old Workflow Builder; its sidebar+ // item comes from the extension manifest.{id: 'databases',label: 'Databases',@@ -178,9 +179,9 @@ export const SIDEBAR_ITEMS = [category: 'system',icon: '<path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/>'},- // GPU Monitor is now the serverkit-gpu builtin extension; its sidebar item- // (still gated on gpuAvailable via requiresCondition) is contributed by the- // extension manifest.+ // GPU Monitor lives in the standalone serverkit-gpu extension (own repo,+ // registry-installed); its sidebar item (still gated on gpuAvailable via+ // requiresCondition) is contributed by the extension manifest.{// Inbound webhook console. Secret storage ("Vaults") that used to share// this page now lives under the Organization tab group (/vaults); onlydiff --git a/frontend/src/components/wordpress/detail/AnalyticsTab.jsx b/frontend/src/components/wordpress/detail/AnalyticsTab.jsxindex c1f930f6..21652a78 100644--- a/frontend/src/components/wordpress/detail/AnalyticsTab.jsx+++ b/frontend/src/components/wordpress/detail/AnalyticsTab.jsx@@ -69,11 +69,11 @@ const AnalyticsTab = ({ siteId }) => {<div className="wp-analytics-banner"><LineChart size={16} /><div className="wp-analytics-banner__text">- <strong>Web Analytics is installed.</strong>+ <strong>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} />+ Open Analytics <ExternalLink size={13} /></Link></div>)}diff --git a/frontend/src/pages/GpuMonitor.jsx b/frontend/src/pages/GpuMonitor.jsxdeleted file mode 100644index 3e6f8310..00000000--- a/frontend/src/pages/GpuMonitor.jsx+++ /dev/null@@ -1,198 +0,0 @@-import { useState, useEffect, useCallback } from 'react';-import { Cpu, RefreshCw, Thermometer, Zap, Fan } from 'lucide-react';-import { PageTopbar } from '@/components/ds';-import api from '../services/api';-import { useToast } from '../contexts/ToastContext';-import EmptyState from '../components/EmptyState';-import { Button } from '@/components/ui/button';--function clampPercent(value) {- const n = Number(value);- if (!Number.isFinite(n)) return 0;- return Math.min(100, Math.max(0, n));-}--function utilTone(percent) {- if (percent >= 85) return 'is-red';- if (percent >= 60) return 'is-amber';- return 'is-green';-}--function formatMib(value) {- const n = Number(value);- if (!Number.isFinite(n)) return '—';- if (n >= 1024) return `${(n / 1024).toFixed(1)} GiB`;- return `${Math.round(n)} MiB`;-}--const GpuCard = ({ gpu }) => {- const util = clampPercent(gpu.utilization_gpu);- const memPercent = clampPercent(- gpu.memory_percent != null- ? gpu.memory_percent- : (gpu.memory_total ? (gpu.memory_used / gpu.memory_total) * 100 : 0)- );-- return (- <div className="gpu-card">- <div className="gpu-card__head">- <div className="gpu-card__title">- <Cpu size={16} />- <span className="gpu-card__name">{gpu.name || `GPU ${gpu.index}`}</span>- </div>- <span className="gpu-card__index">#{gpu.index}</span>- </div>-- <div className="gpu-card__bars">- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">GPU Utilization</span>- <span className="gpu-bar__value">{util}%</span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(util)}`} style={{ width: `${util}%` }} />- </div>- </div>-- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">VRAM</span>- <span className="gpu-bar__value">- {formatMib(gpu.memory_used)} / {formatMib(gpu.memory_total)} ({Math.round(memPercent)}%)- </span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(memPercent)}`} style={{ width: `${memPercent}%` }} />- </div>- </div>- </div>-- <div className="gpu-stats">- <div className="gpu-stat">- <Thermometer size={14} />- <span className="gpu-stat__label">Temp</span>- <span className="gpu-stat__value">- {gpu.temperature != null ? `${gpu.temperature}°C` : '—'}- </span>- </div>- <div className="gpu-stat">- <Zap size={14} />- <span className="gpu-stat__label">Power</span>- <span className="gpu-stat__value">- {gpu.power_draw != null ? `${Math.round(gpu.power_draw)}W` : '—'}- {gpu.power_limit != null && (- <span className="gpu-stat__sub"> / {Math.round(gpu.power_limit)}W</span>- )}- </span>- </div>- <div className="gpu-stat">- <Fan size={14} />- <span className="gpu-stat__label">Fan</span>- <span className="gpu-stat__value">- {gpu.fan_speed != null ? `${gpu.fan_speed}%` : '—'}- </span>- </div>- <div className="gpu-stat">- <Cpu size={14} />- <span className="gpu-stat__label">Driver</span>- <span className="gpu-stat__value">{gpu.driver_version || '—'}</span>- </div>- </div>- </div>- );-};--const GpuMonitor = () => {- const toast = useToast();- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);-- const load = useCallback(async (isRefresh = false) => {- if (isRefresh) setRefreshing(true);- try {- const result = await api.getGpuInfo();- setData(result);- } catch (err) {- if (isRefresh) toast.error(err.message || 'Failed to load GPU info');- console.error('Failed to load GPU info:', err);- } finally {- setLoading(false);- setRefreshing(false);- }- }, [toast]);-- useEffect(() => { load(); }, [load]);-- const gpus = data?.gpus || [];- const processes = data?.processes || [];-- return (- <div className="page-container gpu-page">- <PageTopbar- icon={<Cpu size={18} />}- title="GPU Monitor"- meta={data?.available ? `${gpus.length} GPU${gpus.length !== 1 ? 's' : ''}` : undefined}- actions={- <Button variant="outline" size="sm" onClick={() => load(true)} disabled={refreshing}>- <RefreshCw size={15} />- {refreshing ? 'Refreshing…' : 'Refresh'}- </Button>- }- />-- {loading ? (- <EmptyState loading title="Loading GPU data" />- ) : !data?.available ? (- <EmptyState- icon={Cpu}- size="lg"- title="No NVIDIA GPU detected"- description="This host has no NVIDIA GPU, or the NVIDIA drivers / nvidia-smi are not available."- />- ) : (- <>- <div className="gpu-grid">- {gpus.map((gpu) => (- <GpuCard key={gpu.index} gpu={gpu} />- ))}- </div>-- <div className="gpu-procs">- <div className="gpu-procs__head">- <h2>GPU Processes</h2>- <span className="text-muted">{processes.length} running</span>- </div>- <table className="sk-dtable gpu-procs__table">- <thead>- <tr>- <th>PID</th>- <th>Process</th>- <th>Container</th>- <th>VRAM</th>- </tr>- </thead>- <tbody>- {processes.map((proc, i) => (- <tr key={`${proc.pid}-${i}`}>- <td className="sk-cell-mono">{proc.pid}</td>- <td>{proc.process_name || '—'}</td>- <td>{proc.container || '—'}</td>- <td className="sk-cell-mono">{formatMib(proc.used_memory)}</td>- </tr>- ))}- {processes.length === 0 && (- <tr>- <td colSpan={4} className="text-center text-muted">No active GPU processes</td>- </tr>- )}- </tbody>- </table>- </div>- </>- )}- </div>- );-};--export default GpuMonitor;diff --git a/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx b/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsxdeleted file mode 100644index 41bdb9f1..00000000--- a/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx+++ /dev/null@@ -1,142 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { NavLink, useParams, useNavigate } from 'react-router-dom';-import { BarChart3, FileText, Link2, Monitor, Radio, Globe, Plus } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';-import { useToast } from '@/contexts/ToastContext';--import OverviewTab from './tabs/OverviewTab.jsx';-import PagesTab from './tabs/PagesTab.jsx';-import ReferrersTab from './tabs/ReferrersTab.jsx';-import DevicesTab from './tabs/DevicesTab.jsx';-import RealtimeTab from './tabs/RealtimeTab.jsx';-import SitesTab from './tabs/SitesTab.jsx';--import '../styles/analytics.scss';--// Route-driven tabs. plugin.json maps /analytics and /analytics/:tab here, so the-// active tab is read from useParams().tab (undefined => overview).-const TABS = [- { slug: 'overview', to: '/analytics', label: 'Overview', end: true, icon: <BarChart3 size={15} /> },- { slug: 'pages', to: '/analytics/pages', label: 'Pages', icon: <FileText size={15} /> },- { slug: 'referrers', to: '/analytics/referrers', label: 'Referrers', icon: <Link2 size={15} /> },- { slug: 'devices', to: '/analytics/devices', label: 'Devices', icon: <Monitor size={15} /> },- { slug: 'realtime', to: '/analytics/realtime', label: 'Realtime', icon: <Radio size={15} /> },- { slug: 'sites', to: '/analytics/sites', label: 'Sites', icon: <Globe size={15} /> },-];-const VALID_TABS = TABS.map((t) => t.slug);-const REPORT_TABS = ['overview', 'pages', 'referrers', 'devices', 'realtime'];--export function AnalyticsPage() {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [sites, setSites] = useState([]);- const [sitesLoading, setSitesLoading] = useState(true);- const [selectedSiteId, setSelectedSiteId] = useState(null);-- const loadSites = useCallback(async () => {- setSitesLoading(true);- try {- const data = await api.request('/analytics/sites');- setSites(data?.sites || []);- } catch (error) {- toast.error(`Could not load sites: ${error.message}`);- setSites([]);- } finally {- setSitesLoading(false);- }- }, [toast]);-- useEffect(() => { loadSites(); }, [loadSites]);-- // Keep a valid selection: default to the first site, and re-point if the- // current selection disappears (e.g. after a delete).- useEffect(() => {- if (sites.length === 0) { setSelectedSiteId(null); return; }- setSelectedSiteId((prev) => {- if (prev != null && sites.some((s) => String(s.id) === String(prev))) return prev;- return String(sites[0].id);- });- }, [sites]);-- const isReport = REPORT_TABS.includes(activeTab);-- const renderReportBody = () => {- if (sitesLoading || (sites.length > 0 && selectedSiteId == null)) {- return <EmptyState loading title="Loading analytics…" />;- }- if (sites.length === 0) {- return (- <div className="analytics-empty">- <EmptyState- icon={Globe}- title="No tracked sites yet"- description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."- action={(- <Button variant="default" size="sm" onClick={() => navigate('/analytics/sites')}>- <Plus size={14} /> Add a site- </Button>- )}- />- </div>- );- }- // Remount on site change so each tab resets its own range/loading state.- switch (activeTab) {- case 'pages': return <PagesTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'referrers': return <ReferrersTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'devices': return <DevicesTab key={selectedSiteId} siteId={selectedSiteId} />;- case 'realtime': return <RealtimeTab key={selectedSiteId} siteId={selectedSiteId} />;- default: return <OverviewTab key={selectedSiteId} siteId={selectedSiteId} />;- }- };-- // Report tabs get a site picker in the topbar; the Sites tab manages its own.- const topbarActions = isReport && sites.length > 0 ? (- <select- className="analytics-site-select"- value={selectedSiteId ?? ''}- onChange={(e) => setSelectedSiteId(e.target.value)}- aria-label="Selected site"- >- {sites.map((s) => (- <option key={s.id} value={String(s.id)}>{s.name}</option>- ))}- </select>- ) : null;-- return (- <div className="analytics-page">- <PageTopbar- icon={<BarChart3 size={18} />}- title="Web Analytics"- actions={topbarActions}- />-- <nav className="analytics-tabs" aria-label="Web Analytics sections">- {TABS.map((t) => (- <NavLink- key={t.slug}- to={t.to}- end={t.end}- className={({ isActive }) => `analytics-tabs__tab${isActive ? ' is-active' : ''}`}- >- {t.icon}- {t.label}- </NavLink>- ))}- </nav>-- <div className="analytics-page__body">- {activeTab === 'sites'- ? <SitesTab sites={sites} loading={sitesLoading} reload={loadSites} />- : renderReportBody()}- </div>- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsx b/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsxdeleted file mode 100644index aa86c32a..00000000--- a/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsx+++ /dev/null@@ -1,28 +0,0 @@-// Shared date-range picker for the report tabs. Rendered as a small segmented-// button group styled by our own `.analytics-range` rules (isolated SCSS).-const RANGES = [- { value: '1d', label: '24h' },- { value: '7d', label: '7d' },- { value: '14d', label: '14d' },- { value: '30d', label: '30d' },- { value: '90d', label: '90d' },-];--export default function RangePicker({ value, onChange }) {- return (- <div className="analytics-range" role="tablist" aria-label="Date range">- {RANGES.map((r) => (- <button- key={r.value}- type="button"- role="tab"- aria-selected={value === r.value}- className={`analytics-range__btn${value === r.value ? ' is-active' : ''}`}- onClick={() => onChange(r.value)}- >- {r.label}- </button>- ))}- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsxdeleted file mode 100644index 7bb48205..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsx+++ /dev/null@@ -1,73 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Monitor, Globe, Cpu, MapPin } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, labelOrDirect } from '../../utils/format.js';--const makeColumns = (header) => [- { key: 'value', header, className: 'analytics-col-grow', render: (r) => (- <span title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },-];--const SECTIONS = [- { key: 'device', label: 'Device class', icon: Monitor, columns: makeColumns('Device') },- { key: 'browser', label: 'Browser', icon: Globe, columns: makeColumns('Browser') },- { key: 'os', label: 'Operating system', icon: Cpu, columns: makeColumns('OS') },- { key: 'country', label: 'Country', icon: MapPin, columns: makeColumns('Country') },-];--export default function DevicesTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/devices?range=${range}`);- setData(res);- } catch (error) {- toast.error(`Could not load devices: ${error.message}`);- setData(null);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- {loading ? (- <EmptyState loading title="Loading devices…" />- ) : (- <div className="analytics-grid analytics-grid--devices">- {SECTIONS.map(({ key, label, icon: Icon, columns }) => (- <div className="analytics-panel" key={key}>- <div className="analytics-panel__head">- <Icon size={15} /> {label}- </div>- <DataTable- columns={columns}- data={data?.[key] || []}- keyField="value"- emptyTitle={`No ${label.toLowerCase()} data`}- emptyMessage="Nothing recorded in this range yet."- />- </div>- ))}- </div>- )}- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsxdeleted file mode 100644index 8bad763b..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsx+++ /dev/null@@ -1,160 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import {- ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,-} from 'recharts';-import { Users, Eye, TrendingDown, Zap, Radio, BarChart3 } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, formatMs, formatPct, formatDay, labelOrDirect } from '../../utils/format.js';--const KPIS = [- { key: 'visitors', label: 'Visitors', icon: Users, tone: 'accent', fmt: formatInt },- { key: 'pageviews', label: 'Pageviews', icon: Eye, tone: 'cyan', fmt: formatInt },- { key: 'bounce_rate', label: 'Bounce rate', icon: TrendingDown, tone: 'amber', fmt: formatPct },- { key: 'avg_load_ms', label: 'Avg load', icon: Zap, tone: 'violet', fmt: formatMs },-];--const pageColumns = [- { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },- { key: 'avg_load_ms', header: 'Avg load', render: (r) => formatMs(r.avg_load_ms) },-];--const referrerColumns = [- { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },-];--export default function OverviewTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/overview?range=${range}`);- setData(res);- } catch (error) {- toast.error(`Could not load overview: ${error.message}`);- setData(null);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- const totals = data?.totals || {};- const timeseries = data?.timeseries || [];- const realtime = data?.realtime || {};- const hasTraffic = (totals.pageviews || 0) > 0 || (totals.visitors || 0) > 0;-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- <span className="analytics-live" title="Active visitors in the last 30 minutes">- <Radio size={14} className="analytics-live__dot" />- {formatInt(realtime.active_visitors)} active now- </span>- </div>-- <div className="analytics-kpis">- {KPIS.map(({ key, label, icon: Icon, tone, fmt }) => (- <div className="analytics-kpi" key={key}>- <span className={`analytics-kpi__icon analytics-kpi__icon--${tone}`}>- <Icon size={16} />- </span>- <div className="analytics-kpi__val">{loading ? '—' : fmt(totals[key])}</div>- <div className="analytics-kpi__label">{label}</div>- </div>- ))}- </div>-- {loading ? (- <EmptyState loading title="Loading overview…" />- ) : !hasTraffic ? (- <div className="analytics-empty">- <EmptyState- icon={BarChart3}- title="No traffic in this range yet"- description="Once the tracking snippet is installed and visitors arrive, their pageviews show up here."- />- </div>- ) : (- <>- <div className="analytics-chart-card">- <div className="analytics-chart-card__head">Visitors & pageviews</div>- <ResponsiveContainer width="100%" height={260}>- <AreaChart data={timeseries} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>- <defs>- <linearGradient id="anVisitors" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />- <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />- </linearGradient>- <linearGradient id="anPageviews" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#22c7d6" stopOpacity={0.3} />- <stop offset="95%" stopColor="#22c7d6" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />- <XAxis- dataKey="date"- tickFormatter={formatDay}- tick={{ fontSize: 11, fill: '#888' }}- minTickGap={24}- axisLine={false}- tickLine={false}- />- <YAxis- allowDecimals={false}- tick={{ fontSize: 11, fill: '#888' }}- width={40}- axisLine={false}- tickLine={false}- />- <Tooltip labelFormatter={formatDay} />- <Area type="monotone" dataKey="visitors" name="Visitors" stroke="#8b93ff" fill="url(#anVisitors)" strokeWidth={2} />- <Area type="monotone" dataKey="pageviews" name="Pageviews" stroke="#22c7d6" fill="url(#anPageviews)" strokeWidth={2} />- </AreaChart>- </ResponsiveContainer>- </div>-- <div className="analytics-grid">- <div className="analytics-panel">- <div className="analytics-panel__head">Top pages</div>- <DataTable- columns={pageColumns}- data={data?.top_pages || []}- keyField="value"- emptyTitle="No pages yet"- emptyMessage="Pageviews will appear here once visitors browse the site."- />- </div>- <div className="analytics-panel">- <div className="analytics-panel__head">Top referrers</div>- <DataTable- columns={referrerColumns}- data={data?.top_referrers || []}- keyField="value"- emptyTitle="No referrers yet"- emptyMessage="Sources that send traffic to the site will appear here."- />- </div>- </div>- </>- )}- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsxdeleted file mode 100644index a4c70add..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsx+++ /dev/null@@ -1,56 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, formatMs, labelOrDirect } from '../../utils/format.js';--const columns = [- { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },- { key: 'avg_load_ms', header: 'Avg load', sortable: true, sortValue: (r) => r.avg_load_ms ?? -1, render: (r) => formatMs(r.avg_load_ms) },-];--export default function PagesTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [rows, setRows] = useState([]);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/pages?range=${range}`);- setRows(res?.rows || []);- } catch (error) {- toast.error(`Could not load pages: ${error.message}`);- setRows([]);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- <div className="analytics-panel">- <DataTable- columns={columns}- data={rows}- keyField="value"- loading={loading}- defaultSort={{ key: 'pageviews', direction: 'desc' }}- emptyTitle="No pages yet"- emptyMessage="Pageviews will appear here once visitors browse the site."- />- </div>- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsxdeleted file mode 100644index 6a8af6b2..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsx+++ /dev/null@@ -1,102 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Radio, Users, Eye } from 'lucide-react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import { formatInt, formatClock, labelOrDirect } from '../../utils/format.js';--const MINUTE_OPTIONS = [5, 15, 30, 60];-const POLL_MS = 15000;--const columns = [- { key: 'ts', header: 'Time', render: (r) => <span className="analytics-cell-mono">{formatClock(r.ts)}</span> },- { key: 'path', header: 'Page', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.path}>{labelOrDirect(r.path)}</span>- ) },- { key: 'referrer_host', header: 'Referrer', render: (r) => labelOrDirect(r.referrer_host) },- { key: 'device_class', header: 'Device', render: (r) => r.device_class || '—' },- { key: 'country', header: 'Country', render: (r) => r.country || '—' },-];--export default function RealtimeTab({ siteId }) {- const toast = useToast();- const [minutes, setMinutes] = useState(30);- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);-- // `silent` polls skip the loading skeleton so the feed refreshes without flicker.- const load = useCallback(async (silent = false) => {- if (!silent) setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/realtime?minutes=${minutes}`);- setData(res);- } catch (error) {- if (!silent) {- toast.error(`Could not load realtime: ${error.message}`);- setData(null);- }- } finally {- if (!silent) setLoading(false);- }- }, [siteId, minutes, toast]);-- useEffect(() => {- load(false);- const id = setInterval(() => load(true), POLL_MS);- return () => clearInterval(id);- }, [load]);-- // Realtime events carry no id; synthesize a stable unique key per row so the- // table never collides two hits sharing a timestamp.- const recent = (data?.recent || []).map((r, i) => ({ ...r, _rid: `${r.ts || 'x'}-${i}` }));-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <div className="analytics-range" role="tablist" aria-label="Time window">- {MINUTE_OPTIONS.map((m) => (- <button- key={m}- type="button"- role="tab"- aria-selected={minutes === m}- className={`analytics-range__btn${minutes === m ? ' is-active' : ''}`}- onClick={() => setMinutes(m)}- >- {m}m- </button>- ))}- </div>- <span className="analytics-live" title="Auto-refreshing">- <Radio size={14} className="analytics-live__dot" />- Live · last {data?.minutes ?? minutes} min- </span>- </div>-- <div className="analytics-realtime">- <div className="analytics-realtime__stat">- <span className="analytics-realtime__icon analytics-realtime__icon--accent"><Users size={18} /></span>- <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.active_visitors)}</div>- <div className="analytics-realtime__label">Active visitors</div>- </div>- <div className="analytics-realtime__stat">- <span className="analytics-realtime__icon analytics-realtime__icon--cyan"><Eye size={18} /></span>- <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.pageviews)}</div>- <div className="analytics-realtime__label">Pageviews</div>- </div>- </div>-- <div className="analytics-panel">- <div className="analytics-panel__head">Recent activity</div>- <DataTable- columns={columns}- data={recent}- keyField="_rid"- loading={loading}- emptyTitle="No activity yet"- emptyMessage="Hits from the last few minutes will stream in here."- />- </div>- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsxdeleted file mode 100644index b86b093d..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsx+++ /dev/null@@ -1,55 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import api from '@/services/api';-import { DataTable } from '@/components/ds';-import { useToast } from '@/contexts/ToastContext';-import RangePicker from '../RangePicker.jsx';-import { formatInt, labelOrDirect } from '../../utils/format.js';--const columns = [- { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (- <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>- ) },- { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },- { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },-];--export default function ReferrersTab({ siteId }) {- const toast = useToast();- const [range, setRange] = useState('7d');- const [rows, setRows] = useState([]);- const [loading, setLoading] = useState(true);-- const load = useCallback(async () => {- setLoading(true);- try {- const res = await api.request(`/analytics/sites/${siteId}/referrers?range=${range}`);- setRows(res?.rows || []);- } catch (error) {- toast.error(`Could not load referrers: ${error.message}`);- setRows([]);- } finally {- setLoading(false);- }- }, [siteId, range, toast]);-- useEffect(() => { load(); }, [load]);-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar">- <RangePicker value={range} onChange={setRange} />- </div>- <div className="analytics-panel">- <DataTable- columns={columns}- data={rows}- keyField="value"- loading={loading}- defaultSort={{ key: 'pageviews', direction: 'desc' }}- emptyTitle="No referrers yet"- emptyMessage="Sources that send traffic to the site will appear here."- />- </div>- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsxdeleted file mode 100644index 3aeaee43..00000000--- a/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsx+++ /dev/null@@ -1,318 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Plus, Trash2, RefreshCw, Copy, Check, Code2, Power, Globe } from 'lucide-react';-import api from '@/services/api';-import { DataTable, Pill } from '@/components/ds';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { useToast } from '@/contexts/ToastContext';-import { useClipboard } from '@/hooks/useClipboard';--const INITIAL_FORM = { name: '', hostnames: '', allowedOrigins: '', honorDnt: true, enabled: true };--// Split a textarea value on newlines/commas into a clean list of tokens.-const parseList = (raw) => (raw || '').split(/[\n,]/).map((s) => s.trim()).filter(Boolean);--export default function SitesTab({ sites, loading, reload }) {- const toast = useToast();- const { copy, copied } = useClipboard({ successMessage: 'Snippet copied' });-- const [busy, setBusy] = useState(false);- const [confirm, setConfirm] = useState(null);-- // Add-site modal- const [addOpen, setAddOpen] = useState(false);- const [form, setForm] = useState(INITIAL_FORM);-- // Snippet modal- const [snippetSite, setSnippetSite] = useState(null);- const [snippetData, setSnippetData] = useState(null);- const [snippetLoading, setSnippetLoading] = useState(false);- const [snippetOutlinks, setSnippetOutlinks] = useState(false);-- const fetchSnippet = useCallback(async (site, outlinks) => {- setSnippetLoading(true);- try {- const res = await api.request(`/analytics/sites/${site.id}/snippet?outlinks=${outlinks}`);- setSnippetData(res);- } catch (error) {- toast.error(`Could not load snippet: ${error.message}`);- setSnippetData(null);- } finally {- setSnippetLoading(false);- }- }, [toast]);-- useEffect(() => {- if (snippetSite) fetchSnippet(snippetSite, snippetOutlinks);- }, [snippetSite, snippetOutlinks, fetchSnippet]);-- const openAdd = () => { setForm(INITIAL_FORM); setAddOpen(true); };- const openSnippet = (site) => { setSnippetOutlinks(false); setSnippetSite(site); };- const closeSnippet = () => { setSnippetSite(null); setSnippetData(null); };-- const handleCreate = async () => {- const name = form.name.trim();- const hostnames = parseList(form.hostnames);- if (!name) { toast.error('Name is required.'); return; }- if (hostnames.length === 0) { toast.error('Add at least one hostname.'); return; }- setBusy(true);- try {- const site = await api.request('/analytics/sites', {- method: 'POST',- body: {- name,- hostnames,- allowed_origins: parseList(form.allowedOrigins),- honor_dnt: form.honorDnt,- enabled: form.enabled,- },- });- setAddOpen(false);- toast.success(`Site "${site.name}" created`);- await reload();- openSnippet(site);- } catch (error) {- toast.error(`Could not create site: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggle = async (site) => {- try {- await api.request(`/analytics/sites/${site.id}`, { method: 'PUT', body: { enabled: !site.enabled } });- await reload();- } catch (error) {- toast.error(`Could not update site: ${error.message}`);- }- };-- const handleRotate = (site) => setConfirm({- title: `Rotate key for ${site.name}?`,- message: 'A new site key is generated immediately. The old key stops accepting hits, so update the installed snippet afterward.',- confirmText: 'Rotate key',- variant: 'warning',- onConfirm: async () => {- setConfirm(null);- setBusy(true);- try {- await api.request(`/analytics/sites/${site.id}/rotate-key`, { method: 'POST' });- toast.success('Site key rotated');- await reload();- if (snippetSite && snippetSite.id === site.id) fetchSnippet(site, snippetOutlinks);- } catch (error) {- toast.error(`Could not rotate key: ${error.message}`);- } finally {- setBusy(false);- }- },- });-- const handleDelete = (site) => setConfirm({- title: `Delete ${site.name}?`,- message: 'This removes the site and all of its collected analytics. This cannot be undone.',- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- setConfirm(null);- setBusy(true);- try {- await api.request(`/analytics/sites/${site.id}`, { method: 'DELETE' });- toast.success('Site deleted');- if (snippetSite && snippetSite.id === site.id) closeSnippet();- await reload();- } catch (error) {- toast.error(`Could not delete site: ${error.message}`);- } finally {- setBusy(false);- }- },- });-- const columns = [- { key: 'name', header: 'Site', sortable: true, render: (s) => (- <div className="analytics-site-name">- <span className="analytics-site-name__title">{s.name}</span>- <span className="analytics-cell-mono analytics-site-name__key">{s.site_key}</span>- </div>- ) },- { key: 'hostnames', header: 'Hostnames', render: (s) => {- const list = (s.hostnames || []).join(', ');- return <span className="analytics-cell-mono" title={list}>{list || '—'}</span>;- } },- { key: 'enabled', header: 'Status', render: (s) => (- s.enabled ? <Pill kind="green">Enabled</Pill> : <Pill kind="gray">Disabled</Pill>- ) },- { key: 'actions', header: '', className: 'analytics-col-actions', render: (s) => (- <div className="analytics-row-actions">- <Button variant="secondary" size="sm" onClick={() => openSnippet(s)} title="Tracking snippet">- <Code2 size={14} />- </Button>- <Button variant="secondary" size="sm" onClick={() => handleToggle(s)} title={s.enabled ? 'Disable' : 'Enable'}>- <Power size={14} />- </Button>- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRotate(s)} title="Rotate key">- <RefreshCw size={14} />- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDelete(s)} title="Delete">- <Trash2 size={14} />- </Button>- </div>- ) },- ];-- return (- <div className="analytics-tabbody">- <div className="analytics-toolbar analytics-toolbar--between">- <span className="analytics-toolbar__hint">- {sites.length} site{sites.length === 1 ? '' : 's'} tracked- </span>- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add site- </Button>- </div>-- <div className="analytics-panel">- <DataTable- columns={columns}- data={sites}- keyField="id"- loading={loading}- emptyState={(- <EmptyState- icon={Globe}- title="No tracked sites yet"- description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."- action={(- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add site- </Button>- )}- />- )}- />- </div>-- {/* Add-site modal */}- <Modal- open={addOpen}- onClose={() => setAddOpen(false)}- title="Add a site"- size="lg"- footer={(- <>- <Button variant="outline" onClick={() => setAddOpen(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreate} disabled={busy || !form.name.trim()}>- <Plus size={14} /> Create site- </Button>- </>- )}- >- <div className="analytics-form">- <div className="form-group">- <Label>Name</Label>- <Input- value={form.name}- placeholder="My website"- autoFocus- onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Hostnames</Label>- <textarea- className="analytics-textarea"- value={form.hostnames}- placeholder={'example.com\nwww.example.com'}- spellCheck={false}- onChange={(e) => setForm((f) => ({ ...f, hostnames: e.target.value }))}- />- <p className="analytics-form__hint">One per line (or comma-separated). Hits are accepted from these hostnames.</p>- </div>- <div className="form-group">- <Label>Allowed origins (optional)</Label>- <textarea- className="analytics-textarea"- value={form.allowedOrigins}- placeholder={'https://example.com'}- spellCheck={false}- onChange={(e) => setForm((f) => ({ ...f, allowedOrigins: e.target.value }))}- />- <p className="analytics-form__hint">Restrict the collector to these CORS origins. Leave empty to allow any.</p>- </div>- <label className="analytics-check">- <input- type="checkbox"- checked={form.honorDnt}- onChange={(e) => setForm((f) => ({ ...f, honorDnt: e.target.checked }))}- />- <span>Honor the browser's Do Not Track signal</span>- </label>- <label className="analytics-check">- <input- type="checkbox"- checked={form.enabled}- onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}- />- <span>Start collecting immediately</span>- </label>- </div>- </Modal>-- {/* Tracking snippet modal */}- <Modal- open={!!snippetSite}- onClose={closeSnippet}- title={snippetSite ? `Tracking snippet · ${snippetSite.name}` : 'Tracking snippet'}- size="lg"- footer={<Button variant="outline" onClick={closeSnippet}>Close</Button>}- >- {snippetLoading ? (- <EmptyState loading title="Loading snippet…" />- ) : !snippetData ? (- <EmptyState title="Snippet unavailable" description="Could not load the tracking snippet for this site." />- ) : (- <div className="analytics-snippet-wrap">- <p className="analytics-form__hint">- Paste this into the <head> of every page you want to track. It is cookieless and under 4 KB.- </p>- <label className="analytics-check">- <input- type="checkbox"- checked={snippetOutlinks}- onChange={(e) => setSnippetOutlinks(e.target.checked)}- />- <span>Include outbound-link tracking</span>- </label>- <pre className="analytics-snippet"><code>{snippetData.snippet}</code></pre>- <div className="analytics-snippet__foot">- <span className="analytics-cell-mono analytics-snippet__key" title={snippetData.tracker_url}>- {snippetData.site_key}- </span>- <Button variant="default" size="sm" onClick={() => copy(snippetData.snippet)}>- {copied ? <Check size={14} /> : <Copy size={14} />}- {copied ? 'Copied' : 'Copy'}- </Button>- </div>- </div>- )}- </Modal>-- {confirm && (- <ConfirmDialog- isOpen- title={confirm.title}- message={confirm.message}- confirmText={confirm.confirmText}- variant={confirm.variant}- onConfirm={confirm.onConfirm}- onCancel={() => setConfirm(null)}- />- )}- </div>- );-}diff --git a/frontend/src/plugins/serverkit-analytics/index.jsx b/frontend/src/plugins/serverkit-analytics/index.jsxdeleted file mode 100644index 077ede6e..00000000--- a/frontend/src/plugins/serverkit-analytics/index.jsx+++ /dev/null@@ -1,10 +0,0 @@-// 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.jsondeleted file mode 100644index 30389e4e..00000000--- a/frontend/src/plugins/serverkit-analytics/plugin.json+++ /dev/null@@ -1,152 +0,0 @@-{- "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/styles/analytics.scss b/frontend/src/plugins/serverkit-analytics/styles/analytics.scssdeleted file mode 100644index 818fab99..00000000--- a/frontend/src/plugins/serverkit-analytics/styles/analytics.scss+++ /dev/null@@ -1,410 +0,0 @@-/* serverkit-analytics — isolated plugin styles.- Compiled in ISOLATION from the host: no SCSS $variables, no @import of host- partials. Colours come from the host theme via CSS custom properties- (var(--token, fallback)) plus neutral rgba(128,128,128,α) tints, so the- dashboard tracks light/dark automatically.-- Every in-page rule is namespaced under .analytics-page. The Modal /- ConfirmDialog primitives portal to <body> — OUTSIDE the .analytics-page- subtree — so the modal-content rules near the bottom of this file are- intentionally top-level (same idiom as the tramo extension). All of our- class names are `.analytics-*` prefixed, so the few top-level rules cannot- collide with the host or other plugins. */--.analytics-page {- display: flex;- flex-direction: column;- min-height: 0;-- &__body {- padding: 18px 24px 28px;- }-- /* ── Route-driven tab bar (replaces sidebar sub-menus) ── */- .analytics-tabs {- display: flex;- align-items: center;- gap: 4px;- padding: 0 24px;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.18));- overflow-x: auto;-- &__tab {- display: inline-flex;- align-items: center;- gap: 7px;- padding: 11px 14px;- font-size: 13.5px;- font-weight: 500;- color: var(--text-secondary, rgba(128, 128, 128, 0.9));- text-decoration: none;- border-bottom: 2px solid transparent;- white-space: nowrap;- transition: color 0.15s ease, border-color 0.15s ease;-- svg { opacity: 0.8; }-- &:hover { color: var(--text-primary, inherit); }-- &.is-active {- color: var(--accent-bright, #6366f1);- border-bottom-color: var(--accent-bright, #6366f1);- }- }- }-- /* Site picker in the topbar actions slot */- .analytics-site-select {- height: 32px;- max-width: 220px;- padding: 0 10px;- border-radius: 8px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.06));- color: inherit;- font-size: 13px;- cursor: pointer;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- }-- /* ── Tab body scaffolding ── */- .analytics-tabbody {- display: flex;- flex-direction: column;- gap: 16px;- }-- .analytics-toolbar {- display: flex;- align-items: center;- gap: 12px;- flex-wrap: wrap;-- &--between { justify-content: space-between; }-- &__hint {- font-size: 12.5px;- opacity: 0.65;- }- }-- .analytics-live {- display: inline-flex;- align-items: center;- gap: 6px;- margin-left: auto;- font-size: 12.5px;- font-weight: 500;- color: var(--green, #22c55e);-- &__dot {- color: var(--green, #22c55e);- animation: analytics-pulse 1.8s ease-in-out infinite;- }- }-- /* Range / minutes segmented control */- .analytics-range {- display: inline-flex;- gap: 2px;- padding: 3px;- border-radius: 9px;- background: rgba(128, 128, 128, 0.1);-- &__btn {- border: 0;- background: transparent;- color: var(--text-secondary, inherit);- font-size: 12.5px;- font-weight: 500;- padding: 5px 11px;- border-radius: 7px;- cursor: pointer;- transition: background 0.15s ease, color 0.15s ease;-- &:hover { color: var(--text-primary, inherit); }-- &.is-active {- background: var(--bg-card, rgba(128, 128, 128, 0.9));- color: var(--accent-bright, #6366f1);- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);- }- }- }-- /* ── KPI tiles ── */- .analytics-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));- gap: 12px;- }-- .analytics-kpi {- display: flex;- flex-direction: column;- gap: 6px;- padding: 16px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));-- &__icon {- width: 34px;- height: 34px;- border-radius: 9px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);- color: var(--accent-bright, #818cf8);-- &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }- &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }- &--amber { background: rgba(234, 179, 8, 0.16); color: #eab308; }- &--violet { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }- }-- &__val {- font-size: 24px;- font-weight: 700;- line-height: 1.1;- color: var(--text-primary, inherit);- }-- &__label {- font-size: 12.5px;- opacity: 0.65;- }- }-- /* ── Chart card ── */- .analytics-chart-card {- padding: 16px 16px 8px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));-- &__head {- font-size: 13px;- font-weight: 600;- margin-bottom: 12px;- opacity: 0.85;- }- }-- /* ── Grids of tables ── */- .analytics-grid {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 16px;-- &--devices {- grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));- }-- @media (max-width: 720px) {- grid-template-columns: 1fr;- }- }-- .analytics-panel {- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- overflow: hidden;-- &__head {- display: flex;- align-items: center;- gap: 7px;- padding: 12px 16px;- font-size: 13px;- font-weight: 600;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.12));- opacity: 0.9;-- svg { opacity: 0.7; }- }- }-- /* ── Realtime counters ── */- .analytics-realtime {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));- gap: 12px;-- &__stat {- display: flex;- flex-direction: column;- gap: 6px;- padding: 18px;- border-radius: 12px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.16));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- }-- &__icon {- width: 38px;- height: 38px;- border-radius: 10px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);-- &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }- &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }- }-- &__val {- font-size: 30px;- font-weight: 700;- line-height: 1;- color: var(--text-primary, inherit);- }-- &__label {- font-size: 12.5px;- opacity: 0.65;- }- }-- /* ── Sites table cells ── */- .analytics-site-name {- display: flex;- flex-direction: column;- gap: 2px;-- &__title { font-weight: 600; font-size: 13.5px; }- &__key { font-size: 11px; opacity: 0.55; }- }-- .analytics-row-actions {- display: flex;- gap: 6px;- justify-content: flex-end;- flex-wrap: wrap;- }-- .analytics-col-actions {- text-align: right;- white-space: nowrap;- }-- .analytics-col-grow {- min-width: 150px;- }-- /* In-page empty/dashed wrapper */- .analytics-empty {- border-radius: 12px;- border: 1px dashed var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- }-}--/* Shared monospace utility — used in-page (tables) AND inside the portaled- snippet modal, so it lives at top level to match both DOM locations. */-.analytics-cell-mono {- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12.5px;-}--@keyframes analytics-pulse {- 0%, 100% { opacity: 1; }- 50% { opacity: 0.35; }-}--@media (prefers-reduced-motion: reduce) {- .analytics-live__dot { animation: none; }-}--/* ── Portaled modal content (Modal / ConfirmDialog render into <body>, OUTSIDE- .analytics-page) — these MUST stay top-level or they never match. ── */-.analytics-form {- display: flex;- flex-direction: column;- gap: 14px;-- .form-group { margin: 0; }-- &__hint {- margin: 6px 0 0;- font-size: 12px;- line-height: 1.45;- opacity: 0.62;- }-}--.analytics-textarea {- width: 100%;- min-height: 78px;- resize: vertical;- padding: 10px 12px;- border-radius: 9px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.05));- color: inherit;- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 12.5px;- line-height: 1.5;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- &::placeholder { opacity: 0.4; }-}--.analytics-check {- display: flex;- align-items: center;- gap: 9px;- font-size: 13px;- cursor: pointer;-- input {- width: 15px;- height: 15px;- cursor: pointer;- accent-color: var(--accent-bright, #6366f1);- }-}--.analytics-snippet-wrap {- display: flex;- flex-direction: column;- gap: 12px;-}--.analytics-snippet {- margin: 0;- max-height: 260px;- overflow: auto;- padding: 14px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-elevated, rgba(128, 128, 128, 0.08));- color: var(--text-primary, inherit);- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12px;- line-height: 1.55;- white-space: pre-wrap;- word-break: break-all;-- code {- font: inherit;- color: inherit;- background: none;- }-- &__foot {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- }-- &__key {- opacity: 0.7;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-}diff --git a/frontend/src/plugins/serverkit-analytics/utils/format.js b/frontend/src/plugins/serverkit-analytics/utils/format.jsdeleted file mode 100644index 47bd7469..00000000--- a/frontend/src/plugins/serverkit-analytics/utils/format.js+++ /dev/null@@ -1,28 +0,0 @@-// Small, dependency-free formatting helpers for the analytics dashboard.-// Kept isolated (no host imports) so the plugin bundle stays self-contained.--export const formatInt = (n) => Number(n ?? 0).toLocaleString();--export const formatMs = (ms) => (ms == null ? '—' : `${Math.round(ms)} ms`);--export const formatPct = (n) => `${Number(n ?? 0).toFixed(1)}%`;--// A 'YYYY-MM-DD' rollup date → a short "Jul 18" label. Parsed as local midnight-// (append time) so the label never drifts a day across time zones.-export const formatDay = (iso) => {- if (!iso) return '';- const d = new Date(`${iso}T00:00:00`);- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleDateString([], { month: 'short', day: 'numeric' });-};--// An ISO timestamp → a wall-clock "14:03:21" label for the realtime feed.-export const formatClock = (iso) => {- if (!iso) return '—';- const d = new Date(iso);- if (Number.isNaN(d.getTime())) return '—';- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });-};--// Referrer/path dimension value → a readable label ("Direct / none" for empties).-export const labelOrDirect = (value) => (value && value.trim() ? value : 'Direct / none');diff --git a/frontend/src/plugins/serverkit-crowdsec/components/CrowdSecPage.jsx b/frontend/src/plugins/serverkit-crowdsec/components/CrowdSecPage.jsxdeleted file mode 100644index 3e0c9379..00000000--- a/frontend/src/plugins/serverkit-crowdsec/components/CrowdSecPage.jsx+++ /dev/null@@ -1,566 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { ShieldCheck, RefreshCw, Ban, ListChecks, Activity, Plus } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill, MetricCard } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--const DURATIONS = ['1h', '4h', '12h', '24h', '7d'];--const formatDate = (d) => (d ? new Date(d).toLocaleString() : '—');--// Best-effort: pull a headline number out of `cscli metrics -o json`, whose-// shape varies across CrowdSec versions. Null when nothing recognizable.-function parsedEventsTotal(metrics) {- try {- const acq = metrics?.acquisition;- if (!acq || typeof acq !== 'object') return null;- let total = 0;- for (const source of Object.values(acq)) {- const n = source?.parsed ?? source?.lines_parsed;- if (typeof n === 'number') total += n;- }- return total > 0 ? total : null;- } catch {- return null;- }-}--const CrowdSecPage = () => {- const toast = useToast();-- const [status, setStatus] = useState(null);- const [decisions, setDecisions] = useState([]);- const [alerts, setAlerts] = useState([]);- const [allowlists, setAllowlists] = useState({ supported: false, allowlists: [], message: null });- const [metrics, setMetrics] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Ban modal- const [showBanModal, setShowBanModal] = useState(false);- const [banForm, setBanForm] = useState({ ip: '', duration: '4h', reason: '' });-- // Allowlist manager- const [showListModal, setShowListModal] = useState(false);- const [listForm, setListForm] = useState({ name: '', description: '' });- const [selectedList, setSelectedList] = useState(null);- const [listItems, setListItems] = useState([]);- const [entryForm, setEntryForm] = useState({ value: '', comment: '' });-- const loadData = useCallback(async () => {- setLoading(true);- try {- const statusData = await api.request('/crowdsec/status');- setStatus(statusData);- if (statusData?.installed) {- const [d, a, al, m] = await Promise.all([- api.request('/crowdsec/decisions').catch(() => ({ decisions: [] })),- api.request('/crowdsec/alerts').catch(() => ({ alerts: [] })),- api.request('/crowdsec/allowlists').catch(() => ({ supported: false, allowlists: [] })),- api.request('/crowdsec/metrics').catch(() => null),- ]);- setDecisions(d.decisions || []);- setAlerts(a.alerts || []);- setAllowlists(al || { supported: false, allowlists: [] });- setMetrics(m?.metrics ?? null);- }- } catch (error) {- toast.error(`Failed to load CrowdSec data: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => {- loadData();- }, [loadData]);-- const handleBan = async () => {- if (!banForm.ip.trim()) return;- setActionLoading(true);- try {- await api.request('/crowdsec/decisions', {- method: 'POST',- body: {- ip: banForm.ip.trim(),- duration: banForm.duration,- reason: banForm.reason.trim() || undefined,- },- });- toast.success(`Decision added for ${banForm.ip}`);- setShowBanModal(false);- setBanForm({ ip: '', duration: '4h', reason: '' });- await loadData();- } catch (error) {- toast.error(`Failed to ban IP: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteDecision = (value) => {- setConfirmDialog({- title: 'Remove decision',- message: `Remove all active decisions for ${value}?`,- confirmText: 'Remove',- variant: 'warning',- onConfirm: async () => {- try {- await api.request(`/crowdsec/decisions/${encodeURIComponent(value)}`, { method: 'DELETE' });- toast.success(`Decisions removed for ${value}`);- await loadData();- } catch (error) {- toast.error(`Failed to remove decision: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleCreateList = async () => {- if (!listForm.name.trim()) return;- setActionLoading(true);- try {- await api.request('/crowdsec/allowlists', {- method: 'POST',- body: { name: listForm.name.trim(), description: listForm.description.trim() },- });- toast.success(`Allowlist ${listForm.name} created`);- setShowListModal(false);- setListForm({ name: '', description: '' });- await loadData();- } catch (error) {- toast.error(`Failed to create allowlist: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const openList = async (name) => {- setSelectedList(name);- setListItems([]);- try {- const res = await api.request(`/crowdsec/allowlists/${encodeURIComponent(name)}`);- setListItems(res?.allowlist?.items || []);- } catch (error) {- toast.error(`Failed to load allowlist: ${error.message}`);- }- };-- const handleAddEntry = async () => {- if (!selectedList || !entryForm.value.trim()) return;- setActionLoading(true);- try {- await api.request(`/crowdsec/allowlists/${encodeURIComponent(selectedList)}/items`, {- method: 'POST',- body: { value: entryForm.value.trim(), comment: entryForm.comment.trim() || undefined },- });- toast.success(`Added ${entryForm.value} to ${selectedList}`);- setEntryForm({ value: '', comment: '' });- await openList(selectedList);- } catch (error) {- toast.error(`Failed to add entry: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRemoveEntry = async (value) => {- try {- await api.request(- `/crowdsec/allowlists/${encodeURIComponent(selectedList)}/items?value=${encodeURIComponent(value)}`,- { method: 'DELETE' }- );- toast.success(`Removed ${value} from ${selectedList}`);- await openList(selectedList);- } catch (error) {- toast.error(`Failed to remove entry: ${error.message}`);- }- };-- if (loading) {- return (- <div className="page-container crowdsec-page">- <PageTopbar icon={<ShieldCheck size={18} />} title="CrowdSec" />- <EmptyState loading title="Loading CrowdSec status..." />- </div>- );- }-- // ── Not installed: guidance, never auto-install ──- if (!status?.installed) {- return (- <div className="page-container crowdsec-page">- <PageTopbar icon={<ShieldCheck size={18} />} title="CrowdSec" />- <div className="empty-state">- <ShieldCheck size={48} strokeWidth={1} />- <h3>CrowdSec Is Not Installed</h3>- <p>- CrowdSec is a collaborative security engine that detects attacks in your- logs and shares blocklists across its community. Install it on this host- and this page will surface its decisions, alerts, and allowlists.- </p>- <p>- ServerKit does not install it for you — follow the official guide, then- refresh this page.- </p>- <div className="cs-empty-actions">- <Button asChild variant="default">- <a href={status?.docs_url || 'https://docs.crowdsec.net/'} target="_blank" rel="noreferrer">- Installation Guide- </a>- </Button>- <Button variant="outline" onClick={loadData}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- );- }-- const parsedEvents = parsedEventsTotal(metrics);-- return (- <div className="page-container crowdsec-page">- <PageTopbar- icon={<ShieldCheck size={18} />}- title="CrowdSec"- actions={- <>- <Button variant="default" size="sm" onClick={() => setShowBanModal(true)}>- <Ban size={14} /> Ban an IP- </Button>- <Button variant="outline" size="sm" onClick={loadData}>- <RefreshCw size={14} /> Refresh- </Button>- </>- }- />-- {/* ── Status ── */}- <div className="card">- <div className="card-header">- <h3>Engine Status</h3>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Service</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Local API</span>- <Pill kind={status.lapi_ok ? 'green' : 'amber'}>- {status.lapi_ok ? 'Reachable' : 'Unreachable'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Version</span>- <span className="v">{status.version || 'Unknown'}</span>- </div>- <div className="sk-info-row">- <span className="k">Allowlists</span>- <span className="v">- {status.allowlists_supported- ? 'Supported'- : 'Not supported by this CrowdSec version'}- </span>- </div>- <div className="sk-info-row">- <span className="k">AppSec / WAF</span>- <span className="v">- In-line request filtering needs the CrowdSec AppSec component and a- bouncer on your reverse proxy — configured outside the panel.- </span>- </div>- </div>- </div>- </div>-- {/* ── Metric cards (best-effort) ── */}- <div className="cs-kpis">- <MetricCard icon={<Ban size={15} />} tone="red" value={decisions.length} label="Active decisions" />- <MetricCard icon={<Activity size={15} />} tone="amber" value={alerts.length} label="Recent alerts" />- <MetricCard- icon={<ListChecks size={15} />}- tone="green"- value={allowlists.supported ? (allowlists.allowlists || []).length : '—'}- label="Allowlists"- />- {parsedEvents != null && (- <MetricCard icon={<Activity size={15} />} tone="cyan" value={parsedEvents} label="Parsed log lines" />- )}- </div>-- {/* ── Decisions ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Decisions {decisions.length > 0 && <span className="sec-count">· {decisions.length}</span>}</h3>- </div>- {decisions.length === 0 ? (- <div className="card-body">- <p className="text-muted">No active decisions — nothing is currently banned.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Value</th>- <th>Scope</th>- <th>Type</th>- <th>Origin</th>- <th>Reason</th>- <th>Expires</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {decisions.map((d, i) => (- <tr key={d.id ?? i}>- <td className="sk-cell-mono">{d.value}</td>- <td><span className="sk-tag">{d.scope || '—'}</span></td>- <td>{d.type || '—'}</td>- <td>{d.origin || '—'}</td>- <td>{d.reason || '—'}</td>- <td>{d.until ? formatDate(d.until) : (d.duration || '—')}</td>- <td>- <Button variant="secondary" size="sm" onClick={() => handleDeleteDecision(d.value)}>- Delete- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Alerts ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Alerts {alerts.length > 0 && <span className="sec-count">· {alerts.length}</span>}</h3>- </div>- {alerts.length === 0 ? (- <div className="card-body">- <p className="text-muted">No recent alerts.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Scenario</th>- <th>Source</th>- <th>Country</th>- <th>Events</th>- <th>Decisions</th>- <th>Created</th>- </tr>- </thead>- <tbody>- {alerts.map((a, i) => (- <tr key={a.id ?? i}>- <td>{a.scenario || '—'}</td>- <td className="sk-cell-mono">{a.source || '—'}</td>- <td>{a.country || '—'}</td>- <td>{a.events_count ?? '—'}</td>- <td>{a.decisions ?? '—'}</td>- <td>{formatDate(a.created_at)}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Allowlists ── */}- <div className="card">- <div className="card-header">- <h3>Allowlists</h3>- {allowlists.supported && (- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowListModal(true)}>- <Plus size={14} /> New Allowlist- </Button>- </div>- )}- </div>- <div className="card-body">- {!allowlists.supported ? (- <p className="text-muted">- {allowlists.message- || 'The installed CrowdSec version does not support centralized allowlists. Upgrade CrowdSec to manage allowlists from the panel.'}- </p>- ) : (allowlists.allowlists || []).length === 0 ? (- <p className="text-muted">No allowlists yet. Create one to exempt trusted IPs from remediation.</p>- ) : (- <div className="cs-allowlists">- <div className="cs-allowlists__names">- {(allowlists.allowlists || []).map((l, i) => (- <button- key={l.name ?? i}- type="button"- className={`cs-allowlists__name${selectedList === l.name ? ' is-active' : ''}`}- onClick={() => openList(l.name)}- >- <span className="sk-tag">{l.name}</span>- {l.description && <span className="text-muted"> {l.description}</span>}- </button>- ))}- </div>- {selectedList && (- <div className="cs-allowlists__detail">- <h4>{selectedList}</h4>- {listItems.length === 0 ? (- <p className="text-muted">No entries in this allowlist.</p>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Value</th>- <th>Comment</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {listItems.map((it, i) => {- const value = typeof it === 'string' ? it : it.value;- return (- <tr key={value ?? i}>- <td className="sk-cell-mono">{value}</td>- <td>{(typeof it === 'object' && (it.description || it.comment)) || '—'}</td>- <td>- <Button variant="secondary" size="sm" onClick={() => handleRemoveEntry(value)}>- Remove- </Button>- </td>- </tr>- );- })}- </tbody>- </table>- )}- <div className="cs-entry-form">- <Input- type="text"- value={entryForm.value}- onChange={(e) => setEntryForm((f) => ({ ...f, value: e.target.value }))}- placeholder="IP or CIDR, e.g. 203.0.113.7 or 10.0.0.0/8"- />- <Input- type="text"- value={entryForm.comment}- onChange={(e) => setEntryForm((f) => ({ ...f, comment: e.target.value }))}- placeholder="Comment (optional)"- />- <Button- variant="default"- size="sm"- onClick={handleAddEntry}- disabled={actionLoading || !entryForm.value.trim()}- >- Add Entry- </Button>- </div>- </div>- )}- </div>- )}- </div>- </div>-- {/* ── Ban modal ── */}- <Modal open={showBanModal} onClose={() => setShowBanModal(false)} title="Ban an IP">- <div className="form-group">- <Label>IP address or CIDR range</Label>- <Input- type="text"- value={banForm.ip}- onChange={(e) => setBanForm((f) => ({ ...f, ip: e.target.value }))}- placeholder="203.0.113.7 or 203.0.113.0/24"- />- </div>- <div className="form-group">- <Label>Duration</Label>- <Select value={banForm.duration} onValueChange={(v) => setBanForm((f) => ({ ...f, duration: v }))}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {DURATIONS.map((d) => (- <SelectItem key={d} value={d}>{d}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="form-group">- <Label>Reason</Label>- <Input- type="text"- value={banForm.reason}- onChange={(e) => setBanForm((f) => ({ ...f, reason: e.target.value }))}- placeholder="Manual ban from ServerKit"- />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowBanModal(false)}>Cancel</Button>- <Button variant="destructive" onClick={handleBan} disabled={actionLoading || !banForm.ip.trim()}>- {actionLoading ? 'Banning...' : 'Ban IP'}- </Button>- </div>- </Modal>-- {/* ── New allowlist modal ── */}- <Modal open={showListModal} onClose={() => setShowListModal(false)} title="New Allowlist">- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={listForm.name}- onChange={(e) => setListForm((f) => ({ ...f, name: e.target.value }))}- placeholder="trusted-ips"- />- </div>- <div className="form-group">- <Label>Description</Label>- <Input- type="text"- value={listForm.description}- onChange={(e) => setListForm((f) => ({ ...f, description: e.target.value }))}- placeholder="Office and monitoring IPs"- />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowListModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreateList} disabled={actionLoading || !listForm.name.trim()}>- {actionLoading ? 'Creating...' : 'Create'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default CrowdSecPage;diff --git a/frontend/src/plugins/serverkit-crowdsec/index.jsx b/frontend/src/plugins/serverkit-crowdsec/index.jsxdeleted file mode 100644index 09905699..00000000--- a/frontend/src/plugins/serverkit-crowdsec/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// CrowdSec integration UI, contributed through the extension system. Unlike the-// re-export builtins (ftp/status/email…), this page is fully self-contained in-// the extension — no core page to wrap. After sync this folder lives at-// frontend/src/plugins/serverkit-crowdsec/, so '@/…' host aliases resolve.-export { default as CrowdSecPage } from './components/CrowdSecPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/frontend/src/plugins/serverkit-crowdsec/plugin.json b/frontend/src/plugins/serverkit-crowdsec/plugin.jsondeleted file mode 100644index b3903946..00000000--- a/frontend/src/plugins/serverkit-crowdsec/plugin.json+++ /dev/null@@ -1,45 +0,0 @@-{- "name": "serverkit-crowdsec",- "display_name": "CrowdSec",- "version": "1.0.0",- "description": "CrowdSec security engine integration. Surface active decisions and alerts, ban/unban IPs, and manage allowlists straight from the panel. Read/write via cscli on the host; shows install guidance when CrowdSec is absent (never auto-installs).",- "author": "ServerKit",- "license": "MIT",- "category": "security",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell"- ],- "min_panel_version": "1.7.0",- "entry_point": "crowdsec:crowdsec_bp",- "url_prefix": "/api/v1/crowdsec",- "icon": "<path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\"/><path d=\"m9 12 2 2 4-4\"/>",- "contributions": {- "nav": [- {- "id": "crowdsec",- "label": "CrowdSec",- "route": "/crowdsec",- "category": "operations",- "icon": "<path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\"/><path d=\"m9 12 2 2 4-4\"/>"- }- ],- "routes": [- {- "path": "crowdsec",- "component": "CrowdSecPage"- }- ],- "page_titles": {- "/crowdsec": "CrowdSec"- },- "command_palette": [- {- "label": "CrowdSec",- "path": "/crowdsec",- "category": "Pages",- "keywords": "crowdsec decisions alerts bans ips allowlist security waf appsec"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-crowdsec/styles/crowdsec.css b/frontend/src/plugins/serverkit-crowdsec/styles/crowdsec.cssdeleted file mode 100644index 0d110e6c..00000000--- a/frontend/src/plugins/serverkit-crowdsec/styles/crowdsec.css+++ /dev/null@@ -1,53 +0,0 @@-/* CrowdSec extension — layout-only styles; colors/typography inherit from the- host design system (card, sk-dtable, sk-info-row, sk-kpi, empty-state…). */--.crowdsec-page .cs-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));- gap: 12px;- margin: 12px 0;-}--.crowdsec-page .cs-empty-actions {- display: flex;- gap: 8px;- justify-content: center;- margin-top: 12px;-}--.crowdsec-page .cs-allowlists {- display: flex;- flex-direction: column;- gap: 12px;-}--.crowdsec-page .cs-allowlists__names {- display: flex;- flex-wrap: wrap;- gap: 8px;-}--.crowdsec-page .cs-allowlists__name {- background: none;- border: none;- padding: 2px 4px;- cursor: pointer;- text-align: left;- border-radius: 6px;-}--.crowdsec-page .cs-allowlists__name.is-active {- outline: 1px solid currentColor;- outline-offset: 2px;-}--.crowdsec-page .cs-entry-form {- display: flex;- gap: 8px;- margin-top: 12px;- align-items: center;-}--.crowdsec-page .cs-entry-form input {- max-width: 320px;-}diff --git a/frontend/src/plugins/serverkit-dns-server/components/DnsServerPage.jsx b/frontend/src/plugins/serverkit-dns-server/components/DnsServerPage.jsxdeleted file mode 100644index ef0a4caa..00000000--- a/frontend/src/plugins/serverkit-dns-server/components/DnsServerPage.jsx+++ /dev/null@@ -1,381 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { Globe, RefreshCw, Plus, Trash2, Server } from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';-import ZoneDetail from './ZoneDetail.jsx';--const DnsServerPage = () => {- const toast = useToast();-- const [status, setStatus] = useState(null);- const [zones, setZones] = useState([]);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);- const [selectedZone, setSelectedZone] = useState(null);-- // Install form- const [installForm, setInstallForm] = useState({ ns_hostname: '', admin_email: '' });-- // New zone modal- const [showZoneModal, setShowZoneModal] = useState(false);- const [zoneName, setZoneName] = useState('');-- const loadData = useCallback(async () => {- setLoading(true);- try {- const statusData = await api.request('/dns-server/status');- setStatus(statusData);- if (statusData?.installed) {- const z = await api.request('/dns-server/zones').catch(() => ({ zones: [] }));- setZones(z.zones || []);- }- } catch (error) {- toast.error(`Failed to load DNS server status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => {- loadData();- }, [loadData]);-- const handleInstall = async () => {- if (!installForm.ns_hostname.trim() || !installForm.admin_email.trim()) return;- setActionLoading(true);- try {- await api.request('/dns-server/install', {- method: 'POST',- body: {- ns_hostname: installForm.ns_hostname.trim(),- admin_email: installForm.admin_email.trim(),- },- });- toast.success('PowerDNS authoritative server installed');- await loadData();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove DNS server',- message: keepData- ? 'Remove the PowerDNS container? Zone data stays on disk and a reinstall picks it back up.'- : 'Remove the PowerDNS container AND delete all zone data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/dns-server/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('DNS server removed');- setSelectedZone(null);- await loadData();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleCreateZone = async () => {- if (!zoneName.trim()) return;- setActionLoading(true);- try {- await api.request('/dns-server/zones', {- method: 'POST',- body: { name: zoneName.trim() },- });- toast.success(`Zone ${zoneName} created`);- setShowZoneModal(false);- setZoneName('');- await loadData();- } catch (error) {- toast.error(`Failed to create zone: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteZone = (name) => {- setConfirmDialog({- title: 'Delete zone',- message: `Delete zone ${name} and all of its records?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/dns-server/zones/${encodeURIComponent(name)}`, { method: 'DELETE' });- toast.success(`Zone ${name} deleted`);- if (selectedZone === name) setSelectedZone(null);- await loadData();- } catch (error) {- toast.error(`Failed to delete zone: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- if (loading) {- return (- <div className="page-container dns-server-page">- <PageTopbar icon={<Globe size={18} />} title="DNS Server" />- <EmptyState loading title="Loading DNS server status..." />- </div>- );- }-- // ── Not installed: explainer + install form ──- if (!status?.installed) {- return (- <div className="page-container dns-server-page">- <PageTopbar icon={<Globe size={18} />} title="DNS Server" />- <div className="card">- <div className="card-header">- <h3>Host Your Own Nameserver</h3>- </div>- <div className="card-body">- <p>- Run PowerDNS (authoritative, SQLite backend) in a managed Docker- container so this box answers DNS for your domains directly —- handy for homelabs and air-gapped networks where a hosted DNS- provider is not an option.- </p>- <ul className="dns-explainer">- <li>- <strong>Authoritative only.</strong> This serves the zones you- create; it never resolves other names for clients. Keep using- your normal resolver.- </li>- <li>- <strong>Port 53 must be free</strong> on this host (tcp + udp).- systemd-resolved or another DNS service will conflict.- </li>- <li>- <strong>Delegation happens at your registrar.</strong> Point the- domain's NS (and glue) records at this box's nameserver- hostname so the world finds it.- </li>- <li>- This complements provider integrations (Cloudflare etc.) — it- does not replace them.- </li>- </ul>- <div className="dns-install-form">- <div className="form-group">- <Label>Nameserver hostname</Label>- <Input- type="text"- value={installForm.ns_hostname}- onChange={(e) => setInstallForm((f) => ({ ...f, ns_hostname: e.target.value }))}- placeholder="ns1.example.com"- />- <p className="text-muted">- The hostname other resolvers will use to reach this server.- It should resolve (via glue records) to this box's public IP.- </p>- </div>- <div className="form-group">- <Label>Hostmaster email</Label>- <Input- type="email"- value={installForm.admin_email}- onChange={(e) => setInstallForm((f) => ({ ...f, admin_email: e.target.value }))}- placeholder="[email protected]"- />- <p className="text-muted">Used in each zone's SOA record.</p>- </div>- <div className="dns-install-actions">- <Button- variant="default"- onClick={handleInstall}- disabled={actionLoading || !installForm.ns_hostname.trim() || !installForm.admin_email.trim()}- >- {actionLoading ? 'Installing...' : 'Install DNS Server'}- </Button>- <Button variant="outline" onClick={loadData}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- </div>- </div>- );- }-- return (- <div className="page-container dns-server-page">- <PageTopbar- icon={<Globe size={18} />}- title="DNS Server"- actions={- <>- <Button variant="default" size="sm" onClick={() => setShowZoneModal(true)}>- <Plus size={14} /> New Zone- </Button>- <Button variant="outline" size="sm" onClick={loadData}>- <RefreshCw size={14} /> Refresh- </Button>- </>- }- />-- {/* ── Status ── */}- <div className="card">- <div className="card-header">- <h3>Server Status</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)}>- <Trash2 size={14} /> Remove + data- </Button>- </div>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Container</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Engine</span>- <span className="v">- PowerDNS Authoritative {status.version ? `v${status.version}` : '(version unavailable)'}- </span>- </div>- <div className="sk-info-row">- <span className="k">Nameserver</span>- <span className="v sk-cell-mono">{status.ns_hostname || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Mode</span>- <span className="v">Authoritative only — no recursion, by design.</span>- </div>- </div>- </div>- </div>-- {/* ── Zones ── */}- <div className="card sec-flush">- <div className="card-header">- <h3>Zones {zones.length > 0 && <span className="sec-count">· {zones.length}</span>}</h3>- </div>- {zones.length === 0 ? (- <div className="card-body">- <p className="text-muted">- No zones yet. Create one, then point the domain's nameservers here- at your registrar.- </p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Zone</th>- <th>Kind</th>- <th>Serial</th>- <th>DNSSEC</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {zones.map((z) => (- <tr key={z.name}>- <td className="sk-cell-mono">- <button- type="button"- className="dns-zone-link"- onClick={() => setSelectedZone(z.name)}- >- {z.name}- </button>- </td>- <td>{z.kind || '—'}</td>- <td>{z.serial ?? '—'}</td>- <td>- <Pill kind={z.dnssec ? 'green' : 'gray'}>- {z.dnssec ? 'Signed' : 'Off'}- </Pill>- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => setSelectedZone(z.name)}>- <Server size={14} /> Manage- </Button>{' '}- <Button variant="secondary" size="sm" onClick={() => handleDeleteZone(z.name)}>- Delete- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>-- {/* ── Zone detail ── */}- {selectedZone && (- <ZoneDetail- zoneName={selectedZone}- onClose={() => setSelectedZone(null)}- onChanged={loadData}- />- )}-- {/* ── New zone modal ── */}- <Modal open={showZoneModal} onClose={() => setShowZoneModal(false)} title="New Zone">- <div className="form-group">- <Label>Zone name</Label>- <Input- type="text"- value={zoneName}- onChange={(e) => setZoneName(e.target.value)}- placeholder="example.com"- />- <p className="text-muted">- SOA and NS records are bootstrapped from the nameserver hostname and- hostmaster email you provided at install.- </p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowZoneModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreateZone} disabled={actionLoading || !zoneName.trim()}>- {actionLoading ? 'Creating...' : 'Create Zone'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default DnsServerPage;diff --git a/frontend/src/plugins/serverkit-dns-server/components/ZoneDetail.jsx b/frontend/src/plugins/serverkit-dns-server/components/ZoneDetail.jsxdeleted file mode 100644index 4d9a1fb3..00000000--- a/frontend/src/plugins/serverkit-dns-server/components/ZoneDetail.jsx+++ /dev/null@@ -1,333 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { RefreshCw, Plus, ShieldCheck, X } from 'lucide-react';-import api from '@/services/api';-import { Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import { useToast } from '@/contexts/ToastContext';--const RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'CAA', 'PTR'];-const EMPTY_FORM = { name: '', type: 'A', ttl: 3600, records: '' };--const ZoneDetail = ({ zoneName, onClose, onChanged }) => {- const toast = useToast();-- const [zone, setZone] = useState(null);- const [dsRecords, setDsRecords] = useState([]);- const [delegation, setDelegation] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Record editor modal (add or edit — edit pre-fills, save is an upsert)- const [showRecordModal, setShowRecordModal] = useState(false);- const [recordForm, setRecordForm] = useState(EMPTY_FORM);-- const loadZone = useCallback(async () => {- setLoading(true);- try {- const data = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}`);- setZone(data.zone || null);- setDsRecords(data.ds_records || []);- setDelegation(data.delegation || null);- } catch (error) {- toast.error(`Failed to load zone: ${error.message}`);- } finally {- setLoading(false);- }- }, [zoneName, toast]);-- useEffect(() => {- loadZone();- }, [loadZone]);-- const openAdd = () => {- setRecordForm(EMPTY_FORM);- setShowRecordModal(true);- };-- const openEdit = (rrset) => {- setRecordForm({- name: rrset.name,- type: rrset.type,- ttl: rrset.ttl ?? 3600,- records: (rrset.records || []).join('\n'),- });- setShowRecordModal(true);- };-- const handleSaveRecord = async () => {- const values = recordForm.records.split('\n').map((v) => v.trim()).filter(Boolean);- if (!values.length) return;- setActionLoading(true);- try {- await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets`, {- method: 'POST',- body: {- name: recordForm.name.trim(),- type: recordForm.type,- ttl: Number(recordForm.ttl) || 3600,- records: values,- },- });- toast.success(`${recordForm.type} record set saved`);- setShowRecordModal(false);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`Failed to save record set: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteRecord = (rrset) => {- setConfirmDialog({- title: 'Delete record set',- message: `Delete the ${rrset.type} record set for ${rrset.name}?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- const qs = `name=${encodeURIComponent(rrset.name)}&type=${encodeURIComponent(rrset.type)}`;- await api.request(- `/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets?${qs}`,- { method: 'DELETE' }- );- toast.success(`${rrset.type} record set deleted`);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`Failed to delete record set: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleDnssec = async (enable) => {- setActionLoading(true);- try {- const res = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/dnssec`, {- method: 'POST',- body: { action: enable ? 'enable' : 'disable' },- });- toast.success(res.message || `DNSSEC ${enable ? 'enabled' : 'disabled'}`);- await loadZone();- onChanged?.();- } catch (error) {- toast.error(`DNSSEC update failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- return (- <div className="card dns-zone-detail">- <div className="card-header">- <h3 className="sk-cell-mono">{zoneName}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={openAdd}>- <Plus size={14} /> Add Record- </Button>- <Button variant="outline" size="sm" onClick={loadZone}>- <RefreshCw size={14} /> Refresh- </Button>- <Button variant="secondary" size="sm" onClick={onClose}>- <X size={14} /> Close- </Button>- </div>- </div>- <div className="card-body">- {loading ? (- <p className="text-muted">Loading zone...</p>- ) : !zone ? (- <p className="text-muted">Zone could not be loaded.</p>- ) : (- <>- {/* ── Delegation banner ── */}- {delegation && (- <div- className={`dns-delegation dns-delegation--${- delegation.checked === false ? 'unknown' : delegation.delegated ? 'ok' : 'warn'- }`}- >- {delegation.checked === false ? (- <span>Delegation check unavailable: {delegation.note}</span>- ) : delegation.delegated ? (- <span>- Delegation looks correct — the public NS set matches this- zone ({(delegation.public_ns || []).join(', ')}).- </span>- ) : (- <span>- {delegation.note}{' '}- {delegation.public_ns?.length > 0 && (- <>Public: {delegation.public_ns.join(', ')} · Zone:{' '}- {(delegation.zone_ns || []).join(', ') || 'none'}</>- )}- </span>- )}- </div>- )}-- {/* ── Records ── */}- <table className="sk-dtable">- <thead>- <tr>- <th>Name</th>- <th>Type</th>- <th>TTL</th>- <th>Values</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {(zone.rrsets || []).map((r) => (- <tr key={`${r.name}|${r.type}`}>- <td className="sk-cell-mono">{r.name}</td>- <td><span className="sk-tag">{r.type}</span></td>- <td>{r.ttl ?? '—'}</td>- <td className="sk-cell-mono dns-values">- {(r.records || []).map((v) => <div key={v}>{v}</div>)}- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => openEdit(r)}>- Edit- </Button>{' '}- {r.type !== 'SOA' && (- <Button variant="secondary" size="sm" onClick={() => handleDeleteRecord(r)}>- Delete- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>-- {/* ── DNSSEC ── */}- <div className="dns-dnssec">- <div className="dns-dnssec__head">- <h4><ShieldCheck size={16} /> DNSSEC</h4>- <Pill kind={zone.dnssec ? 'green' : 'gray'}>- {zone.dnssec ? 'Enabled' : 'Disabled'}- </Pill>- <Button- variant={zone.dnssec ? 'secondary' : 'default'}- size="sm"- disabled={actionLoading}- onClick={() => handleDnssec(!zone.dnssec)}- >- {zone.dnssec ? 'Disable' : 'Enable'}- </Button>- </div>- {zone.dnssec && (- dsRecords.length > 0 ? (- <div className="dns-ds">- <p className="text-muted">- Publish these DS records at your registrar (the parent- zone) to complete the chain of trust:- </p>- {dsRecords.map((ds) => (- <code key={ds} className="dns-ds__record">{ds}</code>- ))}- </div>- ) : (- <p className="text-muted">- DNSSEC is enabled but no DS records were returned yet —- refresh in a moment.- </p>- )- )}- </div>- </>- )}- </div>-- {/* ── Record editor ── */}- <Modal- open={showRecordModal}- onClose={() => setShowRecordModal(false)}- title={`${recordForm.name ? 'Edit' : 'Add'} Record Set`}- >- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={recordForm.name}- onChange={(e) => setRecordForm((f) => ({ ...f, name: e.target.value }))}- placeholder={`@ or www (relative to ${zoneName})`}- />- </div>- <div className="form-group">- <Label>Type</Label>- <Select- value={recordForm.type}- onValueChange={(v) => setRecordForm((f) => ({ ...f, type: v }))}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {RECORD_TYPES.map((t) => (- <SelectItem key={t} value={t}>{t}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="form-group">- <Label>TTL (seconds)</Label>- <Input- type="number"- min={1}- max={604800}- value={recordForm.ttl}- onChange={(e) => setRecordForm((f) => ({ ...f, ttl: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Values (one per line)</Label>- <textarea- className="dns-record-values"- rows={4}- value={recordForm.records}- onChange={(e) => setRecordForm((f) => ({ ...f, records: e.target.value }))}- placeholder={'203.0.113.7\n203.0.113.8'}- />- <p className="text-muted">- Saving replaces the whole record set for this name + type.- </p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowRecordModal(false)}>Cancel</Button>- <Button- variant="default"- onClick={handleSaveRecord}- disabled={actionLoading || !recordForm.records.trim()}- >- {actionLoading ? 'Saving...' : 'Save Record Set'}- </Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default ZoneDetail;diff --git a/frontend/src/plugins/serverkit-dns-server/index.jsx b/frontend/src/plugins/serverkit-dns-server/index.jsxdeleted file mode 100644index 8e9bc6b1..00000000--- a/frontend/src/plugins/serverkit-dns-server/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// Authoritative DNS hosting UI, contributed through the extension system.-// Fully self-contained in the extension — no core page to wrap. After sync-// this folder lives at frontend/src/plugins/serverkit-dns-server/, so '@/…'-// host aliases resolve.-export { default as DnsServerPage } from './components/DnsServerPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/frontend/src/plugins/serverkit-dns-server/plugin.json b/frontend/src/plugins/serverkit-dns-server/plugin.jsondeleted file mode 100644index 7d9efe65..00000000--- a/frontend/src/plugins/serverkit-dns-server/plugin.json+++ /dev/null@@ -1,46 +0,0 @@-{- "name": "serverkit-dns-server",- "display_name": "DNS Server",- "version": "1.0.0",- "description": "Host authoritative DNS on this box with PowerDNS (SQLite backend) in a managed Docker container, covering zones, records, DNSSEC, and delegation checks from the panel. Authoritative only (no recursion); complements provider integrations like Cloudflare, never replaces them. Built for homelab and air-gapped setups.",- "author": "ServerKit",- "license": "MIT",- "category": "networking",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell",- "docker"- ],- "min_panel_version": "1.7.0",- "entry_point": "dns_server:dns_server_bp",- "url_prefix": "/api/v1/dns-server",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>",- "contributions": {- "nav": [- {- "id": "dns-server",- "label": "DNS Server",- "route": "/dns-server",- "category": "operations",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>"- }- ],- "routes": [- {- "path": "dns-server",- "component": "DnsServerPage"- }- ],- "page_titles": {- "/dns-server": "DNS Server"- },- "command_palette": [- {- "label": "DNS Server",- "path": "/dns-server",- "category": "Pages",- "keywords": "dns server powerdns authoritative nameserver zones records dnssec delegation hosting"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-dns-server/styles/dns-server.css b/frontend/src/plugins/serverkit-dns-server/styles/dns-server.cssdeleted file mode 100644index 738c42fa..00000000--- a/frontend/src/plugins/serverkit-dns-server/styles/dns-server.css+++ /dev/null@@ -1,92 +0,0 @@-/* DNS Server extension — layout-only styles; colors/typography inherit from- the host design system (card, sk-dtable, sk-info-row, empty-state…). */--.dns-server-page .dns-explainer {- margin: 12px 0;- padding-left: 20px;- display: flex;- flex-direction: column;- gap: 6px;-}--.dns-server-page .dns-install-form {- max-width: 480px;- margin-top: 16px;-}--.dns-server-page .dns-install-actions {- display: flex;- gap: 8px;- margin-top: 12px;-}--.dns-server-page .dns-zone-link {- background: none;- border: none;- padding: 0;- cursor: pointer;- font: inherit;- color: inherit;- text-decoration: underline;-}--.dns-server-page .dns-delegation {- border-radius: 8px;- padding: 10px 12px;- margin-bottom: 12px;- border: 1px solid currentColor;-}--.dns-server-page .dns-delegation--ok { opacity: 0.9; }-.dns-server-page .dns-delegation--warn { font-weight: 500; }-.dns-server-page .dns-delegation--unknown { opacity: 0.7; }--.dns-server-page .dns-values div {- line-height: 1.5;- word-break: break-all;-}--.dns-server-page .dns-dnssec {- margin-top: 16px;- padding-top: 12px;- border-top: 1px solid rgba(128, 128, 128, 0.25);-}--.dns-server-page .dns-dnssec__head {- display: flex;- align-items: center;- gap: 10px;-}--.dns-server-page .dns-dnssec__head h4 {- display: flex;- align-items: center;- gap: 6px;- margin: 0;-}--.dns-server-page .dns-ds {- margin-top: 10px;- display: flex;- flex-direction: column;- gap: 6px;-}--.dns-server-page .dns-ds__record {- display: block;- padding: 6px 8px;- border-radius: 6px;- word-break: break-all;- background: rgba(128, 128, 128, 0.12);-}--.dns-server-page .dns-record-values {- width: 100%;- font-family: inherit;- border-radius: 6px;- padding: 8px;- resize: vertical;- background: transparent;- color: inherit;- border: 1px solid rgba(128, 128, 128, 0.35);-}diff --git a/frontend/src/plugins/serverkit-gpu/components/GpuMonitor.jsx b/frontend/src/plugins/serverkit-gpu/components/GpuMonitor.jsxdeleted file mode 100644index 1dca0948..00000000--- a/frontend/src/plugins/serverkit-gpu/components/GpuMonitor.jsx+++ /dev/null@@ -1,202 +0,0 @@-// GPU Monitor page — the serverkit-gpu extension's UI, moved out of core as the-// first CORE_SLIM slice (plan 32 #7). Imports come from the SDK (PageTopbar,-// KpiBand, api, useToast); EmptyState + Button are host components not yet on the-// SDK surface, so they resolve via the `@/` alias (fine for the baked path — a-// future runtime-ESM build would bundle them or promote them into the SDK).-import { useState, useEffect, useCallback } from 'react';-import { Cpu, RefreshCw, Thermometer, Zap, Fan } from 'lucide-react';-import { PageTopbar, KpiBand, api, useToast } from 'serverkit-sdk';-import EmptyState from '@/components/EmptyState';-import { Button } from '@/components/ui/button';--function clampPercent(value) {- const n = Number(value);- if (!Number.isFinite(n)) return 0;- return Math.min(100, Math.max(0, n));-}--function utilTone(percent) {- if (percent >= 85) return 'is-red';- if (percent >= 60) return 'is-amber';- return 'is-green';-}--function formatMib(value) {- const n = Number(value);- if (!Number.isFinite(n)) return '—';- if (n >= 1024) return `${(n / 1024).toFixed(1)} GiB`;- return `${Math.round(n)} MiB`;-}--const GpuCard = ({ gpu }) => {- const util = clampPercent(gpu.utilization_gpu);- const memPercent = clampPercent(- gpu.memory_percent != null- ? gpu.memory_percent- : (gpu.memory_total ? (gpu.memory_used / gpu.memory_total) * 100 : 0)- );-- return (- <div className="gpu-card">- <div className="gpu-card__head">- <div className="gpu-card__title">- <Cpu size={16} />- <span className="gpu-card__name">{gpu.name || `GPU ${gpu.index}`}</span>- </div>- <span className="gpu-card__index">#{gpu.index}</span>- </div>-- <div className="gpu-card__bars">- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">GPU Utilization</span>- <span className="gpu-bar__value">{util}%</span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(util)}`} style={{ width: `${util}%` }} />- </div>- </div>-- <div className="gpu-bar">- <div className="gpu-bar__head">- <span className="gpu-bar__label">VRAM</span>- <span className="gpu-bar__value">- {formatMib(gpu.memory_used)} / {formatMib(gpu.memory_total)} ({Math.round(memPercent)}%)- </span>- </div>- <div className="gpu-bar__track">- <div className={`gpu-bar__fill ${utilTone(memPercent)}`} style={{ width: `${memPercent}%` }} />- </div>- </div>- </div>-- <div className="gpu-stats">- <div className="gpu-stat">- <Thermometer size={14} />- <span className="gpu-stat__label">Temp</span>- <span className="gpu-stat__value">- {gpu.temperature != null ? `${gpu.temperature}°C` : '—'}- </span>- </div>- <div className="gpu-stat">- <Zap size={14} />- <span className="gpu-stat__label">Power</span>- <span className="gpu-stat__value">- {gpu.power_draw != null ? `${Math.round(gpu.power_draw)}W` : '—'}- {gpu.power_limit != null && (- <span className="gpu-stat__sub"> / {Math.round(gpu.power_limit)}W</span>- )}- </span>- </div>- <div className="gpu-stat">- <Fan size={14} />- <span className="gpu-stat__label">Fan</span>- <span className="gpu-stat__value">- {gpu.fan_speed != null ? `${gpu.fan_speed}%` : '—'}- </span>- </div>- <div className="gpu-stat">- <Cpu size={14} />- <span className="gpu-stat__label">Driver</span>- <span className="gpu-stat__value">{gpu.driver_version || '—'}</span>- </div>- </div>- </div>- );-};--const GpuMonitor = () => {- const toast = useToast();- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);-- const load = useCallback(async (isRefresh = false) => {- if (isRefresh) setRefreshing(true);- try {- const result = await api.getGpuInfo();- setData(result);- } catch (err) {- if (isRefresh) toast.error(err.message || 'Failed to load GPU info');- console.error('Failed to load GPU info:', err);- } finally {- setLoading(false);- setRefreshing(false);- }- }, [toast]);-- useEffect(() => { load(); }, [load]);-- const gpus = data?.gpus || [];- const processes = data?.processes || [];-- return (- <div className="page-container gpu-page">- <PageTopbar- icon={<Cpu size={18} />}- title="GPU Monitor"- meta={data?.available ? `${gpus.length} GPU${gpus.length !== 1 ? 's' : ''}` : undefined}- actions={- <Button variant="outline" size="sm" onClick={() => load(true)} disabled={refreshing}>- <RefreshCw size={15} />- {refreshing ? 'Refreshing…' : 'Refresh'}- </Button>- }- />-- {loading ? (- <EmptyState loading title="Loading GPU data" />- ) : !data?.available ? (- <EmptyState- icon={Cpu}- size="lg"- title="No NVIDIA GPU detected"- description="This host has no NVIDIA GPU, or the NVIDIA drivers / nvidia-smi are not available."- />- ) : (- <>- {/* Custom live-meter tiles kept per Plan 20 Decision 5 — band supplies grid/spacing only */}- <KpiBand max={5}>- {gpus.map((gpu) => (- <GpuCard key={gpu.index} gpu={gpu} />- ))}- </KpiBand>-- <div className="gpu-procs">- <div className="gpu-procs__head">- <h2>GPU Processes</h2>- <span className="text-muted">{processes.length} running</span>- </div>- <table className="sk-dtable gpu-procs__table">- <thead>- <tr>- <th>PID</th>- <th>Process</th>- <th>Container</th>- <th>VRAM</th>- </tr>- </thead>- <tbody>- {processes.map((proc, i) => (- <tr key={`${proc.pid}-${i}`}>- <td className="sk-cell-mono">{proc.pid}</td>- <td>{proc.process_name || '—'}</td>- <td>{proc.container || '—'}</td>- <td className="sk-cell-mono">{formatMib(proc.used_memory)}</td>- </tr>- ))}- {processes.length === 0 && (- <tr>- <td colSpan={4} className="text-center text-muted">No active GPU processes</td>- </tr>- )}- </tbody>- </table>- </div>- </>- )}- </div>- );-};--export default GpuMonitor;diff --git a/frontend/src/plugins/serverkit-gpu/index.jsx b/frontend/src/plugins/serverkit-gpu/index.jsxdeleted file mode 100644index 481f84aa..00000000--- a/frontend/src/plugins/serverkit-gpu/index.jsx+++ /dev/null@@ -1,11 +0,0 @@-// GPU Monitor, contributed through the extension system. As of the first-// CORE_SLIM slice (plan 32 #7) the page component lives INSIDE the extension-// (./components/GpuMonitor) and its /api/v1/gpu backend is bridged from-// builtin-extensions/serverkit-gpu/backend — the core page + core blueprint are-// gone. The extension owns the /gpu route + sidebar/palette entries via its-// manifest, and declares an sdk_version range for the runtime SDK gate.-import GpuMonitor from './components/GpuMonitor';--export function GpuMonitorPage() {- return <GpuMonitor />;-}diff --git a/frontend/src/plugins/serverkit-gpu/plugin.json b/frontend/src/plugins/serverkit-gpu/plugin.jsondeleted file mode 100644index 20669cee..00000000--- a/frontend/src/plugins/serverkit-gpu/plugin.json+++ /dev/null@@ -1,49 +0,0 @@-{- "name": "serverkit-gpu",- "display_name": "GPU Monitor",- "version": "1.0.0",- "description": "Live NVIDIA GPU metrics covering utilization, memory, temperature, power and fan, for servers with a GPU.",- "author": "ServerKit",- "license": "MIT",- "category": "monitoring",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell"- ],- "min_panel_version": "1.7.0",- "featured": true,- "feature_score": 60,- "sdk_version": "^1.0.0",- "entry_point": "gpu:gpu_bp",- "url_prefix": "/api/v1/gpu",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>",- "contributions": {- "nav": [- {- "id": "gpu",- "label": "GPU Monitor",- "route": "/gpu",- "category": "system",- "requiresCondition": "gpuAvailable",- "icon": "<rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"2\"/><path d=\"M7 6v12\"/><circle cx=\"13\" cy=\"12\" r=\"2.5\"/><path d=\"M17 6v12\"/>"- }- ],- "routes": [- {- "path": "gpu",- "component": "GpuMonitorPage"- }- ],- "page_titles": {- "/gpu": "GPU Monitor"- },- "command_palette": [- {- "label": "GPU Monitor",- "path": "/gpu",- "category": "Pages",- "keywords": "nvidia cuda metrics gpu"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsx b/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsxdeleted file mode 100644index 1f9ac198..00000000--- a/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsx+++ /dev/null@@ -1,696 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- ShipWheel, RefreshCw, Plus, Trash2, Server, Boxes, Network,- Layers, RotateCw, ScrollText, Star, Cable, FileCode, X,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/k8s.scss';--// Route-driven tabs (manifest maps /k8s and /k8s/:tab to this component).-const TABS = [- { slug: 'overview', to: '/k8s', label: 'Overview', end: true },- { slug: 'workloads', to: '/k8s/workloads', label: 'Workloads' },- { slug: 'pods', to: '/k8s/pods', label: 'Pods' },- { slug: 'services', to: '/k8s/services', label: 'Services' },- { slug: 'nodes', to: '/k8s/nodes', label: 'Nodes' },- { slug: 'apply', to: '/k8s/apply', label: 'Apply' },- { slug: 'clusters', to: '/k8s/clusters', label: 'Clusters' },-];-const VALID_TABS = TABS.map((t) => t.slug);--const phasePill = (phase) => {- const kind = phase === 'Running' || phase === 'Succeeded' || phase === 'Active'- ? 'green'- : phase === 'Pending' ? 'amber' : phase === 'Failed' ? 'red' : 'gray';- return <Pill kind={kind}>{phase || 'Unknown'}</Pill>;-};--const K8sPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [kubectlAvailable, setKubectlAvailable] = useState(true);- const [clusters, setClusters] = useState([]);- const [selectedId, setSelectedId] = useState(null);- const [loading, setLoading] = useState(true);- const [busy, setBusy] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Per-tab data- const [overview, setOverview] = useState(null);- const [namespace, setNamespace] = useState('all');- const [namespaces, setNamespaces] = useState([]);- const [workloadKind, setWorkloadKind] = useState('deployment');- const [rows, setRows] = useState([]);- const [dataLoading, setDataLoading] = useState(false);-- // Modals- const [addClusterOpen, setAddClusterOpen] = useState(false);- const [addForm, setAddForm] = useState({ name: '', context: '', kubeconfig: '', make_default: false });- const [logsModal, setLogsModal] = useState(null); // {pod, namespace, container, text, loading}- const [manifest, setManifest] = useState('');- const [applyOutput, setApplyOutput] = useState(null);-- const selected = useMemo(- () => clusters.find((c) => String(c.id) === String(selectedId)) || null,- [clusters, selectedId],- );-- // ── Cluster list ──- const loadStatus = useCallback(async () => {- setLoading(true);- try {- const data = await api.request('/k8s/status');- setKubectlAvailable(data.kubectl_available);- setClusters(data.clusters || []);- setSelectedId((prev) => {- if (prev && (data.clusters || []).some((c) => String(c.id) === String(prev))) return prev;- return data.default_cluster_id || (data.clusters?.[0]?.id ?? null);- });- } catch (error) {- toast.error(`Could not load Kubernetes status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- useEffect(() => { loadStatus(); }, [loadStatus]);-- // ── Namespaces (for the namespace filter) ──- const loadNamespaces = useCallback(async () => {- if (!selected || !kubectlAvailable) return;- try {- const data = await api.request(`/k8s/clusters/${selected.id}/namespaces`);- setNamespaces((data.items || []).map((n) => n.name).filter(Boolean));- } catch { /* namespace filter is optional */ }- }, [selected, kubectlAvailable]);-- useEffect(() => { loadNamespaces(); }, [loadNamespaces]);-- // ── Tab data ──- const loadTab = useCallback(async () => {- if (!selected || !kubectlAvailable) { setRows([]); setOverview(null); return; }- setDataLoading(true);- try {- if (activeTab === 'overview') {- setOverview(await api.request(`/k8s/clusters/${selected.id}/overview`));- } else if (activeTab === 'workloads') {- const data = await api.request(`/k8s/clusters/${selected.id}/workloads?namespace=${namespace}&kind=${workloadKind}`);- setRows(data.items || []);- } else if (activeTab === 'pods') {- const data = await api.request(`/k8s/clusters/${selected.id}/pods?namespace=${namespace}`);- setRows(data.items || []);- } else if (activeTab === 'services') {- const data = await api.request(`/k8s/clusters/${selected.id}/services?namespace=${namespace}`);- setRows(data.items || []);- } else if (activeTab === 'nodes') {- const data = await api.request(`/k8s/clusters/${selected.id}/nodes`);- setRows(data.items || []);- }- } catch (error) {- toast.error(error.message);- setRows([]);- } finally {- setDataLoading(false);- }- }, [selected, kubectlAvailable, activeTab, namespace, workloadKind, toast]);-- useEffect(() => { loadTab(); }, [loadTab]);-- // ── Cluster actions ──- const handleAddCluster = async () => {- if (!addForm.name.trim() || !addForm.kubeconfig.trim()) {- toast.error('Name and kubeconfig are required.');- return;- }- setBusy(true);- try {- await api.request('/k8s/clusters', { method: 'POST', body: addForm });- toast.success(`Cluster "${addForm.name}" added`);- setAddClusterOpen(false);- setAddForm({ name: '', context: '', kubeconfig: '', make_default: false });- await loadStatus();- } catch (error) {- toast.error(`Could not add cluster: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleDeleteCluster = (cluster) => {- setConfirmDialog({- title: `Remove ${cluster.name}?`,- message: 'This deletes the stored connection and its kubeconfig from the panel. The cluster itself is not touched.',- confirmText: 'Remove',- variant: 'destructive',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/k8s/clusters/${cluster.id}`, { method: 'DELETE' });- toast.success('Cluster removed');- await loadStatus();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleSetDefault = async (cluster) => {- try {- await api.request(`/k8s/clusters/${cluster.id}/default`, { method: 'POST' });- await loadStatus();- } catch (error) {- toast.error(error.message);- }- };-- const handleTest = async (cluster) => {- setBusy(true);- try {- const res = await api.request(`/k8s/clusters/${cluster.id}/test`, { method: 'POST' });- if (res.ok) toast.success(`Reachable — ${res.server_version}`);- else toast.error(`Unreachable: ${res.error}`);- await loadStatus();- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- // ── Workload actions ──- const handleScale = (w, delta) => {- const next = Math.max(0, (w.desired || 0) + delta);- return doScale(w, next);- };-- const doScale = async (w, replicas) => {- setBusy(true);- try {- await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/scale`,- { method: 'POST', body: { replicas } });- toast.success(`Scaled ${w.name} to ${replicas}`);- await loadTab();- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- const handleRestart = async (w) => {- setBusy(true);- try {- await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/restart`,- { method: 'POST' });- toast.success(`Restart triggered for ${w.name}`);- } catch (error) {- toast.error(error.message);- } finally {- setBusy(false);- }- };-- const handleDeleteResource = (kind, row) => {- setConfirmDialog({- title: `Delete ${kind} ${row.name}?`,- message: `This removes ${row.name} from namespace ${row.namespace} on the live cluster.`,- confirmText: 'Delete',- variant: 'destructive',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/k8s/clusters/${selected.id}/delete-resource`,- { method: 'POST', body: { kind, name: row.name, namespace: row.namespace } });- toast.success(`${kind} ${row.name} deleted`);- await loadTab();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- // ── Pod logs ──- const openLogs = async (pod) => {- const container = pod.containers?.[0] || '';- setLogsModal({ pod: pod.name, namespace: pod.namespace, container, text: '', loading: true });- try {- const q = container ? `?container=${container}&tail=200` : '?tail=200';- const data = await api.request(`/k8s/clusters/${selected.id}/pods/${pod.namespace}/${pod.name}/logs${q}`);- setLogsModal((m) => m && ({ ...m, text: data.logs || '(no output)', loading: false }));- } catch (error) {- setLogsModal((m) => m && ({ ...m, text: `Error: ${error.message}`, loading: false }));- }- };-- // ── Apply ──- const handleApply = async () => {- if (!manifest.trim()) { toast.error('Paste a manifest first.'); return; }- setBusy(true);- setApplyOutput(null);- try {- const res = await api.request(`/k8s/clusters/${selected.id}/apply`, { method: 'POST', body: { manifest } });- setApplyOutput(res.output || '(applied)');- toast.success('Manifest applied');- } catch (error) {- setApplyOutput(`Error: ${error.message}`);- toast.error(error.message);- } finally {- setBusy(false);- }- };-- // ── Renderers ──- const NamespaceFilter = () => (- <div className="k8s-filter">- <Label>Namespace</Label>- <select className="k8s-select" value={namespace} onChange={(e) => setNamespace(e.target.value)}>- <option value="all">All namespaces</option>- {namespaces.map((n) => <option key={n} value={n}>{n}</option>)}- </select>- </div>- );-- const renderOverview = () => {- if (dataLoading && !overview) return <EmptyState loading title="Querying cluster..." />;- if (!overview) return <EmptyState icon={ShipWheel} title="No data" description="Select a reachable cluster." />;- if (!overview.reachable) {- return (- <div className="card">- <div className="card-body">- <EmptyState icon={Cable} title="Cluster unreachable"- description={overview.error || 'kubectl could not reach the API server with the stored kubeconfig.'} />- <div className="k8s-center">- <Button variant="outline" size="sm" onClick={() => handleTest(selected)}>- <RefreshCw size={14} /> Retry- </Button>- </div>- </div>- </div>- );- }- const c = overview.counts;- const cards = [- { label: 'Server', value: overview.server_version, icon: ShipWheel },- { label: 'Nodes ready', value: `${c.nodes_ready}/${c.nodes}`, icon: Server },- { label: 'Namespaces', value: c.namespaces, icon: Layers },- { label: 'Pods running', value: `${c.pods_running}/${c.pods}`, icon: Boxes },- { label: 'Deployments', value: c.deployments, icon: Network },- ];- return (- <div className="k8s-kpis">- {cards.map((k) => (- <div className="card k8s-kpi" key={k.label}>- <div className="card-body">- <div className="k8s-kpi__icon"><k.icon size={18} /></div>- <div className="k8s-kpi__val">{k.value ?? '—'}</div>- <div className="k8s-kpi__label">{k.label}</div>- </div>- </div>- ))}- </div>- );- };-- const renderWorkloads = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Workloads</h3>- <div className="card-actions k8s-toolbar">- <select className="k8s-select" value={workloadKind} onChange={(e) => setWorkloadKind(e.target.value)}>- <option value="deployment">Deployments</option>- <option value="statefulset">StatefulSets</option>- <option value="daemonset">DaemonSets</option>- </select>- <NamespaceFilter />- </div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading workloads..." />- : rows.length === 0 ? <EmptyState icon={Network} title="No workloads" description="Nothing found in this namespace." />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Replicas</th><th>Status</th><th>Image</th><th /></tr>- </thead>- <tbody>- {rows.map((w) => (- <tr key={`${w.namespace}/${w.name}`}>- <td className="sk-cell-mono">{w.name}</td>- <td>{w.namespace}</td>- <td>- {workloadKind === 'deployment' ? (- <span className="k8s-scale">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, -1)}>−</Button>- <span className="k8s-scale__n">{w.ready}/{w.desired}</span>- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, +1)}>+</Button>- </span>- ) : <span className="sk-cell-mono">{w.ready}/{w.desired}</span>}- </td>- <td><Pill kind={w.healthy ? 'green' : 'amber'}>{w.healthy ? 'healthy' : 'degraded'}</Pill></td>- <td className="sk-cell-mono k8s-truncate" title={(w.images || []).join(', ')}>{(w.images || [])[0] || '—'}</td>- <td className="k8s-row-actions">- {workloadKind === 'deployment' && (- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRestart(w)} title="Rolling restart">- <RotateCw size={14} />- </Button>- )}- <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource(workloadKind, w)}>- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderPods = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Pods</h3>- <div className="card-actions"><NamespaceFilter /></div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading pods..." />- : rows.length === 0 ? <EmptyState icon={Boxes} title="No pods" description="Nothing running in this namespace." />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Ready</th><th>Status</th><th>Restarts</th><th>Node</th><th /></tr>- </thead>- <tbody>- {rows.map((p) => (- <tr key={`${p.namespace}/${p.name}`}>- <td className="sk-cell-mono k8s-truncate" title={p.name}>{p.name}</td>- <td>{p.namespace}</td>- <td className="sk-cell-mono">{p.ready}</td>- <td>{phasePill(p.phase)}</td>- <td className="sk-cell-mono">{p.restarts > 0 ? <Pill kind="amber">{p.restarts}</Pill> : 0}</td>- <td className="sk-cell-mono k8s-truncate">{p.node || '—'}</td>- <td className="k8s-row-actions">- <Button variant="secondary" size="sm" onClick={() => openLogs(p)} title="Logs">- <ScrollText size={14} />- </Button>- <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource('pod', p)}>- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderServices = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Services</h3>- <div className="card-actions"><NamespaceFilter /></div>- </div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading services..." />- : rows.length === 0 ? <EmptyState icon={Cable} title="No services" />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Namespace</th><th>Type</th><th>Cluster IP</th><th>External</th><th>Ports</th></tr>- </thead>- <tbody>- {rows.map((s) => (- <tr key={`${s.namespace}/${s.name}`}>- <td className="sk-cell-mono">{s.name}</td>- <td>{s.namespace}</td>- <td><Pill kind={s.type === 'LoadBalancer' ? 'green' : 'gray'}>{s.type}</Pill></td>- <td className="sk-cell-mono">{s.cluster_ip || '—'}</td>- <td className="sk-cell-mono">{s.external_ip || '—'}</td>- <td className="sk-cell-mono">{(s.ports || []).join(', ') || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderNodes = () => (- <div className="card sec-flush">- <div className="card-header"><h3>Nodes</h3></div>- <div className="card-body">- {dataLoading ? <EmptyState loading title="Loading nodes..." />- : rows.length === 0 ? <EmptyState icon={Server} title="No nodes" />- : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Status</th><th>Roles</th><th>Version</th><th>OS</th><th>CPU</th><th>Memory</th></tr>- </thead>- <tbody>- {rows.map((n) => (- <tr key={n.name}>- <td className="sk-cell-mono">{n.name}</td>- <td><Pill kind={n.ready ? 'green' : 'red'}>{n.ready ? 'Ready' : 'NotReady'}</Pill></td>- <td>{(n.roles || []).join(', ')}</td>- <td className="sk-cell-mono">{n.kubelet_version || '—'}</td>- <td className="k8s-truncate" title={n.os_image}>{n.os_image || '—'}</td>- <td className="sk-cell-mono">{n.cpu || '—'}</td>- <td className="sk-cell-mono">{n.memory || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderApply = () => (- <div className="card">- <div className="card-header"><h3>Apply manifest</h3></div>- <div className="card-body k8s-apply">- <p className="text-muted">- Paste a Kubernetes YAML or JSON manifest. It is sent to the selected cluster with- <code> kubectl apply -f -</code>. Admin only.- </p>- <textarea- className="k8s-textarea"- rows={16}- spellCheck={false}- placeholder={'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: demo'}- value={manifest}- onChange={(e) => setManifest(e.target.value)}- />- <div className="k8s-apply__actions">- <Button variant="default" size="sm" disabled={busy || !selected} onClick={handleApply}>- <FileCode size={14} /> Apply- </Button>- <Button variant="outline" size="sm" onClick={() => { setManifest(''); setApplyOutput(null); }}>Clear</Button>- </div>- {applyOutput != null && <pre className="k8s-output">{applyOutput}</pre>}- </div>- </div>- );-- const renderClusters = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Clusters</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setAddClusterOpen(true)}>- <Plus size={14} /> Add cluster- </Button>- </div>- </div>- <div className="card-body">- {clusters.length === 0 ? (- <EmptyState icon={ShipWheel} title="No clusters yet"- description="Add a cluster by pasting its kubeconfig to start managing workloads." />- ) : (- <table className="sk-dtable">- <thead>- <tr><th>Name</th><th>Context</th><th>Reachable</th><th>Server</th><th>Last checked</th><th /></tr>- </thead>- <tbody>- {clusters.map((c) => (- <tr key={c.id}>- <td className="sk-cell-mono">- {c.is_default && <Star size={12} className="k8s-default-star" title="Default" />} {c.name}- </td>- <td className="sk-cell-mono">{c.context || '—'}</td>- <td>- {c.last_reachable == null- ? <Pill kind="gray">unknown</Pill>- : <Pill kind={c.last_reachable ? 'green' : 'red'}>{c.last_reachable ? 'yes' : 'no'}</Pill>}- </td>- <td className="sk-cell-mono">{c.status?.server_version || '—'}</td>- <td className="sk-cell-mono">{c.last_checked_at ? new Date(c.last_checked_at).toLocaleString() : '—'}</td>- <td className="k8s-row-actions">- <Button variant="secondary" size="sm" disabled={busy || !kubectlAvailable} onClick={() => handleTest(c)}>Test</Button>- {!c.is_default && <Button variant="secondary" size="sm" onClick={() => handleSetDefault(c)}>Set default</Button>}- <Button variant="destructive" size="sm" onClick={() => handleDeleteCluster(c)}><Trash2 size={14} /></Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- // ── Page shell ──- if (loading) {- return (- <div className="page-container page-container--full-bleed sk-tabgroup k8s-page">- <PageTopbar icon={<ShipWheel size={18} />} title="Kubernetes" />- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- <EmptyState loading title="Loading Kubernetes..." />- </div>- </div>- </div>- );- }-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));- const needsCluster = activeTab !== 'clusters' && clusters.length === 0;-- return (- <div className="page-container page-container--full-bleed sk-tabgroup k8s-page">- <PageTopbar- icon={<ShipWheel size={18} />}- title="Kubernetes"- tabs={topbarTabs}- actions={- <div className="k8s-topbar-actions">- {clusters.length > 0 && activeTab !== 'clusters' && (- <select className="k8s-select" value={selectedId ?? ''} onChange={(e) => setSelectedId(e.target.value)}>- {clusters.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}- </select>- )}- <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadTab(); }}>- <RefreshCw size={14} /> Refresh- </Button>- </div>- }- />-- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- {!kubectlAvailable && (- <div className="card k8s-warn">- <div className="card-body">- <strong>kubectl is not installed on the panel host.</strong> You can still add and- store cluster connections, but live cluster data and actions are unavailable until- <code> kubectl</code> is on the panel host PATH.- </div>- </div>- )}-- {needsCluster ? (- <div className="card">- <div className="card-body">- <EmptyState icon={ShipWheel} title="No clusters connected"- description="Add a cluster on the Clusters tab by pasting its kubeconfig." />- <div className="k8s-center">- <Button variant="default" size="sm" onClick={() => navigate('/k8s/clusters')}>- <Plus size={14} /> Go to Clusters- </Button>- </div>- </div>- </div>- ) : (- <>- {activeTab === 'overview' && renderOverview()}- {activeTab === 'workloads' && renderWorkloads()}- {activeTab === 'pods' && renderPods()}- {activeTab === 'services' && renderServices()}- {activeTab === 'nodes' && renderNodes()}- {activeTab === 'apply' && renderApply()}- {activeTab === 'clusters' && renderClusters()}- </>- )}- </div>- </div>-- {/* Add cluster modal */}- <Modal open={addClusterOpen} onClose={() => setAddClusterOpen(false)} title="Add Kubernetes cluster">- <div className="k8s-form">- <div className="form-group">- <Label>Name</Label>- <Input type="text" value={addForm.name} placeholder="prod-eu"- onChange={(e) => setAddForm((f) => ({ ...f, name: e.target.value }))} />- </div>- <div className="form-group">- <Label>Context (optional)</Label>- <Input type="text" value={addForm.context} placeholder="Leave blank for the kubeconfig's current-context"- onChange={(e) => setAddForm((f) => ({ ...f, context: e.target.value }))} />- </div>- <div className="form-group">- <Label>Kubeconfig</Label>- <textarea className="k8s-textarea" rows={10} spellCheck={false}- placeholder="Paste the full kubeconfig YAML here"- value={addForm.kubeconfig}- onChange={(e) => setAddForm((f) => ({ ...f, kubeconfig: e.target.value }))} />- <p className="text-muted">Stored encrypted with the panel key. Never shown again after saving.</p>- </div>- <label className="k8s-checkbox">- <input type="checkbox" checked={addForm.make_default}- onChange={(e) => setAddForm((f) => ({ ...f, make_default: e.target.checked }))} />- Make this the default cluster- </label>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setAddClusterOpen(false)}>Cancel</Button>- <Button variant="default" onClick={handleAddCluster} disabled={busy}>Add cluster</Button>- </div>- </Modal>-- {/* Logs modal */}- <Modal open={!!logsModal} onClose={() => setLogsModal(null)}- title={logsModal ? `Logs · ${logsModal.pod}` : 'Logs'}>- {logsModal?.loading- ? <EmptyState loading title="Fetching logs..." />- : <pre className="k8s-logs">{logsModal?.text}</pre>}- <div className="modal-footer">- <Button variant="outline" onClick={() => setLogsModal(null)}><X size={14} /> Close</Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default K8sPage;diff --git a/frontend/src/plugins/serverkit-k8s/index.jsx b/frontend/src/plugins/serverkit-k8s/index.jsxdeleted file mode 100644index bb282478..00000000--- a/frontend/src/plugins/serverkit-k8s/index.jsx+++ /dev/null@@ -1,7 +0,0 @@-// Kubernetes cluster management UI, contributed through the extension system.-// Fully self-contained in the extension. After sync this folder lives at-// frontend/src/plugins/serverkit-k8s/, so '@/…' host aliases resolve.-export { default as K8sPage } from './components/K8sPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/frontend/src/plugins/serverkit-k8s/plugin.json b/frontend/src/plugins/serverkit-k8s/plugin.jsondeleted file mode 100644index 5e8791e6..00000000--- a/frontend/src/plugins/serverkit-k8s/plugin.json+++ /dev/null@@ -1,56 +0,0 @@-{- "name": "serverkit-k8s",- "display_name": "Kubernetes",- "version": "1.0.0",- "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell",- "filesystem",- "network"- ],- "min_panel_version": "1.7.0",- "entry_point": "k8s:k8s_bp",- "url_prefix": "/api/v1/k8s",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>",- "contributions": {- "nav": [- {- "id": "k8s",- "label": "Kubernetes",- "route": "/k8s",- "category": "infrastructure",- "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>"- }- ],- "routes": [- {- "path": "k8s",- "component": "K8sPage"- },- {- "path": "k8s/:tab",- "component": "K8sPage"- }- ],- "page_titles": {- "/k8s": "Kubernetes"- },- "command_palette": [- {- "label": "Kubernetes",- "path": "/k8s",- "category": "Pages",- "keywords": "k8s kubernetes kubectl cluster node namespace pod deployment workload statefulset daemonset service ingress scale restart apply kubeconfig"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-k8s/styles/k8s.scss b/frontend/src/plugins/serverkit-k8s/styles/k8s.scssdeleted file mode 100644index 7c732390..00000000--- a/frontend/src/plugins/serverkit-k8s/styles/k8s.scss+++ /dev/null@@ -1,177 +0,0 @@-/* Kubernetes extension — layout-only styles. Colors, typography, spacing and- controls all inherit from the host design system (card, sk-dtable, Pill,- empty-state, form controls). No hardcoded palette; surface tints lean on- currentColor / neutral rgba so they read in both themes. */--.k8s-page {- .k8s-topbar-actions {- display: flex;- align-items: center;- gap: 8px;- }-- .k8s-select {- height: 32px;- padding: 0 10px;- border-radius: 6px;- border: 1px solid rgba(128, 128, 128, 0.35);- background: transparent;- color: inherit;- font-size: 13px;- }-- .k8s-filter {- display: flex;- align-items: center;- gap: 8px;-- label {- margin: 0;- white-space: nowrap;- }- }-- .k8s-toolbar {- display: flex;- align-items: center;- gap: 12px;- flex-wrap: wrap;- }-- .k8s-warn {- margin-bottom: 16px;-- code {- padding: 1px 5px;- border-radius: 4px;- background: rgba(128, 128, 128, 0.15);- }- }-- .k8s-center {- display: flex;- justify-content: center;- margin-top: 12px;- }-- /* Overview KPI band */- .k8s-kpis {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));- gap: 12px;- }-- .k8s-kpi {- .card-body {- display: flex;- flex-direction: column;- gap: 4px;- }-- &__icon {- opacity: 0.6;- margin-bottom: 4px;- }-- &__val {- font-size: 20px;- font-weight: 600;- word-break: break-word;- }-- &__label {- font-size: 12px;- opacity: 0.7;- }- }-- /* Tables */- .k8s-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;- justify-content: flex-end;- }-- .k8s-truncate {- max-width: 240px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- .k8s-scale {- display: inline-flex;- align-items: center;- gap: 8px;-- &__n {- min-width: 44px;- text-align: center;- font-variant-numeric: tabular-nums;- }- }-- .k8s-default-star {- color: #eab308;- vertical-align: middle;- }-- /* Forms */- .k8s-form {- display: flex;- flex-direction: column;- gap: 12px;- }-- .k8s-textarea,- .k8s-logs,- .k8s-output {- width: 100%;- font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12.5px;- border-radius: 8px;- border: 1px solid rgba(128, 128, 128, 0.3);- background: rgba(128, 128, 128, 0.06);- color: inherit;- padding: 12px;- box-sizing: border-box;- }-- .k8s-textarea {- resize: vertical;- }-- .k8s-checkbox {- display: flex;- align-items: center;- gap: 8px;- font-size: 13px;- cursor: pointer;- }-- /* Apply */- .k8s-apply {- display: flex;- flex-direction: column;- gap: 12px;-- &__actions {- display: flex;- gap: 8px;- }- }-- .k8s-logs,- .k8s-output {- max-height: 55vh;- overflow: auto;- white-space: pre-wrap;- word-break: break-word;- margin: 0;- }-- .k8s-output {- margin-top: 4px;- }-}diff --git a/frontend/src/plugins/serverkit-mail/components/MailPage.jsx b/frontend/src/plugins/serverkit-mail/components/MailPage.jsxdeleted file mode 100644index 490fdf4b..00000000--- a/frontend/src/plugins/serverkit-mail/components/MailPage.jsx+++ /dev/null@@ -1,1383 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- Mail, RefreshCw, Plus, Trash2, ShieldCheck, ShieldAlert,- Globe, AtSign, Forward, KeyRound, Inbox, Copy, Power, Send,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--// Route-driven tabs (manifest maps /mail and /mail/:tab to this component).-const TABS = [- { slug: 'overview', to: '/mail', label: 'Overview', end: true },- { slug: 'domains', to: '/mail/domains', label: 'Domains' },- { slug: 'mailboxes', to: '/mail/mailboxes', label: 'Mailboxes' },- { slug: 'forwarders', to: '/mail/forwarders', label: 'Forwarders' },- { slug: 'dns', to: '/mail/dns', label: 'DNS & DKIM' },- { slug: 'queue', to: '/mail/queue', label: 'Queue' },-];-const VALID_TABS = TABS.map((t) => t.slug);--// A preflight check either passed, failed, or was skipped (e.g. on a dev box).-function checkPill(ok, skipped) {- if (skipped) return <Pill kind="gray">skipped</Pill>;- return ok ? <Pill kind="green">pass</Pill> : <Pill kind="red">fail</Pill>;-}--const MailPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';-- const [status, setStatus] = useState(null);- const [preflight, setPreflight] = useState(null);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Overview / install- const [installHostname, setInstallHostname] = useState('');-- // Domains- const [domains, setDomains] = useState([]);- const [showDomainForm, setShowDomainForm] = useState(false);- const [newDomain, setNewDomain] = useState({ name: '', catch_all_target: '' });- const [catchAllModal, setCatchAllModal] = useState(null); // { id, name, value }-- // Selected domain (shared by mailboxes / forwarders / dns)- const [selectedDomainId, setSelectedDomainId] = useState('');-- // Mailboxes- const [mailboxes, setMailboxes] = useState([]);- const [showMailboxForm, setShowMailboxForm] = useState(false);- const [newMailbox, setNewMailbox] = useState({ local_part: '', password: '', quota_mb: 0, display_name: '' });- const [passwordModal, setPasswordModal] = useState(null); // { id, address }- const [newPassword, setNewPassword] = useState('');- const [autoModal, setAutoModal] = useState(null); // { id, address }- const [autoResponder, setAutoResponder] = useState({ enabled: false, subject: '', body: '', start_at: '', end_at: '' });-- // Forwarders- const [forwarders, setForwarders] = useState([]);- const [showForwarderForm, setShowForwarderForm] = useState(false);- const [newForwarder, setNewForwarder] = useState({ source_local_part: '', destination: '', keep_copy: true });-- // DNS & DKIM- const [dnsInfo, setDnsInfo] = useState(null);-- // Queue- const [queue, setQueue] = useState({ messages: [], note: null });-- // ── Loaders ──-- const loadStatus = useCallback(async () => {- setLoading(true);- try {- const data = await api.request('/mail/status');- setStatus(data);- setPreflight(data?.preflight ?? null);- } catch (error) {- toast.error(`Failed to load mail server status: ${error.message}`);- } finally {- setLoading(false);- }- }, [toast]);-- const loadDomains = useCallback(async () => {- try {- const data = await api.request('/mail/domains');- setDomains(data.domains || []);- } catch (error) {- toast.error(`Failed to load domains: ${error.message}`);- }- }, [toast]);-- const loadMailboxes = useCallback(async (domainId) => {- if (!domainId) { setMailboxes([]); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/mailboxes`);- setMailboxes(data.mailboxes || []);- } catch (error) {- toast.error(`Failed to load mailboxes: ${error.message}`);- }- }, [toast]);-- const loadForwarders = useCallback(async (domainId) => {- if (!domainId) { setForwarders([]); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/forwarders`);- setForwarders(data.forwarders || []);- } catch (error) {- toast.error(`Failed to load forwarders: ${error.message}`);- }- }, [toast]);-- const loadDns = useCallback(async (domainId) => {- if (!domainId) { setDnsInfo(null); return; }- try {- const data = await api.request(`/mail/domains/${domainId}/dns`);- setDnsInfo(data);- } catch (error) {- toast.error(`Failed to load DNS records: ${error.message}`);- setDnsInfo(null);- }- }, [toast]);-- const loadQueue = useCallback(async () => {- try {- const data = await api.request('/mail/queue');- setQueue({ messages: data.messages || [], note: data.note || null });- } catch (error) {- // 503 before install, or the admin API is unreachable — degrade gracefully.- setQueue({ messages: [], note: error.message });- }- }, []);-- useEffect(() => { loadStatus(); }, [loadStatus]);-- // Domains feed the selector on the mailboxes/forwarders/dns tabs too.- useEffect(() => {- if (['domains', 'mailboxes', 'forwarders', 'dns'].includes(activeTab)) loadDomains();- }, [activeTab, loadDomains]);-- useEffect(() => {- if (activeTab === 'mailboxes') loadMailboxes(selectedDomainId);- }, [activeTab, selectedDomainId, loadMailboxes]);-- useEffect(() => {- if (activeTab === 'forwarders') loadForwarders(selectedDomainId);- }, [activeTab, selectedDomainId, loadForwarders]);-- useEffect(() => {- if (activeTab === 'dns') loadDns(selectedDomainId);- }, [activeTab, selectedDomainId, loadDns]);-- useEffect(() => {- if (activeTab === 'queue') loadQueue();- }, [activeTab, loadQueue]);-- // ── Overview actions ──-- const handleInstall = async () => {- if (!installHostname.trim()) return;- setActionLoading(true);- try {- await api.request('/mail/install', {- method: 'POST',- body: { hostname: installHostname.trim() },- });- toast.success('Mail server installed');- setInstallHostname('');- await loadStatus();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove mail server',- message: keepData- ? 'Remove the Stalwart container? Mail data stays on disk and a reinstall picks it back up.'- : 'Remove the Stalwart container AND delete all mail data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('Mail server removed');- await loadStatus();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleService = async (action) => {- setActionLoading(true);- try {- await api.request(`/mail/service/${action}`, { method: 'POST' });- toast.success(`Mail server ${action} successful`);- await loadStatus();- } catch (error) {- toast.error(`Failed to ${action} mail server: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRunPreflight = async () => {- const hostname = status?.hostname || installHostname.trim() || preflight?.hostname || '';- if (!hostname) {- toast.error('Install the mail server (or set a hostname) before running preflight.');- return;- }- setActionLoading(true);- try {- const result = await api.request('/mail/preflight', {- method: 'POST',- body: { hostname },- });- setPreflight(result);- if (result?.passed) toast.success('Deliverability preflight passed');- else toast.error('Preflight found blocking issues — see the checks below');- } catch (error) {- toast.error(`Preflight failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Domain actions ──-- const handleAddDomain = async (e) => {- e.preventDefault();- if (!newDomain.name.trim()) return;- setActionLoading(true);- try {- await api.request('/mail/domains', {- method: 'POST',- body: {- name: newDomain.name.trim(),- catch_all_target: newDomain.catch_all_target.trim() || undefined,- },- });- toast.success(`Domain ${newDomain.name} added`);- setShowDomainForm(false);- setNewDomain({ name: '', catch_all_target: '' });- await loadDomains();- } catch (error) {- toast.error(`Failed to add domain: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleToggleDomain = async (domain) => {- try {- await api.request(`/mail/domains/${domain.id}`, {- method: 'PATCH',- body: { is_active: !domain.is_active },- });- toast.success(`Domain ${domain.is_active ? 'deactivated' : 'activated'}`);- await loadDomains();- } catch (error) {- // Preflight gate returns 409 — surface the guidance clearly.- toast.error(`Could not change domain state: ${error.message}`);- }- };-- const handleSaveCatchAll = async () => {- if (!catchAllModal) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${catchAllModal.id}`, {- method: 'PATCH',- body: { catch_all_target: catchAllModal.value.trim() },- });- toast.success('Catch-all updated');- setCatchAllModal(null);- await loadDomains();- } catch (error) {- toast.error(`Failed to update catch-all: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteDomain = (domain) => {- setConfirmDialog({- title: 'Delete domain',- message: `Delete ${domain.name} and all of its mailboxes and forwarders?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/domains/${domain.id}`, { method: 'DELETE' });- toast.success(`Domain ${domain.name} deleted`);- await loadDomains();- } catch (error) {- toast.error(`Failed to delete domain: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const openDnsForDomain = (domainId) => {- setSelectedDomainId(String(domainId));- navigate('/mail/dns');- };-- // ── Mailbox actions ──-- const handleAddMailbox = async (e) => {- e.preventDefault();- if (!selectedDomainId || !newMailbox.local_part.trim() || !newMailbox.password) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/mailboxes`, {- method: 'POST',- body: {- local_part: newMailbox.local_part.trim(),- password: newMailbox.password,- quota_mb: Number(newMailbox.quota_mb) || 0,- display_name: newMailbox.display_name.trim() || undefined,- },- });- toast.success('Mailbox created');- setShowMailboxForm(false);- setNewMailbox({ local_part: '', password: '', quota_mb: 0, display_name: '' });- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to create mailbox: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleToggleMailbox = async (mailbox) => {- try {- await api.request(`/mail/mailboxes/${mailbox.id}`, {- method: 'PATCH',- body: { is_active: !mailbox.is_active },- });- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to update mailbox: ${error.message}`);- }- };-- const handleChangePassword = async () => {- if (!passwordModal || !newPassword) return;- setActionLoading(true);- try {- await api.request(`/mail/mailboxes/${passwordModal.id}/password`, {- method: 'POST',- body: { password: newPassword },- });- toast.success('Password changed');- setPasswordModal(null);- setNewPassword('');- } catch (error) {- toast.error(`Failed to change password: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteMailbox = (mailbox) => {- setConfirmDialog({- title: 'Delete mailbox',- message: `Delete ${mailbox.address || mailbox.local_part}? The mailbox and its mail are removed.`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/mailboxes/${mailbox.id}`, { method: 'DELETE' });- toast.success('Mailbox deleted');- await loadMailboxes(selectedDomainId);- } catch (error) {- toast.error(`Failed to delete mailbox: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- const openAutoResponder = async (mailbox) => {- setAutoModal({ id: mailbox.id, address: mailbox.address || mailbox.local_part });- setAutoResponder({ enabled: false, subject: '', body: '', start_at: '', end_at: '' });- try {- const data = await api.request(`/mail/mailboxes/${mailbox.id}/autoresponder`);- const ar = data.autoresponder || {};- setAutoResponder({- enabled: !!ar.enabled,- subject: ar.subject || '',- body: ar.body || '',- start_at: ar.start_at || '',- end_at: ar.end_at || '',- });- } catch (error) {- toast.error(`Failed to load autoresponder: ${error.message}`);- }- };-- const handleSaveAutoResponder = async () => {- if (!autoModal) return;- setActionLoading(true);- try {- await api.request(`/mail/mailboxes/${autoModal.id}/autoresponder`, {- method: 'PUT',- body: {- enabled: autoResponder.enabled,- subject: autoResponder.subject,- body: autoResponder.body,- start_at: autoResponder.start_at || null,- end_at: autoResponder.end_at || null,- },- });- toast.success('Autoresponder saved');- setAutoModal(null);- } catch (error) {- toast.error(`Failed to save autoresponder: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Forwarder actions ──-- const handleAddForwarder = async (e) => {- e.preventDefault();- if (!selectedDomainId || !newForwarder.source_local_part.trim() || !newForwarder.destination.trim()) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/forwarders`, {- method: 'POST',- body: {- source_local_part: newForwarder.source_local_part.trim(),- destination: newForwarder.destination.trim(),- keep_copy: newForwarder.keep_copy,- },- });- toast.success('Forwarder created');- setShowForwarderForm(false);- setNewForwarder({ source_local_part: '', destination: '', keep_copy: true });- await loadForwarders(selectedDomainId);- } catch (error) {- toast.error(`Failed to create forwarder: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeleteForwarder = (forwarder) => {- setConfirmDialog({- title: 'Delete forwarder',- message: `Delete the forwarder for ${forwarder.source || forwarder.source_local_part}?`,- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- try {- await api.request(`/mail/forwarders/${forwarder.id}`, { method: 'DELETE' });- toast.success('Forwarder deleted');- await loadForwarders(selectedDomainId);- } catch (error) {- toast.error(`Failed to delete forwarder: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null),- });- };-- // ── DNS & DKIM actions ──-- const handleGenerateDkim = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- await api.request(`/mail/domains/${selectedDomainId}/dkim`, { method: 'POST' });- toast.success('DKIM key generated');- await loadDns(selectedDomainId);- await loadDomains();- } catch (error) {- toast.error(`DKIM generation failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDeployDns = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- const result = await api.request(`/mail/domains/${selectedDomainId}/dns/deploy`, { method: 'POST' });- if (result?.manual) toast.error('No DNS provider connected — publish the records manually');- else toast.success('DNS records deployed');- await loadDns(selectedDomainId);- } catch (error) {- toast.error(`DNS deploy failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRequestCert = async () => {- if (!selectedDomainId) return;- setActionLoading(true);- try {- const result = await api.request(`/mail/domains/${selectedDomainId}/cert`, { method: 'POST' });- if (result?.skipped) toast.error(result.error || 'Certificate request skipped');- else toast.success('Certificate requested');- } catch (error) {- toast.error(`Certificate request failed: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const copyValue = async (value) => {- try {- await navigator.clipboard.writeText(value);- toast.success('Copied to clipboard');- } catch {- toast.error('Could not copy to clipboard');- }- };-- // ── Queue actions ──-- const handleFlushQueue = async () => {- setActionLoading(true);- try {- await api.request('/mail/queue/flush', { method: 'POST' });- toast.success('Queue flush requested');- await loadQueue();- } catch (error) {- toast.error(`Failed to flush queue: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- // ── Render helpers ──-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));- const installed = !!status?.installed;- const selectedDomain = domains.find((d) => String(d.id) === String(selectedDomainId));-- const DomainSelector = () => (- <div className="mail-domain-picker">- <Label>Domain</Label>- <select- value={selectedDomainId}- onChange={(e) => setSelectedDomainId(e.target.value)}- className="mail-select"- >- <option value="">— Select a domain —</option>- {domains.map((d) => (- <option key={d.id} value={d.id}>{d.name}</option>- ))}- </select>- </div>- );-- const renderPreflightBanner = () => {- const passed = !!preflight?.passed;- return (- <div className={`card mail-preflight mail-preflight--${passed ? 'ok' : 'warn'}`}>- <div className="card-header">- <h3>- {passed- ? <><ShieldCheck size={16} /> Deliverability preflight passed</>- : <><ShieldAlert size={16} /> Sending is blocked until preflight passes</>}- </h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={handleRunPreflight} disabled={actionLoading}>- <RefreshCw size={14} /> Run preflight- </Button>- </div>- </div>- <div className="card-body">- {!preflight ? (- <p className="text-muted">- No preflight has run yet. Outbound mail stays disabled until PTR, port-25- egress and RBL checks pass — run a preflight to see where this host stands.- </p>- ) : (- <>- <div className="mail-preflight__checks">- <div className="mail-check">- <div className="mail-check__head">- <span className="k">PTR / reverse DNS</span>- {checkPill(preflight.ptr_ok, preflight.ptr_ok === null)}- </div>- <p className="text-muted">- {preflight.ptr_value- ? `Resolves to ${preflight.ptr_value}.`- : 'The public IP must resolve back to your mail hostname or receivers reject you.'}- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">Port 25 egress</span>- {checkPill(preflight.port25_ok, preflight.port25_ok === null)}- </div>- <p className="text-muted">- Many providers block outbound port 25. Without it this host cannot deliver mail directly.- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">RBL / blocklists</span>- {checkPill(preflight.rbl_ok, preflight.rbl_ok === null)}- </div>- <p className="text-muted">- {(preflight.rbl_hits && preflight.rbl_hits.length)- ? `Listed on: ${preflight.rbl_hits.join(', ')}`- : 'The IP is not on the blocklists we check.'}- </p>- </div>- <div className="mail-check">- <div className="mail-check__head">- <span className="k">Listening ports</span>- {checkPill(preflight.ports_ok, preflight.ports_ok === null)}- </div>- <p className="text-muted">- SMTP/submission/IMAPS ports (25/465/587/993) should be reachable on this host.- </p>- </div>- </div>- {preflight.checked_at && (- <p className="text-muted mail-preflight__ts">- Last checked {new Date(preflight.checked_at).toLocaleString()}- {' · '}- {passed- ? 'sending is allowed.'- : 'fix the failing checks (or force-activate a domain knowingly) before relying on delivery.'}- </p>- )}- </>- )}- </div>- </div>- );- };-- // ── Tab bodies ──-- const renderOverview = () => {- if (!installed) {- return (- <>- {renderPreflightBanner()}- <div className="card">- <div className="card-header"><h3>Mail Server Not Installed</h3></div>- <div className="card-body">- <p className="text-muted">- Run Stalwart (SMTP + IMAP + admin API) in a managed Docker container so this- box hosts mail for your domains — mailboxes, forwarders, autoresponders, and- automatic DKIM/SPF/DMARC/MX records.- </p>- <div className="mail-install-form">- <div className="form-group">- <Label>Mail hostname</Label>- <Input- type="text"- value={installHostname}- onChange={(e) => setInstallHostname(e.target.value)}- placeholder="mail.example.com"- />- <p className="text-muted">- The public hostname clients connect to. It should resolve to this box's- public IP and have a matching PTR record.- </p>- </div>- <div className="mail-install-actions">- <Button- variant="default"- onClick={handleInstall}- disabled={actionLoading || !installHostname.trim()}- >- {actionLoading ? 'Installing...' : 'Install Mail Server'}- </Button>- <Button variant="outline" onClick={loadStatus}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- </div>- </div>- </>- );- }-- return (- <>- {renderPreflightBanner()}- {status?.needs_setup === true && (- <div className="card mail-preflight mail-preflight--warn">- <div className="mail-preflight__head">- <span className="mail-preflight__title">- <ShieldAlert size={16} /> Finish the one-time Stalwart setup- </span>- </div>- <p className="text-muted">- The container is running in bootstrap mode — its admin API stays- offline until you complete the initial setup wizard, which creates- the permanent administrator. For safety the setup UI is bound to the- server's loopback only ({status.setup_url || 'http://127.0.0.1:8080/account'});- reach it over an SSH tunnel, then re-check.- </p>- <div className="mail-install-actions">- <Button variant="outline" size="sm" onClick={loadStatus}>- <RefreshCw size={14} /> Re-check- </Button>- </div>- </div>- )}- <div className="card">- <div className="card-header">- <h3>Server Status</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)}>- <Trash2 size={14} /> Remove + data- </Button>- </div>- </div>- <div className="card-body">- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Container</span>- <Pill kind={status.running ? 'green' : 'red'}>- {status.running ? 'Running' : 'Stopped'}- </Pill>- </div>- <div className="sk-info-row">- <span className="k">Engine</span>- <span className="v">- {status.engine || 'Stalwart'} {status.version ? `v${status.version}` : ''}- </span>- </div>- {status.hostname && (- <div className="sk-info-row">- <span className="k">Hostname</span>- <span className="v sk-cell-mono">{status.hostname}</span>- </div>- )}- {status.ports && (- <div className="sk-info-row">- <span className="k">Ports</span>- <span className="v sk-cell-mono">- {Array.isArray(status.ports) ? status.ports.join(', ') : String(status.ports)}- </span>- </div>- )}- </div>- <div className="mail-service-actions">- <Button variant="outline" size="sm" onClick={() => handleService('restart')} disabled={actionLoading}>- <RefreshCw size={14} /> Restart- </Button>- {status.running ? (- <Button variant="outline" size="sm" onClick={() => handleService('stop')} disabled={actionLoading}>- <Power size={14} /> Stop- </Button>- ) : (- <Button variant="default" size="sm" onClick={() => handleService('start')} disabled={actionLoading}>- <Power size={14} /> Start- </Button>- )}- </div>- </div>- </div>- </>- );- };-- const renderDomains = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Domains {domains.length > 0 && <span className="sec-count">· {domains.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowDomainForm((v) => !v)}>- <Plus size={14} /> {showDomainForm ? 'Cancel' : 'Add Domain'}- </Button>- </div>- </div>- {showDomainForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddDomain}>- <div className="form-group">- <Label>Domain name</Label>- <Input- type="text"- value={newDomain.name}- onChange={(e) => setNewDomain((f) => ({ ...f, name: e.target.value }))}- placeholder="example.com"- />- </div>- <div className="form-group">- <Label>Catch-all target (optional)</Label>- <Input- type="text"- value={newDomain.catch_all_target}- onChange={(e) => setNewDomain((f) => ({ ...f, catch_all_target: e.target.value }))}- placeholder="[email protected]"- />- </div>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newDomain.name.trim()}>- Add Domain- </Button>- </div>- </form>- </div>- )}- {domains.length === 0 ? (- <div className="card-body">- <p className="text-muted">No mail domains yet. Add one, then generate DKIM and publish its DNS records.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Domain</th>- <th>Catch-all</th>- <th>Sync</th>- <th>Status</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {domains.map((d) => (- <tr key={d.id}>- <td className="sk-cell-name">- <span className="mail-fav"><Globe size={14} /></span>- <span className="sk-cell-mono">{d.name}</span>- </td>- <td className="sk-cell-mono">{d.catch_all_target || '—'}</td>- <td>- {d.sync_state === 'error'- ? <Pill kind="amber" title={d.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={d.sync_state === 'synced' ? 'green' : 'gray'}>{d.sync_state || 'pending'}</Pill>}- </td>- <td>- <Pill kind={d.is_active ? 'green' : 'gray'}>{d.is_active ? 'active' : 'inactive'}</Pill>- </td>- <td>- <div className="mail-row-actions">- <Button variant="secondary" size="sm" onClick={() => handleToggleDomain(d)}>- {d.is_active ? 'Deactivate' : 'Activate'}- </Button>- <Button variant="secondary" size="sm" onClick={() => setCatchAllModal({ id: d.id, name: d.name, value: d.catch_all_target || '' })}>- Catch-all- </Button>- <Button variant="secondary" size="sm" onClick={() => openDnsForDomain(d.id)}>- <KeyRound size={14} /> DNS- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteDomain(d)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- );-- const renderMailboxes = () => (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>Mailboxes {mailboxes.length > 0 && <span className="sec-count">· {mailboxes.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowMailboxForm((v) => !v)}>- <Plus size={14} /> {showMailboxForm ? 'Cancel' : 'Add Mailbox'}- </Button>- </div>- </div>- {showMailboxForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddMailbox}>- <div className="form-grid">- <div className="form-group">- <Label>Local part</Label>- <Input- type="text"- value={newMailbox.local_part}- onChange={(e) => setNewMailbox((f) => ({ ...f, local_part: e.target.value }))}- placeholder="alice"- />- </div>- <div className="form-group">- <Label>Display name (optional)</Label>- <Input- type="text"- value={newMailbox.display_name}- onChange={(e) => setNewMailbox((f) => ({ ...f, display_name: e.target.value }))}- placeholder="Alice Doe"- />- </div>- <div className="form-group">- <Label>Password</Label>- <Input- type="password"- value={newMailbox.password}- onChange={(e) => setNewMailbox((f) => ({ ...f, password: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Quota (MB, 0 = unlimited)</Label>- <Input- type="number"- min="0"- value={newMailbox.quota_mb}- onChange={(e) => setNewMailbox((f) => ({ ...f, quota_mb: e.target.value }))}- />- </div>- </div>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newMailbox.local_part.trim() || !newMailbox.password}>- Create Mailbox- </Button>- </div>- </form>- </div>- )}- {mailboxes.length === 0 ? (- <div className="card-body">- <p className="text-muted">No mailboxes for {selectedDomain?.name} yet.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Address</th>- <th>Quota</th>- <th>Sync</th>- <th>Status</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {mailboxes.map((m) => (- <tr key={m.id}>- <td className="sk-cell-name">- <span className="mail-fav mail-fav--cyan"><AtSign size={14} /></span>- <span className="sk-cell-mono">{m.address || `${m.local_part}@${selectedDomain?.name || ''}`}</span>- </td>- <td className="sk-cell-mono">{m.quota_mb ? `${m.quota_mb} MB` : 'unlimited'}</td>- <td>- {m.sync_state === 'error'- ? <Pill kind="amber" title={m.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={m.sync_state === 'synced' ? 'green' : 'gray'}>{m.sync_state || 'pending'}</Pill>}- </td>- <td>- <Pill kind={m.is_active ? 'green' : 'gray'}>{m.is_active ? 'active' : 'disabled'}</Pill>- </td>- <td>- <div className="mail-row-actions">- <Button variant="secondary" size="sm" onClick={() => handleToggleMailbox(m)}>- {m.is_active ? 'Disable' : 'Enable'}- </Button>- <Button variant="secondary" size="sm" onClick={() => { setPasswordModal({ id: m.id, address: m.address || m.local_part }); setNewPassword(''); }}>- Password- </Button>- <Button variant="secondary" size="sm" onClick={() => openAutoResponder(m)}>- Autoreply- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteMailbox(m)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}- </>- );-- const renderForwarders = () => (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>Forwarders {forwarders.length > 0 && <span className="sec-count">· {forwarders.length}</span>}</h3>- <div className="card-actions">- <Button variant="default" size="sm" onClick={() => setShowForwarderForm((v) => !v)}>- <Plus size={14} /> {showForwarderForm ? 'Cancel' : 'Add Forwarder'}- </Button>- </div>- </div>- {showForwarderForm && (- <div className="card-body">- <form className="mail-form" onSubmit={handleAddForwarder}>- <div className="form-grid">- <div className="form-group">- <Label>Source local part</Label>- <Input- type="text"- value={newForwarder.source_local_part}- onChange={(e) => setNewForwarder((f) => ({ ...f, source_local_part: e.target.value }))}- placeholder="sales"- />- </div>- <div className="form-group">- <Label>Destination</Label>- <Input- type="text"- value={newForwarder.destination}- onChange={(e) => setNewForwarder((f) => ({ ...f, destination: e.target.value }))}- placeholder="[email protected]"- />- </div>- </div>- <label className="mail-check-label">- <input- type="checkbox"- checked={newForwarder.keep_copy}- onChange={(e) => setNewForwarder((f) => ({ ...f, keep_copy: e.target.checked }))}- />- {' '}Keep a copy in the local mailbox- </label>- <div className="mail-install-actions">- <Button type="submit" variant="default" size="sm" disabled={actionLoading || !newForwarder.source_local_part.trim() || !newForwarder.destination.trim()}>- Add Forwarder- </Button>- </div>- </form>- </div>- )}- {forwarders.length === 0 ? (- <div className="card-body">- <p className="text-muted">No forwarders for {selectedDomain?.name} yet.</p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Source</th>- <th />- <th>Destination</th>- <th>Copy</th>- <th>Sync</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {forwarders.map((f) => (- <tr key={f.id}>- <td className="sk-cell-mono">{f.source || `${f.source_local_part}@${selectedDomain?.name || ''}`}</td>- <td className="mail-arrow"><Forward size={14} /></td>- <td className="sk-cell-mono">{f.destination}</td>- <td><Pill kind={f.keep_copy ? 'cyan' : 'gray'}>{f.keep_copy ? 'keeps copy' : 'no copy'}</Pill></td>- <td>- {f.sync_state === 'error'- ? <Pill kind="amber" title={f.sync_error || 'Out of sync with the engine'}>drift</Pill>- : <Pill kind={f.sync_state === 'synced' ? 'green' : 'gray'}>{f.sync_state || 'pending'}</Pill>}- </td>- <td>- <div className="mail-row-actions">- <Button variant="destructive" size="sm" onClick={() => handleDeleteForwarder(f)}>- Delete- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}- </>- );-- const renderDns = () => {- const records = dnsInfo?.records || [];- return (- <>- <div className="card">- <div className="card-body">- <DomainSelector />- </div>- </div>- {selectedDomainId && (- <div className="card sec-flush">- <div className="card-header">- <h3>DNS & DKIM {selectedDomain ? `· ${selectedDomain.name}` : ''}</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={handleGenerateDkim} disabled={actionLoading}>- <KeyRound size={14} /> Generate DKIM- </Button>- <Button variant="default" size="sm" onClick={handleDeployDns} disabled={actionLoading}>- Push to provider- </Button>- <Button variant="secondary" size="sm" onClick={handleRequestCert} disabled={actionLoading}>- Request cert- </Button>- </div>- </div>- <div className="card-body">- <div className="sk-info-row">- <span className="k">Deploy status</span>- {dnsInfo?.deployed- ? <Pill kind="green">deployed</Pill>- : <Pill kind="amber">{dnsInfo?.manual ? 'manual publish needed' : 'not deployed'}</Pill>}- </div>- {dnsInfo?.provider && (- <div className="sk-info-row">- <span className="k">Provider</span>- <span className="v">{dnsInfo.provider}</span>- </div>- )}- <p className="text-muted mail-dns-hint">- Publish these records at your DNS provider (or push them automatically if a- provider is connected). MX + SPF + DKIM + DMARC are what receivers check to- trust your mail.- </p>- </div>- {records.length === 0 ? (- <div className="card-body">- <p className="text-muted">- No records yet. Generate a DKIM key to produce the full record set for {selectedDomain?.name}.- </p>- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Type</th>- <th>Name</th>- <th>Value</th>- <th>State</th>- <th />- </tr>- </thead>- <tbody>- {records.map((r, i) => {- const value = r.priority != null ? `${r.priority} ${r.value}` : r.value;- return (- <tr key={`${r.type}-${r.name}-${i}`}>- <td><span className="sk-tag">{r.type}</span></td>- <td className="sk-cell-mono">{r.name}</td>- <td className="sk-cell-mono mail-dns-value">{value}</td>- <td>- {(r.deployed ?? r.status === 'deployed')- ? <Pill kind="green">set</Pill>- : <Pill kind="gray">pending</Pill>}- </td>- <td>- <Button variant="secondary" size="sm" onClick={() => copyValue(value)}>- <Copy size={14} /> Copy- </Button>- </td>- </tr>- );- })}- </tbody>- </table>- )}- </div>- )}- </>- );- };-- const renderQueue = () => (- <div className="card sec-flush">- <div className="card-header">- <h3>Outbound Queue {queue.messages.length > 0 && <span className="sec-count">· {queue.messages.length}</span>}</h3>- <div className="card-actions">- <Button variant="secondary" size="sm" onClick={loadQueue} disabled={actionLoading}>- <RefreshCw size={14} /> Refresh- </Button>- <Button variant="default" size="sm" onClick={handleFlushQueue} disabled={actionLoading}>- <Send size={14} /> Flush queue- </Button>- </div>- </div>- {queue.messages.length === 0 ? (- <div className="card-body">- <EmptyState- icon={Inbox}- title="Queue is empty"- description={queue.note || 'No messages are waiting to be delivered.'}- />- </div>- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>ID</th>- <th>From</th>- <th>Recipients</th>- <th>Status</th>- <th>Queued</th>- </tr>- </thead>- <tbody>- {queue.messages.map((m, i) => (- <tr key={m.id ?? m.queue_id ?? i}>- <td className="sk-cell-mono">{m.id ?? m.queue_id ?? '—'}</td>- <td className="sk-cell-mono">{m.from || m.sender || '—'}</td>- <td className="sk-cell-mono">- {Array.isArray(m.recipients) ? m.recipients.join(', ') : (m.to || m.recipients || '—')}- </td>- <td>{m.status || m.state || '—'}</td>- <td className="sk-cell-mono">{m.created || m.arrival_time || '—'}</td>- </tr>- ))}- </tbody>- </table>- )}- </div>- );-- // ── Page shell ──-- if (loading) {- return (- <div className="page-container mail-page">- <PageTopbar icon={<Mail size={18} />} title="Mail Server" />- <EmptyState loading title="Loading mail server status..." />- </div>- );- }-- return (- <div className="page-container mail-page">- <PageTopbar- icon={<Mail size={18} />}- title="Mail Server"- meta={<>Stalwart · SMTP · IMAP · DKIM</>}- tabs={topbarTabs}- actions={- <Button variant="outline" size="sm" onClick={loadStatus}>- <RefreshCw size={14} /> Refresh- </Button>- }- />-- {activeTab === 'overview' && renderOverview()}- {activeTab === 'domains' && renderDomains()}- {activeTab === 'mailboxes' && renderMailboxes()}- {activeTab === 'forwarders' && renderForwarders()}- {activeTab === 'dns' && renderDns()}- {activeTab === 'queue' && renderQueue()}-- {/* ── Catch-all modal ── */}- <Modal open={!!catchAllModal} onClose={() => setCatchAllModal(null)} title={`Catch-all · ${catchAllModal?.name || ''}`}>- <div className="form-group">- <Label>Catch-all target</Label>- <Input- type="text"- value={catchAllModal?.value || ''}- onChange={(e) => setCatchAllModal((m) => ({ ...m, value: e.target.value }))}- placeholder="[email protected]"- />- <p className="text-muted">Leave empty to disable catch-all delivery for this domain.</p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setCatchAllModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleSaveCatchAll} disabled={actionLoading}>Save</Button>- </div>- </Modal>-- {/* ── Password modal ── */}- <Modal open={!!passwordModal} onClose={() => setPasswordModal(null)} title={`Change password · ${passwordModal?.address || ''}`}>- <div className="form-group">- <Label>New password</Label>- <Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setPasswordModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleChangePassword} disabled={actionLoading || !newPassword}>Change</Button>- </div>- </Modal>-- {/* ── Autoresponder modal ── */}- <Modal open={!!autoModal} onClose={() => setAutoModal(null)} title={`Autoresponder · ${autoModal?.address || ''}`}>- <label className="mail-check-label">- <input- type="checkbox"- checked={autoResponder.enabled}- onChange={(e) => setAutoResponder((a) => ({ ...a, enabled: e.target.checked }))}- />- {' '}Enabled- </label>- <div className="form-group">- <Label>Subject</Label>- <Input- type="text"- value={autoResponder.subject}- onChange={(e) => setAutoResponder((a) => ({ ...a, subject: e.target.value }))}- placeholder="Out of office"- />- </div>- <div className="form-group">- <Label>Body</Label>- <textarea- className="mail-textarea"- rows={5}- value={autoResponder.body}- onChange={(e) => setAutoResponder((a) => ({ ...a, body: e.target.value }))}- placeholder="I'm away until..."- />- </div>- <div className="form-grid">- <div className="form-group">- <Label>Start (optional)</Label>- <Input- type="datetime-local"- value={autoResponder.start_at || ''}- onChange={(e) => setAutoResponder((a) => ({ ...a, start_at: e.target.value }))}- />- </div>- <div className="form-group">- <Label>End (optional)</Label>- <Input- type="datetime-local"- value={autoResponder.end_at || ''}- onChange={(e) => setAutoResponder((a) => ({ ...a, end_at: e.target.value }))}- />- </div>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setAutoModal(null)}>Cancel</Button>- <Button variant="default" onClick={handleSaveAutoResponder} disabled={actionLoading}>Save</Button>- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export default MailPage;diff --git a/frontend/src/plugins/serverkit-mail/index.jsx b/frontend/src/plugins/serverkit-mail/index.jsxdeleted file mode 100644index 3fc7e623..00000000--- a/frontend/src/plugins/serverkit-mail/index.jsx+++ /dev/null@@ -1,8 +0,0 @@-// Self-hosted mail server UI (Stalwart engine), contributed through the-// extension system. Fully self-contained in the extension — no core page to-// wrap. After sync this folder lives at frontend/src/plugins/serverkit-mail/,-// so '@/…' host aliases resolve.-export { default as MailPage } from './components/MailPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contribution resolves the NAMED export.diff --git a/frontend/src/plugins/serverkit-mail/plugin.json b/frontend/src/plugins/serverkit-mail/plugin.jsondeleted file mode 100644index 0f622529..00000000--- a/frontend/src/plugins/serverkit-mail/plugin.json+++ /dev/null@@ -1,74 +0,0 @@-{- "name": "serverkit-mail",- "display_name": "Mail Server",- "version": "1.0.0",- "description": "Self-hosted mail server powered by Stalwart in a managed Docker container, providing domains, mailboxes, forwarders, and autoresponders, with automatic DKIM/SPF/DMARC/MX record deployment, a deliverability preflight (PTR, port-25 egress, RBL) that gates outbound sending, brute-force jails, and maildir backups. Most panels never run a mail server, so it ships as an opt-in extension.",- "author": "ServerKit",- "license": "MIT",- "category": "integration",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": [- "shell",- "filesystem",- "network",- "docker"- ],- "min_panel_version": "1.7.0",- "entry_point": "mail:mail_bp",- "url_prefix": "/api/v1/mail",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "jobs": [- {- "kind": "mail.preflight.run",- "handler": "jobs:run_preflight"- },- {- "kind": "mail.queue.flush",- "handler": "jobs:flush_queue"- }- ],- "schedules": [- {- "name": "mail-preflight-daily",- "kind": "mail.preflight.run",- "cron": "0 6 * * *"- }- ],- "icon": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"/><path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\"/>",- "contributions": {- "nav": [- {- "id": "mail",- "label": "Mail Server",- "route": "/mail",- "category": "operations",- "icon": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"/><path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\"/>"- }- ],- "routes": [- {- "path": "mail",- "component": "MailPage"- },- {- "path": "mail/:tab",- "component": "MailPage"- }- ],- "page_titles": {- "/mail": "Mail Server"- },- "command_palette": [- {- "label": "Mail Server",- "path": "/mail",- "category": "Pages",- "keywords": "mail smtp imap stalwart mailbox domain dkim spf dmarc mx deliverability forwarder autoresponder queue"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-mail/styles/mail.scss b/frontend/src/plugins/serverkit-mail/styles/mail.scssdeleted file mode 100644index f2b89802..00000000--- a/frontend/src/plugins/serverkit-mail/styles/mail.scss+++ /dev/null@@ -1,156 +0,0 @@-/* Mail Server extension — layout-only styles. Colors, typography, spacing and- controls all inherit from the host design system (card, sk-dtable,- sk-info-row, Pill, empty-state…). No hardcoded palette; the few surface tints- below lean on currentColor / neutral rgba so they read in both themes. */--.mail-page .mail-install-form {- max-width: 480px;- margin-top: 16px;-}--.mail-page .mail-install-actions {- display: flex;- gap: 8px;- margin-top: 12px;-}--.mail-page .mail-service-actions {- display: flex;- gap: 8px;- margin-top: 16px;-}--.mail-page .mail-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;-}--.mail-page .mail-form {- display: flex;- flex-direction: column;- gap: 12px;- max-width: 640px;-}--.mail-page .form-grid {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 12px;-}--@media (max-width: 640px) {- .mail-page .form-grid {- grid-template-columns: 1fr;- }-}--.mail-page .mail-domain-picker {- display: flex;- flex-direction: column;- gap: 6px;- max-width: 360px;-}--.mail-page .mail-select {- width: 100%;- padding: 8px 10px;- border-radius: 6px;- font: inherit;- color: inherit;- background: transparent;- border: 1px solid rgba(128, 128, 128, 0.35);-}--.mail-page .mail-fav {- display: inline-flex;- align-items: center;- justify-content: center;- margin-right: 8px;- opacity: 0.75;-}--.mail-page .mail-arrow {- text-align: center;- opacity: 0.6;-}--.mail-page .mail-check-label {- display: inline-flex;- align-items: center;- gap: 6px;- cursor: pointer;-}--.mail-page .mail-textarea {- width: 100%;- font: inherit;- color: inherit;- background: transparent;- border: 1px solid rgba(128, 128, 128, 0.35);- border-radius: 6px;- padding: 8px;- resize: vertical;-}--.mail-page .mail-dns-hint {- margin-top: 10px;-}--.mail-page .mail-dns-value {- word-break: break-all;- max-width: 420px;-}--/* ── Preflight banner (the deliverability gate) ── */--.mail-page .mail-preflight .card-header h3 {- display: flex;- align-items: center;- gap: 8px;-}--.mail-page .mail-preflight--warn {- border-color: rgba(214, 158, 46, 0.55);-}--.mail-page .mail-preflight__checks {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 14px;- margin-top: 4px;-}--@media (max-width: 720px) {- .mail-page .mail-preflight__checks {- grid-template-columns: 1fr;- }-}--.mail-page .mail-check {- padding: 10px 12px;- border-radius: 8px;- border: 1px solid rgba(128, 128, 128, 0.25);-}--.mail-page .mail-check__head {- display: flex;- align-items: center;- justify-content: space-between;- gap: 8px;- margin-bottom: 4px;-}--.mail-page .mail-check__head .k {- font-weight: 500;-}--.mail-page .mail-check p {- margin: 0;- font-size: 0.85em;-}--.mail-page .mail-preflight__ts {- margin-top: 12px;- font-size: 0.85em;-}diff --git a/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsx b/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsxdeleted file mode 100644index ca7bdd27..00000000--- a/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsx+++ /dev/null@@ -1,120 +0,0 @@-import { Suspense, lazy, useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import { ArrowLeft, Play, Rocket, Check, AlertCircle, Loader2 } from 'lucide-react';-import api from '@/services/api';-import { Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/tramo-automations.scss';--// The tramo editor is the heavy chunk (canvas engine + 21 integration packs +-// tramo/styles.css). Lazy-load it so it never lands in the panel entry bundle.-const TramoEditor = lazy(() => import('./TramoEditor.jsx'));--// Map the editor's save lifecycle to a small header indicator.-const SaveIndicator = ({ state }) => {- const status = state?.status || 'idle';- if (status === 'saving' || status === 'pending') {- return <span className="tramo-save tramo-save--busy"><Loader2 size={13} className="tramo-spin" /> Saving…</span>;- }- if (status === 'saved') {- return <span className="tramo-save tramo-save--ok"><Check size={13} /> Saved</span>;- }- if (status === 'error') {- return <span className="tramo-save tramo-save--err"><AlertCircle size={13} /> {state?.error || 'Save failed'}</span>;- }- return <span className="tramo-save tramo-save--idle">All changes saved</span>;-};--const AutomationEditorPage = () => {- const { slug } = useParams();- const navigate = useNavigate();- const toast = useToast();-- const [workflow, setWorkflow] = useState(null);- const [saveState, setSaveState] = useState(null);- const [busy, setBusy] = useState(false);-- // Header metadata (name, enabled) — the doc itself is owned by the editor.- useEffect(() => {- let cancelled = false;- (async () => {- try {- const data = await api.request(`/tramo/workflows/${slug}`);- if (!cancelled) setWorkflow(data);- } catch (error) {- if (!cancelled) toast.error(`Could not load workflow: ${error.message}`);- }- })();- return () => { cancelled = true; };- }, [slug, toast]);-- const onSaveStateChange = useCallback((s) => setSaveState(s), []);-- const handleRun = async () => {- setBusy(true);- try {- const res = await api.request(`/tramo/workflows/${slug}/run`, { method: 'POST', body: {} });- const status = res?.run?.status || res?.result?.status || 'started';- toast.success(`Run ${status} — see Runs for details`, {- action: { label: 'View runs', onClick: () => navigate('/automations/runs') },- });- } catch (error) {- toast.error(`Run failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleDeploy = async () => {- setBusy(true);- try {- const res = await api.request('/tramo/deploy', { method: 'POST' });- toast.success(res?.message || 'Deployed to the tramo engine');- } catch (error) {- toast.error(`Deploy failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- return (- <div className="tramo-editor-page">- <div className="tramo-editor-page__bar">- <div className="tramo-editor-page__left">- <Button variant="ghost" size="sm" onClick={() => navigate('/automations')} title="Back to Automations">- <ArrowLeft size={16} />- </Button>- <div className="tramo-editor-page__title">- <span className="tramo-editor-page__name">{workflow?.name || slug}</span>- {workflow && (- <Pill kind={workflow.enabled ? 'green' : 'gray'}>- {workflow.enabled ? 'enabled' : 'disabled'}- </Pill>- )}- </div>- <SaveIndicator state={saveState} />- </div>- <div className="tramo-editor-page__actions">- <Button variant="secondary" size="sm" onClick={handleRun} disabled={busy}>- <Play size={14} /> Run- </Button>- <Button variant="default" size="sm" onClick={handleDeploy} disabled={busy}>- <Rocket size={14} /> Deploy- </Button>- </div>- </div>-- <div className="tramo-editor-page__body">- <Suspense fallback={<EmptyState loading title="Loading editor..." />}>- <TramoEditor slug={slug} onSaveStateChange={onSaveStateChange} />- </Suspense>- </div>- </div>- );-};--export { AutomationEditorPage };-export default AutomationEditorPage;diff --git a/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsx b/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsxdeleted file mode 100644index 9a3ceb2b..00000000--- a/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsx+++ /dev/null@@ -1,1076 +0,0 @@-import { useCallback, useEffect, useState } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import {- Workflow, RefreshCw, Plus, Trash2, Rocket, Pencil, Play, LayoutTemplate,- Server, Power, KeyRound, CheckCircle2, X, Send, Github, MessageSquare,- Zap, MousePointerClick, Clock, Webhook, Check, Search, Star,- Upload, FileJson,-} from 'lucide-react';-import api from '@/services/api';-import { PageTopbar, Pill } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import Modal from '@/components/Modal';-import ConfirmDialog from '@/components/ConfirmDialog';-import EmptyState from '@/components/EmptyState';-import { useToast } from '@/contexts/ToastContext';--import '../styles/tramo-automations.scss';--// Route-driven tabs (manifest maps /automations and /automations/:tab here).-const TABS = [- { slug: 'workflows', to: '/automations', label: 'Workflows', end: true },- { slug: 'templates', to: '/automations/templates', label: 'Templates' },- { slug: 'runs', to: '/automations/runs', label: 'Runs' },- { slug: 'settings', to: '/automations/settings', label: 'Settings' },-];-const VALID_TABS = TABS.map((t) => t.slug);--// Favorited template ids live in the browser for now (per-device). A server-side-// favorites store can replace this later without touching the card UI.-const FAVORITES_KEY = 'tramo:favorite-templates';-const readFavorites = () => {- try {- const raw = JSON.parse(localStorage.getItem(FAVORITES_KEY) || '[]');- return new Set(Array.isArray(raw) ? raw : []);- } catch {- return new Set();- }-};--// Presentation for the starter templates (icon + accent + tags). Keyed by the-// backend template id; unknown ids fall back to a neutral card so new templates-// still render cleanly.-const TEMPLATE_META = {- 'backup-failed-telegram': { Icon: Send, brand: 'telegram', tags: ['Backups', 'Telegram'] },- 'nightly-health-github': { Icon: Github, brand: 'github', tags: ['Schedule', 'GitHub'] },- 'panel-event-discord': { Icon: MessageSquare, brand: 'discord', tags: ['Events', 'Discord'] },-};-const DEFAULT_TEMPLATE_META = { Icon: Zap, brand: 'default', tags: [] };--// Trigger choices for a new workflow. Each seeds a valid builtin tramo trigger-// node so the editor opens with the trigger already placed. Panel events arrive-// at a webhook-trigger on the /sk/events path (the events bridge posts there),-// so no custom node type is needed.-const TRIGGERS = [- {- id: 'manual', Icon: MousePointerClick, title: 'Manually trigger',- subtitle: 'Run it on demand from the Automations page',- node: () => ({ id: 'trigger', type: 'manual-trigger', position: { x: 80, y: 120 }, config: {} }),- },- {- id: 'schedule', Icon: Clock, title: 'On a schedule',- subtitle: 'Run on a cron schedule, e.g. every night',- node: () => ({ id: 'trigger', type: 'cron-trigger', position: { x: 80, y: 120 }, config: { expression: '0 3 * * *' } }),- },- {- id: 'event', Icon: Zap, title: 'On a panel event',- subtitle: 'React to app, backup, health, or security events',- node: () => ({ id: 'trigger', type: 'webhook-trigger', position: { x: 80, y: 120 }, config: { path: '/sk/events', method: 'POST' } }),- },- {- id: 'webhook', Icon: Webhook, title: 'Incoming webhook',- subtitle: 'Trigger from an external HTTP request',- node: () => ({ id: 'trigger', type: 'webhook-trigger', position: { x: 80, y: 120 }, config: { path: '/hooks/my-hook', method: 'POST' } }),- },-];--// Run status → Pill colour.-const runPill = (status) => {- const kind = status === 'succeeded' || status === 'success' ? 'green'- : status === 'running' || status === 'pending' ? 'amber'- : status === 'failed' || status === 'error' ? 'red'- : status === 'awaiting_approval' ? 'cyan' : 'gray';- return <Pill kind={kind}>{status || 'unknown'}</Pill>;-};--// Host lifecycle state → Pill colour.-const hostPill = (state) => {- const kind = state === 'ready' ? 'green'- : state === 'unhealthy' ? 'amber'- : state === 'stopped' ? 'gray' : 'red';- return <Pill kind={kind}>{state || 'not_installed'}</Pill>;-};--const formatDuration = (start, finish) => {- if (!start || !finish) return '—';- const ms = new Date(finish).getTime() - new Date(start).getTime();- if (Number.isNaN(ms) || ms < 0) return '—';- if (ms < 1000) return `${ms}ms`;- return `${(ms / 1000).toFixed(1)}s`;-};--const AutomationsPage = () => {- const toast = useToast();- const navigate = useNavigate();- const { tab } = useParams();- const activeTab = VALID_TABS.includes(tab) ? tab : 'workflows';-- const [busy, setBusy] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);-- // Workflows tab- const [workflows, setWorkflows] = useState([]);- const [wfLoading, setWfLoading] = useState(false);- const [newModal, setNewModal] = useState(false);- const [newName, setNewName] = useState('');- const [newTrigger, setNewTrigger] = useState('manual');- const [templates, setTemplates] = useState([]);- const [templatesLoading, setTemplatesLoading] = useState(false);- const [templateSearch, setTemplateSearch] = useState('');- const [favorites, setFavorites] = useState(readFavorites);- const [importModal, setImportModal] = useState(false);- const [importName, setImportName] = useState('');- const [importText, setImportText] = useState('');-- // Runs tab- const [runs, setRuns] = useState([]);- const [approvals, setApprovals] = useState([]);- const [runsLoading, setRunsLoading] = useState(false);-- // Settings tab- const [host, setHost] = useState(null);- const [settings, setSettings] = useState(null);- const [settingsLoading, setSettingsLoading] = useState(false);- const [settingsSection, setSettingsSection] = useState('engine');- const [installPort, setInstallPort] = useState('');- const [newSecret, setNewSecret] = useState({ name: '', value: '' });- const [hostPortDraft, setHostPortDraft] = useState('');-- // ── Loaders ──- const loadWorkflows = useCallback(async () => {- setWfLoading(true);- try {- const data = await api.request('/tramo/workflows');- setWorkflows(data.workflows || []);- } catch (error) {- toast.error(`Could not load workflows: ${error.message}`);- } finally {- setWfLoading(false);- }- }, [toast]);-- const loadRuns = useCallback(async () => {- setRunsLoading(true);- try {- const [runData, apprData] = await Promise.all([- api.request('/tramo/runs?limit=100'),- api.request('/tramo/approvals'),- ]);- setRuns(runData.runs || []);- setApprovals(apprData.approvals || []);- } catch (error) {- toast.error(`Could not load runs: ${error.message}`);- } finally {- setRunsLoading(false);- }- }, [toast]);-- const loadSettings = useCallback(async () => {- setSettingsLoading(true);- try {- const [statusData, settingsData] = await Promise.all([- api.request('/tramo/host/status'),- api.request('/tramo/settings'),- ]);- setHost(statusData);- setSettings(settingsData);- setHostPortDraft(String(settingsData.host_port ?? statusData.host_port ?? ''));- } catch (error) {- toast.error(`Could not load settings: ${error.message}`);- } finally {- setSettingsLoading(false);- }- }, [toast]);-- const loadTemplates = useCallback(async () => {- setTemplatesLoading(true);- try {- const data = await api.request('/tramo/templates');- setTemplates(data.templates || []);- } catch (error) {- toast.error(`Could not load templates: ${error.message}`);- } finally {- setTemplatesLoading(false);- }- }, [toast]);-- useEffect(() => {- if (activeTab === 'workflows') loadWorkflows();- else if (activeTab === 'templates') loadTemplates();- else if (activeTab === 'runs') loadRuns();- else if (activeTab === 'settings') loadSettings();- }, [activeTab, loadWorkflows, loadTemplates, loadRuns, loadSettings]);-- const toggleFavorite = (id) => {- setFavorites((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id); else next.add(id);- try { localStorage.setItem(FAVORITES_KEY, JSON.stringify([...next])); } catch { /* ignore */ }- return next;- });- };-- // ── Workflow actions ──- const openNewModal = () => {- setNewName('');- setNewTrigger('manual');- setNewModal(true);- };-- const handleCreate = async () => {- if (!newName.trim()) { toast.error('Name is required.'); return; }- const trigger = TRIGGERS.find((t) => t.id === newTrigger) || TRIGGERS[0];- const doc = { name: newName.trim(), nodes: [trigger.node()], edges: [] };- setBusy(true);- try {- const wf = await api.request('/tramo/workflows', {- method: 'POST', body: { name: newName.trim(), doc },- });- setNewModal(false);- setNewName('');- toast.success(`Workflow "${wf.name}" created`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not create workflow: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleFromTemplate = async (template) => {- setBusy(true);- try {- const wf = await api.request(`/tramo/workflows/from-template/${template.id}`, { method: 'POST', body: {} });- toast.success(`Created "${wf.name}" from ${template.name}`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not create from template: ${error.message}`);- } finally {- setBusy(false);- }- };-- const openImportModal = () => {- setImportName('');- setImportText('');- setImportModal(true);- };-- const handleImportFile = async (e) => {- const file = e.target.files?.[0];- if (!file) return;- try {- setImportText(await file.text());- if (!importName.trim()) setImportName(file.name.replace(/\.json$/i, ''));- } catch {- toast.error('Could not read that file.');- }- e.target.value = '';- };-- const handleImport = async () => {- let doc;- try {- doc = JSON.parse(importText);- } catch {- toast.error('That is not valid JSON. Paste a tramo workflow document.');- return;- }- if (!doc || typeof doc !== 'object' || !Array.isArray(doc.nodes)) {- toast.error('That JSON does not look like a workflow (missing a nodes array).');- return;- }- const name = importName.trim() || doc.name || 'Imported automation';- setBusy(true);- try {- const wf = await api.request('/tramo/workflows', {- method: 'POST', body: { name, doc: { ...doc, name } },- });- setImportModal(false);- toast.success(`Imported "${wf.name}"`);- navigate(`/automations/edit/${wf.slug}`);- } catch (error) {- toast.error(`Could not import: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggleEnabled = async (wf) => {- try {- await api.request(`/tramo/workflows/${wf.slug}`, { method: 'PUT', body: { enabled: !wf.enabled } });- await loadWorkflows();- } catch (error) {- toast.error(`Could not update workflow: ${error.message}`);- }- };-- const handleDeleteWorkflow = (wf) => {- setConfirmDialog({- title: `Delete ${wf.name}?`,- message: 'This removes the workflow and its stored document. Deployed runs already recorded are kept.',- confirmText: 'Delete',- variant: 'danger',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/tramo/workflows/${wf.slug}`, { method: 'DELETE' });- toast.success('Workflow deleted');- await loadWorkflows();- } catch (error) {- toast.error(error.message);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleDeploy = async () => {- setBusy(true);- try {- const res = await api.request('/tramo/deploy', { method: 'POST' });- toast.success(res?.message || 'Deployed to the tramo engine');- await loadWorkflows();- } catch (error) {- toast.error(`Deploy failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleRunWorkflow = async (wf) => {- setBusy(true);- try {- const res = await api.request(`/tramo/workflows/${wf.slug}/run`, { method: 'POST', body: {} });- const status = res?.run?.status || res?.result?.status || 'started';- toast.success(`Run ${status} — see the Runs tab`);- } catch (error) {- toast.error(`Run failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Run actions ──- const handleApprove = async (runId) => {- setBusy(true);- try {- await api.request(`/tramo/runs/${runId}/approve`, { method: 'POST', body: {} });- toast.success('Approved');- await loadRuns();- } catch (error) {- toast.error(`Approve failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleReplay = async (runId) => {- setBusy(true);- try {- await api.request(`/tramo/runs/${runId}/replay`, { method: 'POST' });- toast.success('Replay queued');- await loadRuns();- } catch (error) {- toast.error(`Replay failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Host / settings actions ──- const handleInstall = async () => {- setBusy(true);- try {- const body = installPort ? { host_port: Number(installPort) } : {};- await api.request('/tramo/host/install', { method: 'POST', body });- toast.success('tramo engine installed');- setInstallPort('');- await loadSettings();- } catch (error) {- toast.error(`Install failed: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleUninstall = (keepData) => {- setConfirmDialog({- title: 'Remove tramo engine',- message: keepData- ? 'Remove the tramo container? Workflow data stays on disk and a reinstall picks it back up.'- : 'Remove the tramo container AND delete all engine data? This cannot be undone.',- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- setConfirmDialog(null);- try {- await api.request(`/tramo/host/install?keep_data=${keepData}`, { method: 'DELETE' });- toast.success('tramo engine removed');- await loadSettings();- } catch (error) {- toast.error(`Uninstall failed: ${error.message}`);- }- },- onCancel: () => setConfirmDialog(null),- });- };-- const handleControl = async (action) => {- setBusy(true);- try {- await api.request(`/tramo/host/control/${action}`, { method: 'POST' });- toast.success(`Engine ${action} requested`);- await loadSettings();- } catch (error) {- toast.error(`Could not ${action} engine: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleAddSecret = async () => {- if (!newSecret.name.trim() || !newSecret.value) { toast.error('Name and value are required.'); return; }- setBusy(true);- try {- await api.request('/tramo/settings', {- method: 'PUT',- body: { pack_secrets: { [newSecret.name.trim()]: newSecret.value } },- });- toast.success(`Secret ${newSecret.name.trim()} saved`);- setNewSecret({ name: '', value: '' });- await loadSettings();- } catch (error) {- toast.error(`Could not save secret: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleToggleBridge = async () => {- setBusy(true);- try {- await api.request('/tramo/settings', {- method: 'PUT',- body: { events_bridge_enabled: !settings?.events_bridge_enabled },- });- await loadSettings();- } catch (error) {- toast.error(`Could not update events bridge: ${error.message}`);- } finally {- setBusy(false);- }- };-- const handleSaveHostPort = async () => {- const port = Number(hostPortDraft);- if (!port) { toast.error('Enter a valid port.'); return; }- setBusy(true);- try {- await api.request('/tramo/settings', { method: 'PUT', body: { host_port: port } });- toast.success('Host port updated');- await loadSettings();- } catch (error) {- toast.error(`Could not update host port: ${error.message}`);- } finally {- setBusy(false);- }- };-- // ── Renderers ──- const renderTemplates = () => {- const q = templateSearch.trim().toLowerCase();- const filtered = templates.filter((t) => !q- || t.name.toLowerCase().includes(q)- || (t.description || '').toLowerCase().includes(q));- // Favorites float to the top; otherwise preserve the incoming order.- const sorted = [...filtered].sort(- (a, b) => (favorites.has(a.id) ? 0 : 1) - (favorites.has(b.id) ? 0 : 1));- return (- <div className="tramo-templates">- <div className="tramo-templates__bar">- <div className="tramo-search">- <Search size={15} />- <input- type="text"- placeholder="Search templates..."- value={templateSearch}- onChange={(e) => setTemplateSearch(e.target.value)}- />- </div>- <span className="tramo-templates__count">- {filtered.length} template{filtered.length === 1 ? '' : 's'}- </span>- </div>- {templatesLoading ? (- <EmptyState loading title="Loading templates..." />- ) : sorted.length === 0 ? (- <EmptyState- icon={LayoutTemplate}- title={q ? 'No templates match your search' : 'No templates yet'}- description={q ? 'Try a different search.' : 'Import your own to get started.'}- />- ) : (- <div className="tramo-tpl-grid">- {sorted.map((t) => {- const meta = TEMPLATE_META[t.id] || DEFAULT_TEMPLATE_META;- const { Icon } = meta;- const fav = favorites.has(t.id);- return (- <div className="tramo-card" key={t.id}>- <div className="tramo-card__top">- <span className={`tramo-card__icon tramo-card__icon--${meta.brand}`}>- <Icon size={20} />- </span>- <button- type="button"- className={`tramo-card__fav${fav ? ' is-fav' : ''}`}- onClick={() => toggleFavorite(t.id)}- title={fav ? 'Remove from favorites' : 'Add to favorites'}- aria-pressed={fav}- >- <Star size={16} />- </button>- </div>- <h4 className="tramo-card__name">{t.name}</h4>- {t.description && <p className="tramo-card__desc">{t.description}</p>}- {meta.tags.length > 0 && (- <div className="tramo-card__tags">- {meta.tags.map((tag) => (- <span className="tramo-card__tag" key={tag}>{tag}</span>- ))}- </div>- )}- <div className="tramo-card__foot">- <Button variant="default" size="sm" disabled={busy} onClick={() => handleFromTemplate(t)}>- <Plus size={14} /> Use template- </Button>- </div>- </div>- );- })}- </div>- )}- </div>- );- };-- const renderWorkflows = () => (- <div className="card">- <div className="card-body">- {wfLoading ? <EmptyState loading title="Loading workflows..." />- : workflows.length === 0 ? (- <EmptyState- icon={Workflow}- title="No automations yet"- description="Create a workflow on the visual canvas, or start from a template. Enable it and deploy to run it headless on the tramo engine."- />- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Name</th><th>Enabled</th><th>State</th><th>Version</th><th>Updated</th><th /></tr>- </thead>- <tbody>- {workflows.map((wf) => (- <tr key={wf.id ?? wf.slug}>- <td className="sk-cell-mono">{wf.name}</td>- <td>- <button- type="button"- className={`tramo-toggle${wf.enabled ? ' tramo-toggle--on' : ''}`}- onClick={() => handleToggleEnabled(wf)}- aria-pressed={wf.enabled}- title={wf.enabled ? 'Disable' : 'Enable'}- >- <span className="tramo-toggle__knob" />- </button>- </td>- <td>- {wf.dirty- ? <Pill kind="amber" title="Edited since last deploy">undeployed</Pill>- : <Pill kind="green">deployed</Pill>}- </td>- <td className="sk-cell-mono">{wf.doc_version ?? '—'}</td>- <td className="sk-cell-mono">{wf.updated_at ? new Date(wf.updated_at).toLocaleString() : '—'}</td>- <td className="tramo-row-actions">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRunWorkflow(wf)} title="Run now">- <Play size={14} />- </Button>- <Button variant="secondary" size="sm" onClick={() => navigate(`/automations/edit/${wf.slug}`)} title="Edit">- <Pencil size={14} />- </Button>- <Button variant="destructive" size="sm" onClick={() => handleDeleteWorkflow(wf)} title="Delete">- <Trash2 size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- );-- const renderRuns = () => (- <>- {approvals.length > 0 && (- <div className="card tramo-approvals">- <div className="card-header">- <h3>Pending approvals <span className="sec-count">· {approvals.length}</span></h3>- </div>- <div className="card-body">- {approvals.map((a) => (- <div className="tramo-approval" key={a.run_id}>- <div className="tramo-approval__info">- <span className="sk-cell-mono">{a.workflow_slug || a.workflow || '—'}</span>- <span className="text-muted">{a.node || a.message || 'Awaiting approval'}</span>- </div>- <Button variant="default" size="sm" disabled={busy} onClick={() => handleApprove(a.run_id)}>- <CheckCircle2 size={14} /> Approve- </Button>- </div>- ))}- </div>- </div>- )}- <div className="card">- <div className="card-body">- {runsLoading ? <EmptyState loading title="Loading runs..." />- : runs.length === 0 ? (- <EmptyState icon={Play} title="No runs yet" description="Deploy an enabled workflow, then trigger it or wait for a matching event." />- ) : (- <table className="sk-dtable">- <thead>- <tr>- <th>Status</th><th>Workflow</th><th>Source</th><th>Duration</th><th>Tokens</th><th>Error</th><th /></tr>- </thead>- <tbody>- {runs.map((r) => (- <tr key={r.run_id}>- <td>{runPill(r.status)}</td>- <td className="sk-cell-mono">{r.workflow_slug || '—'}</td>- <td><Pill kind="gray">{r.source || 'manual'}</Pill></td>- <td className="sk-cell-mono">{formatDuration(r.started_at, r.finished_at)}</td>- <td className="sk-cell-mono">{r.usage?.total_tokens ?? r.usage?.tokens ?? '—'}</td>- <td className="sk-cell-mono tramo-truncate" title={r.error || ''}>{r.error || '—'}</td>- <td className="tramo-row-actions">- <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleReplay(r.run_id)} title="Replay">- <RefreshCw size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>- </>- );-- const SETTINGS_SECTIONS = [- { id: 'engine', label: 'Engine', Icon: Server },- { id: 'general', label: 'Events & port', Icon: Zap },- { id: 'secrets', label: 'Pack secrets', Icon: KeyRound },- ];-- const renderSettings = () => {- const state = host?.state || 'not_installed';- const installed = !!host?.installed;- const notSupported = !installed && !!host?.error;-- const engineCard = (- <div className="card">- <div className="card-header">- <h3><Server size={16} /> Automation engine</h3>- </div>- <div className="card-body">- {settingsLoading && !host ? <EmptyState loading title="Loading engine status..." /> : (- <>- <div className="sec-rows">- <div className="sk-info-row">- <span className="k">Status</span>- {hostPill(state)}- </div>- <div className="sk-info-row">- <span className="k">Container</span>- <span className="v sk-cell-mono">{host?.container || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Image</span>- <span className="v sk-cell-mono">{host?.image || '—'}</span>- </div>- <div className="sk-info-row">- <span className="k">Host port</span>- <span className="v sk-cell-mono">{host?.host_port ?? '—'}</span>- </div>- {host?.version && (- <div className="sk-info-row">- <span className="k">Version</span>- <span className="v sk-cell-mono">{host.version}</span>- </div>- )}- </div>-- {notSupported && (- <div className="tramo-note">- Docker is required to run the tramo engine, and it is not available on this- host (the engine does not run on Windows dev boxes). You can still design- workflows; deploying and running them needs a Linux host with Docker.- <div className="tramo-note__detail">{host.error}</div>- </div>- )}-- <div className="tramo-host-actions">- {!installed ? (- <div className="tramo-install">- <div className="form-group">- <Label>Host port (optional)</Label>- <Input- type="number"- value={installPort}- placeholder={String(host?.host_port ?? 3737)}- onChange={(e) => setInstallPort(e.target.value)}- />- </div>- <Button variant="default" size="sm" onClick={handleInstall} disabled={busy}>- <Power size={14} /> Install engine- </Button>- </div>- ) : (- <>- <Button variant="outline" size="sm" onClick={() => handleControl('restart')} disabled={busy}>- <RefreshCw size={14} /> Restart- </Button>- {host?.running ? (- <Button variant="outline" size="sm" onClick={() => handleControl('stop')} disabled={busy}>- <Power size={14} /> Stop- </Button>- ) : (- <Button variant="default" size="sm" onClick={() => handleControl('start')} disabled={busy}>- <Power size={14} /> Start- </Button>- )}- <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)} disabled={busy}>- Remove (keep data)- </Button>- <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)} disabled={busy}>- <Trash2 size={14} /> Remove + data- </Button>- </>- )}- </div>- </>- )}- </div>- </div>- );-- const generalCard = (- <div className="card">- <div className="card-header"><h3><Zap size={16} /> Events & port</h3></div>- <div className="card-body tramo-settings">- <div className="tramo-field">- <div className="tramo-field__label">- <Label>Events bridge</Label>- <p className="text-muted">Forward panel events to tramo so workflows can react to them.</p>- </div>- <button- type="button"- className={`tramo-toggle${settings?.events_bridge_enabled ? ' tramo-toggle--on' : ''}`}- onClick={handleToggleBridge}- disabled={busy}- aria-pressed={!!settings?.events_bridge_enabled}- >- <span className="tramo-toggle__knob" />- </button>- </div>- <div className="tramo-field tramo-field--inline">- <div className="tramo-field__label">- <Label>Host port</Label>- <p className="text-muted">Port the tramo container is published on.</p>- </div>- <div className="tramo-field__control">- <Input type="number" value={hostPortDraft} onChange={(e) => setHostPortDraft(e.target.value)} />- <Button variant="secondary" size="sm" onClick={handleSaveHostPort} disabled={busy}>Save</Button>- </div>- </div>- </div>- </div>- );-- const secretsCard = (- <div className="card sec-flush">- <div className="card-header">- <h3><KeyRound size={16} /> Pack secrets</h3>- </div>- <div className="card-body">- <p className="text-muted">- Credentials integration packs need (API keys, tokens). Values are write-only — they are- stored encrypted and never shown again after saving.- </p>- {(settings?.pack_secret_names?.length ?? 0) === 0 ? (- <p className="text-muted">No pack secrets set yet.</p>- ) : (- <div className="tramo-secret-list">- {settings.pack_secret_names.map((name) => (- <div className="tramo-secret" key={name}>- <span className="sk-cell-mono">{name}</span>- <Pill kind="green">set</Pill>- </div>- ))}- </div>- )}- <div className="tramo-secret-add">- <div className="form-group">- <Label>Name</Label>- <Input- type="text"- value={newSecret.name}- placeholder="TELEGRAM_BOT_TOKEN"- onChange={(e) => setNewSecret((s) => ({ ...s, name: e.target.value }))}- />- </div>- <div className="form-group">- <Label>Value</Label>- <Input- type="password"- value={newSecret.value}- onChange={(e) => setNewSecret((s) => ({ ...s, value: e.target.value }))}- />- </div>- <Button variant="default" size="sm" onClick={handleAddSecret} disabled={busy}>- <Plus size={14} /> Add secret- </Button>- </div>- </div>- </div>- );-- return (- <div className="settings-layout tramo-settings-layout">- <nav className="settings-nav">- {SETTINGS_SECTIONS.map(({ id, label, Icon }) => (- <Button- key={id}- variant="ghost"- className={`settings-nav-item ${settingsSection === id ? 'active' : ''}`}- onClick={() => setSettingsSection(id)}- >- <Icon size={18} /> {label}- </Button>- ))}- </nav>- <div className="settings-content">- {settingsSection === 'engine' && engineCard}- {settingsSection === 'general' && generalCard}- {settingsSection === 'secrets' && secretsCard}- </div>- </div>- );- };-- const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));-- // Actions live in the topbar (like Domains / WordPress) and are contextual- // to the active tab, so the content area carries no second header row.- let topbarActions = null;- if (activeTab === 'workflows') {- topbarActions = (- <>- <Button variant="outline" size="sm" onClick={handleDeploy} disabled={busy}>- <Rocket size={14} /> Deploy- </Button>- <Button variant="default" size="sm" onClick={openNewModal}>- <Plus size={14} /> New workflow- </Button>- </>- );- } else if (activeTab === 'templates') {- topbarActions = (- <Button variant="default" size="sm" onClick={openImportModal}>- <Upload size={14} /> Import template- </Button>- );- } else if (activeTab === 'runs') {- topbarActions = (- <Button variant="outline" size="sm" onClick={loadRuns} disabled={runsLoading}>- <RefreshCw size={14} /> Refresh- </Button>- );- } else if (activeTab === 'settings') {- topbarActions = (- <Button variant="outline" size="sm" onClick={loadSettings} disabled={settingsLoading}>- <RefreshCw size={14} /> Refresh- </Button>- );- }-- return (- <div className="page-container page-container--full-bleed sk-tabgroup tramo-page">- <PageTopbar- icon={<Workflow size={18} />}- title="Automations"- tabs={topbarTabs}- actions={topbarActions}- />-- <div className="sk-tabgroup__content">- <div className="sk-tabgroup__inner">- {activeTab === 'workflows' && renderWorkflows()}- {activeTab === 'templates' && renderTemplates()}- {activeTab === 'runs' && renderRuns()}- {activeTab === 'settings' && renderSettings()}- </div>- </div>-- {/* New workflow modal — two-column: explainer + name/trigger picker */}- <Modal- open={newModal}- onClose={() => setNewModal(false)}- title="Create an automation"- size="2xl"- className="tramo-newflow-modal"- footer={(- <>- <Button variant="outline" onClick={() => setNewModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleCreate} disabled={busy || !newName.trim()}>- <Plus size={14} /> Create- </Button>- </>- )}- >- <div className="tramo-newflow">- <aside className="tramo-newflow__hero">- <span className="tramo-newflow__hero-badge"><Workflow size={26} /></span>- <div className="tramo-newflow__hero-diagram" aria-hidden="true">- <span className="tramo-newflow__hero-node"><Zap size={15} /></span>- <span className="tramo-newflow__hero-line" />- <span className="tramo-newflow__hero-node"><Workflow size={15} /></span>- <span className="tramo-newflow__hero-line" />- <span className="tramo-newflow__hero-node"><Send size={15} /></span>- </div>- <h3 className="tramo-newflow__hero-title">Automate the boring parts</h3>- <p className="tramo-newflow__hero-text">- Chain triggers and actions on a visual canvas that runs headless- on the tramo engine. Pick a starting trigger below, then design- the rest in the editor.- </p>- <ul className="tramo-newflow__hero-list">- <li>Message yourself on Telegram when a backup fails</li>- <li>Open a GitHub issue on a nightly health check</li>- <li>Relay any panel event to a Discord channel</li>- </ul>- </aside>-- <div className="tramo-newflow__form">- <div className="form-group">- <Label>Automation name</Label>- <Input- type="text"- value={newName}- autoFocus- placeholder="Notify me when a backup fails"- onChange={(e) => setNewName(e.target.value)}- onKeyDown={(e) => { if (e.key === 'Enter' && newName.trim()) handleCreate(); }}- />- </div>-- <div className="tramo-newflow__triggers">- <span className="tramo-newflow__triggers-label">How should it start?</span>- <div className="tramo-trigger-list" role="radiogroup" aria-label="Trigger">- {TRIGGERS.map((tr) => {- const { Icon } = tr;- const selected = newTrigger === tr.id;- return (- <button- type="button"- key={tr.id}- role="radio"- aria-checked={selected}- className={`tramo-trigger${selected ? ' is-selected' : ''}`}- onClick={() => setNewTrigger(tr.id)}- >- <span className="tramo-trigger__icon"><Icon size={18} /></span>- <span className="tramo-trigger__body">- <span className="tramo-trigger__title">{tr.title}</span>- <span className="tramo-trigger__sub">{tr.subtitle}</span>- </span>- <span className="tramo-trigger__check">- {selected && <Check size={15} />}- </span>- </button>- );- })}- </div>- </div>- </div>- </div>- </Modal>-- {/* Import template / workflow modal */}- <Modal- open={importModal}- onClose={() => setImportModal(false)}- title="Import a template"- size="lg"- footer={(- <>- <Button variant="outline" onClick={() => setImportModal(false)}>Cancel</Button>- <Button variant="default" onClick={handleImport} disabled={busy || !importText.trim()}>- <Upload size={14} /> Import- </Button>- </>- )}- >- <p className="tramo-tpl-intro">- Paste a tramo workflow document (JSON), or load one from a file. It is- created as a new automation you can edit and deploy.- </p>- <div className="form-group">- <Label>Name (optional)</Label>- <Input- type="text"- value={importName}- placeholder="My imported automation"- onChange={(e) => setImportName(e.target.value)}- />- </div>- <div className="form-group">- <div className="tramo-import__labelrow">- <Label>Workflow JSON</Label>- <label className="tramo-import__file">- <FileJson size={14} /> Load file- <input type="file" accept="application/json,.json" onChange={handleImportFile} hidden />- </label>- </div>- <textarea- className="tramo-import__text"- value={importText}- placeholder={'{\n "name": "My flow",\n "nodes": [],\n "edges": []\n}'}- onChange={(e) => setImportText(e.target.value)}- spellCheck={false}- />- </div>- </Modal>-- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-};--export { AutomationsPage };-export default AutomationsPage;diff --git a/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsx b/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsxdeleted file mode 100644index 3801d659..00000000--- a/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsx+++ /dev/null@@ -1,67 +0,0 @@-// TramoEditor — the heavy editor chunk.-//-// Everything tramo-visual lives behind this module so it code-splits away from-// the panel entry bundle. AutomationEditorPage React.lazy()-imports it; nothing-// on the entry path may import this file (or tramo/react / tramo/styles.css)-// statically, or the split collapses.-import { useEffect } from 'react';-import { Canvas, RightRail, useWorkflow } from 'tramo/react';-import api from '@/services/api';-import EmptyState from '@/components/EmptyState';-import { registry } from '../registry.js';--// tramo's own canvas + inspector CSS. Imported here (inside the lazy chunk) so-// it ships with the editor, not the entry bundle.-import 'tramo/styles.css';--const TramoEditor = ({ slug, onSaveStateChange }) => {- const handle = useWorkflow({- registry,- key: slug,- loadDoc: async () => {- const data = await api.request(`/tramo/workflows/${slug}`);- const doc = data.doc || { version: 1, id: slug, name: slug, nodes: [], edges: [], meta: {} };- // The editor's Canvas reads `doc.meta.mcpServers` unconditionally, so a- // doc without `meta` crashes it. Guarantee `meta` for brand-new- // workflows and any doc persisted by an older version.- if (!doc.meta) doc.meta = {};- return doc;- },- saveDoc: async (doc) => {- await api.request(`/tramo/workflows/${slug}`, { method: 'PUT', body: { doc } });- },- });-- // Surface the debounced save lifecycle up to the page's top strip.- useEffect(() => {- if (onSaveStateChange) onSaveStateChange(handle.saveState);- }, [handle.saveState, onSaveStateChange]);-- if (!handle.ready) {- return (- <div className="tramo-editor__loading">- <EmptyState loading title="Loading workflow..." />- </div>- );- }-- return (- <div className="tramo-editor">- <div className="tramo-editor__canvas">- <Canvas workflow={handle} />- </div>- <div className="tramo-editor__rail">- <RightRail- selection={handle.selection}- registry={handle.registry}- onApply={handle.applyPatch}- onClose={handle.clearSelection}- saveState={handle.saveState}- doc={handle.doc}- />- </div>- </div>- );-};--export default TramoEditor;diff --git a/frontend/src/plugins/serverkit-tramo/index.jsx b/frontend/src/plugins/serverkit-tramo/index.jsxdeleted file mode 100644index 12933af4..00000000--- a/frontend/src/plugins/serverkit-tramo/index.jsx+++ /dev/null@@ -1,12 +0,0 @@-// Automations (tramo) UI, contributed through the extension system. Fully-// self-contained in the extension. After sync this folder lives at-// frontend/src/plugins/serverkit-tramo/, so '@/…' host aliases resolve.-//-// plugin.json declares two route components — AutomationsPage (the tabbed-// list/runs/settings surface) and AutomationEditorPage (the full-bleed canvas).-// Both are resolved by name from these exports.-export { AutomationsPage } from './components/AutomationsPage.jsx';-export { AutomationEditorPage } from './components/AutomationEditorPage.jsx';--// No default export on purpose: PluginLoader legacy-auto-renders any plugin-// default export globally. The route contributions resolve the NAMED exports.diff --git a/frontend/src/plugins/serverkit-tramo/plugin.json b/frontend/src/plugins/serverkit-tramo/plugin.jsondeleted file mode 100644index b60b5eb3..00000000--- a/frontend/src/plugins/serverkit-tramo/plugin.json+++ /dev/null@@ -1,86 +0,0 @@-{- "name": "serverkit-tramo",- "display_name": "Automations",- "version": "1.0.0",- "description": "Node-based automation builder powered by tramo. Design workflows on a visual canvas (triggers, actions, branches, loops, approval gates) that react to panel events or run on a schedule, with 21 brand integration packs (Telegram, GitHub, Gmail, Discord, Notion, Stripe, Cloudflare, Postgres, Twilio and more). Enabled workflows deploy to a managed tramo container on the panel host that runs them headless, with run history, approvals, and inbound webhooks proxied through the panel. This replaces the older drag-and-drop Workflow Builder.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "featured": true,- "feature_score": 90,- "permissions": [- "docker",- "shell",- "filesystem",- "network"- ],- "min_panel_version": "1.7.0",- "entry_point": "tramo:tramo_bp",- "url_prefix": "/api/v1/tramo",- "models": "models:register",- "lifecycle": {- "install": "lifecycle:on_install",- "uninstall": "lifecycle:on_uninstall"- },- "jobs": [- {- "kind": "tramo.harvest_runs",- "handler": "jobs:harvest_runs"- },- {- "kind": "tramo.health_check",- "handler": "jobs:health_check"- }- ],- "schedules": [- {- "name": "tramo-harvest-runs",- "kind": "tramo.harvest_runs",- "interval_seconds": 120- },- {- "name": "tramo-health-check",- "kind": "tramo.health_check",- "interval_seconds": 300- }- ],- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>",- "contributions": {- "nav": [- {- "id": "automations",- "label": "Automations",- "route": "/automations",- "category": "operations",- "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>"- }- ],- "routes": [- {- "path": "automations",- "component": "AutomationsPage"- },- {- "path": "automations/:tab",- "component": "AutomationsPage"- },- {- "path": "automations/edit/:slug",- "component": "AutomationEditorPage",- "layout": "full"- }- ],- "page_titles": {- "/automations": "Automations"- },- "command_palette": [- {- "label": "Automations",- "path": "/automations",- "category": "Pages",- "keywords": "automation workflow tramo trigger action schedule webhook telegram github integration pipeline event"- }- ]- }-}diff --git a/frontend/src/plugins/serverkit-tramo/registry.js b/frontend/src/plugins/serverkit-tramo/registry.jsdeleted file mode 100644index 3a6cc291..00000000--- a/frontend/src/plugins/serverkit-tramo/registry.js+++ /dev/null@@ -1,69 +0,0 @@-// Node registry for the tramo editor.-//-// tramo ships its node definitions as "packs": the built-in pack plus one pack-// per brand integration. `combinePacks` merges them into a single registry of-// editor-side node definitions (`.nodes`) and runtime executors (`.executors`).-// The editor only needs `.nodes` — executors run server-side inside the managed-// tramo container, never in the browser.-//-// This module is imported by TramoEditor.jsx (the lazy chunk) so all of these-// integration packs code-split into the editor bundle and never reach the-// panel's entry bundle.-import { combinePacks, BUILTIN_PACK } from 'tramo/runtime';--import gmail from 'tramo/integrations/gmail';-import github from 'tramo/integrations/github';-import telegram from 'tramo/integrations/telegram';-import discord from 'tramo/integrations/discord';-import notion from 'tramo/integrations/notion';-import openai from 'tramo/integrations/openai';-import anthropic from 'tramo/integrations/anthropic';-import linear from 'tramo/integrations/linear';-import airtable from 'tramo/integrations/airtable';-import stripe from 'tramo/integrations/stripe';-import cloudflare from 'tramo/integrations/cloudflare';-import googleDrive from 'tramo/integrations/google-drive';-import googleSheets from 'tramo/integrations/google-sheets';-import googleTasks from 'tramo/integrations/google-tasks';-import outlook from 'tramo/integrations/outlook';-import postgres from 'tramo/integrations/postgres';-import twilio from 'tramo/integrations/twilio';-import youtube from 'tramo/integrations/youtube';-import x from 'tramo/integrations/x';-import trello from 'tramo/integrations/trello';-import box from 'tramo/integrations/box';--// TODO(plan45): add SERVERKIT_PACK once @tramo/serverkit is published. Its-// executors run server-side; the editor only needs its node definitions here.--// Order matters only for the palette; combinePacks throws on id collisions, so-// the brand packs are all distinct by construction.-export const combined = combinePacks([- BUILTIN_PACK,- gmail,- github,- telegram,- discord,- notion,- openai,- anthropic,- linear,- airtable,- stripe,- cloudflare,- googleDrive,- googleSheets,- googleTasks,- outlook,- postgres,- twilio,- youtube,- x,- trello,- box,-]);--// The editor-side registry of node definitions. Pass straight to useWorkflow.-export const registry = combined.nodes;--export default registry;diff --git a/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scss b/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scssdeleted file mode 100644index d3def94e..00000000--- a/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scss+++ /dev/null@@ -1,747 +0,0 @@-/* Automations (tramo) extension — layout-only styles. Colours, typography,- spacing and controls all inherit from the host design system (card,- sk-dtable, sk-info-row, Pill, empty-state, form controls). Plugin SCSS is- compiled in isolation, so we lean on CSS custom properties (var(--…)) and- neutral rgba tints — never SCSS $variables, which aren't in scope here.- We never restyle tramo's own .tr-* classes; the editor owns those. */--.tramo-page {- .tramo-toolbar {- display: flex;- align-items: center;- gap: 8px;- flex-wrap: wrap;- }-- .tramo-row-actions {- display: flex;- flex-wrap: wrap;- gap: 6px;- justify-content: flex-end;- }-- .tramo-truncate {- max-width: 280px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- /* Pending-approval strip */- .tramo-approvals {- margin-bottom: 16px;- }-- .tramo-approval {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 10px 0;- border-bottom: 1px solid rgba(128, 128, 128, 0.16);-- &:last-child {- border-bottom: 0;- }-- &__info {- display: flex;- flex-direction: column;- gap: 2px;- min-width: 0;- }- }-- /* Unsupported / Docker-required note */- .tramo-note {- margin-top: 14px;- padding: 12px 14px;- border-radius: var(--radius, 8px);- border: 1px solid rgba(234, 179, 8, 0.35);- background: rgba(234, 179, 8, 0.08);- font-size: 13px;- line-height: 1.5;-- &__detail {- margin-top: 8px;- font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);- font-size: 12px;- opacity: 0.75;- word-break: break-word;- }- }-- /* Engine host actions */- .tramo-host-actions {- display: flex;- align-items: flex-end;- flex-wrap: wrap;- gap: 8px;- margin-top: 16px;- }-- .tramo-install {- display: flex;- align-items: flex-end;- gap: 8px;-- .form-group {- margin: 0;- min-width: 180px;- }- }-- /* Settings fields */- .tramo-settings {- display: flex;- flex-direction: column;- gap: 4px;- }-- .tramo-field {- display: flex;- align-items: center;- justify-content: space-between;- gap: 16px;- padding: 12px 0;- border-bottom: 1px solid rgba(128, 128, 128, 0.14);-- &:last-child {- border-bottom: 0;- }-- &__label {- min-width: 0;-- p {- margin: 2px 0 0;- }- }-- &__control {- display: flex;- align-items: center;- gap: 8px;-- input {- width: 140px;- }- }- }-- /* Pack secrets */- .tramo-secret-list {- display: flex;- flex-direction: column;- gap: 6px;- margin: 12px 0;- }-- .tramo-secret {- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 8px 12px;- border-radius: var(--radius-sm, 6px);- background: rgba(128, 128, 128, 0.06);- }-- .tramo-secret-add {- display: flex;- align-items: flex-end;- gap: 8px;- flex-wrap: wrap;- margin-top: 12px;- padding-top: 12px;- border-top: 1px solid rgba(128, 128, 128, 0.14);-- .form-group {- margin: 0;- min-width: 200px;- flex: 1;- }- }-- /* Enable toggle (also used in the settings events-bridge field) */- .tramo-toggle {- --tramo-toggle-w: 38px;- --tramo-toggle-h: 22px;- position: relative;- width: var(--tramo-toggle-w);- height: var(--tramo-toggle-h);- border-radius: 999px;- border: 0;- cursor: pointer;- padding: 0;- background: rgba(128, 128, 128, 0.35);- transition: background 0.15s ease;-- &__knob {- position: absolute;- top: 2px;- left: 2px;- width: calc(var(--tramo-toggle-h) - 4px);- height: calc(var(--tramo-toggle-h) - 4px);- border-radius: 50%;- background: #fff;- transition: transform 0.15s ease;- }-- &--on {- background: var(--accent-bright, #3b82f6);-- .tramo-toggle__knob {- transform: translateX(calc(var(--tramo-toggle-w) - var(--tramo-toggle-h)));- }- }-- &:disabled {- opacity: 0.5;- cursor: not-allowed;- }- }--}--/* Template picker lives inside a <Modal>, which portals to <body> -- OUTSIDE the- .tramo-page subtree -- so these rules must be top-level, not nested under- .tramo-page, or they never match the portaled DOM. */-.tramo-tpl-intro {- margin: 0 0 14px;- font-size: 13px;- line-height: 1.5;- opacity: 0.7;-}--/* Templates marketplace tab (page content) + Import modal (portaled). Kept at- top level so the portaled Import modal picks these up too. */-.tramo-templates {- display: flex;- flex-direction: column;- gap: 16px;-- &__bar {- display: flex;- align-items: center;- gap: 12px;- }-- &__count {- font-size: 12px;- opacity: 0.6;- white-space: nowrap;- }-}--.tramo-search {- display: flex;- align-items: center;- gap: 8px;- flex: 1;- max-width: 340px;- padding: 8px 12px;- border-radius: 9px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-elevated, rgba(128, 128, 128, 0.04));-- svg { flex-shrink: 0; opacity: 0.55; }-- input {- flex: 1;- min-width: 0;- border: 0;- outline: 0;- background: transparent;- color: inherit;- font-size: 13px;-- &::placeholder { opacity: 0.5; }- }-}--.tramo-tpl-grid {- display: grid;- grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));- gap: 14px;-}--.tramo-card {- display: flex;- flex-direction: column;- gap: 10px;- padding: 16px;- border-radius: 14px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.22));- background: var(--bg-card, rgba(128, 128, 128, 0.03));- transition: border-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;-- &:hover {- border-color: rgba(99, 102, 241, 0.4);- transform: translateY(-2px);- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);- }-- &__top {- display: flex;- align-items: flex-start;- justify-content: space-between;- }-- &__icon {- width: 42px;- height: 42px;- border-radius: 11px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.16);- color: var(--accent-bright, #818cf8);-- &--telegram { background: rgba(42, 171, 238, 0.16); color: #2aabee; }- &--github { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }- &--discord { background: rgba(88, 101, 242, 0.16); color: #7c86f5; }- }-- &__fav {- display: grid;- place-items: center;- width: 30px;- height: 30px;- border-radius: 8px;- border: 0;- background: transparent;- color: inherit;- opacity: 0.4;- cursor: pointer;- transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease;-- &:hover { opacity: 0.85; background: rgba(128, 128, 128, 0.12); }-- &.is-fav {- opacity: 1;- color: #f5b301;-- svg { fill: #f5b301; }- }- }-- &__name {- margin: 0;- font-size: 14px;- font-weight: 600;- line-height: 1.3;- }-- &__desc {- margin: 0;- flex: 1;- font-size: 12.5px;- line-height: 1.45;- opacity: 0.68;- }-- &__tags {- display: flex;- flex-wrap: wrap;- gap: 6px;- }-- &__tag {- font-size: 11px;- font-weight: 500;- padding: 2px 9px;- border-radius: 999px;- background: rgba(128, 128, 128, 0.16);- opacity: 0.9;- }-- &__foot {- display: flex;- margin-top: auto;- padding-top: 4px;-- > button { width: 100%; justify-content: center; }- }-}--/* Import modal */-.tramo-import__labelrow {- display: flex;- align-items: center;- justify-content: space-between;- margin-bottom: 6px;-}--.tramo-import__file {- display: inline-flex;- align-items: center;- gap: 6px;- font-size: 12px;- padding: 4px 10px;- border-radius: 7px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- cursor: pointer;- opacity: 0.85;-- &:hover { opacity: 1; border-color: var(--accent-bright, #6366f1); }-}--.tramo-import__text {- width: 100%;- min-height: 200px;- resize: vertical;- padding: 12px 14px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.3));- background: var(--bg-elevated, rgba(128, 128, 128, 0.05));- color: inherit;- font-family: var(--font-mono, ui-monospace, monospace);- font-size: 12.5px;- line-height: 1.5;-- &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }- &::placeholder { opacity: 0.4; }-}--/* New-automation two-column modal (portaled -> top-level scope). Kill the modal- body padding so the hero panel can bleed to the dialog edges. */-.tramo-newflow-modal .sk-modal__body { padding: 0; }--.tramo-newflow {- display: grid;- grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr);- min-height: 430px;-}--.tramo-newflow__hero {- padding: 28px 26px;- display: flex;- flex-direction: column;- gap: 14px;- background: linear-gradient(160deg, rgba(99, 102, 241, 0.12), rgba(99, 102, 241, 0.02));- border-right: 1px solid var(--border, rgba(128, 128, 128, 0.18));-- &-badge {- width: 52px;- height: 52px;- border-radius: 14px;- display: grid;- place-items: center;- background: rgba(99, 102, 241, 0.16);- color: var(--accent-bright, #818cf8);- }-- &-diagram {- display: flex;- align-items: center;- gap: 6px;- margin: 2px 0 4px;- }-- &-node {- flex-shrink: 0;- width: 30px;- height: 30px;- border-radius: 8px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.16);- color: var(--accent-bright, #818cf8);- }-- &-line {- flex: 1;- max-width: 24px;- height: 2px;- border-radius: 2px;- background: rgba(128, 128, 128, 0.35);- }-- &-title {- margin: 0;- font-size: 15px;- font-weight: 600;- }-- &-text {- margin: 0;- font-size: 12.5px;- line-height: 1.5;- opacity: 0.72;- }-- &-list {- margin: 6px 0 0;- padding: 0;- list-style: none;- display: flex;- flex-direction: column;- gap: 9px;-- li {- position: relative;- padding-left: 20px;- font-size: 12px;- line-height: 1.4;- opacity: 0.78;-- &::before {- content: '';- position: absolute;- left: 4px;- top: 6px;- width: 6px;- height: 6px;- border-radius: 50%;- background: var(--accent-bright, #818cf8);- }- }- }-}--.tramo-newflow__form {- padding: 24px 26px;- display: flex;- flex-direction: column;- gap: 18px;-}--.tramo-newflow__triggers {- display: flex;- flex-direction: column;- gap: 10px;-- &-label {- font-size: 11px;- font-weight: 600;- letter-spacing: 0.04em;- text-transform: uppercase;- opacity: 0.6;- }-}--.tramo-trigger-list {- display: flex;- flex-direction: column;- gap: 8px;-}--.tramo-trigger {- display: flex;- align-items: center;- gap: 12px;- width: 100%;- text-align: left;- padding: 11px 13px;- border-radius: 10px;- border: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: transparent;- color: inherit;- cursor: pointer;- transition: border-color 0.15s ease, background 0.15s ease;-- &:hover {- border-color: rgba(99, 102, 241, 0.5);- background: rgba(99, 102, 241, 0.04);- }-- &.is-selected {- border-color: var(--accent-bright, #6366f1);- background: rgba(99, 102, 241, 0.09);- }-- &__icon {- flex-shrink: 0;- width: 34px;- height: 34px;- border-radius: 9px;- display: grid;- place-items: center;- background: rgba(128, 128, 128, 0.14);- color: var(--accent-bright, #818cf8);- }-- &__body {- flex: 1;- min-width: 0;- display: flex;- flex-direction: column;- gap: 2px;- }-- &__title {- font-weight: 600;- font-size: 13.5px;- }-- &__sub {- font-size: 12px;- line-height: 1.35;- opacity: 0.65;- }-- &__check {- flex-shrink: 0;- width: 20px;- height: 20px;- border-radius: 50%;- display: grid;- place-items: center;- border: 1.5px solid var(--border, rgba(128, 128, 128, 0.45));- color: #fff;- }-- &.is-selected &__check {- background: var(--accent-bright, #6366f1);- border-color: var(--accent-bright, #6366f1);- }-}--@media (max-width: 640px) {- .tramo-newflow {- grid-template-columns: 1fr;- min-height: 0;- }-- .tramo-newflow__hero {- display: none;- }-}--/* ── Full-bleed editor page (route automations/edit/:slug, layout "full") ── */-.tramo-editor-page {- height: 100%;- min-height: 0;- display: flex;- flex-direction: column;- background: var(--bg-body, transparent);-- &__bar {- flex-shrink: 0;- display: flex;- align-items: center;- justify-content: space-between;- gap: 12px;- padding: 10px 16px;- border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-card, transparent);- }-- &__left {- display: flex;- align-items: center;- gap: 12px;- min-width: 0;- }-- &__title {- display: flex;- align-items: center;- gap: 8px;- min-width: 0;- }-- &__name {- font-weight: 600;- font-size: 15px;- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;- max-width: 320px;- }-- &__actions {- display: flex;- align-items: center;- gap: 8px;- flex-shrink: 0;- }-- &__body {- flex: 1;- min-height: 0;- position: relative;- }-}--/* Save-state indicator in the editor top strip */-.tramo-save {- display: inline-flex;- align-items: center;- gap: 5px;- font-size: 12.5px;-- &--busy { color: var(--text-dim, #9aa0a6); }- &--ok { color: var(--green, #22c55e); }- &--err { color: var(--red, #ef4444); }- &--idle { color: var(--text-dim, #9aa0a6); opacity: 0.7; }-}--.tramo-spin {- animation: tramo-spin 0.9s linear infinite;-}--@keyframes tramo-spin {- to { transform: rotate(360deg); }-}--@media (prefers-reduced-motion: reduce) {- .tramo-spin { animation: none; }-}--/* ── Editor composition: canvas fills, inspector rail is fixed-width ── */-.tramo-editor {- position: absolute;- inset: 0;- display: flex;- min-height: 0;-- /* Theme bridge — tramo's editor ships only a light `:root` palette- (--tr-*). We don't restyle its .tr-* classes; we feed its documented- colour variables from the host design tokens instead. Because custom- properties inherit down the DOM, defining them here (an ancestor of the- whole editor subtree) overrides tramo's :root values without any- specificity battle — and since the host tokens flip with data-theme,- the canvas + inspector track dark/light automatically. */- --tr-bg: var(--bg-body);- --tr-surface: var(--bg-card);- --tr-surface-alt: var(--bg-hover);- --tr-border: var(--border-default);- --tr-border-strong: var(--border-strong);- --tr-text: var(--text-primary);- --tr-text-muted: var(--text-secondary);- --tr-edge: var(--border-strong);- --tr-plus: var(--text-tertiary);- --tr-accent: var(--accent);- --tr-accent-soft: var(--accent-bg);- --tr-shadow: 0 1px 2px rgba(0, 0, 0, 0.28), 0 4px 12px rgba(0, 0, 0, 0.22);-- &__canvas {- position: relative;- flex: 1;- min-width: 0;- min-height: 0;- overflow: hidden;- }-- &__rail {- flex-shrink: 0;- width: 340px;- min-height: 0;- overflow-y: auto;- border-left: 1px solid var(--border, rgba(128, 128, 128, 0.25));- background: var(--bg-card, transparent);- }-- &__loading {- position: absolute;- inset: 0;- display: flex;- align-items: center;- justify-content: center;- }-- @media (max-width: 768px) {- &__rail { width: 260px; }- }-}diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 16d3ec87..20758659 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -138,7 +138,6 @@@import 'pages/_style-guide';@import 'pages/_app-map';@import 'pages/_secrets';-@import 'pages/_gpu';@import 'pages/_queue-operations';@import 'pages/_telemetry';@import 'pages/_jobs';diff --git a/frontend/src/styles/pages/_gpu.scss b/frontend/src/styles/pages/_gpu.scssdeleted file mode 100644index 01e4f59a..00000000--- a/frontend/src/styles/pages/_gpu.scss+++ /dev/null@@ -1,150 +0,0 @@-// GPU Monitor page styles--.gpu-page {- &__loading {- display: flex;- justify-content: center;- padding: $spacing-xl 0;- }-- // Per-GPU meter cards now lay out via <KpiBand> (grid/spacing/responsive- // collapse); the .gpu-card internals below stay as custom live-meter tiles- // (Plan 20 Decision 5).-}--.gpu-card {- background: var(--surface);- border: 1px solid var(--border-soft);- border-radius: var(--radius);- padding: $spacing-lg;- display: flex;- flex-direction: column;- gap: $spacing-md;-- &__head {- display: flex;- align-items: center;- justify-content: space-between;- gap: $spacing-sm;- }-- &__title {- display: inline-flex;- align-items: center;- gap: $spacing-sm;- min-width: 0;-- svg { color: var(--accent-bright); flex-shrink: 0; }- }-- &__name {- font-weight: $font-weight-semibold;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- &__index {- font-family: var(--mono);- font-size: 12px;- color: var(--text-faint);- }-- &__bars {- display: flex;- flex-direction: column;- gap: $spacing-md;- }-}--.gpu-bar {- &__head {- display: flex;- align-items: center;- justify-content: space-between;- margin-bottom: 6px;- }-- &__label {- font-size: 12.5px;- color: var(--text-dim);- }-- &__value {- font-family: var(--mono);- font-size: 12px;- color: var(--text);- }-- &__track {- height: 6px;- background: var(--surface-3);- border-radius: 3px;- overflow: hidden;- }-- &__fill {- display: block;- height: 100%;- border-radius: 3px;- transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);- background: var(--accent-bright);-- &.is-green { background: var(--green); }- &.is-amber { background: var(--amber); }- &.is-red { background: var(--red); }- }-}--.gpu-stats {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: $spacing-sm;- padding-top: $spacing-md;- border-top: 1px solid var(--border-soft);-}--.gpu-stat {- display: inline-flex;- align-items: center;- gap: 6px;- font-size: 13px;-- svg { color: var(--text-faint); flex-shrink: 0; }-- &__label {- color: var(--text-faint);- margin-right: auto;- }-- &__value {- font-family: var(--mono);- font-size: 12.5px;- color: var(--text);- }-- &__sub {- color: var(--text-faint);- }-}--.gpu-procs {- margin-top: $spacing-lg;- background: var(--surface);- border: 1px solid var(--border-soft);- border-radius: var(--radius);- padding: $spacing-lg;-- &__head {- display: flex;- align-items: baseline;- justify-content: space-between;- margin-bottom: $spacing-md;-- h2 { margin: 0; font-size: 1rem; }- }-- &__table {- width: 100%;- }-}diff --git a/scripts/build-analytics-tracker.mjs b/scripts/build-analytics-tracker.mjsdeleted file mode 100644index 9ed6361f..00000000--- a/scripts/build-analytics-tracker.mjs+++ /dev/null@@ -1,70 +0,0 @@-#!/usr/bin/env node-/**- * Build the serverkit-analytics tracker artifact.- *- * node scripts/build-analytics-tracker.mjs # build sk.min.js- * node scripts/build-analytics-tracker.mjs --check # fail (exit 1) on drift- *- * Reads the readable source- * builtin-extensions/serverkit-analytics/backend/tracker/sk.js- * and writes the served artifact- * builtin-extensions/serverkit-analytics/backend/tracker/sk.min.js- * (the backend serves it at GET /api/v1/analytics/tracker.js).- *- * Dependency-free, conservative minification: strip block comments, drop- * full-line `//` comments, trim per-line whitespace, drop blank lines. Newlines- * between statements are KEPT so ASI can't break. The source is authored to make- * this safe (no block-comment tokens inside strings/regex, no inline `//`).- */-import { promises as fs } from 'fs';-import path from 'path';-import { fileURLToPath } from 'url';--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const ROOT = path.resolve(__dirname, '..');-const DIR = path.join(ROOT, 'builtin-extensions', 'serverkit-analytics',- 'backend', 'tracker');-const SRC = path.join(DIR, 'sk.js');-const OUT = path.join(DIR, 'sk.min.js');--const CHECK = process.argv.includes('--check');--function minify(src) {- // Remove /* ... */ block comments (source avoids these tokens elsewhere).- let out = src.replace(/\/\*[\s\S]*?\*\//g, '');- const lines = out.split('\n')- .map((l) => l.trim())- .filter((l) => l.length && !l.startsWith('//'));- return lines.join('\n') + '\n';-}--async function main() {- const src = await fs.readFile(SRC, 'utf8');- const built = minify(src);-- if (built.includes('/*') || built.includes('*/')) {- console.error('Refusing to write: comment tokens survived minification.');- process.exit(1);- }- const bytes = Buffer.byteLength(built, 'utf8');-- if (CHECK) {- let current = null;- try { current = await fs.readFile(OUT, 'utf8'); } catch { /* missing */ }- if (current !== built) {- console.error('Tracker artifact drift: sk.min.js is out of date.\n'- + 'Run: node scripts/build-analytics-tracker.mjs and commit it.');- process.exit(1);- }- console.log(`sk.min.js in sync (${bytes} bytes).`);- return;- }-- await fs.writeFile(OUT, built);- console.log(`Built sk.min.js (${bytes} bytes, ${(bytes / 1024).toFixed(1)} KB).`);- if (bytes > 4096) {- console.warn('Warning: tracker exceeds the 4 KB budget.');- }-}--main().catch((e) => { console.error(e); process.exit(1); });