ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(extensions): CrowdSec integration extension
Juan Denisce6d0b11fbf1
diff --git a/backend/tests/test_crowdsec_extension.py b/backend/tests/test_crowdsec_extension.pynew file mode 100644index 00000000..e77c4e9e--- /dev/null+++ b/backend/tests/test_crowdsec_extension.py@@ -0,0 +1,427 @@+"""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/builtin-extensions/serverkit-crowdsec/backend/__init__.py b/builtin-extensions/serverkit-crowdsec/backend/__init__.pynew file mode 100644index 00000000..9d503ce7--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/backend/__init__.py@@ -0,0 +1 @@+"""ServerKit CrowdSec extension backend package."""diff --git a/builtin-extensions/serverkit-crowdsec/backend/crowdsec.py b/builtin-extensions/serverkit-crowdsec/backend/crowdsec.pynew file mode 100644index 00000000..fbf82544--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/backend/crowdsec.py@@ -0,0 +1,205 @@+"""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.pynew file mode 100644index 00000000..e5e9ce08--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/backend/crowdsec_service.py@@ -0,0 +1,343 @@+"""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.jsxnew file mode 100644index 00000000..3e0c9379--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/frontend/components/CrowdSecPage.jsx@@ -0,0 +1,566 @@+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.jsxnew file mode 100644index 00000000..09905699--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/frontend/index.jsx@@ -0,0 +1,8 @@+// 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.cssnew file mode 100644index 00000000..0d110e6c--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/frontend/styles/crowdsec.css@@ -0,0 +1,53 @@+/* 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.jsonnew file mode 100644index 00000000..082a3695--- /dev/null+++ b/builtin-extensions/serverkit-crowdsec/plugin.json@@ -0,0 +1,40 @@+{+ "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"+ }+ ]+ }+}