From a4d2ea37ef5b0abcfb56505f1305ffca2f9e8b5f Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 00:04:58 -0500 Subject: [PATCH 01/70] feat(agents): permission levels, signed report endpoint, health alerts Agent-reported monitor/protect/full level (never settable from the panel), POST /api/v1/agent/report for report-only agents, silence-based offline detection, service-check alerts via MetricAlert, a panel-side command gate, docs, and a demo seed script. Migration 112. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 9 + SECURITY.md | 6 + backend/app/agent_gateway.py | 5 +- backend/app/api/agent_poll.py | 4 +- backend/app/api/agent_report.py | 53 +++++ backend/app/api/servers.py | 8 + backend/app/api/servers_agents.py | 12 +- backend/app/core_blueprints.py | 1 + backend/app/jobs/builtin_handlers.py | 6 +- backend/app/models/metric_alert.py | 3 + backend/app/models/server.py | 17 ++ backend/app/services/agent_health_service.py | 223 ++++++++++++++++++ backend/app/services/agent_registry.py | 37 ++- backend/app/services/permission_levels.py | 56 +++++ .../app/services/server_timeline_service.py | 1 + .../versions/112_agent_permission_levels.py | 36 +++ backend/scripts/seed_permission_demo.py | 80 +++++++ backend/tests/test_agent_permission_levels.py | 208 ++++++++++++++++ backend/tests/test_core_blueprint_registry.py | 4 +- backend/tests/test_route_authz_static.py | 1 + backend/tests/test_route_authz_sweep.py | 1 + backend/tests/test_seed_permission_demo.py | 17 ++ docs/AGENT_PERMISSION_LEVELS.md | 81 +++++++ docs/API_SURFACE.md | 1 + docs/MIGRATION_INVENTORY.md | 2 +- docs/README.md | 1 + 26 files changed, 861 insertions(+), 12 deletions(-) create mode 100644 backend/app/api/agent_report.py create mode 100644 backend/app/services/agent_health_service.py create mode 100644 backend/app/services/permission_levels.py create mode 100644 backend/migrations/versions/112_agent_permission_levels.py create mode 100644 backend/scripts/seed_permission_demo.py create mode 100644 backend/tests/test_agent_permission_levels.py create mode 100644 backend/tests/test_seed_permission_demo.py create mode 100644 docs/AGENT_PERMISSION_LEVELS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e447d1f..6357b9da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,15 @@ release history; historical `agent-v*` tags are not panel releases. ### Added +- Agent permission levels (Monitor / Protect / Full), enforced by the agent and + reported to the panel. Adds a signed `POST /api/v1/agent/report` endpoint for + report-only Monitor agents, per-server level and service-check state (server + list badge and health, server detail panel), offline / service-down alerts + through the existing fleet alerts and notification channels, audited level + changes, and a panel-side command gate. The panel cannot set the level; it is + changed on the server with `serverkit-agent permissions set`. See + [docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md). Migration + 112. The Add Server commands now pass `--level` / `-Level`. - `GET /api/v1/servers` now accepts an API key (`X-API-Key`) carrying the `servers:read` scope, in addition to the usual JWT, so external tools can poll the server list read-only without a short-lived token. JWT callers are diff --git a/SECURITY.md b/SECURITY.md index 2c693641..a6c941f1 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -47,6 +47,12 @@ trust boundaries: (`system:exec`) and interactive PTY sessions are controlled by the agent's `Features.Exec` flag, which is **off by default**. Enable it only on servers where you intend the panel to run shell commands. +- **Permission levels bound what a compromised panel can do.** An agent runs as + Monitor (report-only, no inbound command channel), Protect (security allowlist + only) or Full. The level is read only from the agent's local config and can + only be changed on the server (`serverkit-agent permissions set`); the panel + records and audits the reported level but has no API to set it. See + [docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md). - **Transport & connection controls.** Agents authenticate to the panel with per-connection HMAC-SHA256 (with nonce/replay protection and a timestamp-skew check), and the panel enforces a per-server IP allowlist. Use `wss://` diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.py index cefc2de4..7dfb17fa 100644 --- a/backend/app/agent_gateway.py +++ b/backend/app/agent_gateway.py @@ -136,7 +136,10 @@ class AgentNamespace(Namespace): return metrics = data.get('metrics', {}) - agent_registry.ingest_agent_state(agent, metrics=metrics) + agent_registry.ingest_agent_state( + agent, metrics=metrics, + permission_level=data.get('permission_level'), + service_checks=data.get('service_checks')) emit('heartbeat_ack', {'type': 'heartbeat_ack'}) diff --git a/backend/app/api/agent_poll.py b/backend/app/api/agent_poll.py index e63f27bd..11451655 100644 --- a/backend/app/api/agent_poll.py +++ b/backend/app/api/agent_poll.py @@ -108,7 +108,9 @@ def poll(): # Shared transport-neutral ingest: capability # side-effects (e.g. tunnel reconcile) fire exactly as on the WS path. agent_registry.ingest_agent_state(agent, metrics=metrics, sysinfo=sysinfo, - capabilities=caps) + capabilities=caps, + permission_level=body.get('permission_level'), + service_checks=body.get('service_checks')) # Long-poll up to 25s for any queued command. Below the typical # tunnel idle-timeout (Cloudflare ~100s, ngrok ~60s) so we never diff --git a/backend/app/api/agent_report.py b/backend/app/api/agent_report.py new file mode 100644 index 00000000..870c74cd --- /dev/null +++ b/backend/app/api/agent_report.py @@ -0,0 +1,53 @@ +"""Monitor-mode agent report endpoint. + +``POST /api/v1/agent/report`` is the ONLY channel a monitor-level agent uses: +a signed, outbound-only HTTPS POST. The reply never carries commands. + +Auth (no JWT/CSRF; the HMAC is the credential): + X-Agent-Key: -> server looked up by its key prefix + X-Timestamp: -> |skew| <= 300s + X-Nonce: =32 chars> -> single use (TTL cache, 5 min) + X-Signature: hex(HMAC_SHA256(api_secret, ts + "." + nonce + "." + sha256hex(body))) +""" + +from flask import Blueprint, jsonify, request + +from app import limiter +from app.services import agent_health_service, permission_levels +from app.utils.ip_utils import is_ip_allowed + + +agent_report_bp = Blueprint('agent_report', __name__) + +MAX_BODY_BYTES = 64 * 1024 +MAX_SKEW_SECONDS = 300 + + +def _rate_key(): + return f"{request.remote_addr}:{(request.headers.get('X-Agent-Key') or '')[:12]}" + + +@agent_report_bp.route('/report', methods=['POST']) +@limiter.limit("30 per minute", key_func=_rate_key) +def report(): + if (request.content_length or 0) > MAX_BODY_BYTES: + return jsonify({'error': 'payload too large'}), 413 + raw = request.get_data(cache=True) + if len(raw) > MAX_BODY_BYTES: + return jsonify({'error': 'payload too large'}), 413 + + server = agent_health_service.authenticate_report(raw, request.headers, MAX_SKEW_SECONDS) + if not server: + return jsonify({'error': 'authentication failed'}), 401 + if server.allowed_ips and not is_ip_allowed(request.remote_addr, server.allowed_ips): + return jsonify({'error': 'IP not allowed'}), 403 + + body = request.get_json(silent=True) + if not isinstance(body, dict): + return jsonify({'error': 'JSON object required'}), 400 + level = body.get('permission_level') + if level not in permission_levels.LEVELS: + return jsonify({'error': 'permission_level must be monitor, protect or full'}), 400 + + interval = agent_health_service.ingest_report(server, level, body) + return jsonify({'ok': True, 'interval_seconds': interval}) diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index b1c81b8e..c935df8f 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -13,6 +13,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identity from sqlalchemy.orm import joinedload from app import db, limiter +from app.services import permission_levels from app.services.server_metrics_service import latest_metrics_by_server from app.api._query import apply_query, QueryParseError from app.api._request import json_object @@ -440,6 +441,8 @@ def create_server(): registered_by=user_id, workspace_id=ws_id, registration_token_expires=expires_at, + # What the install command asks for; the agent's report is the truth. + requested_permission_level=permission_levels.normalize(data.get('requested_level')), ) server.set_registration_token(registration_token) @@ -718,6 +721,7 @@ def regenerate_token(server_id): registration_token = Server.generate_registration_token() server.set_registration_token(registration_token) server.registration_token_expires = expires_at + server.requested_permission_level = permission_levels.normalize(data.get('requested_level')) server.status = 'pending' server.agent_id = None @@ -792,6 +796,10 @@ def register_agent(): server.total_disk = system_info.get('total_disk', server.total_disk) server.agent_version = data.get('agent_version') + # Level is whatever the agent says it was installed with; the panel never + # sets it. A mismatch with the requested level is surfaced in the UI. + from app.services import agent_health_service + agent_health_service.record_level(server, data.get('permission_level')) # Replace the panel-issued placeholder name with whatever the agent # reports — preferring the OS hostname over the agent's optional diff --git a/backend/app/api/servers_agents.py b/backend/app/api/servers_agents.py index db47e704..c9880829 100644 --- a/backend/app/api/servers_agents.py +++ b/backend/app/api/servers_agents.py @@ -5,6 +5,7 @@ import os import re import requests from app.models.server import AgentVersion, Server +from app.services import permission_levels from flask import Response, current_app, jsonify, redirect, request from app.middleware.rbac import admin_required, developer_required from app.exceptions import agent_offline, field_required @@ -178,8 +179,11 @@ def get_install_instructions(server_id): # Get base URL base_url = _get_external_base_url() api_url = f"{base_url}/api/v1/servers" + level = (permission_levels.normalize(request.args.get('level')) + or server.requested_permission_level or 'monitor') return jsonify({ + 'permission_level': level, 'linux': { # Download-then-run rather than `curl … | sudo bash`: in a pipeline # the shell reports bash's exit status, so a failed download exits 0 @@ -187,7 +191,7 @@ def get_install_instructions(server_id): 'one_liner': ( f'curl -fsSL {api_url}/install.sh -o /tmp/serverkit-agent-install.sh ' f'&& sudo bash /tmp/serverkit-agent-install.sh ' - f'--token "YOUR_TOKEN" --server "{base_url}"' + f'--token "YOUR_TOKEN" --server "{base_url}" --level {level}' ), 'manual': [ f'# Download the script', @@ -195,17 +199,17 @@ def get_install_instructions(server_id): f'chmod +x install.sh', f'', f'# Run installation', - f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}"' + f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}" --level {level}' ] }, 'windows': { - 'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}"', + 'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}', 'manual': [ f'# Download the script (run in PowerShell as Administrator)', f'Invoke-WebRequest -Uri "{api_url}/install.ps1" -OutFile install.ps1', f'', f'# Run installation', - f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}"' + f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}' ] }, 'note': 'Replace YOUR_TOKEN with the registration token shown in the UI' diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.py index 2e815888..4743fbdc 100644 --- a/backend/app/core_blueprints.py +++ b/backend/app/core_blueprints.py @@ -46,6 +46,7 @@ class BlueprintSpec: CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = ( BlueprintSpec('app.api.auth', 'auth_bp', '/api/v1/auth'), BlueprintSpec('app.api.agent_poll', 'agent_poll_bp', '/api/v1/agent'), + BlueprintSpec('app.api.agent_report', 'agent_report_bp', '/api/v1/agent'), BlueprintSpec('app.api.linked_panel', 'linked_panel_bp', '/api/v1/linked-panel'), BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/apps'), BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/services', name='services'), diff --git a/backend/app/jobs/builtin_handlers.py b/backend/app/jobs/builtin_handlers.py index ea0e1446..7708733a 100644 --- a/backend/app/jobs/builtin_handlers.py +++ b/backend/app/jobs/builtin_handlers.py @@ -534,7 +534,7 @@ def _notify_fleet_alerts(opened, resolved): 'metric': alert.metric, 'value': alert.value, 'threshold': alert.threshold, - 'message': ( + 'message': alert.detail or ( f'{hostname}: {alert.metric} averaged {alert.value} over ' f'{alert.duration_seconds}s, past the ' f'{alert.severity} threshold of {alert.threshold}.'), @@ -555,7 +555,9 @@ def _notify_fleet_alerts(opened, resolved): 'hostname': hostname, 'alert_type': f'{alert.metric} recovered', 'metric': alert.metric, - 'message': (f'{hostname}: {alert.metric} is back under its ' + 'message': (f'{hostname}: {alert.metric} recovered.' + if alert.detail else + f'{hostname}: {alert.metric} is back under its ' f'threshold.'), }, ) diff --git a/backend/app/models/metric_alert.py b/backend/app/models/metric_alert.py index 24e29893..7bb5f999 100644 --- a/backend/app/models/metric_alert.py +++ b/backend/app/models/metric_alert.py @@ -49,6 +49,8 @@ class MetricAlert(db.Model): threshold = db.Column(db.Float) # the threshold exceeded duration_seconds = db.Column(db.Integer) # how long it was exceeded + detail = db.Column(db.Text) # human message for offline / service-check alerts + status = db.Column(db.String(20), default='active', index=True) # active, acknowledged, resolved acknowledged_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, index=True) @@ -67,6 +69,7 @@ class MetricAlert(db.Model): 'value': self.value, 'threshold': self.threshold, 'duration_seconds': self.duration_seconds, + 'detail': self.detail, 'status': self.status, 'acknowledged_by': self.acknowledged_by, 'created_at': self.created_at.isoformat() if self.created_at else None, diff --git a/backend/app/models/server.py b/backend/app/models/server.py index ba6e9e80..7b011715 100644 --- a/backend/app/models/server.py +++ b/backend/app/models/server.py @@ -126,6 +126,17 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model): allow_agent_update_observed = db.Column(db.Boolean, nullable=False, default=False, server_default='0') + # Agent permission level (monitor|protect|full). REPORTED BY THE AGENT + # only -- no panel API writes it. NULL = unknown/legacy, treated as full. + # requested_permission_level is what the install command asked for, kept + # only to flag a mismatch with what the agent reports. + permission_level = db.Column(db.String(16), nullable=True) + permission_level_updated_at = db.Column(db.DateTime, nullable=True) + requested_permission_level = db.Column(db.String(16), nullable=True) + last_report_at = db.Column(db.DateTime, nullable=True) + report_interval_seconds = db.Column(db.Integer, nullable=True) + service_checks = db.Column(db.JSON, nullable=True) # latest state per check + @property def is_managed(self): """False only for observed boxes.""" @@ -490,6 +501,12 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model): 'last_error': self.last_error, 'management_mode': self.management_mode or 'managed', 'allow_agent_update_observed': bool(self.allow_agent_update_observed), + 'permission_level': self.permission_level, + 'permission_level_effective': self.permission_level or 'full', + 'permission_level_updated_at': self.permission_level_updated_at.isoformat() if self.permission_level_updated_at else None, + 'requested_permission_level': self.requested_permission_level, + 'last_report_at': self.last_report_at.isoformat() if self.last_report_at else None, + 'service_checks': self.service_checks or [], 'onboarding_state': self.onboarding_state, 'onboarding_updated_at': self.onboarding_updated_at.isoformat() if self.onboarding_updated_at else None, 'agent_version': self.agent_version, diff --git a/backend/app/services/agent_health_service.py b/backend/app/services/agent_health_service.py new file mode 100644 index 00000000..2272469a --- /dev/null +++ b/backend/app/services/agent_health_service.py @@ -0,0 +1,223 @@ +"""Agent-reported health: permission level, service checks, silence, alerts. + +Everything here consumes what the agent REPORTS (registration, auth, heartbeat, +or the monitor-mode ``/agent/report`` POST). Alerts reuse ``MetricAlert`` and the +fleet notification path; one active row per (server, metric) de-duplicates. +""" +import hashlib +import hmac +import logging +import time +from datetime import datetime, timedelta + +from app import db +from app.models.audit_log import AuditLog +from app.models.metric_alert import MetricAlert +from app.models.server import Server +from app.services import permission_levels +from app.services.nonce_service import nonce_service + +logger = logging.getLogger(__name__) + +MIN_SILENCE_SECONDS = 180 # monitor agents: offline after max(3 min, 3x interval) +DEFAULT_INTERVAL_SECONDS = 60 +DEFAULT_INTERVAL = DEFAULT_INTERVAL_SECONDS +OFFLINE_METRIC = 'offline' +OPEN = ('active', 'acknowledged') +BAD = ('down',) + + +def _notify(opened=(), resolved=()): + if not opened and not resolved: + return + try: + from app.jobs.builtin_handlers import _notify_fleet_alerts + _notify_fleet_alerts(list(opened), list(resolved)) + except Exception: + logger.exception('Could not notify agent health alerts') + + +def _open_alert(server, metric, detail): + """Open an alert unless one is already open. Returns it if newly opened.""" + if MetricAlert.query.filter(MetricAlert.server_id == server.id, + MetricAlert.metric == metric, + MetricAlert.status.in_(OPEN)).first(): + return None + alert = MetricAlert(server_id=server.id, metric=metric, severity='critical', + detail=detail, status='active') + db.session.add(alert) + return alert + + +def _resolve_alerts(server, metric): + rows = MetricAlert.query.filter(MetricAlert.server_id == server.id, + MetricAlert.metric == metric, + MetricAlert.status.in_(OPEN)).all() + for row in rows: + row.status = 'resolved' + row.resolved_at = datetime.utcnow() + return rows + + +def record_level(server, reported): + """Persist a level reported by the agent; audit when it changes. + + Invalid/missing values are ignored. Escalations (monitor->protect->full) are + logged like any change but flagged, since they mean someone re-ran the + local confirmation on the box. + """ + level = permission_levels.normalize(reported) + if level is None: + return + old = server.permission_level + if old == level: + return + server.permission_level = level + server.permission_level_updated_at = datetime.utcnow() + AuditLog.log( + 'server.permission_level_changed', target_type='server', target_id=server.id, + details={'server_id': server.id, 'from': old, 'to': level, + 'escalation': permission_levels.is_escalation(old, level), + 'source': 'agent_report'}) + logger.warning('Server %s reported permission level %s -> %s', server.id, old, level) + + +def record_service_checks(server, checks): + """Store the latest per-check state and open/resolve alerts on transitions.""" + if not isinstance(checks, list): + return + previous = {c.get('name'): c.get('status') for c in (server.service_checks or [])} + clean, opened, resolved = [], [], [] + for raw in checks[:50]: + if not isinstance(raw, dict) or not isinstance(raw.get('name'), str): + continue + item = {k: (str(raw.get(k))[:200] if raw.get(k) is not None else None) + for k in ('name', 'kind', 'status', 'detail', 'checked_at')} + item['name'] = item['name'][:60] + if item['status'] not in ('up', 'down', 'degraded', 'unknown'): + item['status'] = 'unknown' + clean.append(item) + metric = f"svc:{item['name']}"[:20] + if item['status'] == 'down': + alert = _open_alert( + server, metric, + f"{server.name}: service '{item['name']}' is down since " + f"{datetime.utcnow():%Y-%m-%d %H:%M} UTC" + + (f" ({item['detail']})" if item['detail'] else '')) + if alert: + opened.append(alert) + elif item['status'] == 'up' or (item['status'] == 'degraded' + and previous.get(item['name']) == 'down'): + resolved += _resolve_alerts(server, metric) + server.service_checks = clean + db.session.flush() + _notify(opened, resolved) + + +def mark_offline(server, reason): + """Open the (de-duplicated) offline alert. Caller commits.""" + since = server.last_report_at or server.last_seen or datetime.utcnow() + alert = _open_alert( + server, OFFLINE_METRIC, + f"{server.name} is offline since {since:%Y-%m-%d %H:%M} UTC: {reason}") + db.session.flush() + _notify([alert] if alert else []) + + +def mark_online(server): + resolved = _resolve_alerts(server, OFFLINE_METRIC) + db.session.flush() + _notify(resolved=resolved) + + +def silence_limit(server): + interval = server.report_interval_seconds or DEFAULT_INTERVAL_SECONDS + return timedelta(seconds=max(MIN_SILENCE_SECONDS, 3 * interval)) + + +def sweep_silent_reporters(now=None): + """Flip report-only (monitor) servers offline once their reports stop. + + Reports are not a socket, so the registry's heartbeat reaper never sees + them. Only servers that have ever reported are considered. + """ + now = now or datetime.utcnow() + flipped = [] + for server in Server.query.filter(Server.permission_level == 'monitor', + Server.last_report_at.isnot(None), + Server.status != 'offline').all(): + if now - server.last_report_at > silence_limit(server): + server.status = 'offline' + server.last_error = 'Agent stopped reporting' + mark_offline(server, 'no report received') + flipped.append(server.id) + if flipped: + db.session.commit() + return flipped + + +def authenticate_report(raw, headers, max_skew): + """Return the Server for a validly signed report request, else None.""" + key = headers.get('X-Agent-Key') or '' + ts = headers.get('X-Timestamp') or '' + nonce = headers.get('X-Nonce') or '' + signature = headers.get('X-Signature') or '' + if not (key and ts and signature) or len(nonce) < 32: + return None + try: + if abs(time.time() - int(ts)) > max_skew: + return None + except ValueError: + return None + + prefix = key[:12] + server = Server.query.filter( + (Server.api_key_prefix == prefix) | (Server.api_key_pending_prefix == prefix) + ).first() + if not server: + return None + pending = (server.api_key_pending_prefix == prefix and server.api_key_prefix != prefix + and server.api_key_rotation_expires + and datetime.utcnow() <= server.api_key_rotation_expires) + secret = server.get_pending_api_secret() if pending else server.get_api_secret() + if not secret: + return None + + message = f"{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}" + expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() + if not hmac.compare_digest(signature, expected): + return None + # Consume the nonce only after the signature proves valid. + if not nonce_service.check_and_record(server.id, nonce): + return None + return server + + +def ingest_report(server, level, body): + """Apply a verified report to the server row; returns the interval in use.""" + interval = body.get('interval_seconds') + interval = interval if isinstance(interval, int) and 5 <= interval <= 3600 else DEFAULT_INTERVAL + + now = datetime.utcnow() + was_offline = server.status != 'online' + server.status = 'online' + server.last_error = None + server.last_seen = now + server.last_report_at = now + server.report_interval_seconds = interval + if isinstance(body.get('agent_version'), str): + server.agent_version = body['agent_version'][:20] + record_level(server, level) + record_service_checks(server, body.get('service_checks')) + if was_offline: + mark_online(server) + db.session.commit() + + metrics = body.get('metrics') + if isinstance(metrics, dict): + from app.services.server_metrics_service import ServerMetricsService + ServerMetricsService.record_metrics(server.id, { + **{k: metrics.get(k) for k in ('cpu_percent', 'memory_percent', 'disk_percent')}, + 'extra': {k: metrics.get(k) for k in ('uptime_seconds', 'load1')}, + }) + return interval diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py index 98162e0a..19f0c81c 100644 --- a/backend/app/services/agent_registry.py +++ b/backend/app/services/agent_registry.py @@ -22,6 +22,7 @@ from collections import defaultdict from app import db from app.models.server import Server, ServerCommand, AgentSession +from app.services import permission_levels # --------------------------------------------------------------------------- # Per-IP auth rate limiter — transport-neutral state shared by the WS @@ -245,6 +246,12 @@ class AgentRegistry: self._agents.pop(server_id, None) self._socket_to_server.pop(socket_id, None) + # Report-only (monitor) agents hold no socket; sweep them too. + if self._app is not None: + with self._app.app_context(): + from app.services import agent_health_service + agent_health_service.sweep_silent_reporters() + except Exception as e: logger.error("Error in heartbeat checker: %s", e) @@ -279,6 +286,8 @@ class AgentRegistry: if server: server.status = 'offline' server.last_error = 'Agent heartbeat timeout' + from app.services import agent_health_service + agent_health_service.mark_offline(server, 'heartbeat timeout') db.session.commit() # Mark session as inactive @@ -392,6 +401,8 @@ class AgentRegistry: # even for healthy connected agents. if ip_address and ip_address != 'unknown': server.ip_address = ip_address + from app.services import agent_health_service + agent_health_service.mark_online(server) db.session.commit() # Create session record @@ -519,6 +530,8 @@ class AgentRegistry: server.last_seen = now if server.status != 'online': server.status = 'online' + from app.services import agent_health_service + agent_health_service.mark_online(server) db.session.commit() # Update session latency @@ -589,6 +602,12 @@ class AgentRegistry: # Check permissions server = Server.query.get(server_id) + # Defence in depth: never send what the agent's reported level refuses. + refused = permission_levels.refusal( + server.permission_level if server else None, action) + if refused: + return {'success': False, 'error': refused, 'code': 'LEVEL_DENIED'} + if server and not server.has_permission(action): return { 'success': False, @@ -863,13 +882,15 @@ class AgentRegistry: # in-memory state — the adapter must not report success. if not session_token: return None, server, 'registration_failed' + self.record_agent_health(server.id, payload.get('permission_level')) logger.info("Agent %s authenticated successfully from %s (%s)", agent_id, ip_address, transport) return session_token, server, None def ingest_agent_state(self, agent, metrics=None, sysinfo=None, - capabilities=None): + capabilities=None, permission_level=None, + service_checks=None): """One ingest path for agent-reported state on BOTH transports. Owns the capability side-effects (the WireGuard tunnel reconcile @@ -882,6 +903,20 @@ class AgentRegistry: self.update_system_info(agent.server_id, sysinfo) if capabilities: self.update_capabilities(agent.server_id, capabilities) + if permission_level is not None or service_checks is not None: + self.record_agent_health(agent.server_id, permission_level, service_checks) + + def record_agent_health(self, server_id, permission_level=None, service_checks=None): + from app.services import agent_health_service + try: + server = Server.query.get(server_id) + if server: + agent_health_service.record_level(server, permission_level) + agent_health_service.record_service_checks(server, service_checks) + db.session.commit() + except Exception: + logger.exception("Error recording agent health") + db.session.rollback() def verify_agent_auth( self, diff --git a/backend/app/services/permission_levels.py b/backend/app/services/permission_levels.py new file mode 100644 index 00000000..c7af05f7 --- /dev/null +++ b/backend/app/services/permission_levels.py @@ -0,0 +1,56 @@ +"""Agent permission levels and the one command-gate table. + +The level is chosen on the server (``permissions.level`` in the agent's +config.yaml) and REPORTED to the panel. The panel never sets it. This module +is only the panel's defence in depth: it refuses to send a command the agent +would refuse anyway. ``PROTECT_ACTIONS`` must stay identical to the agent's +allowlist (docs/AGENT_PERMISSION_LEVELS.md; checked by a test). +""" + +LEVELS = ('monitor', 'protect', 'full') +_RANK = {level: i for i, level in enumerate(LEVELS)} +LABELS = {'monitor': 'Monitor', 'protect': 'Protect', 'full': 'Full'} + +PROTECT_ACTIONS = frozenset({ + 'firewall:allow_port', 'firewall:deny_port', 'firewall:status', + 'firewall:allow_ip', 'firewall:deny_ip', + 'fail2ban:status', 'fail2ban:ban', 'fail2ban:unban', + 'crowdsec:decisions:list', 'crowdsec:ban', 'crowdsec:unban', + 'cloudflare:origin_lock:status', 'cloudflare:origin_lock:apply', + 'cloudflare:origin_lock:remove', +}) + +# Signature-verified key rotation is not control; allowed at every level. +ALWAYS_ALLOWED = frozenset({'credential_update'}) + + +def normalize(level): + """Return a valid level string, or None for missing/unknown values.""" + level = level.strip().lower() if isinstance(level, str) else None + return level if level in _RANK else None + + +def effective_level(level): + """Unknown/legacy (None) means a pre-levels agent, i.e. full.""" + return normalize(level) or 'full' + + +def is_escalation(old, new): + return old is not None and _RANK[new] > _RANK[old] + + +def refusal(level, action): + """Message explaining why ``action`` is refused at ``level``, else None.""" + level = effective_level(level) + if level == 'full' or action in ALWAYS_ALLOWED: + return None + if level == 'protect' and action in PROTECT_ACTIONS: + return None + if level == 'monitor': + return (f"server is in Monitor mode: '{action}' refused. Monitor agents " + "are report-only and accept no commands. The level can only be " + "changed on the server itself (serverkit-agent permissions set).") + return (f"server is in Protect mode: '{action}' refused. Protect agents only " + "run firewall, fail2ban, CrowdSec and Cloudflare origin-lock actions. " + "The level can only be changed on the server itself " + "(serverkit-agent permissions set).") diff --git a/backend/app/services/server_timeline_service.py b/backend/app/services/server_timeline_service.py index 8da66702..40cd2978 100644 --- a/backend/app/services/server_timeline_service.py +++ b/backend/app/services/server_timeline_service.py @@ -52,6 +52,7 @@ _AUDIT_DETAIL_KEYS = frozenset({ 'application_id', 'code', 'endpoint', + 'escalation', 'from', 'kind', 'label', diff --git a/backend/migrations/versions/112_agent_permission_levels.py b/backend/migrations/versions/112_agent_permission_levels.py new file mode 100644 index 00000000..e65a5908 --- /dev/null +++ b/backend/migrations/versions/112_agent_permission_levels.py @@ -0,0 +1,36 @@ +"""Agent-reported permission level, report bookkeeping and service checks.""" +import sqlalchemy as sa +from alembic import op + +revision = '112_agent_permission_levels' +down_revision = '111_preview_runtime' +branch_labels = None +depends_on = None + +SERVER_COLUMNS = [ + ('permission_level', sa.String(16)), + ('permission_level_updated_at', sa.DateTime()), + ('requested_permission_level', sa.String(16)), + ('last_report_at', sa.DateTime()), + ('report_interval_seconds', sa.Integer()), + ('service_checks', sa.JSON()), +] + + +def upgrade(): + inspector = sa.inspect(op.get_bind()) + existing = {c['name'] for c in inspector.get_columns('servers')} + for name, kind in SERVER_COLUMNS: + if name not in existing: + op.add_column('servers', sa.Column(name, kind, nullable=True)) + existing = {c['name'] for c in inspector.get_columns('metric_alerts')} + if 'detail' not in existing: + op.add_column('metric_alerts', sa.Column('detail', sa.Text(), nullable=True)) + + +def downgrade(): + with op.batch_alter_table('metric_alerts') as batch: + batch.drop_column('detail') + with op.batch_alter_table('servers') as batch: + for name, _ in reversed(SERVER_COLUMNS): + batch.drop_column(name) diff --git a/backend/scripts/seed_permission_demo.py b/backend/scripts/seed_permission_demo.py new file mode 100644 index 00000000..a076facc --- /dev/null +++ b/backend/scripts/seed_permission_demo.py @@ -0,0 +1,80 @@ +"""Seed five demo servers showing every permission-level / health state. + +Dev sandbox only; never run automatically. Idempotent: demo rows are keyed by +agent_id 'demo-perm-*' and are rebuilt on each run. + + cd backend && python scripts/seed_permission_demo.py +""" +import os +import sys +from datetime import datetime, timedelta + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from app import create_app, db # noqa: E402 +from app.models.metric_alert import MetricAlert # noqa: E402 +from app.models.server import Server, ServerMetrics # noqa: E402 + +UP, DOWN, DEG = 'up', 'down', 'degraded' + + +def checks(now, web=UP, php=UP, database=UP, disk=UP): + stamp = now.isoformat() + 'Z' + rows = [('nginx', 'web', web, ''), ('php8.2-fpm', 'php_fpm', php, 'slow pool' if php == DEG else ''), + ('mysql', 'database', database, 'connection refused on 3306' if database == DOWN else ''), + ('disk /', 'disk', disk, ''), ('cpu', 'cpu', UP, ''), ('memory', 'memory', UP, '')] + return [{'name': n, 'kind': k, 'status': s, 'detail': d, 'checked_at': stamp} for n, k, s, d in rows] + + +# (name, level, status, minutes since last report, check overrides, cpu) +DEMOS = [ + ('demo-monitor-healthy', 'monitor', 'online', 1, {}, 14.0), + ('demo-monitor-degraded', 'monitor', 'online', 1, {'database': DOWN, 'php': DEG}, 71.0), + ('demo-protect-healthy', 'protect', 'online', 0, {}, 22.0), + ('demo-full-healthy', 'full', 'online', 0, {}, 35.0), + ('demo-monitor-offline', 'monitor', 'offline', 20, {'database': DOWN}, 9.0), +] + + +def seed(): + now = datetime.utcnow() + for name, level, status, age, overrides, cpu in DEMOS: + agent_id = f'demo-perm-{name}' + old = Server.query.filter_by(agent_id=agent_id).first() + if old: + MetricAlert.query.filter_by(server_id=old.id).delete() + ServerMetrics.query.filter_by(server_id=old.id).delete() + db.session.delete(old) + db.session.flush() + reported = now - timedelta(minutes=age) + srv = Server(name=name, agent_id=agent_id, hostname=name, status=status, + os_type='linux', permission_level=level, requested_permission_level=level, + permission_level_updated_at=reported, last_seen=reported, + last_report_at=reported, report_interval_seconds=60, + service_checks=checks(reported, **overrides)) + db.session.add(srv) + db.session.flush() + for i in range(12): + db.session.add(ServerMetrics( + server_id=srv.id, timestamp=reported - timedelta(minutes=i), + cpu_percent=cpu + i % 3, memory_percent=48.0, disk_percent=61.0)) + for check in srv.service_checks: + if check['status'] == DOWN: + db.session.add(MetricAlert( + server_id=srv.id, metric=f"svc:{check['name']}"[:20], severity='critical', + status='active', created_at=reported, + detail=f"{name}: service '{check['name']}' is down since " + f"{reported:%Y-%m-%d %H:%M} UTC ({check['detail']})")) + if status == 'offline': + db.session.add(MetricAlert( + server_id=srv.id, metric='offline', severity='critical', status='active', + created_at=now, detail=f"{name} is offline since {reported:%Y-%m-%d %H:%M} UTC: " + "no report received")) + db.session.commit() + print(f'Seeded {len(DEMOS)} demo servers.') + + +if __name__ == '__main__': + app = create_app(os.environ.get('FLASK_ENV') or 'development') + with app.app_context(): + seed() diff --git a/backend/tests/test_agent_permission_levels.py b/backend/tests/test_agent_permission_levels.py new file mode 100644 index 00000000..b5ab40ab --- /dev/null +++ b/backend/tests/test_agent_permission_levels.py @@ -0,0 +1,208 @@ +"""Agent permission levels: report endpoint, level reporting, dispatch gate, +silence sweep, service-check alerts and install commands.""" +import hashlib +import hmac +import json +import re +import secrets +import time +from datetime import datetime, timedelta +from pathlib import Path + +import pytest + +from app import db +from app.models.audit_log import AuditLog +from app.models.metric_alert import MetricAlert +from app.models.server import Server +from app.services import agent_health_service, permission_levels +from app.services.agent_registry import ConnectedAgent, agent_registry + +REPORT = '/api/v1/agent/report' +SECRET = 'test-secret' + + +@pytest.fixture +def server(app, monkeypatch): + monkeypatch.setattr(Server, 'get_api_secret', lambda self: SECRET) + key, _ = Server.generate_api_credentials() + srv = Server(name='web-1', agent_id=secrets.token_hex(8)) + srv.set_api_key(key) + db.session.add(srv) + db.session.commit() + srv.test_key = key + return srv + + +def _post(client, srv, body=None, ts=None, nonce=None, secret=SECRET, raw=None): + body = body if body is not None else { + 'permission_level': 'monitor', 'interval_seconds': 60, + 'metrics': {'cpu_percent': 12.5, 'memory_percent': 40.0, 'disk_percent': 55.0, + 'uptime_seconds': 99, 'load1': 0.3}, + 'service_checks': []} + raw = raw if raw is not None else json.dumps(body).encode() + ts = str(int(time.time())) if ts is None else str(ts) + nonce = nonce or secrets.token_hex(16) + sig = hmac.new(secret.encode(), + f'{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}'.encode(), + hashlib.sha256).hexdigest() + return client.post(REPORT, data=raw, content_type='application/json', headers={ + 'X-Agent-Key': srv.test_key, 'X-Timestamp': ts, 'X-Nonce': nonce, + 'X-Signature': sig}) + + +def test_good_signature_updates_server(client, server): + resp = _post(client, server) + assert resp.status_code == 200 + assert resp.get_json() == {'ok': True, 'interval_seconds': 60} + srv = db.session.get(Server, server.id) + assert srv.status == 'online' and srv.last_report_at is not None + assert srv.permission_level == 'monitor' + assert 'commands' not in resp.get_json() + + +def test_bad_signature_rejected(client, server): + assert _post(client, server, secret='wrong').status_code == 401 + + +def test_stale_timestamp_rejected(client, server): + assert _post(client, server, ts=int(time.time()) - 400).status_code == 401 + + +def test_replayed_nonce_rejected(client, server): + nonce = secrets.token_hex(16) + assert _post(client, server, nonce=nonce).status_code == 200 + assert _post(client, server, nonce=nonce).status_code == 401 + + +def test_oversize_body_rejected(client, server): + assert _post(client, server, raw=b'{"x":"' + b'a' * 70000 + b'"}').status_code == 413 + + +def test_invalid_level_rejected(client, server): + assert _post(client, server, body={'permission_level': 'root'}).status_code == 400 + + +def test_level_persisted_and_escalation_audited(client, server): + _post(client, server, body={'permission_level': 'monitor'}) + _post(client, server, body={'permission_level': 'full'}) + rows = AuditLog.query.filter_by(action='server.permission_level_changed').order_by(AuditLog.id).all() + details = [r.get_details() for r in rows] + assert [(d['from'], d['to'], d['escalation']) for d in details] == [ + (None, 'monitor', False), ('monitor', 'full', True)] + assert db.session.get(Server, server.id).permission_level == 'full' + + +def test_no_api_sets_level(client, server, auth_headers): + resp = client.put(f'/api/v1/servers/{server.id}', headers=auth_headers, + json={'permission_level': 'full', 'name': 'x'}) + assert resp.status_code in (200, 400) + assert db.session.get(Server, server.id).permission_level is None + writers = [r.rule for r in client.application.url_map.iter_rules() + if 'level' in r.rule and r.methods & {'POST', 'PUT', 'PATCH'}] + assert writers == [] + + +def _connect(server_id): + agent_registry._agents[server_id] = ConnectedAgent( + server_id=server_id, socket_id='s', session_token='t', + connected_at=datetime.utcnow(), last_heartbeat=datetime.utcnow(), + ip_address='1.1.1.1', agent_version='1', transport='poll') + + +@pytest.mark.parametrize('level,action,refused', [ + ('monitor', 'firewall:status', True), + ('monitor', 'docker:container:list', True), + ('protect', 'docker:container:list', True), + ('protect', 'system:exec', True), + ('protect', 'firewall:status', False), + ('protect', 'cloudflare:origin_lock:apply', False), + ('protect', 'credential_update', False), + ('full', 'system:exec', False), + (None, 'system:exec', False), +]) +def test_refusal_table(level, action, refused): + assert bool(permission_levels.refusal(level, action)) is refused + + +@pytest.mark.parametrize('level', ['monitor', 'protect']) +def test_send_command_gate(server, level): + server.permission_level = level + db.session.commit() + _connect(server.id) + try: + result = agent_registry.send_command(server.id, 'system:exec', {}) + finally: + agent_registry._agents.pop(server.id, None) + assert result['code'] == 'LEVEL_DENIED' + assert result['error'].startswith(f'server is in {level.title()} mode') + + +def test_protect_allowlist_matches_documented_contract(): + doc = Path(__file__).parents[2] / 'docs/AGENT_PERMISSION_LEVELS.md' + block = re.search(r'```text allowlist\n(.*?)```', doc.read_text(), re.S).group(1) + assert set(block.split()) == set(permission_levels.PROTECT_ACTIONS) + + +def test_silent_monitor_goes_offline_with_one_alert(server): + server.permission_level = 'monitor' + server.status = 'online' + server.last_report_at = datetime.utcnow() - timedelta(minutes=20) + db.session.commit() + assert agent_health_service.sweep_silent_reporters() == [server.id] + assert agent_health_service.sweep_silent_reporters() == [] + assert db.session.get(Server, server.id).status == 'offline' + assert MetricAlert.query.filter_by(metric='offline', status='active').count() == 1 + + +def test_recent_monitor_stays_online(server): + server.permission_level, server.status = 'monitor', 'online' + server.last_report_at = datetime.utcnow() - timedelta(minutes=2) + db.session.commit() + assert agent_health_service.sweep_silent_reporters() == [] + + +def _checks(status): + return {'permission_level': 'monitor', 'service_checks': [ + {'name': 'mysql', 'kind': 'database', 'status': status, 'detail': 'refused', + 'checked_at': '2026-01-01T00:00:00Z'}]} + + +def test_service_down_alert_dedupes_and_resolves(client, server): + _post(client, server, body=_checks('up')) + assert MetricAlert.query.count() == 0 + _post(client, server, body=_checks('down')) + _post(client, server, body=_checks('down')) + alert = MetricAlert.query.one() + assert alert.status == 'active' and 'mysql' in alert.detail and 'web-1' in alert.detail + _post(client, server, body=_checks('up')) + assert MetricAlert.query.one().status == 'resolved' + + +def test_degraded_to_down_alerts_and_report_recovers_offline(client, server): + _post(client, server, body=_checks('degraded')) + assert MetricAlert.query.count() == 0 + _post(client, server, body=_checks('down')) + assert MetricAlert.query.filter_by(status='active').count() == 1 + agent_health_service.mark_offline(server, 'test') + db.session.commit() + server.status = 'offline' + db.session.commit() + _post(client, server, body=_checks('down')) + assert MetricAlert.query.filter_by(metric='offline', status='resolved').count() == 1 + + +def test_install_instructions_include_level(client, server, auth_headers): + server.set_registration_token('sk_reg_x') + db.session.commit() + data = client.get(f'/api/v1/servers/install-instructions/{server.id}?level=protect', + headers=auth_headers).get_json() + assert data['permission_level'] == 'protect' + assert '--level protect' in data['linux']['one_liner'] + assert '-Level protect' in data['windows']['one_liner'] + + +def test_token_records_requested_level(client, server, auth_headers): + client.post(f'/api/v1/servers/{server.id}/regenerate-token', headers=auth_headers, + json={'requested_level': 'protect'}) + assert db.session.get(Server, server.id).requested_permission_level == 'protect' diff --git a/backend/tests/test_core_blueprint_registry.py b/backend/tests/test_core_blueprint_registry.py index 3b4e86e4..beba6dfe 100644 --- a/backend/tests/test_core_blueprint_registry.py +++ b/backend/tests/test_core_blueprint_registry.py @@ -7,9 +7,9 @@ from pathlib import Path from app.core_blueprints import CORE_BLUEPRINTS -EXPECTED_CORE_BLUEPRINT_COUNT = 116 +EXPECTED_CORE_BLUEPRINT_COUNT = 117 EXPECTED_MANIFEST_SHA256 = ( - '25d28d92ccddddc246d5b2081d84b11f1df10cb662f33c256ebcbe390d2813d5' + '52abbc7429d079c7cf6ea61a638f5dc4dbd991e4f02ec31c81563e01442aa7fb' ) diff --git a/backend/tests/test_route_authz_static.py b/backend/tests/test_route_authz_static.py index a7a1e24d..0c842e91 100644 --- a/backend/tests/test_route_authz_static.py +++ b/backend/tests/test_route_authz_static.py @@ -145,6 +145,7 @@ PUBLIC_ALT_AUTH = { # Public by design; the value names the mechanism that authenticates the call. 'agent_poll.connect': 'agent HMAC handshake + per-IP throttle', 'agent_poll.disconnect': 'X-Session-Token lookup', + 'agent_report.report': 'HMAC over timestamp+nonce+body hash, skew/replay/rate limits', 'agent_poll.poll': 'X-Session-Token resolves the ConnectedAgent', 'agent_poll.result': 'X-Session-Token resolves the ConnectedAgent', 'auth.connect_session': 'loopback-only + Cloud grant verified against JWKS, 30/min', diff --git a/backend/tests/test_route_authz_sweep.py b/backend/tests/test_route_authz_sweep.py index 4265b385..d7af9e6f 100644 --- a/backend/tests/test_route_authz_sweep.py +++ b/backend/tests/test_route_authz_sweep.py @@ -221,6 +221,7 @@ VIEWER_WRITABLE = { 'docker.get_containers_stats', # PUBLIC transport — agent long-poll fallback; user JWT is ignored here. 'agent_poll.disconnect', + 'agent_report.report', # PUBLIC authentication challenge only; credential verification and UV are # required by passkey_authenticate before any session tokens are issued. 'auth.passkey_auth_options', diff --git a/backend/tests/test_seed_permission_demo.py b/backend/tests/test_seed_permission_demo.py new file mode 100644 index 00000000..c629bc81 --- /dev/null +++ b/backend/tests/test_seed_permission_demo.py @@ -0,0 +1,17 @@ +import importlib.util +from pathlib import Path + +from app.models.metric_alert import MetricAlert +from app.models.server import Server + + +def test_seed_is_idempotent(app): + path = Path(__file__).parents[1] / 'scripts/seed_permission_demo.py' + spec = importlib.util.spec_from_file_location('seed_demo', path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + mod.seed() + mod.seed() + assert Server.query.filter(Server.agent_id.like('demo-perm-%')).count() == 5 + assert Server.query.filter_by(status='offline').count() == 1 + assert MetricAlert.query.filter_by(metric='offline').count() == 1 diff --git a/docs/AGENT_PERMISSION_LEVELS.md b/docs/AGENT_PERMISSION_LEVELS.md new file mode 100644 index 00000000..cd8d8286 --- /dev/null +++ b/docs/AGENT_PERMISSION_LEVELS.md @@ -0,0 +1,81 @@ +# Agent permission levels + +Each ServerKit agent runs at one of three levels. The level is chosen **on the +server**, enforced **by the agent**, and merely *reported* to the panel. + +| Level | What it can do | What it cannot do | +|-------|----------------|-------------------| +| **Monitor** (default for new installs) | Send CPU / memory / disk / uptime / load and service checks (web server, PHP-FPM, database, disk, CPU, memory) to the panel with signed outbound HTTPS POSTs. Opens no inbound command channel. | Run any command, open a terminal, touch files, Docker, packages or services. The panel cannot send it anything. | +| **Protect** | Everything in Monitor, plus a fixed security allowlist: firewall (ufw) rules, fail2ban, CrowdSec decisions, Cloudflare origin lock (restrict 80/443 to Cloudflare ranges). | Docker, shell, files, terminal, packages, systemd, cron, SSH keys, WireGuard, runtimes, agent updates. | +| **Full** | Today's behaviour: the whole agent feature set. Legacy installs with no level configured are treated as Full. | — | + +## Install + +The Add Server drawer shows the level picker and puts the choice in the command: + +```bash +curl -fsSL https://panel.example.com/api/v1/servers/install.sh -o /tmp/serverkit-agent-install.sh \ + && sudo bash /tmp/serverkit-agent-install.sh --token "TOKEN" --server "https://panel.example.com" --level monitor +``` + +```powershell +irm https://panel.example.com/api/v1/servers/install.ps1 | iex; Install-ServerKitAgent -Token "TOKEN" -Server "https://panel.example.com" -Level monitor +``` + +The installer scripts under `scripts/` are vendored from the agent repo +(`scripts/sync-agent-installers.sh`); `--level` / `-Level` arrives with the next sync. + +## Changing the level + +Only on the server itself, as root, with a typed confirmation: + +```bash +serverkit-agent permissions show +sudo serverkit-agent permissions set protect +``` + +There is no panel button or API for this, by design. Re-running `install.sh` with a +different `--level` on an installed box refuses unless `--reconfigure` is passed. + +## What the panel does + +- Records the level the agent reports (registration, auth, heartbeat, report). Every + change, escalations included, is written to the audit log and shown in the server + timeline. The Add Server flow remembers the *requested* level so a mismatch with + the reported one is visible. +- Monitor agents POST to `/api/v1/agent/report` (HMAC over timestamp, nonce and body + hash; 300 s skew; single-use nonces; 64 KB cap; per-IP+key rate limit). A monitor + server with no report for max(3 minutes, 3 x its interval) is marked offline. +- Opens an alert (existing fleet alerts + notification channels) when a server goes + offline or stops reporting and when a service check goes down; it resolves on + recovery and does not repeat while the condition persists. +- Refuses to dispatch a command the reported level forbids (`LEVEL_DENIED`, + "server is in Monitor mode: ..."). This is defence in depth; the agent enforces + the same table. The table lives in `backend/app/services/permission_levels.py`. + +Protect allowlist (checked against the panel table by a test): + +```text allowlist +firewall:allow_port firewall:deny_port firewall:status +firewall:allow_ip firewall:deny_ip +fail2ban:status fail2ban:ban fail2ban:unban +crowdsec:decisions:list crowdsec:ban crowdsec:unban +cloudflare:origin_lock:status cloudflare:origin_lock:apply cloudflare:origin_lock:remove +``` + +`credential_update` (signature-verified key rotation) is allowed at every level. + +## Threat model + +The level is read only from the agent's local config at startup; no message from +the panel can change it. A compromised panel therefore **cannot escalate** a Monitor +agent: it has no channel to send commands to, and the report reply never carries any. +The panel's own gate only narrows what it will send. Someone with root on the box +can still change the level, which is the intended re-confirmation path, and the +panel audits the resulting change. A compromised panel can lie in the UI, but +cannot make a Monitor agent act. + +## Demo data + +`python backend/scripts/seed_permission_demo.py` (never run automatically) creates five +demo servers for the dev sandbox. It is idempotent. diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md index 59f85051..56c8c308 100644 --- a/docs/API_SURFACE.md +++ b/docs/API_SURFACE.md @@ -755,6 +755,7 @@ Regenerate (backend/): - `POST /agent/connect` - `POST /agent/disconnect` - `POST /agent/poll` +- `POST /agent/report` - `POST /agent/result` - `POST /ai/chat` - `POST /ai/chat/cancel` diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index fdb4e968..f8323690 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -16,7 +16,7 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`. | Routes on bare @jwt_required() | auth_required() / role decorators | 598 | 598 | REGISTERED EXCEPTION: JWT-only is the deliberate default; conversion grants API-key access and happens per route, on decision | | HTTP statuses chosen by sniffing error text | typed errors from app.exceptions | 0 | 0 | INVARIANT at 0 - migration completed 2026-08-19 | | API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 | -| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise | +| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 855 | 850 | migrate when touched; new endpoints raise | | Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched | | Controller-boundary violations (routes doing service work) | service layer extraction | 453 | 453 | migrate when touched (first-wave ratchet) | | raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched | diff --git a/docs/README.md b/docs/README.md index 25d3a1f5..59c100f0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,7 @@ Welcome to the ServerKit documentation. This guide will help you install, config | [Video: template to live app](https://youtu.be/TXfXFz6bVjs) | Watch a 4-minute AgentSite deployment through the template catalog and live Deploy Console | | [Video: deploy a Git repository](https://youtu.be/Fv28qMERYDU) | Connect a repository, review detected settings and deploy through the three-step New Service wizard | | [Installation Guide](INSTALLATION.md) | Complete setup instructions for Docker and manual installation | +| [Agent permission levels](AGENT_PERMISSION_LEVELS.md) | Monitor / Protect / Full: what each allows and how to change it | | [Architecture](ARCHITECTURE.md) | System design, request flow, and diagrams | | [Deployment Guide](DEPLOYMENT.md) | Production deployment, CLI commands, and configuration | | [Local Development](LOCAL_DEVELOPMENT.md) | Run the panel locally for development | From a0662254aec8d7effacc2072b255347b6f5a9c6a Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 00:07:37 -0500 Subject: [PATCH 02/70] feat(frontend): permission level picker, level badge, health and service checks Co-Authored-By: Claude Sonnet 5.5 --- .../serverdetail/ServerHealthCard.jsx | 102 ++++++++++++++++ .../serverdetail/ServerOverviewTab.jsx | 3 + frontend/src/i18n/locales/en.json | 37 ++++++ frontend/src/pages/Incidents.jsx | 5 +- frontend/src/pages/Servers.jsx | 114 ++++++++++++++++-- frontend/src/styles/pages/_servers.scss | 43 +++++++ .../__tests__/agentPermissionLevel.test.mjs | 28 +++++ frontend/src/utils/agentPermissionLevel.js | 53 ++++++++ 8 files changed, 376 insertions(+), 9 deletions(-) create mode 100644 frontend/src/components/serverdetail/ServerHealthCard.jsx create mode 100644 frontend/src/utils/__tests__/agentPermissionLevel.test.mjs create mode 100644 frontend/src/utils/agentPermissionLevel.js diff --git a/frontend/src/components/serverdetail/ServerHealthCard.jsx b/frontend/src/components/serverdetail/ServerHealthCard.jsx new file mode 100644 index 00000000..9a97d277 --- /dev/null +++ b/frontend/src/components/serverdetail/ServerHealthCard.jsx @@ -0,0 +1,102 @@ +import { useEffect, useState } from 'react'; +import api from '../../services/api'; +import { DataTable, Pill } from '@/components/ds'; +import { InfoList, InfoItem } from '../InfoList'; +import { useTranslation } from 'react-i18next'; +import { formatDateTime } from '@/utils/intl'; +import { levelKind, serverHealth } from '@/utils/agentPermissionLevel'; + +const SET_HINT = 'serverkit-agent permissions set '; + +const checkKind = (status) => { + if (status === 'up') return 'green'; + if (status === 'down') return 'red'; + if (status === 'degraded') return 'amber'; + return 'gray'; +}; + +// Read-only by design: the permission level is enforced by the agent and can +// only be changed on the server itself, so there is deliberately no control. +const ServerHealthCard = ({ server }) => { + const { t } = useTranslation(); + const [alerts, setAlerts] = useState([]); + + useEffect(() => { + let alive = true; + api.getFleetAlerts({ server_id: server.id, status: 'active', limit: 20 }) + .then((res) => { if (alive) setAlerts((Array.isArray(res) ? res : []).filter((a) => a.detail)); }) + .catch(() => { if (alive) setAlerts([]); }); + return () => { alive = false; }; + }, [server.id, server.status, server.last_report_at]); + + const level = server.permission_level_effective || 'full'; + const health = serverHealth(server); + const mismatch = server.requested_permission_level + && server.permission_level + && server.requested_permission_level !== server.permission_level; + const levelName = { + monitor: t('app.serverHealthCard.monitor', 'Monitor'), + protect: t('app.serverHealthCard.protect', 'Protect'), + full: t('app.serverHealthCard.full', 'Full'), + }[level]; + + const columns = [ + { key: 'name', headerKey: 'app.serverHealthCard.service', header: 'Service', sortable: false, hideable: false, render: (c) => c.name }, + { key: 'kind', headerKey: 'app.serverHealthCard.kind', header: 'Kind', sortable: false, cellClassName: 'sk-cell-dim', render: (c) => c.kind || '—' }, + { key: 'status', headerKey: 'common.labels.status', header: 'Status', sortable: false, render: (c) => {c.status} }, + { key: 'detail', headerKey: 'app.serverHealthCard.detail', header: 'Detail', sortable: false, cellClassName: 'sk-cell-dim', render: (c) => c.detail || '—' }, + { key: 'checked', headerKey: 'app.serverHealthCard.lastChecked', header: 'Last checked', sortable: false, cellClassName: 'sk-cell-dim', render: (c) => (c.checked_at ? formatDateTime(c.checked_at) : '—') }, + ]; + + return ( + <> +
+

{t('app.serverHealthCard.permissionLevel', 'Permission level')}

+ + + {levelName} + {!server.permission_level && ( + {t('app.serverHealthCard.legacyAgent', 'Not reported (legacy agent, treated as Full)')} + )} + + + + {mismatch && ( +

+ {t('app.serverHealthCard.mismatch', 'The install command requested a different level than the agent reports. The agent\'s level is the one in effect.')} +

+ )} +

+ {t('app.serverHealthCard.howToChange', 'This level is enforced by the agent and cannot be changed from the panel. To change it, run this on the server as root:')} +

+ {SET_HINT} +
+ +
+

{t('app.serverHealthCard.health', 'Health')} {health.code}

+ {server.last_report_at && ( +

+ {t('app.serverHealthCard.lastReport', 'Last report')}: {formatDateTime(server.last_report_at)} +

+ )} + {alerts.length > 0 && ( +
    + {alerts.map((a) =>
  • {a.detail}
  • )} +
+ )} + +
+ + ); +}; + +export default ServerHealthCard; diff --git a/frontend/src/components/serverdetail/ServerOverviewTab.jsx b/frontend/src/components/serverdetail/ServerOverviewTab.jsx index 909867fb..0dcba474 100644 --- a/frontend/src/components/serverdetail/ServerOverviewTab.jsx +++ b/frontend/src/components/serverdetail/ServerOverviewTab.jsx @@ -2,6 +2,7 @@ import { serverStatusKind } from './serverDetailData'; import { Pill, KpiBand } from '../ds'; import OnboardingWizard from '../server/OnboardingWizard'; import SystemStatusCard from './SystemStatusCard'; +import ServerHealthCard from './ServerHealthCard'; import { formatBytes } from '@/utils/formatBytes'; import { InfoList, InfoItem } from '../InfoList'; import { useTranslation } from 'react-i18next'; @@ -163,6 +164,8 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => + +
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 23a8d25e..02a7c335 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -5443,6 +5443,24 @@ "theAgentUserIsnTIn": "The agent user isn't in the", "theNpipeSocket": "The npipe socket" }, + "serverHealthCard": { + "changedAt": "Last change", + "detail": "Detail", + "full": "Full", + "health": "Health", + "howToChange": "This level is enforced by the agent and cannot be changed from the panel. To change it, run this on the server as root:", + "kind": "Kind", + "lastChecked": "Last checked", + "lastReport": "Last report", + "legacyAgent": "Not reported (legacy agent, treated as Full)", + "level": "Level", + "mismatch": "The install command requested a different level than the agent reports. The agent's level is the one in effect.", + "monitor": "Monitor", + "noChecks": "No service checks reported yet.", + "permissionLevel": "Permission level", + "protect": "Protect", + "service": "Service" + }, "serverKitLogo": { "serverkitLogo": "ServerKit logo" }, @@ -5674,10 +5692,28 @@ "groupDeleted": "Group deleted", "groupUpdated": "Group updated", "groups": "Groups", + "health": "Health", + "healthDegraded": "Degraded", + "healthFailing": "Failing", + "healthHealthy": "Healthy", + "healthOffline": "Offline", + "healthPending": "Pending", + "healthStale": "Stale", "host": "Host", "hostname": "Hostname:", "lastSeen": "Last seen", "leaveBlankToUseTheAgent": "Leave blank to use the agent's hostname.", + "levelColumn": "Level", + "levelEnforcedByAgent": "The level is enforced by the agent and can only be changed on the server itself, with", + "levelFull": "Full", + "levelFullCan": "Everything the agent supports: Docker, files, terminal, packages, services and more.", + "levelFullCannot": "No restrictions. Choose this only for servers you want this panel to fully manage.", + "levelMonitor": "Monitor", + "levelMonitorCan": "Reports CPU, memory, disk and service health (web server, PHP-FPM, database) to this panel.", + "levelMonitorCannot": "Cannot run commands, open a terminal or change anything. The panel cannot send it any instructions.", + "levelProtect": "Protect", + "levelProtectCan": "Everything in Monitor, plus firewall, fail2ban, CrowdSec and Cloudflare origin-lock actions.", + "levelProtectCannot": "Cannot touch Docker, files, packages, services, shell or updates.", "linkPanel": "Link panel", "linux": "Linux", "manageServerGroups": "Manage server groups", @@ -5700,6 +5736,7 @@ "passphrase": "Passphrase *", "pasteThisIntoTheAgentOr": "Paste this into the agent, or run the installer.", "pending": "Pending", + "permissionLevel": "Permission level", "runAsAdministrator": "Run as administrator", "scanningFleet": "Scanning fleet…", "searchServers": "Search servers…", diff --git a/frontend/src/pages/Incidents.jsx b/frontend/src/pages/Incidents.jsx index 02806416..27a57c07 100644 --- a/frontend/src/pages/Incidents.jsx +++ b/frontend/src/pages/Incidents.jsx @@ -288,9 +288,10 @@ export default function Incidents() { kind: 'alert', key: `fleet-${alert.id}`, alertId: alert.id, - title: `${metric} over limit on ${subject}`, + // Offline / service-check alerts carry their own message and no threshold. + title: alert.detail || `${metric} over limit on ${subject}`, subject, - detail: `${metric} ${formatValue(alert.value)} / ${alert.threshold}`, + detail: alert.detail || `${metric} ${formatValue(alert.value)} / ${alert.threshold}`, state: alert.status, tone: alertStatusKind(alert.status), impact: alert.severity, diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsx index ea743b98..99088d97 100644 --- a/frontend/src/pages/Servers.jsx +++ b/frontend/src/pages/Servers.jsx @@ -29,6 +29,9 @@ import { useTranslation } from 'react-i18next'; import { t } from '../i18n/t'; import { toastError } from '@/utils/errorMessage'; import { formatDate } from '@/utils/intl'; +import { + DEFAULT_LEVEL, PERMISSION_LEVELS, buildInstallCommands, levelKind, serverHealth, +} from '@/utils/agentPermissionLevel'; // Radix Select items cannot use '' — stands in for "no group". const NO_GROUP = '__none'; @@ -231,6 +234,38 @@ const SERVER_COLUMNS = [ return {status}; }, }, + { + key: 'level', + headerKey: 'app.servers.levelColumn', header: 'Level', + sortable: true, + type: 'enum', + // NULL is a legacy agent that predates levels, which acts as full. + value: (server) => server.permission_level_effective || 'full', + sortValue: (server) => server.permission_level_effective || 'full', + groupable: true, + render: (server) => { + const level = server.permission_level_effective || 'full'; + return ( + + {levelLabel(level)} + + ); + }, + }, + { + key: 'health', + headerKey: 'app.servers.health', header: 'Health', + sortable: false, + render: (server) => { + const health = serverHealth(server); + const detail = health.failing.length ? ` (${health.failing.join(', ')})` : ''; + return ( + + {healthLabel(health.code) + detail} + + ); + }, + }, meterColumn('cpu', 'CPU', 'cpu_percent'), meterColumn('memory', 'Memory', 'memory_percent'), meterColumn('disk', 'Disk', 'disk_percent'), @@ -766,12 +801,72 @@ const EXPIRY_OPTIONS = [ ]; const DEFAULT_EXPIRY = 7 * 24 * 60 * 60; +const SET_HINT = 'serverkit-agent permissions set '; + +const levelLabel = (level) => { + if (level === 'monitor') return t('app.servers.levelMonitor', 'Monitor'); + if (level === 'protect') return t('app.servers.levelProtect', 'Protect'); + return t('app.servers.levelFull', 'Full'); +}; + +const healthLabel = (code) => { + switch (code) { + case 'healthy': return t('app.servers.healthHealthy', 'Healthy'); + case 'degraded': return t('app.servers.healthDegraded', 'Degraded'); + case 'failing': return t('app.servers.healthFailing', 'Failing'); + case 'stale': return t('app.servers.healthStale', 'Stale'); + case 'offline': return t('app.servers.healthOffline', 'Offline'); + default: return t('app.servers.healthPending', 'Pending'); + } +}; + +const LevelPicker = ({ value, onChange }) => { + const { t } = useTranslation(); + const copy = { + monitor: { + can: t('app.servers.levelMonitorCan', 'Reports CPU, memory, disk and service health (web server, PHP-FPM, database) to this panel.'), + cannot: t('app.servers.levelMonitorCannot', 'Cannot run commands, open a terminal or change anything. The panel cannot send it any instructions.'), + }, + protect: { + can: t('app.servers.levelProtectCan', 'Everything in Monitor, plus firewall, fail2ban, CrowdSec and Cloudflare origin-lock actions.'), + cannot: t('app.servers.levelProtectCannot', 'Cannot touch Docker, files, packages, services, shell or updates.'), + }, + full: { + can: t('app.servers.levelFullCan', 'Everything the agent supports: Docker, files, terminal, packages, services and more.'), + cannot: t('app.servers.levelFullCannot', 'No restrictions. Choose this only for servers you want this panel to fully manage.'), + }, + }; + return ( +
+ {t('app.servers.permissionLevel', 'Permission level')} +
+ {PERMISSION_LEVELS.map((level) => ( + + ))} +
+ + {t('app.servers.levelEnforcedByAgent', 'The level is enforced by the agent and can only be changed on the server itself, with')} + {' '}{SET_HINT} + +
+ ); +}; + const AddServerModal = ({ groups, onClose, onCreated }) => { const { t } = useTranslation(); const [mode, setMode] = useState('install'); const [step, setStep] = useState(1); const [groupId, setGroupId] = useState(''); const [expiresIn, setExpiresIn] = useState(DEFAULT_EXPIRY); + const [level, setLevel] = useState(DEFAULT_LEVEL); const [registrationData, setRegistrationData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); @@ -789,6 +884,7 @@ const AddServerModal = ({ groups, onClose, onCreated }) => { const result = await api.createServer({ expires_in: expiresIn, group_id: groupId || undefined, + requested_level: level, }); setRegistrationData(result); setStep(2); @@ -808,13 +904,15 @@ const AddServerModal = ({ groups, onClose, onCreated }) => { // the operator sees one line of curl noise, the shell says success, and // nothing was installed. The `&&` makes a failed fetch stop the command and // surface curl's non-zero exit (issue #101). - const linuxInstallScript = registrationData ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh -o /tmp/serverkit-agent-install.sh && \\ - sudo bash /tmp/serverkit-agent-install.sh \\ - --server "${window.location.origin}" \\ - --token "${registrationData.registration_token}"` : ''; - - const windowsInstallScript = registrationData ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex -Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registrationData.registration_token}"` : ''; + const installCommands = registrationData + ? buildInstallCommands({ + origin: window.location.origin, + token: registrationData.registration_token, + level, + }) + : { linux: '', windows: '' }; + const linuxInstallScript = installCommands.linux; + const windowsInstallScript = installCommands.windows; // A right-side drawer, not a centred dialog: this flow is a multi-step // wizard with install scripts in it, and it always was a drawer — the @@ -887,6 +985,8 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio {t('app.servers.generateASingleConnectionStringPaste', "Generate a single connection string. Paste it into the agent's pairing wizard, or use it with the one-liner installer. The agent's hostname becomes the server name on first connect; you can rename it later from the server's Settings tab.")}

+ +
diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scss index e880c251..f45ce5d1 100644 --- a/frontend/src/styles/pages/_servers.scss +++ b/frontend/src/styles/pages/_servers.scss @@ -2580,3 +2580,46 @@ flex-direction: column; gap: $space-3; } + +// Permission-level picker in the Add Server drawer +.level-picker { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: $space-2; + + &__opt { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: $space-1; + padding: $space-3; + text-align: start; + background: $bg-card; + border: 1px solid $border-subtle; + border-radius: $radius-control; + cursor: pointer; + transition: border-color $transition-fast, background $transition-fast; + + &:hover { + border-color: $border-active; + } + + &.is-active { + border-color: var(--accent-dim); + background: var(--accent-bg); + } + } + + &__head { + font-size: $text-xs; + font-weight: $font-weight-semibold; + color: $text-primary; + } + + &__desc { + font-size: $text-xs; + color: $text-tertiary; + line-height: 1.45; + white-space: normal; + } +} diff --git a/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs b/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs new file mode 100644 index 00000000..68e5d4f9 --- /dev/null +++ b/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { buildInstallCommands, normalizeLevel, serverHealth } from '../agentPermissionLevel.js'; + +const NOW = Date.parse('2026-01-01T12:00:00Z'); +const ago = (s) => new Date(NOW - s * 1000).toISOString(); + +test('install commands carry the level', () => { + const cmds = buildInstallCommands({ origin: 'https://p.example', token: 'T', level: 'protect' }); + assert.match(cmds.linux, /--level protect$/); + assert.match(cmds.windows, /-Level protect$/); +}); + +test('unknown level falls back to monitor', () => { + assert.equal(normalizeLevel('root'), null); + const cmds = buildInstallCommands({ origin: 'o', token: 'T', level: 'root' }); + assert.match(cmds.linux, /--level monitor$/); +}); + +test('health combines status, report age and checks', () => { + const base = { status: 'online', last_report_at: ago(30), report_interval_seconds: 60 }; + assert.equal(serverHealth(base, NOW).code, 'healthy'); + assert.equal(serverHealth({ ...base, service_checks: [{ name: 'mysql', status: 'down' }] }, NOW).code, 'failing'); + assert.equal(serverHealth({ ...base, service_checks: [{ name: 'php', status: 'degraded' }] }, NOW).kind, 'amber'); + assert.equal(serverHealth({ ...base, last_report_at: ago(600) }, NOW).code, 'stale'); + assert.equal(serverHealth({ ...base, status: 'offline' }, NOW).kind, 'red'); + assert.equal(serverHealth({ status: 'pending' }, NOW).code, 'pending'); +}); diff --git a/frontend/src/utils/agentPermissionLevel.js b/frontend/src/utils/agentPermissionLevel.js new file mode 100644 index 00000000..056fbf6c --- /dev/null +++ b/frontend/src/utils/agentPermissionLevel.js @@ -0,0 +1,53 @@ +// Agent permission levels: install-command builder and server health summary. +// The level is enforced by the agent and only reported to the panel; nothing +// here (or anywhere in the UI) changes it. + +export const PERMISSION_LEVELS = ['monitor', 'protect', 'full']; +export const DEFAULT_LEVEL = 'monitor'; + +const MIN_SILENCE_MS = 3 * 60 * 1000; + +export function normalizeLevel(level) { + return PERMISSION_LEVELS.includes(level) ? level : null; +} + +export function levelKind(level) { + if (level === 'monitor') return 'cyan'; + if (level === 'protect') return 'violet'; + return 'amber'; +} + +export function buildInstallCommands({ origin, token, level }) { + const lvl = normalizeLevel(level) || DEFAULT_LEVEL; + return { + linux: `curl -fsSL ${origin}/api/v1/servers/install.sh -o /tmp/serverkit-agent-install.sh && \\ + sudo bash /tmp/serverkit-agent-install.sh \\ + --server "${origin}" \\ + --token "${token}" \\ + --level ${lvl}`, + windows: `irm ${origin}/api/v1/servers/install.ps1 | iex +Install-ServerKitAgent -Server "${origin}" -Token "${token}" -Level ${lvl}`, + }; +} + +// Health = online/offline + report age + failing service checks. +// -> { kind: Pill kind, code, failing: [check names], degraded: [check names] } +export function serverHealth(server, now = Date.now()) { + const status = server.status || 'pending'; + if (status === 'pending' || status === 'connecting') { + return { kind: 'gray', code: 'pending', failing: [], degraded: [] }; + } + const checks = server.service_checks || []; + const failing = checks.filter((c) => c.status === 'down').map((c) => c.name); + const degraded = checks.filter((c) => c.status === 'degraded').map((c) => c.name); + if (status !== 'online') return { kind: 'red', code: 'offline', failing, degraded }; + + const seen = server.last_report_at || server.last_seen; + const limit = Math.max(MIN_SILENCE_MS, 3 * 1000 * (server.report_interval_seconds || 0)); + if (seen && now - new Date(seen).getTime() > limit) { + return { kind: 'amber', code: 'stale', failing, degraded }; + } + if (failing.length) return { kind: 'red', code: 'failing', failing, degraded }; + if (degraded.length) return { kind: 'amber', code: 'degraded', failing, degraded }; + return { kind: 'green', code: 'healthy', failing, degraded }; +} From 0aab404e35d4bc2f86ed45887fff79c379195f98 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 00:31:21 -0500 Subject: [PATCH 03/70] refactor(agents): raise typed errors from the report endpoint Keeps the hand-shaped error-body ratchet at its ceiling. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/agent_report.py | 15 +++++++++------ backend/app/exceptions.py | 6 ++++++ docs/MIGRATION_INVENTORY.md | 4 ++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/backend/app/api/agent_report.py b/backend/app/api/agent_report.py index 870c74cd..958c2321 100644 --- a/backend/app/api/agent_report.py +++ b/backend/app/api/agent_report.py @@ -13,6 +13,9 @@ Auth (no JWT/CSRF; the HMAC is the credential): from flask import Blueprint, jsonify, request from app import limiter +from app.exceptions import ( + AuthenticationError, PayloadTooLargeError, PermissionDeniedError, ValidationError, +) from app.services import agent_health_service, permission_levels from app.utils.ip_utils import is_ip_allowed @@ -31,23 +34,23 @@ def _rate_key(): @limiter.limit("30 per minute", key_func=_rate_key) def report(): if (request.content_length or 0) > MAX_BODY_BYTES: - return jsonify({'error': 'payload too large'}), 413 + raise PayloadTooLargeError() raw = request.get_data(cache=True) if len(raw) > MAX_BODY_BYTES: - return jsonify({'error': 'payload too large'}), 413 + raise PayloadTooLargeError() server = agent_health_service.authenticate_report(raw, request.headers, MAX_SKEW_SECONDS) if not server: - return jsonify({'error': 'authentication failed'}), 401 + raise AuthenticationError('authentication failed') if server.allowed_ips and not is_ip_allowed(request.remote_addr, server.allowed_ips): - return jsonify({'error': 'IP not allowed'}), 403 + raise PermissionDeniedError('IP not allowed') body = request.get_json(silent=True) if not isinstance(body, dict): - return jsonify({'error': 'JSON object required'}), 400 + raise ValidationError('JSON object required') level = body.get('permission_level') if level not in permission_levels.LEVELS: - return jsonify({'error': 'permission_level must be monitor, protect or full'}), 400 + raise ValidationError('permission_level must be monitor, protect or full') interval = agent_health_service.ingest_report(server, level, body) return jsonify({'ok': True, 'interval_seconds': interval}) diff --git a/backend/app/exceptions.py b/backend/app/exceptions.py index 52f896b4..d0dcb47f 100644 --- a/backend/app/exceptions.py +++ b/backend/app/exceptions.py @@ -57,6 +57,12 @@ class PermissionDeniedError(ApplicationError, PermissionError): default_message = 'Access denied' +class PayloadTooLargeError(ApplicationError): + status_code = 413 + code = 'payload_too_large' + default_message = 'Payload too large' + + class NotFoundError(ApplicationError, LookupError): status_code = 404 code = 'not_found' diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index f8323690..a906a013 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -16,12 +16,12 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`. | Routes on bare @jwt_required() | auth_required() / role decorators | 598 | 598 | REGISTERED EXCEPTION: JWT-only is the deliberate default; conversion grants API-key access and happens per route, on decision | | HTTP statuses chosen by sniffing error text | typed errors from app.exceptions | 0 | 0 | INVARIANT at 0 - migration completed 2026-08-19 | | API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 | -| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 855 | 850 | migrate when touched; new endpoints raise | +| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise | | Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched | | Controller-boundary violations (routes doing service work) | service layer extraction | 453 | 453 | migrate when touched (first-wave ratchet) | | raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 374 | 398 | migrate when touched | | per-page toast.error extractions in pages/ | E1: query-layer error presentation | 191 | 206 | migrate when touched | -| hand-rolled form-group blocks | F2: FormField/useForm | 314 | 321 | migrate when touched | +| hand-rolled form-group blocks | F2: FormField/useForm | 315 | 321 | migrate when touched | | unencoded ?k=${v} query interpolations in services/api | C4: buildQuery/encoding template | 0 | 0 | INVARIANT at 0 | | raw setInterval pollers | E2: usePolling/refetchInterval | 7 | 7 | DELIBERATE RESIDUE: clock ticks, socket-fallback hooks, and sibling-repo extension timers - each listed per file | | direct navigator.clipboard call sites | F3: copyToClipboard | 0 | 0 | INVARIANT at 0 | From 89cb31535329ea3d85fd835d217043b501c4477f Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 00:32:48 -0500 Subject: [PATCH 04/70] chore(agents): re-vendor agent installers with --level support Synced from the agent repo's feat/agent-permission-levels branch; the drift check will pass once that branch is released. --- scripts/install.ps1 | 103 ++++++++++++++++++++++++++++++++++++++-- scripts/install.sh | 112 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 210 insertions(+), 5 deletions(-) mode change 100644 => 100755 scripts/install.sh diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 4f3e219b..645fc563 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -30,6 +30,17 @@ .PARAMETER Version Specific agent version to install (optional, defaults to latest) +.PARAMETER Level + Permission level: monitor (report-only, no inbound commands), protect + (security actions only) or full (everything). If omitted: a menu on an + interactive console, otherwise full with a warning. + +.PARAMETER Reconfigure + Required to change the level of an already-installed agent. + +.PARAMETER Yes + Skip the typed confirmation when reconfiguring. + .EXAMPLE .\install.ps1 -Token "sk_reg_xxx" -Server "https://your-serverkit.com" @@ -53,7 +64,15 @@ param( [string]$Name, [Parameter(Mandatory=$false)] - [string]$Version = "latest" + [string]$Version = "latest", + + [Parameter(Mandatory=$false)] + [ValidateSet("monitor", "protect", "full")] + [string]$Level, + + [switch]$Reconfigure, + + [switch]$Yes ) # Configuration @@ -172,11 +191,61 @@ function New-ConfigDirectory { } } +# Level recorded in an existing config ("" when none; no key = legacy = full). +function Get-InstalledLevel { + $cfg = Join-Path $ConfigDir "config.yaml" + if (-not (Test-Path $cfg)) { return "" } + $m = Select-String -Path $cfg -Pattern '^\s+level:\s*"?(\w+)"?' | Select-Object -First 1 + if ($m) { return $m.Matches[0].Groups[1].Value } + return "full" +} + +# Refuses to silently change an installed agent's level; returns the level to use. +function Resolve-Level { + param([string]$Level, [bool]$Reconfigure, [bool]$Yes) + + $current = Get-InstalledLevel + if ($current) { + if (-not $Level) { return $current } + if ($Level -eq $current) { return $Level } + if (-not $Reconfigure) { + Write-ColorOutput "This agent is already installed at level '$current'. Re-run with -Reconfigure to change it to '$Level'." "Error" + exit 1 + } + if (-not $Yes) { + $answer = Read-Host "Changing level $current -> $Level. Type '$Level' to confirm" + if ($answer -ne $Level) { + Write-ColorOutput "Confirmation did not match; permission level unchanged (use -Yes for scripted use)" "Error" + exit 1 + } + } + $script:ChangeLevelFrom = $current + return $Level + } + if ($Level) { return $Level } + if ([Environment]::UserInteractive -and -not [Console]::IsInputRedirected) { + Write-Host "" + Write-Host " Choose what this agent may do on this server:" + Write-Host " 1) monitor report-only, accepts no commands from the panel" + Write-Host " 2) protect security actions only (firewall, fail2ban, CrowdSec, origin lock)" + Write-Host " 3) full everything" + switch (Read-Host " Selection [1-3]") { + "1" { return "monitor" } + "2" { return "protect" } + "3" { return "full" } + default { Write-ColorOutput "Invalid selection" "Error"; exit 1 } + } + } + Write-ColorOutput "No -Level given and no console: defaulting to FULL control. Pass -Level monitor|protect|full to choose." "Warning" + return "full" +} + function Register-Agent { param( [string]$Token, [string]$Server, - [string]$Name + [string]$Name, + [string]$Level ) Write-ColorOutput "Registering agent with ServerKit..." "Info" @@ -188,6 +257,11 @@ function Register-Agent { if ($Name) { $arguments += @("--name", $Name) } + $arguments += @("--level", $Level) + + if ($script:ChangeLevelFrom) { + Start-Process -FilePath $agentPath -ArgumentList @("--config", $configPath, "permissions", "set", $Level, "--yes") -Wait -NoNewWindow | Out-Null + } try { $process = Start-Process -FilePath $agentPath -ArgumentList $arguments -Wait -PassThru -NoNewWindow @@ -307,7 +381,15 @@ function Install-ServerKitAgent { [string]$Name, [Parameter(Mandatory=$false)] - [string]$Version = "latest" + [string]$Version = "latest", + + [Parameter(Mandatory=$false)] + [ValidateSet("monitor", "protect", "full")] + [string]$Level, + + [switch]$Reconfigure, + + [switch]$Yes ) # Update script-level variables @@ -321,19 +403,30 @@ function Install-ServerKitAgent { exit 1 } + $Level = Resolve-Level -Level $Level -Reconfigure $Reconfigure.IsPresent -Yes $Yes.IsPresent + Get-LatestVersion Install-Agent New-ConfigDirectory - Register-Agent -Token $Token -Server $Server -Name $Name + Register-Agent -Token $Token -Server $Server -Name $Name -Level $Level Install-WindowsService Start-AgentService Add-ToPath Write-SuccessMessage + Write-Host "Permission level: $($Level.ToUpper())" -ForegroundColor Yellow + switch ($Level) { + "monitor" { Write-Host " Report-only: this agent sends metrics out and accepts NO commands." } + "protect" { Write-Host " Security actions only (firewall, fail2ban, CrowdSec, origin lock)." } + default { Write-Host " Full control: the panel can run any supported action." } + } + Write-Host " Change it (elevated prompt, this machine only):" + Write-Host " & '$InstallDir\$AgentBinary' permissions set " + Write-Host "" } # Direct execution with parameters if ($Token -and $Server) { - Install-ServerKitAgent -Token $Token -Server $Server -Name $Name -Version $Version + Install-ServerKitAgent -Token $Token -Server $Server -Name $Name -Version $Version -Level $Level -Reconfigure:$Reconfigure -Yes:$Yes } elseif ($PSBoundParameters.Count -gt 0) { Write-ColorOutput "Both -Token and -Server parameters are required" "Error" diff --git a/scripts/install.sh b/scripts/install.sh old mode 100644 new mode 100755 index 8eb38928..64347495 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -30,8 +30,16 @@ # --server, -s ServerKit server URL (required) # --name, -n Display name for this server (optional) # --version, -v Specific agent version to install (optional, defaults to latest) +# --level, -l Permission level: monitor | protect | full (see below) +# --reconfigure Allow changing the level of an already-installed agent +# --yes, -y Skip the typed confirmation when reconfiguring # --help, -h Show this help message # +# Permission levels: monitor = report-only (no inbound commands), protect = +# security actions only (firewall, fail2ban, CrowdSec, Cloudflare origin lock), +# full = everything. Omitted: a menu on a terminal; `full` (with a warning) +# when non-interactive, for compatibility with older install commands. +# set -e @@ -67,6 +75,9 @@ TOKEN="" SERVER_URL="" SERVER_NAME="" VERSION="latest" +LEVEL="" +RECONFIGURE=false +ASSUME_YES=false # Version injected by the panel when it serves this script (the panel already # resolves the latest agent release for its update endpoints). Empty means @@ -108,6 +119,9 @@ show_help() { echo " --server, -s ServerKit server URL (required)" echo " --name, -n Display name for this server (optional)" echo " --version, -v Specific agent version (optional, defaults to latest)" + echo " --level, -l Permission level: monitor | protect | full (optional)" + echo " --reconfigure Allow changing the level of an already-installed agent" + echo " --yes, -y Skip the typed confirmation when reconfiguring" echo " --help, -h Show this help message" echo "" echo "Example:" @@ -142,6 +156,19 @@ parse_args() { VERSION="$2" shift 2 ;; + --level|-l) + [[ $# -ge 2 ]] || log_error "Option $1 requires a value" + LEVEL="$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]')" + shift 2 + ;; + --reconfigure) + RECONFIGURE=true + shift + ;; + --yes|-y) + ASSUME_YES=true + shift + ;; --help|-h) show_help ;; @@ -159,6 +186,72 @@ parse_args() { if [[ -z "$SERVER_URL" ]]; then log_error "Server URL is required. Use --server or -s" fi + + if [[ -n "$LEVEL" ]]; then + case "$LEVEL" in + monitor|protect|full) ;; + *) log_error "Unknown permission level '$LEVEL' (use monitor, protect or full)" ;; + esac + fi +} + +# Level recorded in an existing config ("" when none; a config without the +# key is a legacy install, which means full). +installed_level() { + local cfg="${CONFIG_DIR}/config.yaml" + [[ -f "$cfg" ]] || return 0 + local lvl + lvl="$(sed -n '/^permissions:/,/^[^ ]/ s/^[[:space:]]*level:[[:space:]]*//p' "$cfg" | head -n1 | tr -d "\"' \r")" + printf '%s' "${lvl:-full}" +} + +is_tty() { [[ -t 0 && -t 1 ]]; } + +# Refuse to silently change the level of an installed agent; --reconfigure +# plus a typed confirmation (or --yes) is required. +check_reconfigure() { + local current + current="$(installed_level)" + [[ -n "$current" ]] || return 0 + if [[ -z "$LEVEL" ]]; then + LEVEL="$current" + return 0 + fi + [[ "$LEVEL" != "$current" ]] || return 0 + if [[ "$RECONFIGURE" != true ]]; then + log_error "This agent is already installed at level '$current'. Re-run with --reconfigure to change it to '$LEVEL'." + fi + if [[ "$ASSUME_YES" != true ]]; then + local answer="" + if is_tty; then + read -r -p " Changing level ${current} -> ${LEVEL}. Type '${LEVEL}' to confirm: " answer + fi + [[ "$answer" == "$LEVEL" ]] || log_error "Confirmation did not match; permission level unchanged (use --yes for scripted use)" + fi + CHANGE_LEVEL_FROM="$current" +} + +# Pick a level when none was given: menu on a terminal, else full + warning. +resolve_level() { + [[ -z "$LEVEL" ]] || return 0 + if is_tty; then + echo "" + echo " Choose what this agent may do on this server:" + echo " 1) monitor report-only, accepts no commands from the panel" + echo " 2) protect security actions only (firewall, fail2ban, CrowdSec, origin lock)" + echo " 3) full everything (docker, files, terminal, packages, ...)" + local choice="" + read -r -p " Selection [1-3]: " choice + case "$choice" in + 1|monitor) LEVEL=monitor ;; + 2|protect) LEVEL=protect ;; + 3|full) LEVEL=full ;; + *) log_error "Invalid selection" ;; + esac + else + log_warn "No --level given and no terminal: defaulting to FULL control. Pass --level monitor|protect|full to choose." + LEVEL=full + fi } check_root() { @@ -351,6 +444,14 @@ register_agent() { if [[ -n "$SERVER_NAME" ]]; then REGISTER_CMD+=(--name "${SERVER_NAME}") fi + REGISTER_CMD+=(--level "${LEVEL}") + + # Re-installing at a different level: apply it locally first so the + # register step sees a consistent config. + if [[ -n "${CHANGE_LEVEL_FROM:-}" ]]; then + "${INSTALL_DIR}/${AGENT_BINARY}" --config "${CONFIG_DIR}/config.yaml" \ + permissions set "${LEVEL}" --yes >/dev/null 2>&1 || true + fi if ! "${REGISTER_CMD[@]}"; then log_error "Agent registration failed" @@ -448,6 +549,15 @@ print_success() { echo -e "${GREEN}║ Installation completed successfully! ║${NC}" echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}" echo "" + echo -e "${YELLOW}Permission level: ${LEVEL^^}${NC}" + case "$LEVEL" in + monitor) echo " Report-only: this agent sends metrics out and accepts NO commands." ;; + protect) echo " Security actions only (firewall, fail2ban, CrowdSec, origin lock)." ;; + *) echo " Full control: the panel can run any supported action." ;; + esac + echo " Change it (as root, on this machine only):" + echo " ${INSTALL_DIR}/${AGENT_BINARY} permissions set " + echo "" echo "Agent Status:" echo " Binary: ${INSTALL_DIR}/${AGENT_BINARY}" echo " Config: ${CONFIG_DIR}/config.yaml" @@ -466,6 +576,8 @@ main() { print_banner parse_args "$@" check_root + check_reconfigure + resolve_level detect_platform check_dependencies get_latest_version From be1968746f8e1810a116a993ff7bf8521bf04367 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 00:59:48 -0500 Subject: [PATCH 05/70] feat(frontend): icon-first permission level picker with info tooltips Each level card now shows an illustration, title and allowed/blocked capability icons; the full explanation moved into an (i) tooltip. The enforced-by-agent note is a single compact line. Co-Authored-By: Claude Sonnet 5.5 --- .../components/servers/LevelIllustrations.jsx | 49 +++++++++ frontend/src/i18n/locales/en.json | 5 +- frontend/src/pages/Servers.jsx | 76 ++++++++++--- frontend/src/styles/pages/_servers.scss | 100 ++++++++++++++++-- .../__tests__/agentPermissionLevel.test.mjs | 12 ++- frontend/src/utils/agentPermissionLevel.js | 18 ++++ 6 files changed, 236 insertions(+), 24 deletions(-) create mode 100644 frontend/src/components/servers/LevelIllustrations.jsx diff --git a/frontend/src/components/servers/LevelIllustrations.jsx b/frontend/src/components/servers/LevelIllustrations.jsx new file mode 100644 index 00000000..bb8671d3 --- /dev/null +++ b/frontend/src/components/servers/LevelIllustrations.jsx @@ -0,0 +1,49 @@ +// Small inline illustrations for the permission-level cards. They use +// currentColor plus the panel accent variables, so they follow the theme. +const common = { + viewBox: '0 0 96 56', + height: 56, + 'aria-hidden': true, + focusable: 'false', + fill: 'none', + stroke: 'currentColor', + strokeWidth: 2, + strokeLinecap: 'round', + strokeLinejoin: 'round', +}; + +const Monitor = () => ( + + + + + +); + +const Protect = () => ( + + + + + +); + +const Full = () => ( + + + + + + + + +); + +const ILLUSTRATIONS = { monitor: Monitor, protect: Protect, full: Full }; + +const LevelIllustration = ({ level }) => { + const Svg = ILLUSTRATIONS[level] || Monitor; + return ; +}; + +export default LevelIllustration; diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 02a7c335..a519601d 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -5670,6 +5670,8 @@ "agentFound": "Agent found", "agentPairedSuccessfully": "Agent paired", "autoDetectedFromAgentOptional": "Auto-detected from agent (optional)", + "capAllowed": "allowed", + "capBlocked": "blocked", "clearSelection": "Clear selection", "confirmThisFingerprintMatchesTheOne": "Confirm this fingerprint matches the one shown by the agent before continuing.", "connectionString": "Connection string", @@ -5704,10 +5706,11 @@ "lastSeen": "Last seen", "leaveBlankToUseTheAgent": "Leave blank to use the agent's hostname.", "levelColumn": "Level", - "levelEnforcedByAgent": "The level is enforced by the agent and can only be changed on the server itself, with", + "levelEnforcedShort": "Enforced on the server by the agent. Change with", "levelFull": "Full", "levelFullCan": "Everything the agent supports: Docker, files, terminal, packages, services and more.", "levelFullCannot": "No restrictions. Choose this only for servers you want this panel to fully manage.", + "levelInfo": "What can {{level}} do?", "levelMonitor": "Monitor", "levelMonitorCan": "Reports CPU, memory, disk and service health (web server, PHP-FPM, database) to this panel.", "levelMonitorCannot": "Cannot run commands, open a terminal or change anything. The panel cannot send it any instructions.", diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsx index 99088d97..485af69b 100644 --- a/frontend/src/pages/Servers.jsx +++ b/frontend/src/pages/Servers.jsx @@ -1,6 +1,8 @@ import { useState, useEffect, useCallback, useMemo, useId } from 'react'; import { useNavigate } from 'react-router-dom'; -import { ChevronRight, Folder, Plus, RefreshCw, Server as ServerLucideIcon, X } from 'lucide-react'; +import { Ban, ChevronRight, Container, Cpu, Database, Flame, Folder, HardDrive, Info, Lock, MemoryStick, Plus, RefreshCw, Server as ServerLucideIcon, Terminal, X } from 'lucide-react'; +import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'; +import LevelIllustration from '../components/servers/LevelIllustrations'; import api from '../services/api'; import { useToast } from '../contexts/useToast.js'; import EmptyState from '../components/EmptyState'; @@ -30,7 +32,7 @@ import { t } from '../i18n/t'; import { toastError } from '@/utils/errorMessage'; import { formatDate } from '@/utils/intl'; import { - DEFAULT_LEVEL, PERMISSION_LEVELS, buildInstallCommands, levelKind, serverHealth, + DEFAULT_LEVEL, PERMISSION_LEVELS, buildInstallCommands, levelAllows, levelKind, serverHealth, } from '@/utils/agentPermissionLevel'; // Radix Select items cannot use '' — stands in for "no group". @@ -820,6 +822,19 @@ const healthLabel = (code) => { } }; +const CAPABILITY_ICONS = { + cpu: [Cpu, 'CPU'], + memory: [MemoryStick, 'Memory'], + disk: [HardDrive, 'Disk'], + services: [ServerLucideIcon, 'Web server and PHP'], + database: [Database, 'Database'], + firewall: [Flame, 'Firewall'], + ban: [Ban, 'Ban (fail2ban, CrowdSec)'], + terminal: [Terminal, 'Terminal'], + docker: [Container, 'Docker'], + files: [Folder, 'Files'], +}; + const LevelPicker = ({ value, onChange }) => { const { t } = useTranslation(); const copy = { @@ -836,24 +851,59 @@ const LevelPicker = ({ value, onChange }) => { cannot: t('app.servers.levelFullCannot', 'No restrictions. Choose this only for servers you want this panel to fully manage.'), }, }; + const onKeyDown = (e, level) => { + if (e.key === ' ' || e.key === 'Enter') { + e.preventDefault(); + onChange(level); + } + }; return (
{t('app.servers.permissionLevel', 'Permission level')}
{PERMISSION_LEVELS.map((level) => ( - +
+
onChange(level)} + onKeyDown={(e) => onKeyDown(e, level)} + > + + {levelLabel(level)} + + {Object.entries(CAPABILITY_ICONS).map(([cap, [Icon, label]]) => { + const allowed = levelAllows(level, cap); + const text = `${label}: ${allowed ? t('app.servers.capAllowed', 'allowed') : t('app.servers.capBlocked', 'blocked')}`; + return ( + + + ); + })} + +
+ + + + + + {copy[level].can} + {copy[level].cannot} + + +
))}
- - {t('app.servers.levelEnforcedByAgent', 'The level is enforced by the agent and can only be changed on the server itself, with')} + +
diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scss index f45ce5d1..86532642 100644 --- a/frontend/src/styles/pages/_servers.scss +++ b/frontend/src/styles/pages/_servers.scss @@ -2584,42 +2584,124 @@ // Permission-level picker in the Add Server drawer .level-picker { display: grid; - grid-template-columns: repeat(3, 1fr); + grid-template-columns: repeat(3, minmax(0, 1fr)); gap: $space-2; + @media (max-width: 560px) { + grid-template-columns: 1fr; + } + + // The (i) button is a sibling of the radio card, not nested in it. + &__cell { + position: relative; + display: flex; + } + &__opt { + flex: 1; display: flex; flex-direction: column; - align-items: flex-start; - gap: $space-1; + align-items: center; + gap: $space-2; padding: $space-3; - text-align: start; + text-align: center; + color: $text-tertiary; background: $bg-card; border: 1px solid $border-subtle; border-radius: $radius-control; cursor: pointer; - transition: border-color $transition-fast, background $transition-fast; + transition: border-color $transition-fast, background $transition-fast, box-shadow $transition-fast; &:hover { border-color: $border-active; + background: $bg-elevated; + } + + &:focus-visible { + outline: 2px solid var(--accent-dim); + outline-offset: 2px; } &.is-active { + color: var(--accent); border-color: var(--accent-dim); background: var(--accent-bg); } } + &__art svg { + display: block; + width: auto; + max-width: 100%; + height: 56px; + } + &__head { - font-size: $text-xs; + font-size: $text-sm; font-weight: $font-weight-semibold; color: $text-primary; } - &__desc { - font-size: $text-xs; + &__caps { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: $space-1; + } + + &__cap { + position: relative; + display: inline-flex; + color: $text-secondary; + + .is-active & { + color: var(--accent); + } + + &.is-blocked { + color: $text-tertiary; + opacity: .5; + + &::after { + content: ''; + position: absolute; + inset: 50% -2px auto; + height: 1.5px; + background: currentColor; + transform: rotate(-45deg); + } + } + } + + &__info { + position: absolute; + top: $space-1; + inset-inline-end: $space-1; + display: inline-flex; + padding: $space-1; color: $text-tertiary; - line-height: 1.45; + background: none; + border: 0; + border-radius: 50%; + cursor: pointer; + + &:hover, + &:focus-visible { + color: $text-primary; + } + } + + &__tip { + flex-direction: column; + align-items: flex-start; + max-width: 260px; white-space: normal; } + + &__note { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: $space-1; + } } diff --git a/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs b/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs index 68e5d4f9..5b5e7a3a 100644 --- a/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs +++ b/frontend/src/utils/__tests__/agentPermissionLevel.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { buildInstallCommands, normalizeLevel, serverHealth } from '../agentPermissionLevel.js'; +import { buildInstallCommands, CAPABILITIES, levelAllows, normalizeLevel, serverHealth } from '../agentPermissionLevel.js'; const NOW = Date.parse('2026-01-01T12:00:00Z'); const ago = (s) => new Date(NOW - s * 1000).toISOString(); @@ -26,3 +26,13 @@ test('health combines status, report age and checks', () => { assert.equal(serverHealth({ ...base, status: 'offline' }, NOW).kind, 'red'); assert.equal(serverHealth({ status: 'pending' }, NOW).code, 'pending'); }); + +test('capability matrix per level', () => { + const blocked = (level) => CAPABILITIES.filter((c) => !levelAllows(level, c)); + assert.deepEqual(blocked('monitor'), ['firewall', 'ban', 'terminal', 'docker', 'files']); + assert.deepEqual(blocked('protect'), ['terminal', 'docker', 'files']); + assert.deepEqual(blocked('full'), []); + assert.equal(levelAllows('protect', 'firewall'), true); + assert.equal(levelAllows('protect', 'ban'), true); + assert.equal(levelAllows('bogus', 'terminal'), false); +}); diff --git a/frontend/src/utils/agentPermissionLevel.js b/frontend/src/utils/agentPermissionLevel.js index 056fbf6c..4d914e82 100644 --- a/frontend/src/utils/agentPermissionLevel.js +++ b/frontend/src/utils/agentPermissionLevel.js @@ -51,3 +51,21 @@ export function serverHealth(server, now = Date.now()) { if (degraded.length) return { kind: 'amber', code: 'degraded', failing, degraded }; return { kind: 'green', code: 'healthy', failing, degraded }; } + +// What each level lets the panel do on a server. Mirrors +// backend/app/services/permission_levels.py: monitor is report-only, protect +// adds the PROTECT_ACTIONS (firewall, fail2ban/CrowdSec, Cloudflare origin +// lock), full is everything. +export const CAPABILITIES = ['cpu', 'memory', 'disk', 'services', 'database', 'firewall', 'ban', 'terminal', 'docker', 'files']; +const HEALTH = ['cpu', 'memory', 'disk', 'services', 'database']; +const PROTECT = [...HEALTH, 'firewall', 'ban']; + +export const LEVEL_CAPABILITIES = { + monitor: HEALTH, + protect: PROTECT, + full: CAPABILITIES, +}; + +export function levelAllows(level, capability) { + return (LEVEL_CAPABILITIES[normalizeLevel(level) || DEFAULT_LEVEL] || []).includes(capability); +} From bddca28881272d9764db52a593290ae8d067c6c1 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 01:45:21 -0500 Subject: [PATCH 06/70] feat(frontend): less text, more icons - shared InfoTip, IconStepStrip and illustrations Move prose into tap-friendly (i) tips and replace intro paragraphs with icons, step strips and chips across settings, security, add-server, server detail, proxy, backups, downloads, imports, marketplace and templates. --- frontend/src/components/FormField.jsx | 19 +- frontend/src/components/IconStepStrip.jsx | 22 ++ frontend/src/components/InfoTip.jsx | 49 +++++ frontend/src/components/SectionIntro.jsx | 11 + .../components/backups/BackupsOverview.jsx | 10 +- frontend/src/components/ds/CatalogCard.jsx | 12 +- .../FileIntegrityIllustration.jsx | 8 + .../illustrations/LockShieldIllustration.jsx | 8 + .../src/components/proxy/ProxyLogoTiles.jsx | 22 ++ .../src/components/proxy/ProxyStackPanel.jsx | 11 +- .../src/components/security/IntegrityTab.jsx | 55 +++-- .../src/components/security/OverviewTab.jsx | 22 +- .../serverdetail/ServerSettingsTab.jsx | 22 +- .../src/components/servers/LinkPanelForm.jsx | 11 +- .../settings/AIConnectionsSettings.jsx | 15 +- .../settings/AIManagementSettings.jsx | 19 +- .../src/components/settings/AISettingsTab.jsx | 14 +- .../src/components/settings/AppearanceTab.jsx | 15 +- .../settings/SecuritySettingsTab.jsx | 17 +- .../components/settings/SiteSettingsTab.jsx | 59 ++---- .../src/components/settings/ThemeGallery.jsx | 10 +- frontend/src/i18n/locales/en.json | 31 ++- frontend/src/pages/Downloads.jsx | 14 +- frontend/src/pages/FleetProxy.jsx | 5 +- frontend/src/pages/ImportWizard.jsx | 49 +++-- frontend/src/pages/Servers.jsx | 26 +-- frontend/src/pages/Templates.jsx | 2 +- frontend/src/styles/components/_forms.scss | 10 + frontend/src/styles/components/_info-tip.scss | 192 ++++++++++++++++++ frontend/src/styles/main.scss | 1 + frontend/src/styles/pages/_import-wizard.scss | 17 +- frontend/src/styles/pages/_settings.scss | 5 + 32 files changed, 602 insertions(+), 181 deletions(-) create mode 100644 frontend/src/components/IconStepStrip.jsx create mode 100644 frontend/src/components/InfoTip.jsx create mode 100644 frontend/src/components/SectionIntro.jsx create mode 100644 frontend/src/components/illustrations/FileIntegrityIllustration.jsx create mode 100644 frontend/src/components/illustrations/LockShieldIllustration.jsx create mode 100644 frontend/src/components/proxy/ProxyLogoTiles.jsx create mode 100644 frontend/src/styles/components/_info-tip.scss diff --git a/frontend/src/components/FormField.jsx b/frontend/src/components/FormField.jsx index 4ec2a80a..b36cab57 100644 --- a/frontend/src/components/FormField.jsx +++ b/frontend/src/components/FormField.jsx @@ -2,6 +2,7 @@ import { useId, useMemo } from 'react'; import { Label } from '@/components/ui/label'; import { FieldContext } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; +import InfoTip from './InfoTip'; /** * Standard form field wrapper: label, hint, error message, and input slot. @@ -22,6 +23,7 @@ export function FormField({ children, error, hint, + info, required = false, className, labelClassName, @@ -42,12 +44,17 @@ export function FormField({ return (
- {label && ( - - )} + {label && (() => { + const labelEl = ( + + ); + return info + ?
{labelEl}{info}
+ : labelEl; + })()}
{children} diff --git a/frontend/src/components/IconStepStrip.jsx b/frontend/src/components/IconStepStrip.jsx new file mode 100644 index 00000000..b4c333ad --- /dev/null +++ b/frontend/src/components/IconStepStrip.jsx @@ -0,0 +1,22 @@ +import { Fragment } from 'react'; +import { ChevronRight } from 'lucide-react'; +import InfoTip from './InfoTip'; + +// 2-4 steps: icon tile, a short label and an optional (i) with the detail. +// steps = [{ icon: ReactNode, label: string, info?: ReactNode }] +export default function IconStepStrip({ steps, className = '' }) { + return ( +
    + {steps.map((s, i) => ( + + {i > 0 && } +
  1. + + {s.label} + {s.info && {s.info}} +
  2. +
    + ))} +
+ ); +} diff --git a/frontend/src/components/InfoTip.jsx b/frontend/src/components/InfoTip.jsx new file mode 100644 index 00000000..d88265ab --- /dev/null +++ b/frontend/src/components/InfoTip.jsx @@ -0,0 +1,49 @@ +import { useRef, useState } from 'react'; +import { Info } from 'lucide-react'; +import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'; +import { t } from '../i18n/t'; + +// An (i) button that holds the explanation a page used to print inline. +// Mouse: hover/focus previews it. Touch, click, Enter and Space: toggles a +// pinned popover that closes on outside tap or Escape. The panel is portalled +// (no button-in-button) and above Modal/Sheet (.info-tip__panel z-index). +export default function InfoTip({ children, label, side = 'top', size = 'sm', className = '' }) { + const [open, setOpen] = useState(false); + const pinned = useRef(false); + const hoverable = (e) => e.pointerType === 'mouse'; + + const onOpenChange = (next) => { + pinned.current = next; + setOpen(next); + }; + const stop = (e) => e.stopPropagation(); + + return ( + + + {/* eslint-disable-next-line no-restricted-syntax -- bare 18px glyph button; Button/IconButton add control-sized chrome and a nested Tip */} + + + e.preventDefault()} + onCloseAutoFocus={(e) => e.preventDefault()} + onClick={stop} + > + {children} + + + ); +} diff --git a/frontend/src/components/SectionIntro.jsx b/frontend/src/components/SectionIntro.jsx new file mode 100644 index 00000000..d4d75041 --- /dev/null +++ b/frontend/src/components/SectionIntro.jsx @@ -0,0 +1,11 @@ +import InfoTip from './InfoTip'; + +// One short line with the longer explanation tucked in an (i). +export default function SectionIntro({ children, info, className = '' }) { + return ( +

+ {children} + {info && {info}} +

+ ); +} diff --git a/frontend/src/components/backups/BackupsOverview.jsx b/frontend/src/components/backups/BackupsOverview.jsx index 90a282ff..4a24e119 100644 --- a/frontend/src/components/backups/BackupsOverview.jsx +++ b/frontend/src/components/backups/BackupsOverview.jsx @@ -9,6 +9,7 @@ import api from '../../services/api'; import { formatBytes } from '@/utils/formatBytes'; import { KpiBand, MetricCard, Pill, DataTable, DataTableFooter } from '@/components/ds'; import EmptyState from '../EmptyState'; +import InfoTip from '../InfoTip'; import { useTranslation } from 'react-i18next'; import { formatDuration, formatNumber } from '@/utils/intl'; @@ -407,9 +408,12 @@ export default function BackupsOverview({
))} {destinations.count === 1 && ( -

- - {t('app.backupsOverview.everythingIsOnOneDiskAdd', 'Everything is on one disk. Add a remote destination so a dead server doesn\'t take the backups with it.')} +

+ + + {t('app.backupsOverview.everythingIsOnOneDiskAdd', 'Everything is on one disk. Add a remote destination so a dead server doesn\'t take the backups with it.')}

)} diff --git a/frontend/src/components/ds/CatalogCard.jsx b/frontend/src/components/ds/CatalogCard.jsx index af4bc3fe..606d752c 100644 --- a/frontend/src/components/ds/CatalogCard.jsx +++ b/frontend/src/components/ds/CatalogCard.jsx @@ -2,6 +2,7 @@ import { Star } from 'lucide-react'; import { cn } from '@/lib/utils'; import { Button } from '@/components/ui/button'; import { t } from '@/i18n/t'; +import InfoTip from '@/components/InfoTip'; /** * The one card for things you browse to install or deploy: extensions, @@ -21,6 +22,9 @@ import { t } from '@/i18n/t'; * /> * * + * `description` lives in an (i) beside the tag, not as a paragraph; `chips` + * (short strings) show as a tag row in its place. + * * One tag, one action. Version, author and counts go in `sub` / `facts` as * plain text rather than as more badges. * @@ -35,6 +39,7 @@ export function CatalogCard({ sub, tag, description, + chips, facts, action, featured = false, @@ -78,8 +83,13 @@ export function CatalogCard({ {sub && {sub}} {tag && {tag}} + {description && {description}}
- {description &&

{description}

} + {chips?.length > 0 && ( +
+ {chips.map((c) => {c})} +
+ )} {(facts || action) && (
{facts} diff --git a/frontend/src/components/illustrations/FileIntegrityIllustration.jsx b/frontend/src/components/illustrations/FileIntegrityIllustration.jsx new file mode 100644 index 00000000..8a98d5fe --- /dev/null +++ b/frontend/src/components/illustrations/FileIntegrityIllustration.jsx @@ -0,0 +1,8 @@ +// Decorative; the surrounding text carries the meaning. +export default function FileIntegrityIllustration() { + return ( + + ); +} diff --git a/frontend/src/components/illustrations/LockShieldIllustration.jsx b/frontend/src/components/illustrations/LockShieldIllustration.jsx new file mode 100644 index 00000000..c6b47b0e --- /dev/null +++ b/frontend/src/components/illustrations/LockShieldIllustration.jsx @@ -0,0 +1,8 @@ +// Decorative; the surrounding text carries the meaning. +export default function LockShieldIllustration() { + return ( + + ); +} diff --git a/frontend/src/components/proxy/ProxyLogoTiles.jsx b/frontend/src/components/proxy/ProxyLogoTiles.jsx new file mode 100644 index 00000000..6bc54071 --- /dev/null +++ b/frontend/src/components/proxy/ProxyLogoTiles.jsx @@ -0,0 +1,22 @@ +import { SiNginx, SiTraefikproxy, SiCaddy } from 'react-icons/si'; +import { t } from '../../i18n/t'; + +// The three proxy choices as logo tiles with a one-line caption each. +export default function ProxyLogoTiles() { + const items = [ + { Icon: SiNginx, name: 'Nginx', sub: t('app.proxyLogoTiles.hostDefault', 'Host default') }, + { Icon: SiTraefikproxy, name: 'Traefik', sub: t('app.proxyLogoTiles.dockerStack', 'Docker stack') }, + { Icon: SiCaddy, name: 'Caddy', sub: t('app.proxyLogoTiles.dockerStack', 'Docker stack') }, + ]; + return ( +
    + {items.map(({ Icon, name, sub }) => ( +
  • + + {name} + {sub} +
  • + ))} +
+ ); +} diff --git a/frontend/src/components/proxy/ProxyStackPanel.jsx b/frontend/src/components/proxy/ProxyStackPanel.jsx index b3e5ead0..65fd1d2a 100644 --- a/frontend/src/components/proxy/ProxyStackPanel.jsx +++ b/frontend/src/components/proxy/ProxyStackPanel.jsx @@ -6,6 +6,8 @@ import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Pill, SegControl, serviceStatusKind } from '../ds'; import EmptyState from '../EmptyState'; +import InfoTip from '../InfoTip'; +import ProxyLogoTiles from './ProxyLogoTiles'; import { AlertTriangle, CheckCircle2, Network } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; @@ -199,9 +201,10 @@ const ProxyStackPanel = ({ serverId }) => {
-

- {t('app.proxyStackPanel.hostNginxIsTheDefaultAnd', 'Host Nginx is the default and is recommended for PHP/WordPress. You can opt into a Dockerized Traefik or Caddy proxy deployed as a Compose stack.')} -

+
+ + {t('app.proxyStackPanel.hostNginxIsTheDefaultAnd', 'Host Nginx is the default and is recommended for PHP/WordPress. You can opt into a Dockerized Traefik or Caddy proxy deployed as a Compose stack.')} +
{audit && audit.mismatch_count > 0 && (
@@ -301,7 +304,7 @@ const ProxyStackPanel = ({ serverId }) => { {t('app.proxyStackPanel.theHostSNginxIsHandling', 'The host\'s Nginx is handling reverse proxying. Switch to Traefik or Caddy above to run a managed Docker proxy stack instead.')}} /> )}
diff --git a/frontend/src/components/security/IntegrityTab.jsx b/frontend/src/components/security/IntegrityTab.jsx index 75de07b1..e8b3a9c2 100644 --- a/frontend/src/components/security/IntegrityTab.jsx +++ b/frontend/src/components/security/IntegrityTab.jsx @@ -11,6 +11,11 @@ import { import { useTableSort } from '@/hooks/useTableSort'; import { useColumnVisibility } from '@/hooks/useColumnVisibility'; import { useTranslation } from 'react-i18next'; +import { Camera, Eye, GitCompare, ShieldOff } from 'lucide-react'; +import InfoTip from '@/components/InfoTip'; +import IconStepStrip from '@/components/IconStepStrip'; +import SectionIntro from '@/components/SectionIntro'; +import FileIntegrityIllustration from '@/components/illustrations/FileIntegrityIllustration'; import { Card as SharedCard, CardHeader as SharedCardHeader, CardContent as SharedCardContent } from '@/components/ui/card'; // Scoped file-integrity monitoring: baseline-and-diff over the paths @@ -309,17 +314,26 @@ const IntegrityTab = () => { : clean)} -

- {baseline - ? t('app.integrityTab.baselineSummary', { + {baseline ? ( +

+ {t('app.integrityTab.baselineSummary', { count: baseline.file_count, age: formatAge(baseline.created_at) || t('app.integrityTab.unknownAge', 'unknown age'), defaultValue_one: 'Baseline: 1 file, {{age}}', defaultValue_other: 'Baseline: {{count}} files, {{age}}', - }) - : t('app.integrityTab.noBaselineYet', 'No baseline yet. Create one to start tracking changes.')} - {check && ` · ${t('app.integrityTab.lastCheck', 'Last check {{age}}', { age: formatAge(check.checked_at) || '' })}`} -

+ })} + {check && ` · ${t('app.integrityTab.lastCheck', 'Last check {{age}}', { age: formatAge(check.checked_at) || '' })}`} +

+ ) : ( +

+ + + {t('app.integrityTab.noBaselineYet', 'No baseline yet. Create one to start tracking changes.')} + {check && ` · ${t('app.integrityTab.lastCheck', 'Last check {{age}}', { age: formatAge(check.checked_at) || '' })}`} +

+ )} {/* These act on the SCOPE and are there whether or not the changes list is open, so they keep their own bar; the table's chrome rides the view line below. */} @@ -427,21 +441,34 @@ const IntegrityTab = () => {
)} -

- {t('app.integrityTab.baselineAndDiffMonitoringOverThe', 'Baseline-and-diff monitoring over the paths ServerKit manages. Baseline a scope, then check it (or let the scheduled sweep do it). Any added, removed or modified files are flagged and admins are notified. Accepting changes re-baselines the scope.')} -

+
+ +
+ + {t('app.integrityTab.headerLine', 'Detect changed config files.')} + + , label: t('app.integrityTab.stepBaseline', 'Baseline'), info: t('app.integrityTab.stepBaselineInfo', 'Snapshot the current files of a scope.') }, + { icon: , label: t('app.integrityTab.stepWatch', 'Watch'), info: t('app.integrityTab.stepWatchInfo', 'Check manually or let the scheduled sweep run.') }, + { icon: , label: t('app.integrityTab.stepDiff', 'Diff'), info: t('app.integrityTab.stepDiffInfo', 'Added, removed or modified files are flagged and admins are notified. Accepting re-baselines.') }, + ]} + /> +
+
{managedScopes.map(renderScopeCard)} {appScopes.map(renderScopeCard)} -

{t('app.integrityTab.applicationDocroots', 'Service docroots')} {t('app.integrityTab.optIn', '· opt-in')}

+

{t('app.integrityTab.applicationDocroots', 'Service docroots')} {t('app.integrityTab.optIn', '· opt-in')}{' '} + {t('app.integrityTab.watchingADocrootHashesEveryFile', 'Watching a docroot hashes every file outside upload/cache directories, so it is opt-in per service.')} +

-

- {t('app.integrityTab.watchingADocrootHashesEveryFile', 'Watching a docroot hashes every file outside upload/cache directories, so it is opt-in per service.')} -

{appsError ? ( ) : apps.length === 0 ? ( diff --git a/frontend/src/components/security/OverviewTab.jsx b/frontend/src/components/security/OverviewTab.jsx index ea30c7ff..9c413c8d 100644 --- a/frontend/src/components/security/OverviewTab.jsx +++ b/frontend/src/components/security/OverviewTab.jsx @@ -15,7 +15,10 @@ import { Siren, Bug, Radar, + Puzzle, + Bell, } from 'lucide-react'; +import InfoTip from '@/components/InfoTip'; import { Card as SharedCard, CardHeader as SharedCardHeader, CardContent as SharedCardContent } from '@/components/ui/card'; // Status glyph per check state — paired with the label so state never relies on @@ -196,17 +199,22 @@ const OverviewTab = ({ status, onRefresh, onNavigateTab }) => { })}
-

+

{!hasSecurityExtensions && ( <> - {t('app.overviewTab.moreSecurityTools', 'More security tools (malware scanning, brute-force protection, vulnerability scans, auto-updates) are available as extensions in the')} - {' '} - {t('app.overviewTab.marketplaceLink', 'Extensions')} - {'. '} + +
diff --git a/frontend/src/components/serverdetail/ServerSettingsTab.jsx b/frontend/src/components/serverdetail/ServerSettingsTab.jsx index 8627202c..d36fcce8 100644 --- a/frontend/src/components/serverdetail/ServerSettingsTab.jsx +++ b/frontend/src/components/serverdetail/ServerSettingsTab.jsx @@ -5,6 +5,7 @@ import { useToast } from '../../contexts/useToast.js'; import { useConfirm } from '../../hooks/useConfirm'; import CopyField from '@/components/CopyField'; import { InfoList, InfoItem } from '../InfoList'; +import InfoTip from '../InfoTip'; import { DangerZone } from '../DangerZone'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -45,12 +46,13 @@ const AgentRegistrationSection = ({ server, onRegenerateToken }) => {
-

{t('app.serverSettingsTab.connectionString', 'Connection string')}

-

+

{t('app.serverSettingsTab.connectionString', 'Connection string')} + {t('app.serverSettingsTab.generateAFreshConnectionStringTo', 'Generate a fresh connection string to pair (or re-pair) this server. Useful after reinstalling the agent: old credentials are gone, but a new string brings the agent right back to this row.')} {isOnline && ` ${t('app.serverSettingsTab.onlineRegenerateNote', 'This server is online now; a new string only affects re-pairing.')}`} {isExpired && ` ${t('app.serverSettingsTab.previousTokenExpired', 'The previous token has expired.')}`} -

+

+

{t('app.serverSettingsTab.pairOrRepair', 'Pair or re-pair this server.')}

{preview &&
{connections.find((item) => item.id === preview.connection_id)?.name} · {preview.model}

{preview.reason}

} {toggle('fallback_enabled', t('ai.management.enableFallback', 'Enable fallback before output starts'))} -

{t('ai.management.fallbackHint', 'Candidates are tried in order using their own saved credentials. Delivered output and tool actions are never replayed. Degradation chooses a lower-priced candidate before a turn at 80% of the conversation allowance; unknown prices cannot be compared.')}

+ {t('ai.management.fallbackHint', 'Candidates are tried in order using their own saved credentials. Delivered output and tool actions are never replayed. Degradation chooses a lower-priced candidate before a turn at 80% of the conversation allowance; unknown prices cannot be compared.')} {candidates('fallbacks')}
@@ -132,10 +131,10 @@ export default function AIManagementSettings({ connections, defaultId }) { {numberField('max_tool_rounds', t('ai.management.toolRounds', 'Maximum tool rounds'), 1, 20)} {numberField('max_tool_result_length', t('ai.management.toolLength', 'Maximum tool result characters'), 256, 32000)} {numberField('max_history_messages', t('ai.management.history', 'Messages kept in model context'), 4, 200)} - + change('temperature', e.target.value === '' ? null : e.target.value)} /> - + setSettings((s) => ({ ...s, max_cost_usd: e.target.value }))} /> -

{t('ai.settings.costHint', 'Used by the budget behavior in Task models and behavior. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.')}

diff --git a/frontend/src/components/settings/AppearanceTab.jsx b/frontend/src/components/settings/AppearanceTab.jsx index 721fa0f8..e9d4923a 100644 --- a/frontend/src/components/settings/AppearanceTab.jsx +++ b/frontend/src/components/settings/AppearanceTab.jsx @@ -13,6 +13,7 @@ import ThemeBrowseModal from './ThemeBrowseModal'; import ThemeStudioModal from './ThemeStudioModal'; import api from '../../services/api'; import { useTranslation } from 'react-i18next'; +import InfoTip from '../InfoTip'; import { toastError } from '@/utils/errorMessage'; const ACCENT_PRESETS = [ @@ -64,8 +65,7 @@ const AppearanceTab = () => {
-

{t('app.appearanceTab.theme', 'Theme')}

-

{t('app.appearanceTab.selectYourPreferredColorScheme', 'Select your preferred color scheme')}

+

{t('app.appearanceTab.theme', 'Theme')} {t('app.appearanceTab.selectYourPreferredColorScheme', 'Select your preferred color scheme')}

-

{t('app.appearanceTab.accentColor', 'Accent color')}

-

{t('app.appearanceTab.chooseThePrimaryAccentColorUsed', 'Choose the primary accent color used across the interface.')}

+

{t('app.appearanceTab.accentColor', 'Accent color')} {t('app.appearanceTab.chooseThePrimaryAccentColorUsed', 'Choose the primary accent color used across the interface.')}

{ACCENT_PRESETS.map(({ label, color }) => (
-

{t('app.appearanceTab.dashboardWidgets', 'Dashboard widgets')}

-

- {t('app.appearanceTab.widgetsAreArrangedOnTheDashboard', 'Widgets are arranged on the dashboard itself now. Add, move, resize and configure them in place, across as many boards as you need.')} -

+

{t('app.appearanceTab.dashboardWidgets', 'Dashboard widgets')} {t('app.appearanceTab.widgetsAreArrangedOnTheDashboard', 'Widgets are arranged on the dashboard itself now. Add, move, resize and configure them in place, across as many boards as you need.')}

- - {t('app.siteSettingsTab.newAppsGetTheFirstFree', 'New services get the first free port at or above this number. Set to')} 0 {t('app.siteSettingsTab.toUseEachTemplateSOwn', 'to use each template\'s own default (WordPress starts at 8300). Ports already in use are always skipped, so collisions can\'t happen.')} -
-

{t('app.siteSettingsTab.managedSitesBaseDomains', 'Managed services: base domains')}

-

{t('app.siteSettingsTab.publishManagedSitesAt', 'Publish managed services at')} <name>.<base-domain>. {t('app.siteSettingsTab.registerBaseDomains', 'Register one or more base domains; a new service can be created under any of them, defaulting to the one marked')} {t('common.labels.default', 'Default')}. {t('app.siteSettingsTab.pointAWildcardRecord', 'Point a wildcard record')} *.<base> {t('app.siteSettingsTab.orPerSiteARecordsAt', '(or per-service A records) at this server.')}

+

{t('app.siteSettingsTab.managedSitesBaseDomains', 'Managed services: base domains')} {t('app.siteSettingsTab.publishManagedSitesAt', 'Publish managed services at')} <name>.<base-domain>. {t('app.siteSettingsTab.registerBaseDomains', 'Register one or more base domains; a new service can be created under any of them, defaulting to the one marked')} {t('common.labels.default', 'Default')}. {t('app.siteSettingsTab.pointAWildcardRecord', 'Point a wildcard record')} *.<base> {t('app.siteSettingsTab.orPerSiteARecordsAt', '(or per-service A records) at this server.')}

{httpsError ? ( {
- + {t('app.siteSettingsTab.sharedByEveryBaseDomainUsed', 'Shared by every base domain. Used to auto-create their DNS A records.')}
{
- {t('app.siteSettingsTab.sharedByEveryBaseDomainUsed', 'Shared by every base domain. Used to auto-create their DNS A records.')}
{https.providers?.length > 0 ? (
-
+
{t('app.siteSettingsTab.usedToIssueEachBaseS', 'Used to issue each base\'s wildcard certificate (DNS-01). Each base can use a different connected provider.')}
- {t('app.siteSettingsTab.usedToIssueEachBaseS', 'Used to issue each base\'s wildcard certificate (DNS-01). Each base can use a different connected provider.')}
) : ( {t('app.siteSettingsTab.connectADnsProviderUnderEmail', 'Connect a DNS provider under Email → DNS providers to enable per-domain wildcard HTTPS.')} @@ -524,6 +510,10 @@ const SiteSettingsTab = ({ onDevModeChange }) => { )} + {t('app.siteSettingsTab.sitesPublishAt', 'Services publish at')} <name>.{b.domain || 'base-domain'}.{' '} + {(b.dns_mode || 'wildcard') === 'wildcard' + ? <>{t('app.siteSettingsTab.point', 'Point')} *.{b.domain || 'base-domain'} {t('app.siteSettingsTab.atThisServer', 'at this server.')} + : <>{t('app.siteSettingsTab.eachNewSiteGetsItsOwn', 'Each new service gets its own A record, auto-created via the provider.')}}
setCategory(cat)} > {cat === 'all' ? t('common.labels.all', 'All') : cat} @@ -214,7 +227,7 @@ export default function Recipes() { {(recipe.requirements?.cpuCores) && {recipe.requirements.cpuCores} vCPU} {(recipe.requirements?.memoryMB) - && {formatBytes(recipe.requirements.memoryMB * GB, { decimals: 0 })}} + && {formatBytes(recipe.requirements.memoryMB * MB, { decimals: 0 })}} {(recipe.requirements?.diskGB) && {formatBytes(recipe.requirements.diskGB * GB, { decimals: 0 })}} {(recipe.requirements?.igpu && recipe.requirements.igpu !== 'none') diff --git a/frontend/src/styles/pages/_recipes.scss b/frontend/src/styles/pages/_recipes.scss index b978a35f..5755acca 100644 --- a/frontend/src/styles/pages/_recipes.scss +++ b/frontend/src/styles/pages/_recipes.scss @@ -5,29 +5,25 @@ &__head { display: flex; - align-items: flex-end; - gap: $spacing-lg; + flex-direction: column; + gap: $spacing-md; margin-bottom: $spacing-md; } - &__lede { + &__intro { flex: 1; min-width: 0; - margin: 0; - color: var(--text-secondary); - font-size: $text-sm; - line-height: 1.55; - max-width: 640px; } &__search { display: flex; align-items: center; gap: $space-2; - width: 260px; + width: 100%; + max-width: 360px; height: $control-md; padding: 0 $space-3; - border: 1px solid var(--border-color); + border: 1px solid var(--border-default); border-radius: $radius-control; background: var(--bg-card); color: var(--text-tertiary); @@ -48,16 +44,27 @@ flex-wrap: wrap; gap: $space-2; margin-bottom: $spacing-md; + } - .sk-pill { - cursor: pointer; - opacity: 0.72; + &__cat { + display: inline-flex; + align-items: center; + min-height: $control-sm; + padding: 0 $space-3; + border: 1px solid var(--border-default); + border-radius: $radius-full; + background: var(--bg-card); + color: var(--text-secondary); + font-size: $text-sm; + font-weight: $font-weight-medium; + cursor: pointer; - &.is-active { - opacity: 1; - border-color: var(--primary-color); - color: var(--primary-color); - } + &:hover { color: var(--text-primary); } + + &.is-active { + border-color: var(--accent); + background: var(--accent-bg); + color: var(--accent); } } @@ -87,7 +94,7 @@ flex-direction: column; gap: $space-3; padding: $spacing-md; - border: 1px solid var(--border-color); + border: 1px solid var(--border-default); border-radius: $radius-card; background: var(--bg-card); @@ -105,8 +112,8 @@ height: 34px; // geometry: icon tile flex-shrink: 0; border-radius: $radius-control; - background: color-mix(in srgb, var(--primary-color) 12%, transparent); - color: var(--primary-color); + background: var(--accent-bg); + color: var(--accent); } &__id { @@ -152,7 +159,7 @@ span { padding: $space-hair $space-2; border-radius: $radius-badge; - border: 1px solid var(--border-color); + border: 1px solid var(--border-default); font-size: $text-xs; color: var(--text-tertiary); @@ -201,7 +208,7 @@ width: 100%; height: $control-md; padding: 0 $space-3; - border: 1px solid var(--border-color); + border: 1px solid var(--border-default); border-radius: $radius-control; background: var(--bg-input, var(--bg-card)); color: var(--text-primary); @@ -220,7 +227,7 @@ width: 100%; padding: $space-3 $space-3; border: none; - border-bottom: 1px solid var(--border-color); + border-bottom: 1px solid var(--border-default); background: transparent; color: var(--text-primary); cursor: pointer; @@ -231,9 +238,9 @@ &:hover { background: var(--bg-hover, rgba(128, 128, 128, 0.06)); } &.is-on { - background: color-mix(in srgb, var(--primary-color) 8%, transparent); + background: var(--accent-bg); - svg { color: var(--primary-color); } + svg { color: var(--accent); } } } @@ -242,11 +249,11 @@ height: 14px; flex-shrink: 0; border-radius: 50%; - border: 1.5px solid var(--border-color); + border: 1.5px solid var(--border-default); .is-on & { - border-color: var(--primary-color); - box-shadow: inset 0 0 0 3.5px var(--primary-color); // geometry: draws the radio's inner dot + border-color: var(--accent); + box-shadow: inset 0 0 0 3.5px var(--accent); // geometry: draws the radio's inner dot } } @@ -298,7 +305,7 @@ align-items: center; gap: $space-2; padding: $space-2 $space-3; - border-bottom: 1px solid var(--border-color); + border-bottom: 1px solid var(--border-default); font-size: $text-sm; &:last-child { border-bottom: none; } @@ -325,7 +332,7 @@ align-items: center; gap: $space-2; padding: $space-2 $space-3; - border-bottom: 1px solid var(--border-color); + border-bottom: 1px solid var(--border-default); font-size: $text-sm; &:last-child { border-bottom: none; } @@ -336,6 +343,6 @@ &__url { font-size: $text-xs; - color: var(--primary-color); + color: var(--accent); } } From 34bc7d081e9e10a2ee627302e5dcab1ec3a0e383 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:04:09 -0500 Subject: [PATCH 17/70] fix(frontend): branch incident copy on alert type and drop null placeholders --- .../monitoring/__tests__/alertCopy.test.mjs | 39 ++++++++++++ .../src/components/monitoring/alertCopy.js | 62 +++++++++++++++++++ frontend/src/i18n/locales/en.json | 23 +++++++ frontend/src/pages/Incidents.jsx | 35 +++++------ 4 files changed, 140 insertions(+), 19 deletions(-) create mode 100644 frontend/src/components/monitoring/__tests__/alertCopy.test.mjs create mode 100644 frontend/src/components/monitoring/alertCopy.js diff --git a/frontend/src/components/monitoring/__tests__/alertCopy.test.mjs b/frontend/src/components/monitoring/__tests__/alertCopy.test.mjs new file mode 100644 index 00000000..dcb8bce6 --- /dev/null +++ b/frontend/src/components/monitoring/__tests__/alertCopy.test.mjs @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { classifyAlertMetric, describeAlert, formatReading } from '../alertCopy.js'; + +// Minimal i18next stand-in: default string + {{var}} interpolation. +const t = (_key, fallback, vars = {}) => fallback.replace(/{{(\w+)}}/g, (_, k) => vars[k]); +const text = (alert) => JSON.stringify(describeAlert(t, alert)); + +test('classifies health signals apart from threshold metrics', () => { + assert.deepEqual(classifyAlertMetric('offline'), { kind: 'offline' }); + assert.deepEqual(classifyAlertMetric('svc:mysql'), { kind: 'service', service: 'mysql' }); + assert.deepEqual(classifyAlertMetric('cpu'), { kind: 'threshold' }); +}); + +test('offline and service alerts never claim a limit or render placeholders', () => { + const offline = describeAlert(t, { metric: 'offline', value: null, threshold: null, subject: 'web-1' }); + assert.equal(offline.title, 'web-1 is offline'); + const service = describeAlert(t, { metric: 'svc:mysql', value: null, threshold: null, subject: 'web-1' }); + assert.equal(service.title, 'mysql is down on web-1'); + assert.equal(service.detail, 'mysql is not running'); + for (const s of [text({ metric: 'offline', subject: 'x' }), text({ metric: 'svc:a', subject: 'x' })]) { + assert.doesNotMatch(s, /null|undefined|—|over limit/); + } +}); + +test('threshold alerts include the reading when present and omit it when not', () => { + const full = describeAlert(t, { metric: 'cpu', value: 93.456, threshold: 90, subject: 'db' }); + assert.equal(full.title, 'CPU % over limit on db'); + assert.equal(full.detail, 'CPU % 93.5 of 90 limit'); + const bare = describeAlert(t, { metric: 'disk', value: null, threshold: null, subject: 'db' }); + assert.equal(bare.detail, 'Disk %'); + assert.doesNotMatch(text({ metric: 'memory', subject: 'db' }), /null|undefined|—/); +}); + +test('unknown or missing metric falls back to a neutral title', () => { + assert.equal(describeAlert(t, { metric: undefined, subject: 'db' }).title, 'Alert on db'); + assert.equal(formatReading('x'), null); +}); diff --git a/frontend/src/components/monitoring/alertCopy.js b/frontend/src/components/monitoring/alertCopy.js new file mode 100644 index 00000000..a7d95413 --- /dev/null +++ b/frontend/src/components/monitoring/alertCopy.js @@ -0,0 +1,62 @@ +import { METRIC_LABELS } from './fleetMetrics.js'; + +// Plain-language title/detail for a metric alert. The backend's `metric` is +// either a threshold metric (cpu, memory, disk, network_*) or a health signal +// with no reading at all: `offline` (server stopped reporting) and +// `svc:` (a watched service is down). Only the first kind has a value and +// limit, so only it may talk about going "over limit". +const SERVICE_PREFIX = 'svc:'; + +export function classifyAlertMetric(metric) { + if (metric === 'offline') return { kind: 'offline' }; + if (typeof metric === 'string' && metric.startsWith(SERVICE_PREFIX)) { + return { kind: 'service', service: metric.slice(SERVICE_PREFIX.length) || null }; + } + return { kind: 'threshold' }; +} + +export function formatReading(value, digits = 1) { + return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(digits) : null; +} + +export function metricLabel(metric) { + return METRIC_LABELS[metric] || metric || null; +} + +// `t` is i18next's translate function (injected so this stays testable). +export function describeAlert(t, { metric, value, threshold, subject }) { + const { kind, service } = classifyAlertMetric(metric); + if (kind === 'offline') { + return { + title: t('app.alertCopy.offlineTitle', '{{subject}} is offline', { subject }), + detail: t('app.alertCopy.offlineDetail', 'Stopped reporting'), + }; + } + if (kind === 'service') { + return service + ? { + title: t('app.alertCopy.serviceDownTitle', '{{service}} is down on {{subject}}', { service, subject }), + detail: t('app.alertCopy.serviceDownDetail', '{{service}} is not running', { service }), + } + : { + title: t('app.alertCopy.serviceDownAnyTitle', 'A service is down on {{subject}}', { subject }), + detail: t('app.alertCopy.serviceDownAnyDetail', 'Service not running'), + }; + } + const label = metricLabel(metric); + const reading = formatReading(value); + const limit = formatReading(threshold, 0); + if (!label) { + return { title: t('app.alertCopy.genericTitle', 'Alert on {{subject}}', { subject }), detail: '' }; + } + let detail = label; + if (reading && limit) { + detail = t('app.alertCopy.readingOfLimit', '{{metric}} {{reading}} of {{limit}} limit', { metric: label, reading, limit }); + } else if (reading) { + detail = t('app.alertCopy.readingOnly', '{{metric}} {{reading}}', { metric: label, reading }); + } + return { + title: t('app.alertCopy.overLimitTitle', '{{metric}} over limit on {{subject}}', { metric: label, subject }), + detail, + }; +} diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index e369fe45..df297b82 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -361,6 +361,18 @@ "decisionFailed": "Couldn't submit your decision.", "requestFailed": "Couldn't reach the assistant." }, + "alertCopy": { + "genericTitle": "Alert on {{subject}}", + "offlineDetail": "Stopped reporting", + "offlineTitle": "{{subject}} is offline", + "overLimitTitle": "{{metric}} over limit on {{subject}}", + "readingOfLimit": "{{metric}} {{reading}} of {{limit}} limit", + "readingOnly": "{{metric}} {{reading}}", + "serviceDownAnyDetail": "Service not running", + "serviceDownAnyTitle": "A service is down on {{subject}}", + "serviceDownDetail": "{{service}} is not running", + "serviceDownTitle": "{{service}} is down on {{subject}}" + }, "alertsTab": { "acknowledged": "Acknowledged", "allClear": "All clear", @@ -3316,7 +3328,9 @@ "rules": "Rules", "searchIncidentsAndAlerts": "Search incidents and alerts…", "subject": "Subject", + "thisServer": "This server", "timeline": "Timeline", + "unknownServer": "Unknown server", "whatChanged": "What changed?", "whatHappened": "What happened" }, @@ -4804,6 +4818,7 @@ "cpu": "CPU", "disk": "Disk", "featured": "Featured", + "headerLine": "One-click installers", "install": "Install", "lede": "Ready-to-go installers that run as real operations: probe, derive, apply, verify. Secrets are asked for mid-run and kept in the vault.", "loadFailed": "Couldn't load the recipe catalog.", @@ -4822,6 +4837,14 @@ "secretAsks_other": "{{count}} secret asks", "startFailed": "Couldn't start the recipe.", "started": "Recipe started on {{server}}", + "stepApply": "Apply", + "stepApplyInfo": "Derive settings and run the install as a real operation.", + "stepProbe": "Probe", + "stepProbeInfo": "Check the target server meets the requirements.", + "stepSecrets": "Secrets", + "stepSecretsInfo": "Secrets are asked for mid-run and kept in the vault.", + "stepVerify": "Verify", + "stepVerifyInfo": "Confirm the service came up healthy.", "stepsCount_one": "1 step", "stepsCount_other": "{{count}} steps", "unavailable": "Recipe catalog unavailable", diff --git a/frontend/src/pages/Incidents.jsx b/frontend/src/pages/Incidents.jsx index 02806416..d78276f2 100644 --- a/frontend/src/pages/Incidents.jsx +++ b/frontend/src/pages/Incidents.jsx @@ -27,7 +27,7 @@ import { Input } from '@/components/ui/input'; import { useTableSort } from '@/hooks/useTableSort'; import { useColumnVisibility } from '@/hooks/useColumnVisibility'; import { useTopbarActions, useTopbarChrome } from '@/hooks/useTopbarActions'; -import { METRIC_LABELS } from '../components/monitoring/fleetMetrics'; +import { describeAlert, formatReading, metricLabel } from '../components/monitoring/alertCopy'; import { impactTone, INCIDENT_STATES } from '../components/monitoring/monitorShared'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; @@ -123,11 +123,6 @@ function formatWhen(iso) { return formatDateTime(date); } -function formatValue(value) { - if (typeof value !== 'number' || Number.isNaN(value)) return '—'; - return value.toFixed(1); -} - export default function Incidents() { const { t } = useTranslation(); const toast = useToast(); @@ -237,15 +232,16 @@ export default function Incidents() { }; }); + const thisServer = t('app.incidents.thisServer', 'This server'); const hostDetail = (alert) => (alert.type - ? `${alert.type} ${formatValue(alert.value)} / ${alert.threshold}` - : 'This server'); + ? describeAlert(t, { metric: alert.type, value: alert.value, threshold: alert.threshold, subject: thisServer }).detail + : thisServer); const fromActive = activeAlerts.map((alert, index) => ({ kind: 'alert', key: `active-${alert.type}-${index}`, title: alert.message, - subject: 'This server', + subject: thisServer, detail: hostDetail(alert), state: 'firing', tone: 'red', @@ -262,7 +258,7 @@ export default function Incidents() { kind: 'alert', key: `history-${alert.timestamp || index}-${index}`, title: alert.message, - subject: 'This server', + subject: thisServer, detail: hostDetail(alert), state: alert.severity, tone: statusKind(alert.severity), @@ -282,15 +278,16 @@ export default function Incidents() { // sources above describe the panel's own box and have no server-side // lifecycle to ack or resolve. const fromFleet = fleetAlerts.map((alert) => { - const metric = METRIC_LABELS[alert.metric] || alert.metric; - const subject = alert.server_name || 'Unknown server'; + const metric = metricLabel(alert.metric); + const subject = alert.server_name || t('app.incidents.unknownServer', 'Unknown server'); + const { title, detail } = describeAlert(t, { ...alert, subject }); return { kind: 'alert', key: `fleet-${alert.id}`, alertId: alert.id, - title: `${metric} over limit on ${subject}`, + title, subject, - detail: `${metric} ${formatValue(alert.value)} / ${alert.threshold}`, + detail, state: alert.status, tone: alertStatusKind(alert.status), impact: alert.severity, @@ -305,7 +302,7 @@ export default function Incidents() { return [...fromActive, ...fromFleet, ...fromIncidents, ...fromHistory] .sort((a, b) => new Date(b.when || 0) - new Date(a.when || 0)); - }, [incidents, activeAlerts, alertHistory, fleetAlerts, monitorsById]); + }, [incidents, activeAlerts, alertHistory, fleetAlerts, monitorsById, t]); // Search only. The active/resolved split used to live here as a segment // filter; it is a column rule now, applied inside the table. @@ -408,7 +405,7 @@ export default function Incidents() { headerKey: 'app.incidents.impact', header: 'Impact', sortable: true, type: 'enum', - value: (item) => item.impact || '—', + value: (item) => item.impact || '', }, { key: 'when', @@ -628,9 +625,9 @@ export default function Incidents() {
-
{t('app.incidents.metric', 'Metric')}
{selected.metric || '—'}
-
{t('app.incidents.reading', 'Reading')}
{formatValue(selected.value)}
-
{t('app.incidents.limit', 'Limit')}
{selected.threshold ?? '—'}
+ {selected.metric &&
{t('app.incidents.metric', 'Metric')}
{selected.metric}
} + {formatReading(selected.value) &&
{t('app.incidents.reading', 'Reading')}
{formatReading(selected.value)}
} + {formatReading(selected.threshold, 0) &&
{t('app.incidents.limit', 'Limit')}
{formatReading(selected.threshold, 0)}
}
{t('common.labels.when', 'When')}
{formatWhen(selected.when)}

From 07e2c76b0716177edf55ecc6a47f824546cba734 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:04:42 -0500 Subject: [PATCH 18/70] fix(frontend): send /git-ext to the git extension's marketplace entry when not installed --- frontend/src/App.jsx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index f632fc84..1e7486a8 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -143,8 +143,17 @@ function SetupRoute({ children }) { return children; } +// /git-ext was the in-tree git page; it now ships as the serverkit-git +// extension at /git. Without the extension that route is never registered, so +// send the operator to its marketplace entry instead of a "page not found". +const GIT_EXTENSION_SLUG = 'serverkit-git'; + function LegacyGitExtRedirect() { const { tab } = useParams(); + const { routes, __ready } = useContributions(); + if (!__ready) return ; + const installed = (routes || []).some((route) => route.plugin === GIT_EXTENSION_SLUG); + if (!installed) return ; return ; } From e6b6b94d0d84b0f0c75bcba511e98dfe8a60d736 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:05:03 -0500 Subject: [PATCH 19/70] fix(frontend): show a single empty state on the firewall tab --- frontend/src/components/security/FirewallTab.jsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/security/FirewallTab.jsx b/frontend/src/components/security/FirewallTab.jsx index c9fbd592..c44e300c 100644 --- a/frontend/src/components/security/FirewallTab.jsx +++ b/frontend/src/components/security/FirewallTab.jsx @@ -447,7 +447,8 @@ const FirewallTab = () => { return (

- {partialError && } + {/* With no firewall installed the rules/blocked reads fail as a side effect; the call to action below already says so. */} + {partialError && status?.any_installed && } {!status?.any_installed ? ( Date: Tue, 3 Nov 2026 13:05:35 -0500 Subject: [PATCH 20/70] fix(frontend): compact the import wizard stepper on phones --- frontend/src/pages/ImportWizard.jsx | 3 +- frontend/src/styles/pages/_import-wizard.scss | 28 +++++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/frontend/src/pages/ImportWizard.jsx b/frontend/src/pages/ImportWizard.jsx index d61142e0..0c07c5b4 100644 --- a/frontend/src/pages/ImportWizard.jsx +++ b/frontend/src/pages/ImportWizard.jsx @@ -417,12 +417,13 @@ function ImportWizard() { {STEPS.map((label, i) => (
  • {i < stepperIndex ? - {label} + {label}
  • ))} diff --git a/frontend/src/styles/pages/_import-wizard.scss b/frontend/src/styles/pages/_import-wizard.scss index 755258ee..deca13d8 100644 --- a/frontend/src/styles/pages/_import-wizard.scss +++ b/frontend/src/styles/pages/_import-wizard.scss @@ -5,7 +5,6 @@ .import-wizard { max-width: 960px; margin: 0 auto; - padding: $space-6; display: flex; flex-direction: column; gap: $space-6; @@ -31,6 +30,10 @@ padding: 0; list-style: none; overflow-x: auto; + + @media (max-width: $breakpoint-sm) { + justify-content: space-between; + } } &__step { @@ -67,9 +70,30 @@ content: ''; width: 16px; height: 1px; - margin-right: $space-2; + margin-inline-end: $space-2; background: $border-default; } + + // Phones: only the current step keeps its label; the rest shrink to + // their numbered dot and the row spreads to fit instead of clipping. + @media (max-width: $breakpoint-sm) { + flex: 0 0 auto; + padding-inline: $space-1; + + &:not(.is-active) .import-wizard__step-label { + display: none; + } + + &.is-active { + padding-inline: $space-3; + } + + & + &::before { + flex: 0 0 auto; + width: $space-3; + margin-inline-end: $space-1; + } + } } &__step-dot { From 184870a8bdc64afdc6505180fcad82babbf12458 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:08:02 -0500 Subject: [PATCH 21/70] feat(frontend): shared scrolling tab strip with edge fades and active-tab reveal --- frontend/src/components/ui/tabs.jsx | 17 +++- .../hooks/__tests__/useScrollTabs.test.mjs | 28 ++++++ frontend/src/hooks/useScrollTabs.js | 87 +++++++++++++++++++ frontend/src/styles/components/_tabs.scss | 37 ++++++++ 4 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 frontend/src/hooks/__tests__/useScrollTabs.test.mjs create mode 100644 frontend/src/hooks/useScrollTabs.js diff --git a/frontend/src/components/ui/tabs.jsx b/frontend/src/components/ui/tabs.jsx index 89b3c6d9..ccf36194 100644 --- a/frontend/src/components/ui/tabs.jsx +++ b/frontend/src/components/ui/tabs.jsx @@ -4,12 +4,16 @@ import { MoreHorizontal } from 'lucide-react'; import { Popover, PopoverTrigger, PopoverContent } from './popover'; import { cn } from '@/lib/utils'; import { useOverflowItems } from '@/hooks/useOverflowItems'; +import { useScrollTabs } from '@/hooks/useScrollTabs'; import { t } from '../../i18n/t'; import { Button as SharedButton } from '@/components/ui/button'; const Tabs = TabsPrimitive.Root; -const TabsList = React.forwardRef(({ className, children, ...props }, ref) => { +// Default: tabs that don't fit collapse into a "More" popover. With `scroll`, +// the strip scrolls sideways instead (edge fades, active tab kept in view) — +// the better fit when every tab should stay one tap away, e.g. on phones. +const TabsList = React.forwardRef(({ className, children, scroll = false, ...props }, ref) => { const childArray = React.Children.toArray(children).filter(React.isValidElement); const [popoverOpen, setPopoverOpen] = React.useState(false); const itemRefs = React.useRef([]); @@ -22,7 +26,7 @@ const TabsList = React.forwardRef(({ className, children, ...props }, ref) => { return active; }, []); - const { containerRef, moreBtnRef, hiddenIndices, hiddenSet, recompute } = useOverflowItems({ + const { containerRef, moreBtnRef, hiddenIndices: overflowIndices, hiddenSet: overflowSet, recompute } = useOverflowItems({ count: childArray.length, itemRefs, gap: 8, @@ -30,8 +34,15 @@ const TabsList = React.forwardRef(({ className, children, ...props }, ref) => { getActiveIndex, }); + const hiddenIndices = scroll ? [] : overflowIndices; + const hiddenSet = scroll ? new Set() : overflowSet; + + const scrollRef = React.useRef(null); + useScrollTabs(scrollRef, scroll); + const setContainerRef = React.useCallback( (node) => { + scrollRef.current = node; containerRef.current = node; if (typeof ref === 'function') ref(node); else if (ref) ref.current = node; @@ -56,7 +67,7 @@ const TabsList = React.forwardRef(({ className, children, ...props }, ref) => { return ( {childArray.map((child, i) => { diff --git a/frontend/src/hooks/__tests__/useScrollTabs.test.mjs b/frontend/src/hooks/__tests__/useScrollTabs.test.mjs new file mode 100644 index 00000000..6a733e47 --- /dev/null +++ b/frontend/src/hooks/__tests__/useScrollTabs.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { scrollEdges, scrollTargetForItem } from '../useScrollTabs.js'; + +const strip = { containerWidth: 300, scrollWidth: 900 }; + +test('centres the active tab in the strip', () => { + assert.equal(scrollTargetForItem({ ...strip, itemLeft: 400, itemWidth: 100 }), 300); +}); + +test('clamps to the start and end of the strip', () => { + assert.equal(scrollTargetForItem({ ...strip, itemLeft: 0, itemWidth: 80 }), 0); + assert.equal(scrollTargetForItem({ ...strip, itemLeft: 820, itemWidth: 80 }), 600); +}); + +test('a strip that fits never scrolls', () => { + assert.equal(scrollTargetForItem({ itemLeft: 50, itemWidth: 50, containerWidth: 300, scrollWidth: 200 }), 0); +}); + +test('edge fades appear only on the sides with hidden content', () => { + assert.deepEqual(scrollEdges({ ...strip, scrollLeft: 0 }), { start: false, end: true }); + assert.deepEqual(scrollEdges({ ...strip, scrollLeft: 300 }), { start: true, end: true }); + assert.deepEqual(scrollEdges({ ...strip, scrollLeft: 600 }), { start: true, end: false }); + assert.deepEqual(scrollEdges({ containerWidth: 300, scrollWidth: 300, scrollLeft: 0 }), { start: false, end: false }); + // RTL scrolls into negative offsets; the magnitude decides. + assert.deepEqual(scrollEdges({ ...strip, scrollLeft: -600 }), { start: true, end: false }); +}); diff --git a/frontend/src/hooks/useScrollTabs.js b/frontend/src/hooks/useScrollTabs.js new file mode 100644 index 00000000..04d28965 --- /dev/null +++ b/frontend/src/hooks/useScrollTabs.js @@ -0,0 +1,87 @@ +import { useCallback, useEffect } from 'react'; + +const ACTIVE_SELECTOR = '[aria-selected="true"], [aria-current], [data-state="active"], .active'; +const FADE_THRESHOLD = 2; // px of slack before an edge counts as "more to scroll" + +/** + * Where to put scrollLeft so an item sits centred in a horizontally scrolling + * strip, clamped to the strip's range. Pure so it is testable without a DOM. + */ +export function scrollTargetForItem({ itemLeft, itemWidth, containerWidth, scrollWidth }) { + const centred = itemLeft + itemWidth / 2 - containerWidth / 2; + return Math.max(0, Math.min(centred, Math.max(0, scrollWidth - containerWidth))); +} + +/** Which edges still have hidden content (drives the fade masks). */ +export function scrollEdges({ scrollLeft, containerWidth, scrollWidth }) { + // scrollLeft is negative in RTL; the magnitude is what matters for both ends. + const offset = Math.abs(scrollLeft); + return { + start: offset > FADE_THRESHOLD, + end: offset + containerWidth < scrollWidth - FADE_THRESHOLD, + }; +} + +/** + * Shared behaviour for every horizontally scrolling tab strip (pair it with the + * `.sk-tabscroll` class): the active tab is scrolled into view on mount and + * whenever the active marker moves (aria-selected / data-state / .active) or + * the tabs themselves change, and `data-fade-start` / `data-fade-end` mirror which + * edges have more to reveal so the stylesheet can fade them. + * + * Only the strip scrolls — `scrollTo` on the container never moves the page. + */ +export function useScrollTabs(ref, enabled = true) { + const syncEdges = useCallback(() => { + const el = ref.current; + if (!el) return; + const { start, end } = scrollEdges({ + scrollLeft: el.scrollLeft, + containerWidth: el.clientWidth, + scrollWidth: el.scrollWidth, + }); + el.toggleAttribute('data-fade-start', start); + el.toggleAttribute('data-fade-end', end); + }, [ref]); + + const revealActive = useCallback(() => { + const el = ref.current; + if (!el) return; + const active = el.querySelector(ACTIVE_SELECTOR); + if (!active) return; + const box = el.getBoundingClientRect(); + const item = active.getBoundingClientRect(); + const rtl = getComputedStyle(el).direction === 'rtl'; + // Item offset within the scroll content, independent of current scroll. + const itemLeft = rtl + ? box.right - item.right + Math.abs(el.scrollLeft) + : item.left - box.left + el.scrollLeft; + const target = scrollTargetForItem({ + itemLeft, itemWidth: item.width, containerWidth: el.clientWidth, scrollWidth: el.scrollWidth, + }); + el.scrollTo({ left: rtl ? -target : target }); + }, [ref]); + + useEffect(() => { + const el = ref.current; + if (!enabled || !el) return undefined; + revealActive(); + syncEdges(); + el.addEventListener('scroll', syncEdges, { passive: true }); + const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(syncEdges); + resize?.observe(el); + const mutations = typeof MutationObserver === 'undefined' ? null : new MutationObserver(() => { + revealActive(); + syncEdges(); + }); + mutations?.observe(el, { + subtree: true, childList: true, attributes: true, + attributeFilter: ['aria-selected', 'aria-current', 'data-state', 'class'], + }); + return () => { + el.removeEventListener('scroll', syncEdges); + resize?.disconnect(); + mutations?.disconnect(); + }; + }, [ref, enabled, revealActive, syncEdges]); +} diff --git a/frontend/src/styles/components/_tabs.scss b/frontend/src/styles/components/_tabs.scss index 3296228e..b5998534 100644 --- a/frontend/src/styles/components/_tabs.scss +++ b/frontend/src/styles/components/_tabs.scss @@ -24,6 +24,43 @@ } } +// Shared horizontally scrolling tab strip. Pair with hooks/useScrollTabs, which +// scrolls the active tab into view and sets data-fade-start / data-fade-end on +// the edges that still have content to reveal. Used by and +// any hand-rolled nav (Settings) that needs to survive narrow viewports. +@mixin tab-scroll { + --sk-tabscroll-fade: 28px; // geometry: edge fade width + flex-wrap: nowrap; + overflow-x: auto; + overscroll-behavior-x: contain; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; + + &::-webkit-scrollbar { display: none; } + + > * { flex-shrink: 0; } + + &[data-fade-end] { + mask-image: linear-gradient(to right, #000 calc(100% - var(--sk-tabscroll-fade)), transparent); + } + + &[data-fade-start] { + mask-image: linear-gradient(to right, transparent, #000 var(--sk-tabscroll-fade)); + } + + &[data-fade-start][data-fade-end] { + mask-image: linear-gradient(to right, transparent, #000 var(--sk-tabscroll-fade), #000 calc(100% - var(--sk-tabscroll-fade)), transparent); + } + + &:dir(rtl)[data-fade-end] { mask-image: linear-gradient(to left, #000 calc(100% - var(--sk-tabscroll-fade)), transparent); } + &:dir(rtl)[data-fade-start] { mask-image: linear-gradient(to left, transparent, #000 var(--sk-tabscroll-fade)); } + &:dir(rtl)[data-fade-start][data-fade-end] { + mask-image: linear-gradient(to left, transparent, #000 var(--sk-tabscroll-fade), #000 calc(100% - var(--sk-tabscroll-fade)), transparent); + } +} + +.sk-tabscroll { @include tab-scroll; } + .tab { display: inline-flex; align-items: center; From 4474a4033a3c0ad61bba52b7d5e288bdb10554a5 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:08:02 -0500 Subject: [PATCH 22/70] fix(frontend): settings tab list scrolls instead of wrapping on narrow screens --- frontend/src/pages/Settings.jsx | 8 +++++- frontend/src/styles/pages/_settings.scss | 32 +++++++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsx index c4c1036d..ef0fd64f 100644 --- a/frontend/src/pages/Settings.jsx +++ b/frontend/src/pages/Settings.jsx @@ -1,5 +1,6 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import useTabParam from '../hooks/useTabParam'; +import { useScrollTabs } from '../hooks/useScrollTabs'; import { refreshDevMode } from '../hooks/useDevMode'; import { useAuth } from '../contexts/useAuth.js'; import api from '../services/api'; @@ -57,6 +58,9 @@ const Settings = () => { if (requestedTab === 'modules') navigate('/marketplace', { replace: true }); }, [requestedTab, navigate]); + const navListRef = useRef(null); + useScrollTabs(navListRef); + const activeGroup = isAdmin && ADMIN_TABS.includes(activeTab) ? 'admin' : 'account'; useEffect(() => { @@ -96,6 +100,7 @@ const Settings = () => { onChange={(group) => setActiveTab(group === 'admin' ? 'users' : 'profile')} /> )} +
    {activeGroup === 'account' && ( <>
    diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scss index 721dc98f..352c3af5 100644 --- a/frontend/src/styles/pages/_settings.scss +++ b/frontend/src/styles/pages/_settings.scss @@ -8,8 +8,11 @@ gap: $space-6; min-height: calc(100vh - 200px); + // minmax(0, …): the nowrap tab strip must scroll, not stretch the column. @media (max-width: $breakpoint-lg) { - grid-template-columns: 1fr; + grid-template-columns: minmax(0, 1fr); + grid-auto-rows: min-content; + min-height: 0; } } @@ -38,8 +41,6 @@ } @media (max-width: $breakpoint-lg) { - flex-direction: row; - flex-wrap: wrap; position: static; max-height: none; overflow-y: visible; @@ -49,6 +50,28 @@ } } +// The tab list: a rail on desktop, a single scrolling strip (edge fades, +// active tab kept in view — see hooks/useScrollTabs) once the rail collapses. +.settings-nav-list { + display: flex; + flex-direction: column; + gap: $space-1; + + @media (max-width: $breakpoint-lg) { + @include tab-scroll; + flex-direction: row; + align-items: center; + + // Section labels become inline captions between groups of tabs. + .settings-nav-divider { + flex-shrink: 0; + margin: 0; + padding: 0 $space-2; + white-space: nowrap; + } + } +} + // Two-way section switch (My Account / Admin) at the top of the settings rail .settings-nav-groups { display: grid; @@ -61,8 +84,8 @@ border-radius: $radius-control; @media (max-width: $breakpoint-lg) { - flex-basis: 100%; width: 100%; + margin-bottom: $space-2; } } @@ -138,6 +161,7 @@ @media (max-width: $breakpoint-lg) { width: auto; + white-space: nowrap; } } From 35394db72c61b3c48e51909b84e5920cf2dcb84b Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 13:08:02 -0500 Subject: [PATCH 23/70] fix(frontend): notifications page uses the shell's fluid width --- frontend/src/pages/Notifications.jsx | 2 +- frontend/src/styles/pages/_notification-center.scss | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/frontend/src/pages/Notifications.jsx b/frontend/src/pages/Notifications.jsx index 19fbf41a..7741252b 100644 --- a/frontend/src/pages/Notifications.jsx +++ b/frontend/src/pages/Notifications.jsx @@ -97,7 +97,7 @@ export default function Notifications() { } title={t('app.notifications.notifications', 'Notifications')} - meta={unreadCount ? `${unreadCount} unread` : 'All caught up'} + meta={unreadCount ? t('app.notifications.unreadCount', '{{count}} unread', { count: unreadCount }) : t('app.notifications.allCaughtUp', 'All caught up')} actions={( <> {isAdmin && ( diff --git a/frontend/src/styles/pages/_notification-center.scss b/frontend/src/styles/pages/_notification-center.scss index 60aecf08..3cf77117 100644 --- a/frontend/src/styles/pages/_notification-center.scss +++ b/frontend/src/styles/pages/_notification-center.scss @@ -1,9 +1,7 @@ // Notifications history page (sk-notif-page). .sk-notif-page { - max-width: 760px; - margin: 0 auto; - padding: $space-5 $space-6 $space-10; + // Width and gutter come from the page shell, as on every page. &__filters { display: inline-flex; From 545c2f0607c245eb17ddc67787f9242e0f9ee70a Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 12:58:36 -0500 Subject: [PATCH 24/70] fix(ui): give App Map canvas a definite height so React Flow renders --- frontend/src/styles/pages/_app-map.scss | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/frontend/src/styles/pages/_app-map.scss b/frontend/src/styles/pages/_app-map.scss index 09d48894..3063b1af 100644 --- a/frontend/src/styles/pages/_app-map.scss +++ b/frontend/src/styles/pages/_app-map.scss @@ -64,8 +64,9 @@ } &__canvas { - flex: 1 1 auto; - min-height: 480px; + // geometry: React Flow sizes to 100% of its parent, so the canvas needs a + // definite height (a flex/min-height box resolves to 0 and renders blank) + height: clamp(360px, 65dvh, 760px); border: 1px solid $border-subtle; border-radius: $radius-card; background: $bg-card; @@ -76,8 +77,19 @@ display: none; } - .react-flow__minimap { - background: var(--bg-elevated); + // Theme React Flow's default (light) chrome via its own CSS variables. + --xy-minimap-background-color-default: var(--bg-elevated); + --xy-minimap-mask-background-color-default: rgba(0, 0, 0, 0.45); + --xy-controls-button-background-color-default: var(--bg-elevated); + --xy-controls-button-background-color-hover-default: var(--bg-hover); + --xy-controls-button-color-default: var(--text-primary); + --xy-controls-button-border-color-default: var(--border-subtle); + + // The minimap covers a third of the canvas on a phone. + @media (max-width: 639px) { + .react-flow__minimap { + display: none; + } } } From 600b96befce9af89d912da7d99cbce0c8afea20a Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 12:58:36 -0500 Subject: [PATCH 25/70] fix(ui): replace corrupt IBM Plex Sans 400 woff2 and guard it in font lint --- frontend/public/fonts/ibm-plex-sans-400.woff2 | Bin 22588 -> 22588 bytes frontend/scripts/check-font-integrity.mjs | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/public/fonts/ibm-plex-sans-400.woff2 b/frontend/public/fonts/ibm-plex-sans-400.woff2 index ab60668be06cf021524b8dbc27577616f10a722c..f0ee65dd7f3ed64dc8d674e5c6007a0e7761bd57 100644 GIT binary patch delta 12397 zcmV-zFp|%_umQZV0iY0n7=~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r=tB%x-fhXABt4)}kcUIXQ86GL?sjbMPN|GW{g8dKf z8la934Gz%I8kRhuIGlj#$R0~!I>Ut^n8FoNh4u|m$L2rbh6cZWOzAGw2*ZBXhT`3{ zNn>(_P;fDX-&j^s^y8}3DD-YYl$NVjOGcYVN2p+ziFRt@EVYkfiCMIjDupyCs%)AZ zfFSWKDc=3HP!LweZ~^mWZ?%F}bHGe%4G0BCSu6++OAM=L7AZD%cfxIzQY#Toq!DAC zPoBf7tyMz^;c(MEW-*{DR30i_tB#{r*LThh?A^c!|}RUaCYSSiVziJ0gqa8s1WVT;5`=v|mUR7K_1n6c=1d zmA&NYnoTV7YjYiiVPIs#4v5#~!fBLI%!YBJYY`in`#(tNgxWZNK?&ji9;oW@by>C{ z)`@CH2DAbpAVyW#tb~)#yuX3WMU&Jrx23lRBgh0OB|NJ}vXG^URFnCOFG-@+FSIGsLDoggp-lC zaslNBs$vw5{i-(TI(^+}N;(LS73FFOr72|<8L&%B3bh%QYi(jQk5!yYk8C~LM6~LA z_fCpjeko4Jh9);YYhYe6ImfJJH7OMpi**xqjjKHc6&;o06YrOdd~9o(Q(sBSxr4*6 zC1)AAtqD#*;{t500i3wh6usH#pj@QT?a9Ln17%K=?4j%wh4}Ipz|X^-6R-0fN>?WA zqT}^uGg8f_NKlQQFs+{ix}CZ5Gg@Ys3*CvQ4m)$K&t_MH_-zB-fv3JZ+s-X^X6;)o zY*U&QKD$qwF&mEKN0x7xprH1G-eB|_wFQ=op=CNCx!tNpa(ed$#Dlm9mv`gjgX&jr ksXq-|3S&9so~-~#TZOq7b^H24>LQQVXcLg@gRNly3p_2XDF6Tf diff --git a/frontend/scripts/check-font-integrity.mjs b/frontend/scripts/check-font-integrity.mjs index f297a3a0..c21c3a59 100644 --- a/frontend/scripts/check-font-integrity.mjs +++ b/frontend/scripts/check-font-integrity.mjs @@ -9,6 +9,7 @@ const FRONTEND = join(dirname(fileURLToPath(import.meta.url)), '..'); const FONT_DIR = join(FRONTEND, 'public', 'fonts'); const FONT_STYLES = join(FRONTEND, 'src', 'styles', 'base', '_fonts.scss'); const FONTS = [ + ['ibm-plex-sans-400.woff2', 400], ['ibm-plex-sans-500.woff2', 500], ['ibm-plex-sans-600.woff2', 600], ['ibm-plex-sans-700.woff2', 700], @@ -34,4 +35,4 @@ for (const [filename, weight] of FONTS) { } } -console.log('✓ font integrity: IBM Plex Sans 500/600/700 are valid WOFF2 assets'); +console.log('✓ font integrity: IBM Plex Sans 400/500/600/700 are valid WOFF2 assets'); From a3c243c952a246e99ed7ccd90b5f03467dfca0c0 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 3 Nov 2026 12:59:09 -0500 Subject: [PATCH 26/70] fix(ui): Recipes page gutter, lede in info tip, readable active filter chip --- frontend/src/i18n/locales/en.json | 1 + frontend/src/pages/Recipes.jsx | 14 ++++++--- frontend/src/styles/pages/_recipes.scss | 41 ++++++++++++++----------- 3 files changed, 33 insertions(+), 23 deletions(-) diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index e369fe45..deba9002 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -4804,6 +4804,7 @@ "cpu": "CPU", "disk": "Disk", "featured": "Featured", + "headerLine": "One-click installers", "install": "Install", "lede": "Ready-to-go installers that run as real operations: probe, derive, apply, verify. Secrets are asked for mid-run and kept in the vault.", "loadFailed": "Couldn't load the recipe catalog.", diff --git a/frontend/src/pages/Recipes.jsx b/frontend/src/pages/Recipes.jsx index af5448b7..2c574090 100644 --- a/frontend/src/pages/Recipes.jsx +++ b/frontend/src/pages/Recipes.jsx @@ -9,6 +9,7 @@ import { import { Drawer } from '../components/ds'; import EmptyState from '../components/EmptyState'; +import SectionIntro from '../components/SectionIntro'; import FormField from '../components/FormField'; import { runRecipe, useRecipeCatalog } from '../hooks/useRecipeCatalog'; import { useToast } from '../contexts/useToast.js'; @@ -143,11 +144,14 @@ export default function Recipes() { }; return ( -
    +
    + } + info={t('app.recipes.lede', 'Ready-to-go installers that run as real operations: probe, derive, apply, verify. Secrets are asked for mid-run and kept in the vault.')} + > + {t('app.recipes.headerLine', 'One-click installers')} +
    -

    - {t('app.recipes.lede', 'Ready-to-go installers that run as real operations: probe, derive, apply, verify. Secrets are asked for mid-run and kept in the vault.')} -