ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
refactor(frontend): Phase 4 §7.1 — delete dead redirected pages
Juan Denisdcf9365ff3fe
diff --git a/frontend/src/components/status/ContainerStatusPill.jsx b/frontend/src/components/status/ContainerStatusPill.jsxdeleted file mode 100644index 9bdc83ec..00000000--- a/frontend/src/components/status/ContainerStatusPill.jsx+++ /dev/null@@ -1,69 +0,0 @@-import { Pill } from '@/components/ds';--// Aggregator enum (backend container_status_service) → Pill kind + label.-const STATUS_META = {- 'running:healthy': { kind: 'green', label: 'Healthy' },- 'running:unhealthy': { kind: 'amber', label: 'Unhealthy' },- degraded: { kind: 'amber', label: 'Degraded' },- restarting: { kind: 'cyan', label: 'Restarting' },- starting: { kind: 'cyan', label: 'Starting' },- exited: { kind: 'gray', label: 'Stopped' },- unknown: { kind: 'gray', label: 'Unknown' },-};--const FALLBACK = { kind: 'gray', label: 'Unknown' };--/**- * Standardized pill for an aggregated container status.- *- * @param {object} status aggregator dict ({status, total, healthy, reasons})- * @param {string} [fallbackLabel] label to show before the status resolves- */-export default function ContainerStatusPill({ status, fallbackLabel = 'Unknown' }) {- if (!status || !status.status) {- return <Pill kind="gray">{fallbackLabel}</Pill>;- }-- const meta = STATUS_META[status.status] || FALLBACK;- const total = status.total ?? 0;- const healthy = status.healthy ?? 0;- const reasons = Array.isArray(status.reasons) ? status.reasons : [];-- const summary = total > 0 ? `${healthy}/${total} containers healthy` : 'no containers';- const tooltipLines = [summary, ...reasons];- // Native title for accessibility / keyboard; the custom tooltip is visual.- const titleText = tooltipLines.join('\n');-- // Surface a degraded sub-state without requiring a hover: when an app has- // more than one container and some are unhealthy (or there are reasons),- // show a small always-visible amber badge. Prefer the issue count when we- // have reasons, else the "healthy/total" ratio.- const showBadge = total > 1 && (healthy < total || reasons.length > 0);- const badgeLabel = reasons.length > 0- ? `${reasons.length} ${reasons.length === 1 ? 'issue' : 'issues'}`- : `${healthy}/${total}`;-- return (- <span className="sk-cstatus" title={titleText}>- <Pill kind={meta.kind}>{meta.label}</Pill>- {showBadge && (- <span- className="sk-cstatus__badge"- aria-label={- reasons.length > 0- ? `${reasons.length} container ${reasons.length === 1 ? 'issue' : 'issues'}`- : `${healthy} of ${total} containers healthy`- }- >- {badgeLabel}- </span>- )}- <span className="sk-cstatus__tip" role="tooltip">- <span className="sk-cstatus__tip-summary">{summary}</span>- {reasons.map((r, i) => (- <span key={i} className="sk-cstatus__tip-reason">{r}</span>- ))}- </span>- </span>- );-}diff --git a/frontend/src/pages/Applications.jsx b/frontend/src/pages/Applications.jsxdeleted file mode 100644index ab707336..00000000--- a/frontend/src/pages/Applications.jsx+++ /dev/null@@ -1,481 +0,0 @@-import React, { useState, useEffect } from 'react';-import { useNavigate } from 'react-router-dom';-import {- Plus, X, Container, Globe, RefreshCw, Boxes, Activity, Square,- FileText, RotateCw, Play, Trash2, Settings,-} from 'lucide-react';-import api from '../services/api';-import EmptyState from '../components/EmptyState';-import { useToast } from '../contexts/ToastContext';-import { useConfirm } from '../hooks/useConfirm';-import { ConfirmDialog } from '../components/ConfirmDialog';-import { getServiceType, getStatusConfig } from '../utils/serviceTypes';-import { Button } from '@/components/ui/button';-import { PageTopbar, MetricCard, Gauge } from '@/components/ds';-import SearchFilterBar from '../components/SearchFilterBar';-import ContainerStatusPill from '../components/status/ContainerStatusPill';-import { useContainerStatus } from '../hooks/useContainerStatus';--const Applications = () => {- const navigate = useNavigate();- const toast = useToast();- const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();- const [apps, setApps] = useState([]);- const [appStats, setAppStats] = useState({});- const [loading, setLoading] = useState(true);- const [showCreateModal, setShowCreateModal] = useState(false);- const [searchTerm, setSearchTerm] = useState('');- const [statusFilter, setStatusFilter] = useState('all');- const [selectedApp, setSelectedApp] = useState(null);- const [stats, setStats] = useState({- total: 0,- running: 0,- stopped: 0,- docker: 0- });-- useEffect(() => {- loadApps();- }, []);-- async function loadApps() {- setLoading(true);- try {- const data = await api.getApps();- // Filter out WordPress apps - they have their own dedicated page at /wordpress- const appList = (data.apps || []).filter(a => a.app_type !== 'wordpress');- setApps(appList);-- // Calculate stats- const running = appList.filter(a => a.status === 'running').length;- const docker = appList.filter(a => a.app_type === 'docker').length;- setStats({- total: appList.length,- running,- stopped: appList.length - running,- docker- });-- // Load resource stats for running Docker apps (via container stats)- const runningDockerApps = appList.filter(a => a.status === 'running' && a.app_type === 'docker');- const statsPromises = runningDockerApps.map(async (app) => {- try {- // Try to get container stats using app name as container reference- const containersData = await api.getContainers(false).catch(() => ({ containers: [] }));- const appContainer = containersData.containers?.find(c =>- c.name?.includes(app.name) || c.name?.includes(app.id)- );- if (appContainer) {- const statsData = await api.getContainerStats(appContainer.id).catch(() => null);- if (statsData?.stats) {- const cpuStr = statsData.stats.CPUPerc || '0%';- const memStr = statsData.stats.MemPerc || '0%';- return {- id: app.id,- stats: {- cpu_percent: parseFloat(cpuStr.replace('%', '')) || 0,- memory_percent: parseFloat(memStr.replace('%', '')) || 0- }- };- }- }- return { id: app.id, stats: null };- } catch {- return { id: app.id, stats: null };- }- });-- const statsResults = await Promise.all(statsPromises);- const statsMap = {};- statsResults.forEach(({ id, stats }) => {- if (stats) statsMap[id] = stats;- });- setAppStats(statsMap);- } catch (err) {- console.error('Failed to load apps:', err);- toast.error('Failed to load applications');- } finally {- setLoading(false);- }- }-- async function handleAction(appId, action) {- try {- if (action === 'start') {- await api.startApp(appId);- toast.success('Application started');- } else if (action === 'stop') {- await api.stopApp(appId);- toast.success('Application stopped');- } else if (action === 'restart') {- await api.restartApp(appId);- toast.success('Application restarted');- } else if (action === 'delete') {- const deleteConfirmed = await confirm({ title: 'Delete Application', message: 'Delete this application? This action cannot be undone.' });- if (!deleteConfirmed) return;- await api.deleteApp(appId);- toast.success('Application deleted');- }- loadApps();- } catch (err) {- console.error(`Failed to ${action} app:`, err);- toast.error(err.message || `Failed to ${action} application`);- }- }-- const filteredApps = apps.filter(app => {- if (statusFilter === 'running' && app.status !== 'running') return false;- if (statusFilter === 'stopped' && app.status === 'running') return false;- if (!searchTerm) return true;- const search = searchTerm.toLowerCase();- return app.name?.toLowerCase().includes(search) ||- app.app_type?.toLowerCase().includes(search);- });-- if (loading) {- return <EmptyState loading size="lg" title="Loading applications..." />;- }-- return (- <div className="page-container applications-page">- <PageTopbar- icon={<Boxes size={18} />}- title="Applications"- meta={`${stats.total} apps · ${stats.running} running`}- actions={(- <>- <Button variant="outline" size="sm" onClick={loadApps}>- <RefreshCw size={14} /> Refresh- </Button>- <Button size="sm" onClick={() => setShowCreateModal(true)}>- <Plus size={16} /> New Application- </Button>- </>- )}- />-- {apps.length > 0 && (- <div className="apps-kpis">- <MetricCard tone="green" icon={<Activity size={16} />} value={stats.running} label="Running" />- <MetricCard tone="amber" icon={<Square size={16} />} value={stats.stopped} label="Stopped" />- <MetricCard tone="cyan" icon={<Container size={16} />} value={stats.docker} label="Docker Apps">- <div className="sk-kpi__sub"><span>Container-based</span></div>- </MetricCard>- <MetricCard tone="accent" icon={<Boxes size={16} />} value={stats.total} label="Total Applications" />- </div>- )}-- <div className="apps-list-card">- <div className="apps-list-head">- <SearchFilterBar- search={searchTerm}- onSearch={setSearchTerm}- placeholder="Search apps..."- filters={[- { key: 'all', label: 'All', count: stats.total },- { key: 'running', label: 'Running', count: stats.running },- { key: 'stopped', label: 'Stopped', count: stats.stopped },- ]}- activeFilter={statusFilter}- onFilterChange={setStatusFilter}- />- </div>-- {filteredApps.length === 0 ? (- <EmptyState- icon={Boxes}- title="No applications"- description={searchTerm || statusFilter !== 'all'- ? 'Try adjusting your filters.'- : 'Create your first application to get started.'}- action={!searchTerm && statusFilter === 'all' && (- <Button onClick={() => setShowCreateModal(true)}><Plus size={16} /> New Application</Button>- )}- />- ) : (- <table className="sk-dtable apps-table">- <thead>- <tr>- <th>Application</th>- <th>Type</th>- <th>Status</th>- <th>Domain</th>- <th>Resources</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {filteredApps.map(app => {- const res = appStats[app.id];- const typeInfo = getServiceType(app.app_type);- const statusInfo = getStatusConfig(app.status);- const isRunning = app.status === 'running';- const cpuPercent = res?.cpu_percent || 0;- const memPercent = res?.memory_percent || 0;-- return (- <tr key={app.id} className="is-clickable" onClick={() => navigate(`/apps/${app.id}`)}>- <td>- <div className="sk-cell-name">- <span- className="apps-type-ico"- style={{ background: typeInfo.bgColor, color: typeInfo.color }}- >- {app.app_type === 'docker'- ? <Container size={16} />- : (app.app_type || '?').charAt(0).toUpperCase()}- </span>- <div>- <div>{app.name}</div>- <div className="sk-cell-sub">id {app.id}</div>- </div>- </div>- </td>- <td>- <span- className="apps-type-chip"- style={{ color: typeInfo.color, background: typeInfo.bgColor, borderColor: typeInfo.borderColor }}- >- {typeInfo.label}- </span>- </td>- <td>- <AppStatusCell app={app} fallbackLabel={statusInfo.label} />- {app.port && (- <div className="sk-cell-sub">port {app.port}</div>- )}- </td>- <td>- {app.domains && app.domains.length > 0 ? (- <div className={`apps-domain ${!isRunning ? 'is-faded' : ''}`}>- {app.domains.map((d, i) => (- <span key={i}>- <Globe size={11} /> {d.name}- </span>- ))}- </div>- ) : (- <span className="apps-none">—</span>- )}- </td>- <td>- <div className={!isRunning ? 'is-faded' : ''}>- <div className="apps-res">- <span className="apps-res__label">CPU</span>- <Gauge value={cpuPercent} color="var(--accent-bright)" />- <span className="apps-res__val">{cpuPercent.toFixed(0)}%</span>- </div>- <div className="apps-res">- <span className="apps-res__label">RAM</span>- <Gauge value={memPercent} color="var(--cyan)" />- <span className="apps-res__val">{memPercent.toFixed(0)}%</span>- </div>- </div>- </td>- <td onClick={(e) => e.stopPropagation()}>- <div className="apps-actions-cell">- <IconAction title="Logs" onClick={() => setSelectedApp(app)}>- <FileText size={14} />- </IconAction>- {isRunning ? (- <>- <IconAction title="Restart" onClick={() => handleAction(app.id, 'restart')}>- <RotateCw size={14} />- </IconAction>- <IconAction title="Stop" tone="red" onClick={() => handleAction(app.id, 'stop')}>- <Square size={13} />- </IconAction>- </>- ) : (- <>- <IconAction title="Start" tone="green" onClick={() => handleAction(app.id, 'start')}>- <Play size={14} />- </IconAction>- <IconAction title="Delete" tone="red" onClick={() => handleAction(app.id, 'delete')}>- <Trash2 size={14} />- </IconAction>- </>- )}- <IconAction title="Manage" onClick={() => navigate(`/apps/${app.id}`)}>- <Settings size={14} />- </IconAction>- </div>- </td>- </tr>- );- })}- </tbody>- </table>- )}- </div>-- {showCreateModal && (- <CreateAppModal onClose={() => setShowCreateModal(false)} />- )}-- {selectedApp && (- <AppLogsModal- app={selectedApp}- onClose={() => setSelectedApp(null)}- />- )}- <ConfirmDialog- isOpen={confirmState.isOpen}- title={confirmState.title}- message={confirmState.message}- confirmText={confirmState.confirmText}- cancelText={confirmState.cancelText}- variant={confirmState.variant}- onConfirm={handleConfirm}- onCancel={handleCancel}- />- </div>- );-};--// Per-row aggregated container status, driven by the centralized aggregator.-// Falls back to the app's persisted status label until the aggregator resolves.-const AppStatusCell = ({ app, fallbackLabel }) => {- const { status } = useContainerStatus(app.id);- return <ContainerStatusPill status={status} fallbackLabel={fallbackLabel} />;-};--// Per-row icon action (tones via modifier classes — no inline colors)-const IconAction = ({ title, onClick, tone, children, disabled }) => (- <button- type="button"- className={`apps-icon-action${tone ? ` apps-icon-action--${tone}` : ''}`}- title={title}- onClick={onClick}- disabled={disabled}- >- {children}- </button>-);--// App Logs Modal-const AppLogsModal = ({ app, onClose }) => {- const [logs, setLogs] = useState('');- const [loading, setLoading] = useState(true);- const [logType, setLogType] = useState('access');-- useEffect(() => {- loadLogs();- }, [app, logType]);-- async function loadLogs() {- setLoading(true);- try {- // For Docker apps, try to get container logs- if (app.app_type === 'docker') {- const data = await api.getDockerAppLogs(app.id, 200);- setLogs(data.logs || data.content || 'No logs available');- return;- }- // For other apps, use app logs endpoint- const data = await api.getAppLogs(app.name, logType, 200);- setLogs(data.logs || data.content || 'No logs available');- } catch (err) {- setLogs('Failed to load logs: ' + (err.message || 'Unknown error'));- } finally {- setLoading(false);- }- }-- return (- <div className="modal-overlay" onClick={onClose}>- <div className="modal modal-lg app-logs-modal" onClick={e => e.stopPropagation()}>- <div className="modal-header">- <h2>Logs: {app.name}</h2>- <button className="modal-close" onClick={onClose}>×</button>- </div>- <div className="modal-body">- {app.app_type !== 'docker' && (- <div className="app-logs-controls">- <select- value={logType}- onChange={(e) => setLogType(e.target.value)}- className="app-logs-select"- >- <option value="access">Access Logs</option>- <option value="error">Error Logs</option>- </select>- </div>- )}- <pre className="log-viewer">{loading ? 'Loading...' : logs}</pre>- </div>- <div className="modal-actions">- <Button variant="outline" onClick={loadLogs}>Refresh</Button>- <Button onClick={onClose}>Close</Button>- </div>- </div>- </div>- );-};--// Create App Modal-const CreateAppModal = ({ onClose }) => {- const navigate = useNavigate();-- // Brand categorical colors (literal on purpose)- const templates = [- { id: 'wordpress', name: 'WordPress', icon: 'W', color: '#21759b', description: 'Full WordPress installation with database' },- { id: 'nextcloud', name: 'Nextcloud', icon: 'N', color: '#0082c9', description: 'Self-hosted cloud storage platform' },- { id: 'grafana', name: 'Grafana', icon: 'G', color: '#f46800', description: 'Monitoring and observability dashboards' },- { id: 'portainer', name: 'Portainer', icon: 'P', color: '#13bef9', description: 'Docker container management UI' },- { id: 'uptime-kuma', name: 'Uptime Kuma', icon: 'U', color: '#5cdd8b', description: 'Self-hosted monitoring tool' },- { id: 'gitea', name: 'Gitea', icon: 'G', color: '#609926', description: 'Lightweight Git hosting service' },- ];-- function selectTemplate(templateId) {- onClose();- // WordPress has its own dedicated management page- if (templateId === 'wordpress') {- navigate('/wordpress');- } else {- navigate(`/templates?install=${templateId}`);- }- }-- function goToAllTemplates() {- onClose();- navigate('/templates');- }-- return (- <div className="modal-overlay" onClick={onClose}>- <div className="modal modal-lg" onClick={e => e.stopPropagation()}>- <div className="modal-header">- <h2>Select Application Type</h2>- <button className="modal-close" onClick={onClose}>- <X size={20} />- </button>- </div>-- <div className="app-type-grid">- {templates.map(template => (- <button- key={template.id}- className="app-type-card"- onClick={() => selectTemplate(template.id)}- >- <div className="app-type-icon" style={{ background: template.color }}>- {template.id === 'portainer' ? <Container size={20} /> : template.icon}- </div>- <h3>{template.name}</h3>- <p>{template.description}</p>- </button>- ))}- </div>-- <div className="modal-footer">- <Button variant="outline" onClick={goToAllTemplates}>- Browse All Templates- </Button>- </div>- </div>- </div>- );-};--export default Applications;diff --git a/frontend/src/pages/Firewall.jsx b/frontend/src/pages/Firewall.jsxdeleted file mode 100644index b968fbc3..00000000--- a/frontend/src/pages/Firewall.jsx+++ /dev/null@@ -1,671 +0,0 @@-import { useState, useEffect } from 'react';-import { ShieldOff, ShieldCheck, Filter, Shield } from 'lucide-react';-import { api } from '../services/api';-import { useToast } from '../contexts/ToastContext';-import Spinner from '../components/Spinner';-import EmptyState from '../components/EmptyState';-import ConfirmDialog from '../components/ConfirmDialog';-import { StatStrip, Stat } from '../components/StatCard';-import { PageTopbar } from '@/components/ds';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Badge } from '@/components/ui/badge';-import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';-import {- Select,- SelectTrigger,- SelectContent,- SelectItem,- SelectValue,-} from '@/components/ui/select';--function Firewall() {- const [status, setStatus] = useState(null);- const [rules, setRules] = useState([]);- const [blockedIPs, setBlockedIPs] = useState([]);- const [loading, setLoading] = useState(true);- const [showBlockIPModal, setShowBlockIPModal] = useState(false);- const [showPortModal, setShowPortModal] = useState(false);- const [showInstallModal, setShowInstallModal] = useState(false);- const [blockIP, setBlockIP] = useState('');- const [newPort, setNewPort] = useState({ port: '', protocol: 'tcp' });- const [selectedFirewall, setSelectedFirewall] = useState('ufw');- const [actionLoading, setActionLoading] = useState(false);- const [confirmDialog, setConfirmDialog] = useState(null);- const toast = useToast();-- const commonPorts = [- { port: 22, name: 'SSH', protocol: 'tcp' },- { port: 80, name: 'HTTP', protocol: 'tcp' },- { port: 443, name: 'HTTPS', protocol: 'tcp' },- { port: 21, name: 'FTP', protocol: 'tcp' },- { port: 25, name: 'SMTP', protocol: 'tcp' },- { port: 3306, name: 'MySQL', protocol: 'tcp' },- { port: 5432, name: 'PostgreSQL', protocol: 'tcp' },- { port: 6379, name: 'Redis', protocol: 'tcp' },- { port: 27017, name: 'MongoDB', protocol: 'tcp' },- ];-- useEffect(() => {- loadData();- }, []);-- const loadData = async () => {- setLoading(true);- try {- await Promise.all([- loadStatus(),- loadRules(),- loadBlockedIPs()- ]);- } catch (error) {- console.error('Failed to load firewall data:', error);- } finally {- setLoading(false);- }- };-- const loadStatus = async () => {- try {- const data = await api.getFirewallStatus();- setStatus(data);- } catch (error) {- console.error('Failed to load status:', error);- }- };-- const loadRules = async () => {- try {- const data = await api.getFirewallRules();- setRules(data.rules || []);- } catch (error) {- console.error('Failed to load rules:', error);- }- };-- const loadBlockedIPs = async () => {- try {- const data = await api.getBlockedIPs();- setBlockedIPs(data.blocked_ips || []);- } catch (error) {- console.error('Failed to load blocked IPs:', error);- }- };-- const handleEnable = async () => {- setActionLoading(true);- try {- await api.enableFirewall();- toast.success('Firewall enabled');- await loadStatus();- } catch (error) {- toast.error(`Failed to enable firewall: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleDisable = async () => {- setConfirmDialog({- title: 'Disable Firewall',- message: 'Are you sure you want to disable the firewall? This will leave your server unprotected.',- confirmText: 'Disable',- variant: 'danger',- onConfirm: async () => {- setActionLoading(true);- try {- await api.disableFirewall();- toast.success('Firewall disabled');- await loadStatus();- } catch (error) {- toast.error(`Failed to disable firewall: ${error.message}`);- } finally {- setActionLoading(false);- setConfirmDialog(null);- }- },- onCancel: () => setConfirmDialog(null)- });- };-- const handleBlockIP = async () => {- if (!blockIP.trim()) return;- setActionLoading(true);- try {- await api.blockIP(blockIP);- toast.success(`IP ${blockIP} blocked`);- setShowBlockIPModal(false);- setBlockIP('');- await loadBlockedIPs();- await loadRules();- } catch (error) {- toast.error(`Failed to block IP: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleUnblockIP = async (ip) => {- setConfirmDialog({- title: 'Unblock IP',- message: `Are you sure you want to unblock ${ip}?`,- confirmText: 'Unblock',- variant: 'warning',- onConfirm: async () => {- try {- await api.unblockIP(ip);- toast.success(`IP ${ip} unblocked`);- await loadBlockedIPs();- await loadRules();- } catch (error) {- toast.error(`Failed to unblock IP: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null)- });- };-- const handleAllowPort = async () => {- if (!newPort.port) return;- setActionLoading(true);- try {- await api.allowPort(parseInt(newPort.port), newPort.protocol);- toast.success(`Port ${newPort.port}/${newPort.protocol} allowed`);- setShowPortModal(false);- setNewPort({ port: '', protocol: 'tcp' });- await loadRules();- } catch (error) {- toast.error(`Failed to allow port: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleQuickAllowPort = async (port, protocol) => {- setActionLoading(true);- try {- await api.allowPort(port, protocol);- toast.success(`Port ${port}/${protocol} allowed`);- await loadRules();- } catch (error) {- toast.error(`Failed to allow port: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const handleRemovePort = async (port, protocol) => {- setConfirmDialog({- title: 'Remove Port Rule',- message: `Are you sure you want to remove the rule for port ${port}/${protocol}?`,- confirmText: 'Remove',- variant: 'danger',- onConfirm: async () => {- try {- await api.denyPort(parseInt(port), protocol);- toast.success(`Port ${port}/${protocol} rule removed`);- await loadRules();- } catch (error) {- toast.error(`Failed to remove port: ${error.message}`);- }- setConfirmDialog(null);- },- onCancel: () => setConfirmDialog(null)- });- };-- const handleInstall = async () => {- setActionLoading(true);- try {- await api.installFirewall(selectedFirewall);- toast.success(`${selectedFirewall.toUpperCase()} installed successfully`);- setShowInstallModal(false);- await loadData();- } catch (error) {- toast.error(`Failed to install firewall: ${error.message}`);- } finally {- setActionLoading(false);- }- };-- const isActive = status?.any_active;- const activeFirewall = status?.active_firewall;-- if (loading) {- return (- <div className="page-container firewall-page">- <div className="page-loading">- <Spinner size="lg" />- </div>- </div>- );- }-- return (- <div className="page-container firewall-page">- <PageTopbar- icon={<Shield size={18} />}- title="Firewall"- actions={<>- {!status?.any_installed ? (- <Button onClick={() => setShowInstallModal(true)}>- Install Firewall- </Button>- ) : (- <>- <Button- variant="outline"- onClick={() => setShowBlockIPModal(true)}- >- Block IP- </Button>- <Button- variant="outline"- onClick={() => setShowPortModal(true)}- >- Allow Port- </Button>- {isActive ? (- <Button- variant="destructive"- onClick={handleDisable}- disabled={actionLoading}- >- Disable Firewall- </Button>- ) : (- <Button- onClick={handleEnable}- disabled={actionLoading}- >- Enable Firewall- </Button>- )}- </>- )}- </>}- />-- {!status?.any_installed ? (- <EmptyState- size="lg"- icon={ShieldOff}- title="No firewall installed"- description="Install a firewall to protect your server from unauthorized access."- action={<Button size="lg" onClick={() => setShowInstallModal(true)}>Install Firewall</Button>}- />- ) : (- <>- <StatStrip ariaLabel="Firewall status">- <Stat- label="Firewall Status"- value={isActive ? 'Active' : 'Inactive'}- state={isActive ? 'success' : 'danger'}- />- <Stat label="Firewall Type" value={activeFirewall?.toUpperCase() || 'None'} />- <Stat label="Active Rules" value={rules.length} />- <Stat- label="Blocked IPs"- value={blockedIPs.length}- state={blockedIPs.length > 0 ? 'warning' : undefined}- />- </StatStrip>-- <Tabs defaultValue="overview">- <TabsList>- <TabsTrigger value="overview">Overview</TabsTrigger>- <TabsTrigger value="rules">Rules</TabsTrigger>- <TabsTrigger value="blocked">Blocked IPs</TabsTrigger>- <TabsTrigger value="quick">Quick Actions</TabsTrigger>- </TabsList>-- <TabsContent value="overview">- <div className="overview-tab">- <div className="info-card">- <h3>Firewall Information</h3>- <div className="info-grid">- <div className="info-item">- <span className="info-label">Type</span>- <span className="info-value">{activeFirewall?.toUpperCase()}</span>- </div>- <div className="info-item">- <span className="info-label">Status</span>- <span className={`info-value ${isActive ? 'text-success' : 'text-danger'}`}>- {isActive ? 'Active' : 'Inactive'}- </span>- </div>- {activeFirewall === 'firewalld' && status?.firewalld?.default_zone && (- <div className="info-item">- <span className="info-label">Default Zone</span>- <span className="info-value">{status.firewalld.default_zone}</span>- </div>- )}- </div>- </div>- <div className="protection-summary">- <h3>Protection Summary</h3>- <div className="summary-grid">- <div className="summary-item">- <span className="summary-icon text-success">- <span className="icon">check_circle</span>- </span>- <span className="summary-text">- {rules.filter(r => r.type === 'port' || r.port).length} ports allowed- </span>- </div>- <div className="summary-item">- <span className="summary-icon text-success">- <span className="icon">check_circle</span>- </span>- <span className="summary-text">- {rules.filter(r => r.type === 'service' || r.service).length} services allowed- </span>- </div>- <div className="summary-item">- <span className="summary-icon text-danger">- <span className="icon">block</span>- </span>- <span className="summary-text">- {blockedIPs.length} IPs blocked- </span>- </div>- </div>- </div>- </div>- </TabsContent>-- <TabsContent value="rules">- <div className="rules-tab">- <div className="section-header">- <h3>Firewall Rules</h3>- <Button onClick={() => setShowPortModal(true)}>- Add Rule- </Button>- </div>- {rules.length === 0 ? (- <EmptyState icon={Filter} title="No rules configured" />- ) : (- <div className="rules-table">- <table>- <thead>- <tr>- <th>Type</th>- <th>Target</th>- <th>Protocol</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {rules.map((rule, index) => (- <tr key={index}>- <td>- <Badge variant="info">{rule.type}</Badge>- </td>- <td>- {rule.type === 'service' && rule.service}- {rule.type === 'port' && rule.port}- {rule.type === 'rich' && (- <code className="rule-code">{rule.rule}</code>- )}- </td>- <td>{rule.protocol || '-'}</td>- <td>- {rule.type === 'port' && (- <Button- variant="destructive"- size="sm"- onClick={() => handleRemovePort(rule.port, rule.protocol)}- >- <span className="icon">delete</span>- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>- </div>- )}- </div>- </TabsContent>-- <TabsContent value="blocked">- <div className="blocked-tab">- <div className="section-header">- <h3>Blocked IP Addresses</h3>- <Button onClick={() => setShowBlockIPModal(true)}>- Block IP- </Button>- </div>- {blockedIPs.length === 0 ? (- <EmptyState icon={ShieldCheck} title="No blocked IPs" />- ) : (- <div className="blocked-list">- {blockedIPs.map((item, index) => (- <div key={index} className="blocked-item">- <div className="blocked-info">- <span className="blocked-ip">{item.ip}</span>- <code className="blocked-rule">{item.rule}</code>- </div>- <Button- variant="secondary"- size="sm"- onClick={() => handleUnblockIP(item.ip)}- >- Unblock- </Button>- </div>- ))}- </div>- )}- </div>- </TabsContent>-- <TabsContent value="quick">- <div className="quick-tab">- <h3>Quick Port Access</h3>- <p className="text-muted">One-click enable/disable common service ports</p>- <div className="quick-ports">- {commonPorts.map(({ port, name, protocol }) => {- const isAllowed = rules.some(r =>- (r.port === String(port) || r.port === port) && r.protocol === protocol- );- return (- <div key={port} className="quick-port-item">- <div className="port-info">- <span className="port-name">{name}</span>- <span className="port-number">{port}/{protocol}</span>- </div>- <div className="port-status">- {isAllowed ? (- <Button- variant="destructive"- size="sm"- onClick={() => handleRemovePort(port, protocol)}- disabled={actionLoading}- >- Block- </Button>- ) : (- <Button- size="sm"- onClick={() => handleQuickAllowPort(port, protocol)}- disabled={actionLoading}- >- Allow- </Button>- )}- </div>- </div>- );- })}- </div>- </div>- </TabsContent>- </Tabs>- </>- )}-- {/* Block IP Modal */}- {showBlockIPModal && (- <div className="modal-overlay" onClick={() => setShowBlockIPModal(false)}>- <div className="modal" onClick={(e) => e.stopPropagation()}>- <div className="modal-header">- <h2>Block IP Address</h2>- <Button variant="ghost" size="icon" onClick={() => setShowBlockIPModal(false)}>- <span className="icon">close</span>- </Button>- </div>- <div className="modal-body">- <div className="form-group">- <Label>IP Address</Label>- <Input- type="text"- value={blockIP}- onChange={(e) => setBlockIP(e.target.value)}- placeholder="192.168.1.100 or 10.0.0.0/24"- />- </div>- <p className="text-muted">- You can block a single IP (192.168.1.100) or a range using CIDR notation (10.0.0.0/24).- </p>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowBlockIPModal(false)}>- Cancel- </Button>- <Button- variant="destructive"- onClick={handleBlockIP}- disabled={actionLoading || !blockIP.trim()}- >- {actionLoading ? 'Blocking...' : 'Block IP'}- </Button>- </div>- </div>- </div>- )}-- {/* Allow Port Modal */}- {showPortModal && (- <div className="modal-overlay" onClick={() => setShowPortModal(false)}>- <div className="modal" onClick={(e) => e.stopPropagation()}>- <div className="modal-header">- <h2>Allow Port</h2>- <Button variant="ghost" size="icon" onClick={() => setShowPortModal(false)}>- <span className="icon">close</span>- </Button>- </div>- <div className="modal-body">- <div className="form-row">- <div className="form-group">- <Label>Port Number</Label>- <Input- type="number"- value={newPort.port}- onChange={(e) => setNewPort({ ...newPort, port: e.target.value })}- placeholder="8080"- min="1"- max="65535"- />- </div>- <div className="form-group">- <Label>Protocol</Label>- <Select value={newPort.protocol} onValueChange={v => setNewPort({ ...newPort, protocol: v })}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="tcp">TCP</SelectItem>- <SelectItem value="udp">UDP</SelectItem>- </SelectContent>- </Select>- </div>- </div>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowPortModal(false)}>- Cancel- </Button>- <Button- onClick={handleAllowPort}- disabled={actionLoading || !newPort.port}- >- {actionLoading ? 'Adding...' : 'Allow Port'}- </Button>- </div>- </div>- </div>- )}-- {/* Install Firewall Modal */}- {showInstallModal && (- <div className="modal-overlay" onClick={() => setShowInstallModal(false)}>- <div className="modal" onClick={(e) => e.stopPropagation()}>- <div className="modal-header">- <h2>Install Firewall</h2>- <Button variant="ghost" size="icon" onClick={() => setShowInstallModal(false)}>- <span className="icon">close</span>- </Button>- </div>- <div className="modal-body">- <div className="form-group">- <Label>Select Firewall</Label>- <Select value={selectedFirewall} onValueChange={setSelectedFirewall}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="ufw">UFW (Recommended for Ubuntu)</SelectItem>- <SelectItem value="firewalld">firewalld (CentOS/RHEL)</SelectItem>- </SelectContent>- </Select>- </div>- <div className="install-info">- {selectedFirewall === 'ufw' ? (- <p>- <strong>UFW (Uncomplicated Firewall)</strong> is a simple and easy-to-use- firewall for Ubuntu and Debian systems. It provides a user-friendly interface- for iptables.- </p>- ) : (- <p>- <strong>firewalld</strong> is a dynamically managed firewall with zone-based- configuration. It's the default firewall on CentOS and RHEL systems.- </p>- )}- </div>- </div>- <div className="modal-footer">- <Button variant="outline" onClick={() => setShowInstallModal(false)}>- Cancel- </Button>- <Button- onClick={handleInstall}- disabled={actionLoading}- >- {actionLoading ? 'Installing...' : 'Install'}- </Button>- </div>- </div>- </div>- )}-- {/* Confirm Dialog */}- {confirmDialog && (- <ConfirmDialog- title={confirmDialog.title}- message={confirmDialog.message}- confirmText={confirmDialog.confirmText}- variant={confirmDialog.variant}- onConfirm={confirmDialog.onConfirm}- onCancel={confirmDialog.onCancel}- />- )}- </div>- );-}--export default Firewall;