Просмотр исходного кода

Merge pull request #99 from kaelthasmanu/reset_connections

Reset connections
Manuel Gorrin 4 месяцев назад
Родитель
Сommit
435a6f1b3d

+ 18 - 0
README_es.md

@@ -187,6 +187,24 @@ _Una herramienta moderna para analizar logs de Squid, proporcionando un panel f
 apt install git python3 python3-pip python3-venv libmariadb-dev curl
 ```
 
+#### Resetear conexiones de un cliente
+
+La acción **Resetear conexiones** del menú de un usuario termina los estados
+de red activos asociados a su IP. Es una operación del sistema operativo, no
+una reconfiguración de Squid, y requiere privilegios equivalentes a root:
+
+- **Linux:** instala `conntrack` (`apt install conntrack`) y concede a
+  SquidStats el acceso necesario al binario. Se ejecuta `conntrack -D -s IP`.
+- **macOS/BSD:** la acción usa `pfctl -k IP`; PF debe estar habilitado y el
+  proceso debe poder ejecutar `pfctl` con privilegios administrativos.
+- **Otros sistemas:** la interfaz informa que esta capacidad no está
+  disponible, sin alterar ninguna conexión.
+
+El reseteo solo afecta estados rastreados por el firewall del host. En una
+instalación Docker o con Squid detrás de otro NAT, debe ejecutarse en el host
+que realmente mantiene esos estados; de lo contrario no se podrán cerrar las
+conexiones del cliente por IP.
+
 > **Nota:** Si tu proxy Squid **no usa autenticación de usuario** (es decir, no usas login o contraseña para clientes), puedes mantener el **formato de log por defecto** que viene con Squid. El formato detallado de abajo solo es requerido para compatibilidad completa con reportes basados en usuarios.
 
 - ⚠️ !!Importante solo funciona antes de la version 7.1 ⚠️ Para compatibilidad con logs de usuarios, usa este formato en /etc/squid/squid.conf:

+ 17 - 3
app.py

@@ -190,9 +190,23 @@ def create_app():
     # Configure response headers
     @app.after_request
     def set_response_headers(response):
-        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
-        response.headers["Pragma"] = "no-cache"
-        response.headers["Expires"] = "0"
+        if request.path.startswith("/static/") and response.status_code == 200:
+            # Static filenames are not content-hashed, so they must remain revalidatable.
+            response.headers["Cache-Control"] = "public, max-age=3600, must-revalidate"
+        else:
+            # Revalidate dynamic/private data without disabling the browser's bfcache.
+            response.headers["Cache-Control"] = "private, no-cache"
+        response.headers["X-Content-Type-Options"] = "nosniff"
+        response.headers["X-Frame-Options"] = "SAMEORIGIN"
+        response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
+        response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
+        response.headers["Permissions-Policy"] = (
+            "camera=(), microphone=(), geolocation=()"
+        )
+        if request.is_secure:
+            response.headers["Strict-Transport-Security"] = (
+                "max-age=31536000; includeSubDomains"
+            )
         return response
 
     return app, scheduler

+ 8 - 6
parsers/connections.py

@@ -107,7 +107,10 @@ def parse_connection_block(block: str, squid_version: str, kid: str | None = Non
             "via_squid",
         ]:
             match = regex.search(block)
-            conn[key] = match.group(1) if match else "N/A"
+            value = match.group(1) if match else "N/A"
+            if key == "client_ip" and match:
+                value = match.group(1).rsplit(":", 1)[0].strip("[]")
+            conn[key] = value
 
     conn["fd_read"] = (
         int(REGEX_MAP["fd_read"].search(block).group(1))
@@ -183,14 +186,13 @@ def group_by_user(connections):
             if indicator is not None
         )
 
+        raw_ip = connection.get("client_ip", "Not found")
         if not is_anonymous:
             key = user
-            client_ip = connection.get("client_ip", "Not found")
+            client_ip = raw_ip
         else:
-            raw_ip = connection.get("client_ip", "Not found")
-            ip_only = raw_ip.split(":")[0] if ":" in raw_ip else raw_ip
-            key = ip_only
-            client_ip = ip_only
+            key = raw_ip
+            client_ip = raw_ip
 
         if not grouped[key]["connections"]:
             grouped[key]["client_ip"] = client_ip

+ 16 - 0
routes/api_routes.py

@@ -16,6 +16,7 @@ from services.notifications.notifications import (
     get_all_notifications,
     mark_notifications_read,
 )
+from services.squid.connection_reset_service import reset_client_connections
 from services.squid.user_restrictions_service import (
     block_user,
     get_user_status,
@@ -318,6 +319,21 @@ def api_unthrottle_user():
         db.close()
 
 
+@api_bp.route("/connections/reset", methods=["POST"])
+@api_admin_required
+def api_reset_client_connections():
+    data = request.get_json(silent=True) or {}
+    ip = str(data.get("ip", "")).strip()
+    # print(f"=== DEBUG api_reset_client_connections: data={data!r}, ip={ip!r}")
+    if not ip:
+        return json_error("Se requiere el campo 'ip'", 400)
+
+    success, message, details = reset_client_connections(ip)
+    if success:
+        return json_success(message)
+    return json_error(message, 501 if "soportado" in message else 409, details=details)
+
+
 @api_bp.route("/delay-pools", methods=["GET"])
 @api_admin_required
 def api_list_delay_pools():

+ 96 - 0
services/squid/connection_reset_service.py

@@ -0,0 +1,96 @@
+"""Terminate tracked network states belonging to a client IP.
+
+This is intentionally a host-level capability. Squid does not expose a
+portable API for closing only one client's active sockets, so unsupported
+platforms must report that fact instead of claiming the reset succeeded.
+"""
+
+import ipaddress
+import platform
+import shutil
+import subprocess  # nosec B404
+
+from loguru import logger
+
+
+def _validate_ip(client_ip: str) -> str:
+    """Return a normalized IP address or raise ValueError."""
+    value = str(client_ip or "").strip()
+    if not value:
+        raise ValueError("Se requiere una dirección IP")
+    try:
+        return str(ipaddress.ip_address(value))
+    except ValueError as exc:
+        raise ValueError("La dirección IP no es válida") from exc
+
+
+def _run_reset(command: list[str], backend: str) -> tuple[bool, str, str | None]:
+    try:
+        result = subprocess.run(  # nosec B603  # noqa: S603
+            command,
+            check=False,
+            capture_output=True,
+            text=True,
+            timeout=30,
+        )
+    except subprocess.TimeoutExpired:
+        return False, "El reseteo de conexiones agotó el tiempo de espera", None
+    except OSError as exc:
+        logger.warning("No se pudo ejecutar %s: %s", backend, exc)
+        return False, f"No se pudo ejecutar {backend}", str(exc)
+
+    if result.returncode == 0:
+        return (
+            True,
+            f"Conexiones activas de {command[-1]} reseteadas mediante {backend}",
+            None,
+        )
+
+    details = (result.stderr or result.stdout).strip() or None
+    logger.warning("%s falló con estado %s: %s", backend, result.returncode, details)
+    if details and any(
+        marker in details.lower()
+        for marker in ("permission denied", "operation not permitted", "must be root")
+    ):
+        return (
+            False,
+            "Se requieren privilegios del sistema para resetear conexiones",
+            details,
+        )
+    return False, f"{backend} no pudo resetear las conexiones", details
+
+
+def reset_client_connections(client_ip: str) -> tuple[bool, str, str | None]:
+    """Reset tracked states for *client_ip* using the host's native firewall.
+
+    Linux uses conntrack and macOS/BSD uses pfctl. Both require the SquidStats
+    process to have the corresponding system privileges (normally root or a
+    narrowly scoped sudo policy).
+    """
+    try:
+        normalized_ip = _validate_ip(client_ip)
+    except ValueError as exc:
+        return False, str(exc), None
+
+    system = platform.system().lower()
+    if system == "linux":
+        binary = shutil.which("conntrack")
+        if not binary:
+            return (
+                False,
+                "No se encontró conntrack. Instálalo en el host para resetear conexiones.",
+                None,
+            )
+        return _run_reset([binary, "-D", "-s", normalized_ip], "conntrack")
+
+    if system in {"darwin", "freebsd", "openbsd", "netbsd"}:
+        binary = shutil.which("pfctl")
+        if not binary:
+            return False, "No se encontró pfctl para resetear conexiones", None
+        return _run_reset([binary, "-k", normalized_ip], "pfctl")
+
+    return (
+        False,
+        f"El reseteo de conexiones no está soportado en {platform.system() or 'este sistema'}",
+        None,
+    )

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
static/all.min.css


+ 4 - 2
static/js/conexiones.js

@@ -12,7 +12,7 @@ function _getCsrf() {
 
 // ── Modal helpers ────────────────────────────────────────────
 function closeAllModals() {
-  ['modal-block', 'modal-unblock', 'modal-throttle', 'modal-unthrottle'].forEach(function(id) {
+  ['modal-block', 'modal-unblock', 'modal-throttle', 'modal-unthrottle', 'modal-reset'].forEach(function(id) {
     var el = document.getElementById(id);
     if (el) el.classList.add('hidden');
   });
@@ -171,6 +171,7 @@ document.addEventListener('click', function(e) {
     if (action === 'unblock')     { _openModal('modal-unblock',     'modal-unblock-subtitle',     user, ip); }
     if (action === 'throttle')    { _openModal('modal-throttle',    'modal-throttle-subtitle',    user, ip); loadDelayPools(); }
     if (action === 'unthrottle')  { _openModal('modal-unthrottle',  'modal-unthrottle-subtitle',  user, ip); }
+    if (action === 'reset')       { _openModal('modal-reset',       'modal-reset-subtitle',       user, ip); }
     return;
   }
 
@@ -188,6 +189,7 @@ document.addEventListener('click', function(e) {
     if (type === 'block')      { _apiAction('/api/connections/block',      { username: _actionUsername, ip: _actionIp }); }
     if (type === 'unblock')    { _apiAction('/api/connections/unblock',    { username: _actionUsername, ip: _actionIp }); }
     if (type === 'unthrottle') { _apiAction('/api/connections/unthrottle', { username: _actionUsername, ip: _actionIp }); }
+    if (type === 'reset')      { _apiAction('/api/connections/reset',      { ip: _actionIp }); }
     if (type === 'throttle') {
       var sel = document.getElementById('throttle-pool-select');
       var poolNum = sel ? parseInt(sel.value) : NaN;
@@ -198,7 +200,7 @@ document.addEventListener('click', function(e) {
   }
 
   // 6. Modal backdrop click
-  var modalIds = ['modal-block', 'modal-unblock', 'modal-throttle', 'modal-unthrottle'];
+  var modalIds = ['modal-block', 'modal-unblock', 'modal-throttle', 'modal-unthrottle', 'modal-reset'];
   if (modalIds.includes(target.id)) {
     closeAllModals();
     return;

+ 2 - 10
static/js/reports-datepicker.js

@@ -144,14 +144,6 @@
     }
   }
 
-  // Wait for Flowbite to attach the picker
-  let retries = 0;
-  (function waitForPicker() {
-    if (input.datepicker || retries > 20) {
-      setup();
-    } else {
-      retries++;
-      setTimeout(waitForPicker, 100);
-    }
-  })();
+  // Native date inputs need no library and are ready immediately.
+  setup();
 })();

BIN
static/squidstats-128.webp


BIN
static/squidstats-64.webp


+ 3 - 2
templates/admin/base.html

@@ -4,6 +4,7 @@
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta name="csrf-token" content="{{ csrf_token() }}">
+    <meta name="description" content="{{ _('Administración y configuración del servidor proxy Squid.') }}">
     <title>{% block title %}{{ _("Administrador Squid Proxy") }}{% endblock %}</title>
     <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"/>
     <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
@@ -18,11 +19,11 @@
             <div class="flex justify-between items-center py-4">
                 <div class="flex items-center space-x-3 md:space-x-6">
                     <!-- Mobile menu button -->
-                    <button @click="sidebarOpen = !sidebarOpen" class="lg:hidden text-white hover:bg-blue-500 p-2 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-300">
+                    <button type="button" aria-label="{{ _('Abrir menú') }}" @click="sidebarOpen = !sidebarOpen" class="lg:hidden text-white hover:bg-blue-500 p-2 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-300">
                         <i class="fas fa-bars text-xl"></i>
                     </button>
                     <div class="flex items-center space-x-3">
-                        <img src="{{ url_for('static', filename='squidstats.webp') }}" alt="{{ _("SquidStats logo") }}" class="w-8 h-8 object-contain" />
+                        <img src="{{ url_for('static', filename='squidstats-64.webp') }}" alt="" width="32" height="32" class="w-8 h-8 object-contain" />
                         <i class="fas fa-server text-2xl md:text-3xl text-blue-200"></i>
                         <div>
                             <h1 class="text-lg md:text-2xl font-bold hidden sm:block">{{ _("Administrador Squid Proxy") }}</h1>

+ 3 - 1
templates/auth/login.html

@@ -4,6 +4,7 @@
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta name="csrf-token" content="{{ csrf_token() }}">
+    <meta name="description" content="{{ _('Acceso seguro al panel de administración de SquidStats.') }}">
     <title>{{ _("Login - SquidStats Admin") }}</title>
     <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"/>
     <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
@@ -55,8 +56,9 @@
         <div class="text-center mb-8">
             <div class="inline-flex items-center justify-center w-24 h-24 mb-4">
                 <img
-                    src="{{ url_for('static', filename='squidstats.webp') }}"
+                    src="{{ url_for('static', filename='squidstats-128.webp') }}"
                     alt="{{ _("SquidStats") }}"
+                    width="96" height="96"
                     class="w-full h-full object-contain drop-shadow-lg"
                 >
             </div>

+ 2 - 4
templates/cacheView.html

@@ -24,10 +24,6 @@
 
 {% block styles %}
   <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
-  <link rel="stylesheet" href="{{ url_for('static', filename='all.min.css') }}"/>
-  <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
-  <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
-  <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
   <style>
     @keyframes progress {
       0% {
@@ -109,6 +105,8 @@
 {% endblock content %}
 
 {% block scripts %}
+  <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
+  <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
   <script>
     Chart.register(ChartDataLabels);
 

+ 7 - 7
templates/components/navbar.html

@@ -4,14 +4,14 @@
     <div class="max-w-7xl mx-auto flex items-center justify-between py-4 h-[64px]">
       <!-- Brand/Logo Section -->
       <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
-        <img src="{{ url_for('static', filename='squidstats.webp') }}" alt="{{ _("Logo SquidStats") }}" class="h-8 w-8 object-contain rounded-md" />
+        <img src="{{ url_for('static', filename='squidstats-64.webp') }}" alt="" width="32" height="32" class="h-8 w-8 object-contain rounded-md" />
         <span class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">{{ _("SquidStats") }}</span>
       </div>
       <!-- Container for mobile icons (notifications + hamburger) -->
       <div class="lg:hidden flex items-center gap-3">
         <!-- Mobile Notifications Button -->
         <div class="relative" x-data="{ open: false }">
-          <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
+          <button type="button" aria-label="{{ _('Notificaciones') }}" @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
             <i class="fas fa-bell"></i>
             <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
           </button>
@@ -29,7 +29,7 @@
             style="display: none">
             <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
               <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
-              <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
+              <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                 <i class="fas fa-times"></i>
               </button>
             </div>
@@ -81,7 +81,7 @@
       <div class="hidden lg:flex items-center gap-3">
         <div class="relative" x-data="{ open: false }">
           <!-- Desktop Notifications Button -->
-          <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
+          <button type="button" aria-label="{{ _('Notificaciones') }}" @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="{{ _("Notificaciones") }}">
             <i class="fas fa-bell"></i>
             <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
           </button>
@@ -99,7 +99,7 @@
             style="display: none">
             <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
               <span class="font-semibold text-gray-800">{{ _("Notificaciones") }}</span>
-              <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
+              <button type="button" aria-label="{{ _('Cerrar notificaciones') }}" @click="open = false" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                 <i class="fas fa-times"></i>
               </button>
             </div>
@@ -241,7 +241,7 @@
 <!-- Scripts -->
 <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
 <script defer src="{{ url_for('static', filename='src/alpine.min.js') }}"></script>
-<script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
+<script defer src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
 <script>
   const IS_DEB_INSTALL = {{ is_deb_install | tojson }};
   // Enhanced Navbar Functionality with Real-time Notifications
@@ -859,4 +859,4 @@
       initNavLoadingOverlay();
     }
   }());
-</script>
+</script>

+ 12 - 13
templates/layouts/base.html

@@ -4,23 +4,24 @@
     <meta charset="UTF-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <meta name="csrf-token" content="{{ csrf_token() }}">
+    <meta name="description" content="{{ meta_description or _('SquidStats: panel de monitorización, estadísticas y administración para servidores proxy Squid.') }}">
     <title>{{ page_title or 'Dashboard Squid' }}</title>
     <!-- Dynamic favicon -->
     <link rel="icon" href="{{ url_for('static', filename=page_icon) }}" type="image/x-icon"/>
     <!-- Stylesheets -->
     <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"/>
     <link rel="stylesheet" href="{{url_for('static',filename='dist/output.css')}}"/> <!-- Tailwind CSS -->
+    <link rel="preload" href="{{ url_for('static', filename='webfonts/fa-solid-900.woff2') }}" as="font" type="font/woff2" crossorigin>
     <link rel="stylesheet" href="{{ url_for('static', filename='all.min.css') }}"/> <!-- Font Awesome -->
-    <!-- Logs CSS Custom-->
-    <link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}"/>
     <!-- Toastr CSS -->
-    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}"/>
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}" media="print" onload="this.media='all'"/>
+    <noscript><link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}"/></noscript>
     <!-- Toastr Custom CSS -->
-    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr-custom.css') }}"/>
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr-custom.css') }}" media="print" onload="this.media='all'"/>
     <!-- Page-specific styles -->
     {% block styles %}{% endblock styles %}
   </head>
-  <body class="overflow-x-hidden overflow-auto" style="visibility: hidden" onload="document.body.style.visibility='visible';">
+  <body class="overflow-x-hidden overflow-auto">
     <!-- Common navigation bar -->
     <div class="relative">
       {% include 'components/navbar.html' %}
@@ -62,15 +63,13 @@
     <!-- Footer -->
     {% include 'components/footer.html' %}
     <!-- Socket.IO -->
-    <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
-    <!-- Flowbite scripts (UI components) -->
-    <script src="{{ url_for('static', filename='src/flowbite.min.js') }}"></script>
+    <script defer src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
     <!-- jQuery (requerido por toastr) -->
-    <script src="{{ url_for('static', filename='js/jquery-4.0.0.min.js') }}"></script>
+    <script defer src="{{ url_for('static', filename='js/jquery-4.0.0.min.js') }}"></script>
     <!-- Toastr JS -->
-    <script src="{{ url_for('static', filename='js/toastr.min.js') }}"></script>
+    <script defer src="{{ url_for('static', filename='js/toastr.min.js') }}"></script>
     <!-- Configuración global de Toastr -->
-    <script src="{{ url_for('static', filename='js/toastr-config.js') }}"></script>
+    <script defer src="{{ url_for('static', filename='js/toastr-config.js') }}"></script>
     <!-- i18n translations for JavaScript -->
     <script>
       window._i18n = window._i18n || {};
@@ -85,7 +84,7 @@
     {% with messages = get_flashed_messages(with_categories=true) %}
       {% if messages %}
         <script>
-          $(document).ready(function () {
+          document.addEventListener('DOMContentLoaded', function () {
             {% for category, message in messages %}
               {% if category == 'success' %}
                 toastr.success({{ message | tojson }});
@@ -104,4 +103,4 @@
     <!-- Page-specific scripts -->
     {% block scripts %}{% endblock scripts %}
   </body>
-</html>
+</html>

+ 2 - 2
templates/logsView.html

@@ -1,6 +1,6 @@
 
 {% extends 'layouts/base.html' %}
-{% block styles %}{% endblock styles %}
+{% block styles %}<link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}"/>{% endblock %}
 
 {% block header_actions %}
   <form method="get" class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
@@ -43,4 +43,4 @@
 
 {% block scripts %}
     <script type="module" src="static/js/dashboard.js"></script>
-{% endblock scripts %}
+{% endblock scripts %}

+ 26 - 3
templates/partials/conexiones.html

@@ -306,9 +306,10 @@
                   <i class="fas fa-circle-check text-blue-500 w-4"></i> {{ _("Desbloquear") }}
                 </button>
                 <div class="border-t border-gray-100 my-1"></div>
-                <button type="button" disabled
-                  class="w-full text-left flex items-center gap-2 px-4 py-2 text-sm text-slate-400 cursor-not-allowed">
-                  <i class="fas fa-rotate text-slate-300 w-4"></i> {{ _("Resetear conexiones") }} <span class="text-xs ml-auto">{{ _("(Próx.)") }}</span>
+                <button type="button"
+                  data-action="reset" data-user="{{ user }}" data-ip="{{ client_ip }}"
+                  class="w-full text-left flex items-center gap-2 px-4 py-2 text-sm text-orange-700 hover:bg-orange-50 transition-colors duration-150">
+                  <i class="fas fa-rotate text-orange-500 w-4"></i> {{ _("Resetear conexiones") }}
                 </button>
               </div>
             </div>
@@ -423,6 +424,28 @@
      MODALES DE ACCIONES
      ============================================================ -->
 
+<!-- Modal: Resetear conexiones -->
+<div id="modal-reset" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
+  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
+    <div class="flex items-center gap-3 mb-4">
+      <div class="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center flex-shrink-0">
+        <i class="fas fa-rotate text-orange-500"></i>
+      </div>
+      <div>
+        <h3 class="text-lg font-bold text-gray-800">{{ _("Resetear conexiones") }}</h3>
+        <p id="modal-reset-subtitle" class="text-sm text-gray-500"></p>
+      </div>
+    </div>
+    <p class="text-sm text-gray-600 mb-6">{{ _("Se cerrarán los estados de red activos asociados a esta IP. Las nuevas conexiones podrán establecerse inmediatamente.") }}</p>
+    <div class="flex justify-end gap-3">
+      <button type="button" data-modal-cancel class="px-4 py-2 rounded-lg border border-gray-200 text-gray-600 text-sm hover:bg-gray-50 transition-colors">{{ _("Cancelar") }}</button>
+      <button type="button" data-modal-confirm="reset" class="px-4 py-2 rounded-lg bg-orange-500 hover:bg-orange-600 text-white text-sm font-semibold transition-colors">
+        <i class="fas fa-rotate mr-1.5"></i> {{ _("Resetear") }}
+      </button>
+    </div>
+  </div>
+</div>
+
 <!-- Modal: Bloquear usuario -->
 <div id="modal-block" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
   <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 animate-fade-in">

+ 4 - 7
templates/reports.html

@@ -12,11 +12,8 @@
 
         <input
           id="reports-date"
-          type="text"
-          datepicker
-          datepicker-orientation="bottom"
-          datepicker-autohide
-          datepicker-container="body"
+          type="date"
+          aria-label="{{ _('Fecha del reporte') }}"
           class="w-28 xs:w-32 rounded-md border border-gray-300 bg-white px-2 py-1 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200"
         />
 
@@ -48,8 +45,6 @@
 
 {% block styles %}
   <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
-  <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
-  <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
 {% endblock styles %}
 
 {% block content %}
@@ -57,6 +52,8 @@
 {% endblock content %}
 
 {% block scripts %}
+  <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
+  <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
   {# Chart data injected as JSON so inline Jinja expressions are evaluated server-side
      and all JS behaviour lives in the external reports-charts.js file. #}
   <script type="application/json" id="chart-data">

+ 51 - 0
tests/test_connection_reset_service.py

@@ -0,0 +1,51 @@
+from unittest.mock import patch
+
+from services.squid.connection_reset_service import reset_client_connections
+
+
+def test_reset_rejects_invalid_ip_without_running_a_command():
+    with patch("services.squid.connection_reset_service.subprocess.run") as mock_run:
+        success, message, details = reset_client_connections("not-an-ip")
+
+    assert success is False
+    assert "válida" in message
+    assert details is None
+    mock_run.assert_not_called()
+
+
+def test_reset_uses_conntrack_for_linux_clients():
+    with (
+        patch(
+            "services.squid.connection_reset_service.platform.system",
+            return_value="Linux",
+        ),
+        patch(
+            "services.squid.connection_reset_service.shutil.which",
+            return_value="/usr/sbin/conntrack",
+        ),
+        patch("services.squid.connection_reset_service.subprocess.run") as mock_run,
+    ):
+        mock_run.return_value.returncode = 0
+        success, message, details = reset_client_connections("192.0.2.10")
+
+    assert success is True
+    assert "conntrack" in message
+    assert details is None
+    assert mock_run.call_args.args[0] == [
+        "/usr/sbin/conntrack",
+        "-D",
+        "-s",
+        "192.0.2.10",
+    ]
+
+
+def test_reset_reports_unsupported_platform():
+    with patch(
+        "services.squid.connection_reset_service.platform.system",
+        return_value="Windows",
+    ):
+        success, message, details = reset_client_connections("192.0.2.10")
+
+    assert success is False
+    assert "soportado" in message
+    assert details is None

Некоторые файлы не были показаны из-за большого количества измененных файлов