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

fix: update datetime handling to use UTC for consistency in AuthService

Manuel 11 месяцев назад
Родитель
Сommit
2c37341135

+ 108 - 0
.github/secrets/private-key.asc

@@ -0,0 +1,108 @@
+-----BEGIN PGP PRIVATE KEY BLOCK-----
+
+lQdGBGjVovIBEADEDVnIkuz0/RWuAGPVTj4R4SXtn0X0KBD0DhgKs3miX9HCz6Q6
+lKRgqlUZ0Tbdex5OlnNWSkRwFMXk3gaDwsdaGbt3VVfQkKuX+ARHnquQtQdRfIUB
+g52E+QhsH4jWhfWbcqkUKmbVLyYnmUcvUvCJ3s9yeG6/DdikaASyEILQzB5hzYCI
+iOf4FFrrM0AB4tHU2o3fmL4NiWoQbrlB5YWpkatvp1KsMWQriLTa8t9mOxPi6aoc
+QPjHtOy1gOzwsogV7qwAF9AP9wlz5us2Il1EAK03ScqNYiNB9Wp90/yZ8QD2nAeK
+jbp7BCzA2jYLkt/0bN2OS/ywdYW2FAfN9MG8d2Mq67xay6sCNgbRrQMj+but9raB
+dXwv2VtjrZC2bLTX3nniPx0XR0Ylj8MqVtkpZuuUSvaQAh3/HLinCMmw/tW3fr83
+20MLBrHdQD1wsPl9eDhuG1fMyw4ZYoHHOapUVkcL4FvLnFaAOij9QcOUelFKvp9J
+E+rXwborqcYkXlISItUTcTVb7tse3G1Mo46fIoLt/kuCBPzGy9VAsRoQGcHR/vMU
+dvcwoNnadPMyaLXPHamFe4E+4iZgUkZQ8GtyLZJxBL2ZW+mcJo3oA/HKJxjyVVDE
+4Fo5G6Qd1NzvuiSmjRET7ZaxUq2+pvL0qvonpoYHQilvjL7RODjJdnI4VQARAQAB
+/gcDAmaIyqx5q25F7I72jUdq3IRjMeTVcqShgYw8xDe7tCk1eOPShoCITLKqs81d
+Y7Tgd5JoeCWRiUE14D6S52Scls5Atwd8y7ZkQrh4tCQVUL1NPGUZ/WqmcgJtp67y
+HnheTPDoSRuJnXPDAnVlFTE2KUlhBW/Iww7W+WfN1bNg68C9QXk54Yz3zx8S6x9E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9TQaUi3D72+xAmWoEFzXjopGcX
+v2lwRprn++S6lI3OgNv2xE5jQJZX58LC3krV8iv+ttA7/sg79AbYIjX3cgLoruhs
+u985PURUmHLTtHQsMwlOxmbGf5Ab7xxKORY2vFUr5643FywSXtvB+iCXWOHo/Vfu
+2syLWUbV+FD4Ti6juxOhjXGCkIFrDwOx/hx93dhei6+EHRb6G71uoSiYcD/ZY2VQ
+ndFSxVUyrPBpVSl1a9Th3HkVgxWhB6/FkVI7J1VyzwnBfRg0gu0WHA8hKIB8A7ch
+ZdOu/1Y8EFa5Ub/USVm5Af2jbgODDPvGwLbDPoAkMXHZZyFEisZ1GmFg880sOr3t
+EzTDHkEZd5wmO6i/m1HPlEL9LBHFwleOtUuTDzuoSEN8ZUJvUVIC4qy8oTm2Mvxt
+49CMMfpKUqLcnkSgCoH+O/fy9KcQ2aL149n31mcA1XRKp6trwPzJFXglt0xt/ZsH
+eE1GrGyyXjVaNWcED2rC7EafAe1UReU=
+=H2+y
+-----END PGP PUBLIC KEY BLOCK-----

+ 8 - 0
.github/secrets/secrets.env

@@ -0,0 +1,8 @@
+# GitHub Secrets para PPA Workflow
+# Generado: Sun Nov 30 23:20:38 CST 2025
+
+GPG_KEY_ID=A3A53E03FD3AD21B9D1AFED413ED7F7A992838DE
+GPG_PASSPHRASE=manuel*19960916
+PPA_NAME=ppa:kaelthasmanu/squidstats
+
+# Nota: GPG_PRIVATE_KEY está en private-key.asc

+ 7 - 0
.github/workflows/.secrets

@@ -0,0 +1,7 @@
+# Archivo de secretos para testing local con act
+# NO SUBIR ESTE ARCHIVO A GITHUB - Ya está en .gitignore
+
+GPG_PRIVATE_KEY=tu-clave-privada-gpg-aqui
+GPG_PASSPHRASE=tu-passphrase-aqui
+GPG_KEY_ID=tu-key-id-aqui
+PPA_NAME=ppa:usuario/nombre-ppa

+ 365 - 0
.github/workflows/LOCAL_TESTING.md

@@ -0,0 +1,365 @@
+# Guía para Probar el Workflow Localmente
+
+Esta guía te ayudará a probar el workflow de GitHub Actions localmente antes de subirlo al repositorio.
+
+## Método 1: Usar act (Recomendado para testing básico)
+
+### 1. Instalar act
+
+```bash
+# macOS con Homebrew
+brew install act
+
+# Verificar instalación
+act --version
+```
+
+### 2. Configurar secretos locales
+
+Edita el archivo `.github/workflows/.secrets` con tus valores reales:
+
+```bash
+# Crear archivo de secretos
+nano .github/workflows/.secrets
+```
+
+Contenido:
+```
+GPG_PRIVATE_KEY=-----BEGIN PGP PRIVATE KEY BLOCK-----
+tu-clave-completa-aqui
+-----END PGP PRIVATE KEY BLOCK-----
+GPG_PASSPHRASE=tu-passphrase
+GPG_KEY_ID=ABCD1234EFGH5678
+PPA_NAME=ppa:usuario/squidstats
+```
+
+### 3. Ejecutar el workflow
+
+```bash
+# Test completo del job build-deb
+act -j build-deb --secret-file .github/workflows/.secrets
+
+# Test solo hasta construir el .deb (sin subir a PPA)
+act -j build-deb --secret-file .github/workflows/.secrets -e .github/workflows/test-event.json
+
+# Listar los jobs disponibles
+act -l
+
+# Dry-run (ver qué haría sin ejecutar)
+act -j build-deb --secret-file .github/workflows/.secrets --dryrun
+```
+
+### 4. Crear evento de prueba manual
+
+```bash
+cat > .github/workflows/test-event.json << 'EOF'
+{
+  "inputs": {
+    "version": "1.0.0-test"
+  }
+}
+EOF
+
+# Ejecutar con evento personalizado
+act workflow_dispatch -j build-deb --secret-file .github/workflows/.secrets --eventpath .github/workflows/test-event.json
+```
+
+### Limitaciones de act:
+- Usa imágenes Docker, puede ser lento la primera vez
+- Algunas acciones de GitHub pueden no funcionar idénticamente
+- No ejecuta la parte de subida al PPA (lo cual está bien para testing)
+
+---
+
+## Método 2: Docker Manual (Más control)
+
+### 1. Crear Dockerfile de prueba
+
+```bash
+cat > .github/workflows/Dockerfile.test << 'EOF'
+FROM ubuntu:22.04
+
+ENV DEBIAN_FRONTEND=noninteractive
+
+RUN apt-get update && apt-get install -y \
+    debhelper \
+    dh-python \
+    python3-all \
+    python3-setuptools \
+    python3-pip \
+    devscripts \
+    build-essential \
+    lintian \
+    git \
+    && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /workspace
+
+CMD ["/bin/bash"]
+EOF
+```
+
+### 2. Script de prueba
+
+```bash
+cat > .github/workflows/test-build.sh << 'EOF'
+#!/bin/bash
+set -e
+
+VERSION="${1:-1.0.0-test}"
+PACKAGE_NAME="squidstats"
+
+echo "=== Building package version: $VERSION ==="
+
+# Crear estructura
+PACKAGE_DIR="${PACKAGE_NAME}-${VERSION}"
+mkdir -p $PACKAGE_DIR
+
+# Copiar archivos (ajusta según tu proyecto)
+cp -r app.py config.py requirements.txt $PACKAGE_DIR/
+cp -r database parsers routes services static templates utils $PACKAGE_DIR/ 2>/dev/null || true
+cp -r assets $PACKAGE_DIR/ 2>/dev/null || true
+
+# Crear debian/
+mkdir -p $PACKAGE_DIR/debian
+
+# (Aquí van todos los cat > debian/* del workflow)
+# ... copia el contenido del workflow aquí ...
+
+echo "=== Building package ==="
+cd $PACKAGE_DIR
+debuild -us -uc -b
+cd ..
+
+echo "=== Checking with lintian ==="
+lintian --info *.deb || true
+
+echo "=== Package built successfully ==="
+ls -lh *.deb
+
+echo "=== Package info ==="
+dpkg-deb --info *.deb
+
+echo "=== Package contents ==="
+dpkg-deb --contents *.deb
+EOF
+
+chmod +x .github/workflows/test-build.sh
+```
+
+### 3. Ejecutar en Docker
+
+```bash
+# Construir imagen
+docker build -f .github/workflows/Dockerfile.test -t squidstats-builder .
+
+# Ejecutar build
+docker run --rm -v "$(pwd):/workspace" squidstats-builder ./github/workflows/test-build.sh 1.0.0-test
+
+# Los archivos .deb quedarán en tu directorio actual
+```
+
+---
+
+## Método 3: VM Local con Vagrant (Más realista)
+
+### 1. Crear Vagrantfile
+
+```bash
+cat > Vagrantfile << 'EOF'
+Vagrant.configure("2") do |config|
+  config.vm.box = "ubuntu/jammy64"
+  
+  config.vm.provider "virtualbox" do |vb|
+    vb.memory = "2048"
+    vb.cpus = 2
+  end
+  
+  config.vm.provision "shell", inline: <<-SHELL
+    apt-get update
+    apt-get install -y debhelper dh-python python3-all python3-setuptools \
+                       devscripts build-essential lintian git
+  SHELL
+  
+  config.vm.synced_folder ".", "/vagrant"
+end
+EOF
+```
+
+### 2. Usar la VM
+
+```bash
+# Iniciar VM
+vagrant up
+
+# Conectar
+vagrant ssh
+
+# Dentro de la VM
+cd /vagrant
+./.github/workflows/test-build.sh 1.0.0-test
+
+# Salir
+exit
+
+# Detener VM
+vagrant halt
+```
+
+---
+
+## Método 4: Testing Incremental (Lo más práctico)
+
+### Script de validación rápida
+
+```bash
+cat > .github/workflows/validate-structure.sh << 'EOF'
+#!/bin/bash
+
+echo "=== Validando estructura del proyecto ==="
+
+# Verificar archivos necesarios
+FILES=(
+    "app.py"
+    "config.py"
+    "requirements.txt"
+    "database/__init__.py"
+    "parsers/__init__.py"
+    "routes/__init__.py"
+    "services/__init__.py"
+)
+
+for file in "${FILES[@]}"; do
+    if [ -f "$file" ]; then
+        echo "✓ $file existe"
+    else
+        echo "✗ $file NO ENCONTRADO"
+        exit 1
+    fi
+done
+
+echo ""
+echo "=== Validando requirements.txt ==="
+cat requirements.txt
+
+echo ""
+echo "=== Simulando creación de estructura debian/ ==="
+TEMP_DIR=$(mktemp -d)
+mkdir -p "$TEMP_DIR/debian"
+
+echo "✓ Estructura básica creada en $TEMP_DIR"
+
+echo ""
+echo "=== Test de sintaxis Python ==="
+python3 -m py_compile app.py config.py
+echo "✓ Sintaxis correcta"
+
+echo ""
+echo "✓ Validación completa"
+rm -rf "$TEMP_DIR"
+EOF
+
+chmod +x .github/workflows/validate-structure.sh
+```
+
+### Ejecutar validación
+
+```bash
+# Validación rápida
+./.github/workflows/validate-structure.sh
+
+# Si pasa, probar con act
+act -j build-deb --secret-file .github/workflows/.secrets -n
+
+# Si act funciona, probar build completo
+act -j build-deb --secret-file .github/workflows/.secrets
+```
+
+---
+
+## Checklist de Validación
+
+Antes de subir al repositorio, verifica:
+
+- [ ] El workflow tiene la sintaxis YAML correcta
+  ```bash
+  # Instalar yamllint
+  pip3 install yamllint
+  
+  # Validar
+  yamllint .github/workflows/create-ppa.yml
+  ```
+
+- [ ] Los paths de archivos son correctos
+  ```bash
+  ./.github/workflows/validate-structure.sh
+  ```
+
+- [ ] El paquete se construye sin errores
+  ```bash
+  act -j build-deb --secret-file .github/workflows/.secrets
+  ```
+
+- [ ] El archivo .deb se crea correctamente
+  ```bash
+  # Después de ejecutar act o el script
+  ls -lh *.deb
+  dpkg-deb --info squidstats_*.deb
+  ```
+
+- [ ] Los secretos están configurados (en local)
+  ```bash
+  cat .github/workflows/.secrets
+  ```
+
+---
+
+## Recomendación Final
+
+**El flujo más eficiente:**
+
+1. **Validación sintaxis**: `yamllint .github/workflows/create-ppa.yml`
+2. **Validación estructura**: `./.github/workflows/validate-structure.sh`
+3. **Build local rápido**: Usar el script de Docker
+4. **Test completo**: `act -j build-deb --secret-file .github/workflows/.secrets`
+5. **Verificar .deb**: `dpkg-deb --info *.deb`
+6. **Subir a GitHub**: Crear rama de prueba primero
+
+```bash
+# Crear rama de testing
+git checkout -b test/github-actions
+git add .github/workflows/
+git commit -m "test: add PPA workflow"
+git push origin test/github-actions
+
+# Probar con tag en la rama
+git tag v0.0.1-test
+git push origin v0.0.1-test
+
+# Ver resultados en GitHub Actions
+# Si funciona, merge a main
+```
+
+---
+
+## Troubleshooting
+
+### act no encuentra Docker
+```bash
+# Verificar Docker está corriendo
+docker ps
+
+# Iniciar Docker Desktop si es necesario
+```
+
+### Errores de permisos en act
+```bash
+# Ejecutar con privilegios si es necesario
+act -j build-deb --secret-file .github/workflows/.secrets --privileged
+```
+
+### Quiero ver el output completo
+```bash
+# Modo verbose
+act -j build-deb --secret-file .github/workflows/.secrets -v
+```

+ 182 - 0
.github/workflows/PPA_SETUP.md

@@ -0,0 +1,182 @@
+# Configuración del GitHub Actions para PPA
+
+Este workflow automatiza la creación de paquetes .deb y su publicación en un PPA de Ubuntu.
+
+## Requisitos Previos
+
+### 1. Cuenta en Launchpad
+
+1. Crea una cuenta en [Launchpad](https://launchpad.net/)
+2. Crea un PPA en tu perfil (por ejemplo: `ppa:tu-usuario/squidstats`)
+
+### 2. Generar clave GPG
+
+```bash
+# Generar nueva clave GPG
+gpg --full-generate-key
+
+# Opciones recomendadas:
+# - Tipo: RSA and RSA
+# - Tamaño: 4096
+# - Validez: 0 (no expira) o el tiempo que prefieras
+# - Nombre: Tu nombre
+# - Email: El mismo email de Launchpad
+
+# Listar claves
+gpg --list-secret-keys --keyid-format=long
+
+# Exportar clave privada (para GitHub Secrets)
+gpg --armor --export-secret-keys TU_KEY_ID > private-key.asc
+
+# Exportar clave pública (para Launchpad)
+gpg --armor --export TU_KEY_ID > public-key.asc
+```
+
+### 3. Subir clave pública a Launchpad
+
+1. Ve a tu perfil de Launchpad
+2. Navega a "OpenPGP keys"
+3. Importa el contenido de `public-key.asc`
+
+### 4. Subir clave pública a Ubuntu Keyserver
+
+```bash
+gpg --keyserver keyserver.ubuntu.com --send-keys TU_KEY_ID
+```
+
+## Configuración de GitHub Secrets
+
+Ve a tu repositorio → Settings → Secrets and variables → Actions y crea los siguientes secrets:
+
+### Secrets Requeridos:
+
+1. **`GPG_PRIVATE_KEY`**
+   - Contenido del archivo `private-key.asc`
+   - Incluye las líneas `-----BEGIN PGP PRIVATE KEY BLOCK-----` y `-----END PGP PRIVATE KEY BLOCK-----`
+
+2. **`GPG_PASSPHRASE`**
+   - La contraseña que usaste al crear la clave GPG
+
+3. **`GPG_KEY_ID`**
+   - El ID de tu clave GPG (formato largo, ej: `ABCD1234EFGH5678`)
+   - Obtenerlo con: `gpg --list-secret-keys --keyid-format=long`
+
+4. **`PPA_NAME`**
+   - El nombre de tu PPA en formato: `ppa:usuario/nombre-ppa`
+   - Ejemplo: `ppa:kaelthasmanu/squidstats`
+
+## Uso del Workflow
+
+### Opción 1: Mediante Tags (Recomendado)
+
+```bash
+# Crear y subir un tag
+git tag -a v1.0.0 -m "Release version 1.0.0"
+git push origin v1.0.0
+```
+
+El workflow se ejecutará automáticamente y:
+- Construirá el paquete .deb
+- Lo firmará con tu clave GPG
+- Lo subirá al PPA
+- Creará un release en GitHub
+
+### Opción 2: Ejecución Manual
+
+1. Ve a Actions en tu repositorio
+2. Selecciona "Build and Publish to PPA"
+3. Haz clic en "Run workflow"
+4. Ingresa la versión deseada (ej: 1.0.0)
+
+**Nota:** La ejecución manual NO sube al PPA, solo construye el paquete.
+
+## Verificación
+
+### Verificar en Launchpad
+
+1. Ve a tu PPA en Launchpad
+2. Deberías ver el paquete en "Packages"
+3. El paquete debe mostrar estado "Published" después de unos minutos
+
+### Instalación desde PPA
+
+```bash
+sudo add-apt-repository ppa:tu-usuario/squidstats
+sudo apt update
+sudo apt install squidstats
+```
+
+## Personalización
+
+Edita las siguientes variables en `.github/workflows/create-ppa.yml`:
+
+```yaml
+env:
+  PACKAGE_NAME: squidstats
+  MAINTAINER_NAME: "Tu Nombre"
+  MAINTAINER_EMAIL: "tu-email@example.com"
+  DESCRIPTION: "Descripción de tu paquete"
+```
+
+## Troubleshooting
+
+### Error: "GPG signing failed"
+- Verifica que `GPG_PRIVATE_KEY` y `GPG_PASSPHRASE` sean correctos
+- Asegúrate de incluir todo el bloque de la clave privada
+
+### Error: "Upload rejected by PPA"
+- Verifica que la clave GPG esté registrada en Launchpad
+- La clave debe estar en el keyserver de Ubuntu
+- El email de la clave debe coincidir con el de Launchpad
+
+### Error: "Package already exists"
+- Incrementa el número de versión
+- O incrementa el número de release en `debian/changelog`
+
+### El paquete no aparece en el PPA
+- Revisa la cola de construcción en Launchpad
+- Pueden tardar varios minutos en procesarse
+- Revisa los logs de construcción en Launchpad
+
+## Estructura del Paquete
+
+El paquete instalará:
+- Aplicación en `/opt/squidstats/`
+- Configuración en `/etc/squidstats/.env`
+- Logs en `/var/log/squidstats/`
+- Servicio systemd: `squidstats.service`
+
+## Comandos útiles después de la instalación
+
+```bash
+# Ver estado del servicio
+sudo systemctl status squidstats
+
+# Reiniciar servicio
+sudo systemctl restart squidstats
+
+# Ver logs
+sudo journalctl -u squidstats -f
+
+# Editar configuración
+sudo nano /etc/squidstats/.env
+
+# Reiniciar después de cambios
+sudo systemctl restart squidstats
+```
+
+## Distribuciones Soportadas
+
+Por defecto, el paquete se construye para Ubuntu 22.04 (Jammy). Para soportar otras versiones:
+
+1. Modifica `debian/changelog` para incluir la distribución
+2. Ajusta las dependencias en `debian/control` según la versión
+
+Ejemplo para múltiples distribuciones:
+```bash
+# En el workflow, construir para cada distribución
+for DIST in jammy focal noble; do
+  debuild -S -sa -d
+  dput ppa:usuario/ppa squidstats_version~${DIST}1_source.changes
+done
+```

+ 197 - 0
.github/workflows/QUICKSTART.md

@@ -0,0 +1,197 @@
+# 🚀 Guía Rápida: Testing del Workflow Localmente
+
+## ✅ ¡El workflow funciona correctamente!
+
+Se ha probado localmente con `act` y el paquete .deb se construye exitosamente.
+
+## 🎯 Resultados del Testing Local
+
+```bash
+# El build completó exitosamente:
+✅ Estructura Debian creada
+✅ Paquete .deb construido
+✅ Lintian verificado (solo warnings menores)
+⚠️  Upload artifacts falló (esperado en act, funcionará en GitHub)
+```
+
+## Opción 1: Testing Rápido con act ✅ PROBADO
+
+### Ejecutar el build:
+```bash
+# Opción A: Con script automatizado
+./.github/workflows/test-build.sh
+
+# Opción B: Manual
+act -j build-deb
+```
+
+**Resultado esperado:**
+- ✅ Success - Main Create Debian package structure
+- ✅ Success - Main Build Debian package  
+- ✅ Success - Main Check package with lintian
+- ❌ Failure - Main Upload artifacts (normal con act)
+
+---
+
+## Opción 2: Testing con Docker (Sin act)
+
+```bash
+# Construir en contenedor Ubuntu
+docker run --rm -v "$(pwd):/workspace" -w /workspace ubuntu:22.04 bash -c "
+  apt-get update && 
+  apt-get install -y debhelper dh-python python3-all devscripts build-essential lintian &&
+  export VERSION=1.0.0-test &&
+  export PACKAGE_NAME=squidstats &&
+  # ... el resto del workflow aquí
+"
+```
+
+---
+
+## Opción 3: Testing en Rama Separada (Más seguro)
+
+```bash
+# 1. Crear rama de prueba
+git checkout -b test/ppa-workflow
+
+# 2. Commit de los cambios
+git add .github/
+git commit -m "test: add PPA build workflow"
+
+# 3. Subir a GitHub
+git push origin test/ppa-workflow
+
+# 4. Crear tag de prueba
+git tag v0.0.1-test
+git push origin v0.0.1-test
+
+# 5. Ver el workflow en GitHub Actions
+# Ve a: https://github.com/kaelthasmanu/SquidStats/actions
+
+# 6. Si todo funciona, merge a main
+git checkout main
+git merge test/ppa-workflow
+git push origin main
+```
+
+---
+
+## ⚙️ Preparación Previa (Una sola vez)
+
+### 1. Crear clave GPG (si no tienes):
+```bash
+gpg --full-generate-key
+# Tipo: RSA and RSA
+# Tamaño: 4096
+# Validez: 0 (no expira)
+```
+
+### 2. Exportar clave:
+```bash
+# Obtener ID
+gpg --list-secret-keys --keyid-format=long
+
+# Exportar privada (para secret)
+gpg --armor --export-secret-keys TU_KEY_ID > private-key.asc
+
+# Exportar pública (para Launchpad)
+gpg --armor --export TU_KEY_ID > public-key.asc
+```
+
+### 3. Registrar en Launchpad:
+1. Ir a https://launchpad.net/~tu-usuario/+editpgpkeys
+2. Pegar contenido de `public-key.asc`
+3. Confirmar email
+
+### 4. Subir a keyserver:
+```bash
+gpg --keyserver keyserver.ubuntu.com --send-keys TU_KEY_ID
+```
+
+### 5. Configurar secretos en GitHub:
+Settings → Secrets → Actions → New secret:
+- `GPG_PRIVATE_KEY`: Contenido de `private-key.asc`
+- `GPG_PASSPHRASE`: Tu passphrase de GPG
+- `GPG_KEY_ID`: Tu key ID
+- `PPA_NAME`: `ppa:usuario/nombre-ppa`
+
+---
+
+## 📋 Checklist antes de usar en producción
+
+- [ ] ✅ Validación pasó: `./.github/workflows/validate-structure.sh`
+- [ ] Workflow probado con act o en rama de testing
+- [ ] Clave GPG creada y registrada en Launchpad
+- [ ] Secretos configurados en GitHub
+- [ ] PPA creado en Launchpad
+- [ ] `MAINTAINER_NAME` y `MAINTAINER_EMAIL` actualizados en el workflow
+- [ ] Versión inicial definida (ej: v1.0.0)
+
+---
+
+## 🎯 Primera Ejecución en Producción
+
+```bash
+# 1. Asegúrate de estar en main y actualizado
+git checkout main
+git pull
+
+# 2. Crear tag de release
+git tag -a v1.0.0 -m "Release version 1.0.0"
+
+# 3. Subir tag
+git push origin v1.0.0
+
+# 4. Verificar en GitHub Actions
+# https://github.com/kaelthasmanu/SquidStats/actions
+
+# 5. Verificar en Launchpad (tarda ~5-10 min)
+# https://launchpad.net/~usuario/+archive/ubuntu/ppa
+```
+
+---
+
+## 🔍 Verificar resultados
+
+### En GitHub:
+- Actions tab → Ver el workflow ejecutándose
+- Releases → Debe aparecer el .deb descargable
+
+### En Launchpad:
+- Tu PPA → Packages → Debe aparecer squidstats
+- Estado debe cambiar a "Published" después de construir
+
+### Instalar desde PPA:
+```bash
+sudo add-apt-repository ppa:usuario/squidstats
+sudo apt update
+sudo apt install squidstats
+```
+
+---
+
+## 📚 Documentación completa
+
+- **Setup completo de PPA**: `.github/workflows/PPA_SETUP.md`
+- **Testing local detallado**: `.github/workflows/LOCAL_TESTING.md`
+- **Workflow**: `.github/workflows/create-ppa.yml`
+
+---
+
+## 🆘 Ayuda rápida
+
+```bash
+# Validar estructura
+./.github/workflows/validate-structure.sh
+
+# Test con act
+act -j build-deb -n
+
+# Ver logs del workflow en GitHub
+gh run list
+gh run view --log
+
+# Ver estado del paquete
+dpkg -l | grep squidstats
+systemctl status squidstats
+```

+ 234 - 0
.github/workflows/TEST_RESULTS.md

@@ -0,0 +1,234 @@
+# ✅ Workflow de PPA - Resultados del Testing
+
+## Estado: PROBADO Y FUNCIONANDO ✅
+
+El workflow ha sido probado localmente con `act` y **funciona correctamente**.
+
+---
+
+## 📊 Resultados de las Pruebas
+
+### ✅ Tests Realizados:
+
+1. **Validación de estructura del proyecto**
+   ```bash
+   ./.github/workflows/validate-structure.sh
+   ```
+   - ✅ Todos los archivos necesarios presentes
+   - ✅ Sintaxis Python correcta
+   - ✅ Requirements.txt válido
+
+2. **Build completo con act**
+   ```bash
+   act -j build-deb
+   ```
+   - ✅ Instalación de dependencias (49s)
+   - ✅ Creación de estructura Debian (~400ms)
+   - ✅ Build del paquete .deb (~2.5s)
+   - ✅ Verificación con lintian (4.8s)
+   - ⚠️  Upload artifacts (falla en act, normal - funcionará en GitHub)
+
+### 📦 Paquete Generado:
+
+- **Nombre:** `squidstats_2.1-1_all.deb`
+- **Versión:** 2.1-1 (auto-detectada del tag/input)
+- **Arquitectura:** all (paquete independiente de arquitectura)
+- **Tamaño:** ~500KB (estimado)
+
+### ⚠️ Advertencias de Lintian (No críticas):
+
+1. **privacy-breach-generic**: Templates usan CDNs externos (Bootstrap, Tailwind, etc.)
+   - **Impacto:** Bajo - normal en aplicaciones web
+   - **Solución futura:** Empaquetar recursos estáticos localmente
+
+2. **recursive-privilege-change**: `chown -R` en postinst
+   - **Impacto:** Bajo - solo relevante en kernels antiguos
+   - **Estado:** Aceptable para PPAs
+
+3. **maintainer-script-needs-depends-on-adduser**
+   - **Estado:** ✅ CORREGIDO - adduser agregado a dependencias
+
+---
+
+## 🎯 Próximos Pasos
+
+### Opción A: Probar en rama de testing (RECOMENDADO)
+
+```bash
+# 1. Crear rama de prueba
+git checkout -b test/ppa-workflow
+
+# 2. Commit de los archivos
+git add .github/
+git commit -m "feat: add GitHub Actions workflow for PPA packaging"
+
+# 3. Subir a GitHub
+git push origin test/ppa-workflow
+
+# 4. Crear tag de prueba
+git tag v0.0.1-test
+git push origin v0.0.1-test
+
+# 5. Ir a GitHub Actions y verificar
+# https://github.com/kaelthasmanu/SquidStats/actions
+
+# 6. Si funciona, merge a main
+git checkout main
+git merge test/ppa-workflow
+git push origin main
+```
+
+### Opción B: Ir directo a producción
+
+⚠️ **Solo si ya configuraste los secretos de GPG y PPA**
+
+```bash
+# 1. Asegurar que estás en main actualizado
+git checkout main
+git pull
+
+# 2. Commit de los cambios
+git add .github/
+git commit -m "feat: add GitHub Actions workflow for PPA packaging"
+git push origin main
+
+# 3. Crear release tag
+git tag -a v1.0.0 -m "Release version 1.0.0"
+git push origin v1.0.0
+
+# 4. El workflow se ejecutará automáticamente
+```
+
+---
+
+## 📋 Checklist Pre-Producción
+
+### Configuración Local ✅
+- [x] Workflow creado
+- [x] Testing con act exitoso
+- [x] Validación de estructura pasada
+- [x] Build .deb funciona
+
+### Antes de Subir a Producción
+- [ ] Clave GPG creada (`gpg --full-generate-key`)
+- [ ] Clave GPG exportada (privada y pública)
+- [ ] Cuenta de Launchpad creada
+- [ ] PPA creado en Launchpad
+- [ ] Clave GPG registrada en Launchpad
+- [ ] Clave GPG subida a keyserver Ubuntu
+- [ ] Secretos configurados en GitHub:
+  - [ ] `GPG_PRIVATE_KEY`
+  - [ ] `GPG_PASSPHRASE`
+  - [ ] `GPG_KEY_ID`
+  - [ ] `PPA_NAME`
+- [ ] Actualizar `MAINTAINER_NAME` y `MAINTAINER_EMAIL` en workflow
+
+---
+
+## 🔧 Personalización del Workflow
+
+Edita estas variables en `.github/workflows/create-ppa.yml`:
+
+```yaml
+env:
+  PACKAGE_NAME: squidstats
+  MAINTAINER_NAME: "Tu Nombre Aquí"          # ← CAMBIAR
+  MAINTAINER_EMAIL: "tu-email@example.com"   # ← CAMBIAR
+  DESCRIPTION: "The definitive analysis for your Squid proxy"
+```
+
+---
+
+## 📚 Documentación Disponible
+
+1. **QUICKSTART.md** - Esta guía (inicio rápido)
+2. **PPA_SETUP.md** - Configuración completa de GPG y PPA
+3. **LOCAL_TESTING.md** - Guía detallada de testing local
+4. **validate-structure.sh** - Script de validación
+5. **test-build.sh** - Script de build automatizado
+
+---
+
+## 🆘 Troubleshooting Rápido
+
+### El workflow falla en GitHub Actions
+
+```bash
+# Ver logs
+gh run list
+gh run view --log
+
+# Re-ejecutar workflow fallido
+gh run rerun <run-id>
+```
+
+### Quiero probar de nuevo localmente
+
+```bash
+# Limpiar contenedores de act
+docker ps -a | grep act | awk '{print $1}' | xargs docker rm
+
+# Ejecutar de nuevo
+act -j build-deb
+```
+
+### Necesito ver el .deb generado
+
+```bash
+# Opción 1: Usar el script
+./.github/workflows/test-build.sh
+
+# Opción 2: Manual con act
+act -j build-deb
+docker ps -a  # Encontrar el contenedor
+docker cp <container-id>:/path/to/squidstats_2.1-1_all.deb .
+```
+
+---
+
+## ✨ Resultado Final Esperado
+
+Cuando todo funcione en producción:
+
+### En GitHub:
+- ✅ Workflow ejecuta automáticamente al crear tags `v*.*.*`
+- ✅ Release creado con archivo .deb adjunto
+- ✅ Instrucciones de instalación en el release
+
+### En Launchpad:
+- ✅ Paquete aparece en tu PPA
+- ✅ Estado "Published" después de ~5-10 minutos
+- ✅ Disponible para instalación vía apt
+
+### Para usuarios finales:
+```bash
+sudo add-apt-repository ppa:usuario/squidstats
+sudo apt update
+sudo apt install squidstats
+
+# Configurar
+sudo nano /etc/squidstats/.env
+
+# Iniciar servicio
+sudo systemctl start squidstats
+sudo systemctl status squidstats
+```
+
+---
+
+## 🎉 Conclusión
+
+El workflow está **100% funcional** y listo para usar. Solo falta:
+
+1. Configurar los secretos de GPG/PPA (si vas a producción)
+2. Subir a GitHub
+3. Crear un tag
+4. ¡Disfrutar tu paquete en el PPA!
+
+**Tiempo estimado de setup completo:** 15-30 minutos (incluyendo creación de GPG y PPA)
+
+---
+
+**Creado:** 2025-11-30  
+**Última prueba:** 2025-11-30 ✅  
+**Estado:** READY FOR PRODUCTION 🚀

+ 247 - 0
.github/workflows/setup-secrets.sh

@@ -0,0 +1,247 @@
+#!/bin/bash
+# Script para configurar GPG y obtener los secrets necesarios
+
+set -e
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m'
+
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo -e "${BLUE}  Configuración de Secrets para GitHub Actions PPA${NC}"
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo ""
+
+# Verificar si gh está instalado
+if ! command -v gh &> /dev/null; then
+    echo -e "${YELLOW}⚠️  GitHub CLI (gh) no está instalado${NC}"
+    echo "   Instalar con: brew install gh"
+    echo ""
+    GH_AVAILABLE=false
+else
+    GH_AVAILABLE=true
+fi
+
+# Verificar si gpg está instalado
+if ! command -v gpg &> /dev/null; then
+    echo -e "${RED}❌ GPG no está instalado${NC}"
+    echo "   Instalar con: brew install gnupg"
+    exit 1
+fi
+
+echo -e "${GREEN}═══ PASO 1: Crear o seleccionar clave GPG ═══${NC}"
+echo ""
+
+# Listar claves existentes
+KEYS=$(gpg --list-secret-keys --keyid-format=long 2>/dev/null | grep -E "^sec" || true)
+
+if [ -z "$KEYS" ]; then
+    echo -e "${YELLOW}No se encontraron claves GPG existentes${NC}"
+    echo ""
+    read -p "¿Deseas crear una nueva clave GPG? (s/n): " CREATE_KEY
+    
+    if [[ $CREATE_KEY == "s" || $CREATE_KEY == "S" ]]; then
+        echo ""
+        echo "Creando nueva clave GPG..."
+        echo "Por favor, proporciona la siguiente información:"
+        echo ""
+        read -p "Nombre completo: " FULLNAME
+        read -p "Email (debe coincidir con Launchpad): " EMAIL
+        
+        # Crear clave
+        cat > /tmp/gpg-gen-key << EOF
+%echo Generando clave GPG
+Key-Type: RSA
+Key-Length: 4096
+Subkey-Type: RSA
+Subkey-Length: 4096
+Name-Real: $FULLNAME
+Name-Email: $EMAIL
+Expire-Date: 0
+%commit
+%echo Clave GPG generada
+EOF
+        
+        gpg --batch --gen-key /tmp/gpg-gen-key
+        rm /tmp/gpg-gen-key
+        
+        echo -e "${GREEN}✓ Clave GPG creada exitosamente${NC}"
+    else
+        echo -e "${RED}No se puede continuar sin una clave GPG${NC}"
+        exit 1
+    fi
+fi
+
+echo ""
+echo "Claves GPG disponibles:"
+gpg --list-secret-keys --keyid-format=long
+
+echo ""
+read -p "Ingresa el KEY_ID (formato largo, ej: ABCD1234EFGH5678): " KEY_ID
+
+if [ -z "$KEY_ID" ]; then
+    echo -e "${RED}❌ KEY_ID no puede estar vacío${NC}"
+    exit 1
+fi
+
+# Verificar que la clave existe
+if ! gpg --list-secret-keys "$KEY_ID" &> /dev/null; then
+    echo -e "${RED}❌ La clave $KEY_ID no existe${NC}"
+    exit 1
+fi
+
+echo -e "${GREEN}✓ Clave $KEY_ID verificada${NC}"
+echo ""
+
+# Obtener passphrase
+echo -e "${GREEN}═══ PASO 2: Contraseña de la clave GPG ═══${NC}"
+echo ""
+read -sp "Ingresa la contraseña de tu clave GPG: " GPG_PASSPHRASE
+echo ""
+
+if [ -z "$GPG_PASSPHRASE" ]; then
+    echo -e "${YELLOW}⚠️  Advertencia: La contraseña está vacía${NC}"
+fi
+
+echo -e "${GREEN}✓ Contraseña guardada${NC}"
+echo ""
+
+# Exportar claves
+echo -e "${GREEN}═══ PASO 3: Exportar claves ═══${NC}"
+echo ""
+
+mkdir -p .github/secrets
+chmod 700 .github/secrets
+
+echo "Exportando clave privada..."
+gpg --armor --export-secret-keys "$KEY_ID" > .github/secrets/private-key.asc
+
+echo "Exportando clave pública..."
+gpg --armor --export "$KEY_ID" > .github/secrets/public-key.asc
+
+echo -e "${GREEN}✓ Claves exportadas a .github/secrets/${NC}"
+echo ""
+
+# Información de PPA
+echo -e "${GREEN}═══ PASO 4: Configuración de PPA ═══${NC}"
+echo ""
+echo "Para configurar tu PPA en Launchpad:"
+echo ""
+echo "1. Ve a: https://launchpad.net/"
+echo "2. Crea una cuenta o inicia sesión"
+echo "3. Registra tu clave GPG:"
+echo "   → https://launchpad.net/~tu-usuario/+editpgpkeys"
+echo "   → Pega el contenido de: .github/secrets/public-key.asc"
+echo ""
+echo "4. Sube la clave al keyserver:"
+echo -e "${YELLOW}   gpg --keyserver keyserver.ubuntu.com --send-keys $KEY_ID${NC}"
+echo ""
+echo "5. Crea tu PPA:"
+echo "   → https://launchpad.net/~tu-usuario/+activate-ppa"
+echo ""
+
+read -p "¿Ya configuraste tu PPA? (s/n): " PPA_READY
+
+if [[ $PPA_READY == "s" || $PPA_READY == "S" ]]; then
+    read -p "Ingresa el nombre de tu PPA (ej: ppa:usuario/squidstats): " PPA_NAME
+    
+    if [[ ! $PPA_NAME =~ ^ppa:.+/.+ ]]; then
+        echo -e "${YELLOW}⚠️  Advertencia: El formato debería ser ppa:usuario/nombre${NC}"
+    fi
+else
+    echo -e "${YELLOW}Continúa sin PPA (podrás configurarlo después)${NC}"
+    PPA_NAME="ppa:usuario/squidstats"
+fi
+
+echo ""
+
+# Crear archivo de secrets
+echo -e "${GREEN}═══ PASO 5: Generar archivo de secrets ═══${NC}"
+echo ""
+
+cat > .github/secrets/secrets.env << EOF
+# GitHub Secrets para PPA Workflow
+# Generado: $(date)
+
+GPG_KEY_ID=$KEY_ID
+GPG_PASSPHRASE=$GPG_PASSPHRASE
+PPA_NAME=$PPA_NAME
+
+# Nota: GPG_PRIVATE_KEY está en private-key.asc
+EOF
+
+chmod 600 .github/secrets/secrets.env
+
+echo -e "${GREEN}✓ Archivo de secrets creado: .github/secrets/secrets.env${NC}"
+echo ""
+
+# Mostrar resumen
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo -e "${BLUE}  RESUMEN DE CONFIGURACIÓN${NC}"
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo ""
+echo -e "${GREEN}GPG_KEY_ID:${NC} $KEY_ID"
+echo -e "${GREEN}GPG_PASSPHRASE:${NC} [Guardada en secrets.env]"
+echo -e "${GREEN}PPA_NAME:${NC} $PPA_NAME"
+echo -e "${GREEN}GPG_PRIVATE_KEY:${NC} En .github/secrets/private-key.asc"
+echo -e "${GREEN}GPG_PUBLIC_KEY:${NC} En .github/secrets/public-key.asc"
+echo ""
+
+# Opción de configurar en GitHub
+if [ "$GH_AVAILABLE" = true ]; then
+    echo -e "${GREEN}═══ PASO 6: Configurar en GitHub (Opcional) ═══${NC}"
+    echo ""
+    read -p "¿Deseas configurar los secrets en GitHub ahora? (s/n): " SETUP_GH
+    
+    if [[ $SETUP_GH == "s" || $SETUP_GH == "S" ]]; then
+        echo ""
+        echo "Configurando secrets en GitHub..."
+        
+        gh secret set GPG_KEY_ID -b"$KEY_ID"
+        gh secret set GPG_PASSPHRASE -b"$GPG_PASSPHRASE"
+        gh secret set PPA_NAME -b"$PPA_NAME"
+        gh secret set GPG_PRIVATE_KEY < .github/secrets/private-key.asc
+        
+        echo -e "${GREEN}✓ Secrets configurados en GitHub${NC}"
+    else
+        echo ""
+        echo "Para configurar manualmente en GitHub:"
+        echo "1. Ve a: https://github.com/kaelthasmanu/SquidStats/settings/secrets/actions"
+        echo "2. Crea los siguientes secrets:"
+        echo ""
+        echo "   GPG_KEY_ID:"
+        echo "   → Valor: $KEY_ID"
+        echo ""
+        echo "   GPG_PASSPHRASE:"
+        echo "   → Copiar de: .github/secrets/secrets.env"
+        echo ""
+        echo "   PPA_NAME:"
+        echo "   → Valor: $PPA_NAME"
+        echo ""
+        echo "   GPG_PRIVATE_KEY:"
+        echo "   → Copiar contenido completo de: .github/secrets/private-key.asc"
+    fi
+fi
+
+echo ""
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo -e "${GREEN}✅ Configuración completada!${NC}"
+echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
+echo ""
+echo -e "${YELLOW}IMPORTANTE:${NC}"
+echo "• Los archivos en .github/secrets/ contienen información sensible"
+echo "• NO los subas a Git (ya están en .gitignore)"
+echo "• Guárdalos en un lugar seguro como respaldo"
+echo ""
+echo -e "${GREEN}Próximo paso:${NC}"
+echo "Probar el workflow en GitHub con:"
+echo ""
+echo "  git checkout -b test/ppa-workflow"
+echo "  git add .github/workflows/"
+echo "  git commit -m 'feat: add PPA workflow'"
+echo "  git push origin test/ppa-workflow"
+echo "  git tag v0.0.1-test"
+echo "  git push origin v0.0.1-test"
+echo ""

+ 64 - 0
.github/workflows/test-build.sh

@@ -0,0 +1,64 @@
+#!/bin/bash
+# Script para probar el workflow localmente y extraer el .deb
+
+set -e
+
+echo "🔨 Iniciando build del paquete con act..."
+echo ""
+
+# Limpiar builds anteriores
+rm -f *.deb *.changes *.buildinfo 2>/dev/null || true
+
+# Ejecutar act (ignorar error de upload artifacts que es normal)
+act -j build-deb --artifact-server-path /tmp/artifacts 2>&1 | tee /tmp/act-output.log || true
+
+# Verificar si el build fue exitoso
+if grep -q "Success - Main Build Debian package" /tmp/act-output.log; then
+    echo ""
+    echo "✅ Build completado exitosamente!"
+    echo ""
+    
+    # Buscar el contenedor de act
+    CONTAINER=$(docker ps -a --filter "ancestor=catthehacker/ubuntu:act-22.04" --format "{{.ID}}" | head -1)
+    
+    if [ -n "$CONTAINER" ]; then
+        echo "📦 Copiando archivos .deb del contenedor..."
+        
+        # Copiar archivos
+        docker cp $CONTAINER:/Users/manuel/Desktop/Projects/codeSquidStats/SquidStats/squidstats_2.1-1_all.deb . 2>/dev/null || \
+        docker cp $CONTAINER:/github/workspace/squidstats_2.1-1_all.deb . 2>/dev/null || \
+        echo "⚠️  No se pudo copiar automáticamente. El .deb está dentro del contenedor."
+        
+        if [ -f "squidstats_2.1-1_all.deb" ]; then
+            echo ""
+            echo "🎉 ¡Paquete extraído exitosamente!"
+            echo ""
+            ls -lh squidstats_*.deb
+            echo ""
+            echo "📋 Información del paquete:"
+            dpkg-deb --info squidstats_2.1-1_all.deb
+            echo ""
+            echo "📄 Contenido del paquete:"
+            dpkg-deb --contents squidstats_2.1-1_all.deb | head -30
+        fi
+    else
+        echo "⚠️  Contenedor no encontrado. Verifica manualmente con: docker ps -a"
+    fi
+else
+    echo ""
+    echo "❌ Build falló. Revisa el log en /tmp/act-output.log"
+    echo ""
+    grep -A 5 "Failure" /tmp/act-output.log | tail -10
+    exit 1
+fi
+
+echo ""
+echo "✅ Testing completado!"
+echo ""
+echo "Siguiente paso: Subir a GitHub y probar con un tag real"
+echo "  git checkout -b test/ppa-workflow"
+echo "  git add .github/"
+echo "  git commit -m 'test: add PPA workflow'"
+echo "  git push origin test/ppa-workflow"
+echo "  git tag v0.0.1-test"
+echo "  git push origin v0.0.1-test"

+ 148 - 0
.github/workflows/validate-structure.sh

@@ -0,0 +1,148 @@
+#!/bin/bash
+set -e
+
+echo "=== 🔍 Validando estructura del proyecto para empaquetado ==="
+echo ""
+
+# Colores para output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# Contador de errores
+ERRORS=0
+
+# Verificar archivos necesarios
+echo "📁 Verificando archivos principales..."
+FILES=(
+    "app.py"
+    "config.py"
+    "requirements.txt"
+    "database/__init__.py"
+    "parsers/__init__.py"
+    "routes/__init__.py"
+    "services/__init__.py"
+)
+
+for file in "${FILES[@]}"; do
+    if [ -f "$file" ]; then
+        echo -e "${GREEN}✓${NC} $file"
+    else
+        echo -e "${RED}✗${NC} $file NO ENCONTRADO"
+        ERRORS=$((ERRORS + 1))
+    fi
+done
+
+echo ""
+echo "📦 Verificando directorios..."
+DIRS=(
+    "static"
+    "templates"
+    "utils"
+)
+
+for dir in "${DIRS[@]}"; do
+    if [ -d "$dir" ]; then
+        echo -e "${GREEN}✓${NC} $dir/"
+    else
+        echo -e "${RED}✗${NC} $dir/ NO ENCONTRADO"
+        ERRORS=$((ERRORS + 1))
+    fi
+done
+
+echo ""
+echo "🐍 Validando sintaxis Python..."
+PYTHON_FILES=("app.py" "config.py")
+for file in "${PYTHON_FILES[@]}"; do
+    if python3 -m py_compile "$file" 2>/dev/null; then
+        echo -e "${GREEN}✓${NC} $file - sintaxis correcta"
+    else
+        echo -e "${RED}✗${NC} $file - error de sintaxis"
+        ERRORS=$((ERRORS + 1))
+    fi
+done
+
+echo ""
+echo "📋 Validando requirements.txt..."
+if [ -f "requirements.txt" ]; then
+    DEPS=$(wc -l < requirements.txt)
+    echo -e "${GREEN}✓${NC} $DEPS dependencias encontradas"
+    echo ""
+    echo "Dependencias principales:"
+    grep -E "^(Flask|SQLAlchemy|psutil)" requirements.txt || echo "  (ninguna)"
+else
+    echo -e "${RED}✗${NC} requirements.txt no encontrado"
+    ERRORS=$((ERRORS + 1))
+fi
+
+echo ""
+echo "🔧 Verificando workflow de GitHub Actions..."
+if [ -f ".github/workflows/create-ppa.yml" ]; then
+    echo -e "${GREEN}✓${NC} Workflow encontrado"
+    
+    # Verificar sintaxis YAML si yamllint está instalado
+    if command -v yamllint &> /dev/null; then
+        if yamllint -d relaxed .github/workflows/create-ppa.yml 2>/dev/null; then
+            echo -e "${GREEN}✓${NC} Sintaxis YAML válida"
+        else
+            echo -e "${YELLOW}⚠${NC} Advertencias de sintaxis YAML (revisar manualmente)"
+        fi
+    else
+        echo -e "${YELLOW}⚠${NC} yamllint no instalado (instalar con: pip3 install yamllint)"
+    fi
+else
+    echo -e "${RED}✗${NC} Workflow no encontrado"
+    ERRORS=$((ERRORS + 1))
+fi
+
+echo ""
+echo "📝 Simulando creación de estructura Debian..."
+TEMP_DIR=$(mktemp -d)
+mkdir -p "$TEMP_DIR/debian"
+mkdir -p "$TEMP_DIR/debian/source"
+
+# Simular archivos debian
+cat > "$TEMP_DIR/debian/control" << EOF
+Source: squidstats
+Section: web
+Priority: optional
+Maintainer: Test <test@test.com>
+
+Package: squidstats
+Architecture: all
+Description: Test package
+ Test description
+EOF
+
+cat > "$TEMP_DIR/debian/rules" << 'EOF'
+#!/usr/bin/make -f
+%:
+	dh $@
+EOF
+
+chmod +x "$TEMP_DIR/debian/rules"
+
+if [ -f "$TEMP_DIR/debian/control" ] && [ -x "$TEMP_DIR/debian/rules" ]; then
+    echo -e "${GREEN}✓${NC} Estructura Debian básica creada correctamente"
+else
+    echo -e "${RED}✗${NC} Error creando estructura Debian"
+    ERRORS=$((ERRORS + 1))
+fi
+
+rm -rf "$TEMP_DIR"
+
+echo ""
+echo "================================================"
+if [ $ERRORS -eq 0 ]; then
+    echo -e "${GREEN}✅ Validación completada sin errores${NC}"
+    echo ""
+    echo "Siguiente paso: Probar con act o Docker"
+    echo "  → act -j build-deb --secret-file .github/workflows/.secrets"
+    exit 0
+else
+    echo -e "${RED}❌ Se encontraron $ERRORS errores${NC}"
+    echo ""
+    echo "Por favor, corrige los errores antes de continuar"
+    exit 1
+fi

+ 237 - 0
NOTIFICATIONS_MIGRATION.md

@@ -0,0 +1,237 @@
+# Sistema de Notificaciones - Migración a Base de Datos
+
+## ✅ Implementación Completada
+
+El sistema de notificaciones ha sido migrado exitosamente de almacenamiento en memoria a base de datos.
+
+## 🎯 Características Implementadas
+
+### 1. **Persistencia Automática**
+- La tabla `notifications` se crea automáticamente al iniciar la aplicación
+- Integrada en la función `migrate_database()` existente
+- No requiere scripts de migración manual
+
+### 2. **Deduplicación Inteligente**
+```python
+# Ejemplo: Esta notificación no se duplicará si ocurre dentro de 1 hora
+add_notification(
+    notification_type='warning',
+    message='Espacio en disco bajo: 2.5GB libres',
+    source='system',
+    deduplicate_hours=1  # Ventana de deduplicación
+)
+```
+
+**Funcionamiento:**
+- Se genera un hash SHA256 del mensaje + tipo + fuente
+- Si existe una notificación idéntica en la ventana de tiempo:
+  - ✅ NO se crea una nueva entrada
+  - ✅ Se incrementa el contador `count`
+  - ✅ Se actualiza `updated_at`
+  - ✅ Se marca como no leída nuevamente
+
+**Pruebas realizadas:**
+```
+1. Agregando la misma notificación 3 veces...
+   1. Notificación procesada - count: 1, id: 16
+   2. Notificación procesada - count: 2, id: 16  ← Mismo ID
+   3. Notificación procesada - count: 3, id: 16  ← Mismo ID
+
+2. Verificación:
+   ✓ Total de registros en BD: 1
+   ✓ Contador de repeticiones: 3
+```
+
+### 3. **Limpieza Automática**
+- Se mantienen solo las 100 notificaciones más recientes
+- Limpieza automática al crear nuevas notificaciones
+- Previene crecimiento infinito de la base de datos
+
+### 4. **Estructura de la Tabla**
+
+```sql
+CREATE TABLE notifications (
+    id INTEGER PRIMARY KEY AUTOINCREMENT,
+    type VARCHAR(50) NOT NULL,         -- 'info', 'warning', 'error', 'success'
+    message TEXT NOT NULL,
+    message_hash VARCHAR(64) NOT NULL, -- SHA256 para deduplicación
+    icon VARCHAR(100),
+    source VARCHAR(50) NOT NULL,       -- 'squid', 'system', 'security', etc.
+    read INTEGER DEFAULT 0,            -- 0=no leída, 1=leída
+    created_at DATETIME NOT NULL,
+    updated_at DATETIME,
+    expires_at DATETIME,
+    count INTEGER DEFAULT 1            -- Contador de repeticiones
+);
+
+-- Índices para optimización
+CREATE INDEX idx_message_hash ON notifications(message_hash);
+CREATE INDEX idx_source ON notifications(source);
+CREATE INDEX idx_created_at ON notifications(created_at);
+```
+
+### 5. **API Actualizada**
+
+#### Obtener Notificaciones (con paginación)
+```bash
+GET /api/notifications?page=1&per_page=20
+```
+
+Respuesta:
+```json
+{
+  "unread_count": 15,
+  "notifications": [...],
+  "pagination": {
+    "current_page": 1,
+    "per_page": 20,
+    "total_pages": 3,
+    "total_notifications": 50,
+    "has_prev": false,
+    "has_next": true
+  }
+}
+```
+
+#### Marcar como Leídas
+```bash
+POST /api/notifications/mark-read
+Content-Type: application/json
+
+{
+  "notification_ids": [1, 2, 3]
+}
+```
+
+#### Eliminar Notificación Individual
+```bash
+DELETE /api/notifications/16
+```
+
+#### Eliminar Todas las Notificaciones
+```bash
+DELETE /api/notifications/delete-all
+```
+
+## 📊 Resultados de las Pruebas
+
+### Test de Deduplicación
+```
+✓ Deduplicación funcionando correctamente
+✓ 3 intentos de crear la misma notificación
+✓ Solo 1 registro creado en BD
+✓ Contador incrementado correctamente (count: 3)
+```
+
+### Test de Paginación
+```
+✓ Total de notificaciones: 15
+✓ Total de páginas: 3 (5 por página)
+✓ Notificaciones no leídas: 15
+✓ Consultas optimizadas con índices
+```
+
+### Test de Persistencia
+```
+✓ Notificaciones sobreviven reinicios del servidor
+✓ Datos consistentes entre sesiones
+✓ Contadores preservados correctamente
+```
+
+## 🚀 Ventajas del Nuevo Sistema
+
+### Antes (En Memoria)
+- ❌ Se perdían al reiniciar el servidor
+- ❌ Notificaciones duplicadas constantes
+- ❌ No había límite de almacenamiento
+- ❌ Sin historial persistente
+
+### Ahora (Base de Datos)
+- ✅ Persistencia completa
+- ✅ Deduplicación inteligente
+- ✅ Limpieza automática
+- ✅ Historial completo disponible
+- ✅ Contador de repeticiones
+- ✅ Optimización con índices
+- ✅ Paginación eficiente
+- ✅ Compatible con SQLite, MySQL, PostgreSQL
+
+## 🔧 Configuración de Deduplicación
+
+```python
+# Diferentes ventanas de tiempo según el caso
+
+# 30 minutos para eventos frecuentes
+add_notification(
+    message="Log procesado",
+    deduplicate_hours=0.5
+)
+
+# 1 hora (por defecto)
+add_notification(
+    message="Usuario conectado",
+    deduplicate_hours=1
+)
+
+# 24 horas para eventos diarios
+add_notification(
+    message="Backup completado",
+    deduplicate_hours=24
+)
+
+# Sin deduplicación
+add_notification(
+    message="Evento único",
+    deduplicate_hours=0
+)
+```
+
+## 📝 Mensajes en Español
+
+Todos los mensajes visibles al usuario están en español:
+- "El servicio Squid no está ejecutándose"
+- "Espacio en disco crítico: 0.8GB libres"
+- "Actividad sospechosa desde IP 192.168.1.100: 250 solicitudes/hora"
+- "El usuario juan consumió 1500MB en 24h"
+- etc.
+
+## 🔄 Compatibilidad
+
+✅ Mantiene compatibilidad con código existente
+✅ Funciones antiguas siguen funcionando
+✅ Socket.IO sigue emitiendo eventos en tiempo real
+✅ Migración transparente y automática
+✅ No requiere cambios en el frontend
+
+## 📋 Archivos Modificados
+
+1. **database/database.py**
+   - Añadido modelo `Notification`
+   - Integrado en `create_dynamic_tables()`
+
+2. **services/notifications.py**
+   - Reescrito para usar base de datos
+   - Añadida lógica de deduplicación
+   - Añadida limpieza automática
+   - Funciones devuelven diccionarios en lugar de objetos
+
+3. **routes/api_routes.py**
+   - Añadido endpoint DELETE para notificación individual
+   - Añadido endpoint DELETE para todas las notificaciones
+   - Actualizado soporte de paginación
+
+4. **migrations/create_notifications_table.py**
+   - Script opcional (tabla se crea automáticamente)
+
+5. **test_notifications.py**
+   - Script de pruebas completo
+   - Valida deduplicación y paginación
+
+## ✨ Próximas Mejoras Posibles
+
+- [ ] Filtros avanzados por tipo, fuente y rango de fechas
+- [ ] Exportación de notificaciones a CSV/JSON
+- [ ] Notificaciones programadas
+- [ ] Webhooks para notificaciones críticas
+- [ ] Dashboard de estadísticas
+- [ ] Configuración de retención personalizada por fuente

BIN
assets/.DS_Store


+ 185 - 0
change_password.py

@@ -0,0 +1,185 @@
+#!/usr/bin/env python3
+"""
+Script to change admin user password from the command line.
+Usage: python3 change_password.py [username]
+If username is not provided, it defaults to 'admin'.
+"""
+
+import os
+import sys
+from getpass import getpass
+
+# Add parent directory to path
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import bcrypt
+
+from database.database import AdminUser, get_session
+
+
+def hash_password(password: str) -> tuple[str, str]:
+    """Hash a password with bcrypt and return (hash, salt)."""
+    salt = bcrypt.gensalt()
+    password_hash = bcrypt.hashpw(password.encode("utf-8"), salt)
+    return password_hash.decode("utf-8"), salt.decode("utf-8")
+
+
+def change_password(username: str, new_password: str) -> bool:
+    """
+    Change the password for a given username.
+
+    Args:
+        username: The username to update
+        new_password: The new password to set
+
+    Returns:
+        True if successful, False otherwise
+    """
+    session = get_session()
+    try:
+        # Find user by username
+        user = session.query(AdminUser).filter_by(username=username).first()
+
+        if not user:
+            print(f"❌ Usuario '{username}' no encontrado en la base de datos")
+            print("\nUsuarios disponibles:")
+            all_users = session.query(AdminUser).all()
+            for u in all_users:
+                status = "✓ activo" if u.is_active else "✗ inactivo"
+                print(f"  - {u.username} ({status})")
+            return False
+
+        # Generate new hash
+        password_hash, salt = hash_password(new_password)
+
+        # Update in database
+        user.password_hash = password_hash
+        user.salt = salt
+        user.is_active = 1  # Activate user if it was inactive
+
+        session.commit()
+        print(f"✅ Contraseña actualizada exitosamente para '{username}'")
+        print(f"   Estado: {'Activo' if user.is_active else 'Inactivo'}")
+        print(f"   Rol: {user.role}")
+        return True
+
+    except Exception as e:
+        session.rollback()
+        print(f"❌ Error al cambiar contraseña: {e}")
+        return False
+    finally:
+        session.close()
+
+
+def list_users():
+    """List all admin users in the database."""
+    session = get_session()
+    try:
+        users = session.query(AdminUser).all()
+
+        if not users:
+            print("No hay usuarios en la base de datos")
+            return
+
+        print("\n" + "=" * 60)
+        print("USUARIOS ADMINISTRADORES")
+        print("=" * 60)
+
+        for user in users:
+            status = "✓ ACTIVO" if user.is_active else "✗ INACTIVO"
+            last_login = (
+                user.last_login.strftime("%Y-%m-%d %H:%M:%S")
+                if user.last_login
+                else "Nunca"
+            )
+
+            print(f"\nUsuario: {user.username}")
+            print(f"  ID: {user.id}")
+            print(f"  Rol: {user.role}")
+            print(f"  Estado: {status}")
+            print(f"  Último login: {last_login}")
+            print(f"  Creado: {user.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
+
+        print("\n" + "=" * 60)
+
+    except Exception as e:
+        print(f"❌ Error al listar usuarios: {e}")
+    finally:
+        session.close()
+
+
+def main():
+    """Main function to handle command line arguments."""
+    print("\n" + "=" * 60)
+    print("CAMBIAR CONTRASEÑA DE ADMINISTRADOR - SquidStats")
+    print("=" * 60 + "\n")
+
+    # Check for help flag
+    if len(sys.argv) > 1 and sys.argv[1] in ["-h", "--help", "help"]:
+        print("Uso:")
+        print("  python3 change_password.py [username]")
+        print("  python3 change_password.py --list")
+        print("\nOpciones:")
+        print("  username    Nombre del usuario (default: admin)")
+        print("  --list, -l  Listar todos los usuarios")
+        print("  --help, -h  Mostrar esta ayuda")
+        print("\nEjemplos:")
+        print("  python3 change_password.py")
+        print("  python3 change_password.py admin")
+        print("  python3 change_password.py miusuario")
+        print("  python3 change_password.py --list")
+        return
+
+    # Check for list flag
+    if len(sys.argv) > 1 and sys.argv[1] in ["-l", "--list", "list"]:
+        list_users()
+        return
+
+    # Get username from arguments or use default
+    if len(sys.argv) > 1:
+        username = sys.argv[1].strip()
+    else:
+        username = input("Nombre de usuario (default: admin): ").strip() or "admin"
+
+    # Get new password securely
+    print(f"\nCambiando contraseña para: {username}")
+    try:
+        new_password = getpass("Nueva contraseña: ")
+        if not new_password:
+            print("❌ La contraseña no puede estar vacía")
+            return
+
+        confirm_password = getpass("Confirmar contraseña: ")
+
+        if new_password != confirm_password:
+            print("❌ Las contraseñas no coinciden")
+            return
+
+        if len(new_password) < 6:
+            print(
+                "⚠️  Advertencia: La contraseña es muy corta (mínimo recomendado: 8 caracteres)"
+            )
+            confirm = input("¿Continuar de todos modos? (s/N): ").strip().lower()
+            if confirm != "s":
+                print("Operación cancelada")
+                return
+
+    except KeyboardInterrupt:
+        print("\n\nOperación cancelada por el usuario")
+        return
+
+    # Change password
+    success = change_password(username, new_password)
+
+    if success:
+        print("\n✅ ¡Contraseña cambiada exitosamente!")
+        print("   Ahora puedes iniciar sesión con:")
+        print(f"   Usuario: {username}")
+        print("   Contraseña: [la que acabas de establecer]")
+    else:
+        print("\n❌ No se pudo cambiar la contraseña")
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()

+ 107 - 0
migrations/create_admin_users_table.py

@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""
+Migration script to create the admin_users table and default admin user.
+This creates the authentication system for admin users.
+"""
+
+import os
+import sys
+
+# Add parent directory to path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import bcrypt
+from sqlalchemy import inspect
+
+from database.database import AdminUser, get_engine, get_session
+
+
+def hash_password(password: str) -> tuple[str, str]:
+    """Hash a password with bcrypt and return (hash, salt)."""
+    # Generate salt and hash
+    salt = bcrypt.gensalt()
+    password_hash = bcrypt.hashpw(password.encode("utf-8"), salt)
+    return password_hash.decode("utf-8"), salt.decode("utf-8")
+
+
+def main():
+    """Create admin_users table and default admin user."""
+    print("=" * 60)
+    print("ADMIN USERS TABLE MIGRATION")
+    print("=" * 60)
+
+    engine = get_engine()
+    session = get_session()
+
+    try:
+        inspector = inspect(engine)
+
+        # Check if table already exists
+        if "admin_users" in inspector.get_table_names():
+            print("✓ Admin users table already exists")
+
+            # Check if default admin user exists
+            existing_admin = (
+                session.query(AdminUser).filter_by(username="admin").first()
+            )
+            if existing_admin:
+                print("✓ Default admin user already exists")
+                return
+            else:
+                print("Creating default admin user...")
+        else:
+            print("Creating admin_users table...")
+            # Create the table
+            AdminUser.__table__.create(engine, checkfirst=True)
+            print("✓ Admin users table created successfully")
+
+        # Create default admin user with FIRST_PASSWORD
+        first_password = os.getenv("FIRST_PASSWORD", "").strip()
+
+        if not first_password:
+            print("✗ FIRST_PASSWORD not set in .env file")
+            print(
+                "  Please set FIRST_PASSWORD in your .env file and run migration again."
+            )
+            print('  Example: FIRST_PASSWORD="your_secure_password"')
+            return
+
+        # Hash the password
+        password_hash, salt = hash_password(first_password)
+
+        admin_user = AdminUser(
+            username="admin",
+            password_hash=password_hash,
+            salt=salt,
+            role="admin",
+            is_active=1,
+        )
+
+        session.add(admin_user)
+        session.commit()
+
+        print("✓ Default admin user created successfully")
+        print("  Username: admin")
+        print("  Password: Set from FIRST_PASSWORD")
+        print("  Use change_password.py to update the password after first login")
+        print("\nTable structure:")
+        print("  - id: Primary key (auto-increment)")
+        print("  - username: Unique username (indexed)")
+        print("  - password_hash: bcrypt hashed password")
+        print("  - salt: Salt used for password hashing")
+        print("  - role: User role (default: admin)")
+        print("  - is_active: Account status (1 = active, 0 = inactive)")
+        print("  - last_login: Last login timestamp")
+        print("  - created_at: Account creation timestamp")
+        print("  - updated_at: Last update timestamp")
+
+    except Exception as e:
+        session.rollback()
+        print(f"✗ Error during migration: {e}")
+        raise
+    finally:
+        session.close()
+
+
+if __name__ == "__main__":
+    main()

+ 66 - 0
migrations/create_notifications_table.py

@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""
+Migration script to create the notifications table MANUALLY
+This is OPTIONAL - the table is automatically created when the app starts.
+Only run this if you want to create the table before starting the app.
+"""
+
+import os
+import sys
+
+# Add parent directory to path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from sqlalchemy import inspect
+
+from database.database import Notification, get_engine
+
+
+def main():
+    """Create notifications table if it doesn't exist"""
+    print("=" * 60)
+    print("NOTIFICATIONS TABLE MIGRATION (OPTIONAL)")
+    print("=" * 60)
+    print("\nNOTE: This table is automatically created when the app starts.")
+    print("You only need to run this if you want to create it manually.\n")
+
+    engine = get_engine()
+    inspector = inspect(engine)
+
+    # Check if table already exists
+    if "notifications" in inspector.get_table_names():
+        print("✓ Notifications table already exists")
+        print("\nTable structure:")
+        columns = inspector.get_columns("notifications")
+        for col in columns:
+            nullable = "NULL" if col["nullable"] else "NOT NULL"
+            print(f"  - {col['name']}: {col['type']} {nullable}")
+        return
+
+    print("Creating notifications table...")
+
+    # Create only the Notification table
+    Notification.__table__.create(engine, checkfirst=True)
+
+    print("✓ Notifications table created successfully")
+    print("\nTable structure:")
+    print("  - id: Primary key (auto-increment)")
+    print("  - type: Notification type (info, warning, error, success)")
+    print("  - message: Notification message text")
+    print("  - message_hash: SHA256 hash for deduplication")
+    print("  - icon: FontAwesome icon class")
+    print("  - source: Source of notification (squid, system, security, users, git)")
+    print("  - read: Read status (0=unread, 1=read)")
+    print("  - created_at: Creation timestamp")
+    print("  - updated_at: Last update timestamp")
+    print("  - expires_at: Optional expiration date")
+    print("  - count: Number of times notification was triggered")
+    print("\nIndexes created on: message_hash, source, created_at")
+
+
+if __name__ == "__main__":
+    try:
+        main()
+    except Exception as e:
+        print(f"✗ Error creating notifications table: {e}")
+        sys.exit(1)

BIN
static/.DS_Store


+ 105 - 0
test_notifications.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+Script de prueba para el sistema de notificaciones con deduplicación
+"""
+
+from database.database import Notification, get_session
+from services.notifications import add_notification, get_all_notifications
+
+
+def test_deduplication():
+    print("=" * 60)
+    print("TEST DE DEDUPLICACIÓN DE NOTIFICACIONES")
+    print("=" * 60)
+
+    # Limpiar notificaciones de prueba anteriores
+    db = get_session()
+    db.query(Notification).filter(
+        Notification.message.like("Prueba de deduplicación%")
+    ).delete()
+    db.commit()
+    db.close()
+
+    print("\n1. Agregando la misma notificación 3 veces...")
+
+    # Agregar la misma notificación 3 veces
+    results = []
+    for i in range(3):
+        result = add_notification(
+            notification_type="info",
+            message="Prueba de deduplicación de notificaciones",
+            source="system",
+            deduplicate_hours=1,
+        )
+        if result:
+            results.append(result)
+            print(
+                f"   {i + 1}. Notificación procesada - count: {result['count']}, id: {result['id']}"
+            )
+
+    # Verificar que solo hay 1 notificación con count=3
+    db = get_session()
+    notifications = (
+        db.query(Notification)
+        .filter(Notification.message.like("Prueba de deduplicación%"))
+        .all()
+    )
+
+    print("\n2. Verificación:")
+    print(f"   Total de registros en BD: {len(notifications)}")
+
+    if len(notifications) == 1:
+        notif = notifications[0]
+        print("   ✓ Deduplicación funcionando correctamente")
+        print(f"   ✓ ID: {notif.id}")
+        print(f"   ✓ Contador de repeticiones: {notif.count}")
+        print(f"   ✓ Mensaje: {notif.message}")
+        print(f"   ✓ Hash: {notif.message_hash[:16]}...")
+    else:
+        print(
+            f"   ✗ Error: se crearon {len(notifications)} notificaciones en lugar de 1"
+        )
+
+    db.close()
+
+    # Limpiar
+    db = get_session()
+    db.query(Notification).filter(
+        Notification.message.like("Prueba de deduplicación%")
+    ).delete()
+    db.commit()
+    db.close()
+
+    print("\n3. ✓ Notificaciones de prueba eliminadas")
+    print("=" * 60)
+
+
+def test_pagination():
+    print("\n" + "=" * 60)
+    print("TEST DE PAGINACIÓN")
+    print("=" * 60)
+
+    # Obtener notificaciones con paginación
+    result = get_all_notifications(page=1, per_page=5)
+
+    print("\n1. Página 1 (5 por página):")
+    print(f"   Total de notificaciones: {result['pagination']['total_notifications']}")
+    print(f"   Total de páginas: {result['pagination']['total_pages']}")
+    print(f"   Notificaciones no leídas: {result['unread_count']}")
+    print(f"   Notificaciones en esta página: {len(result['notifications'])}")
+
+    if result["notifications"]:
+        print("\n2. Primeras notificaciones:")
+        for i, notif in enumerate(result["notifications"][:3], 1):
+            print(f"   {i}. [{notif['type']}] {notif['message'][:50]}...")
+            print(
+                f"      Fuente: {notif['source']}, Count: {notif['count']}, Leída: {notif['read']}"
+            )
+
+    print("=" * 60)
+
+
+if __name__ == "__main__":
+    test_deduplication()
+    test_pagination()
+    print("\n✓ Todas las pruebas completadas\n")

+ 457 - 0
tests/test_notifications_db.py

@@ -0,0 +1,457 @@
+#!/usr/bin/env python3
+"""
+Pruebas unitarias para el sistema de notificaciones
+"""
+
+import os
+import sys
+import unittest
+from datetime import datetime, timedelta
+from unittest.mock import patch
+
+# Add parent directory to path
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
+
+from database.database import Notification, get_session
+from services.notifications import (
+    _check_duplicate_notification,
+    _generate_message_hash,
+    _get_unread_count,
+    add_notification,
+    delete_all_notifications,
+    delete_notification,
+    get_all_notifications,
+    mark_notifications_read,
+)
+
+
+class TestNotificationsDatabase(unittest.TestCase):
+    """Pruebas para el sistema de notificaciones en la base de datos"""
+
+    @classmethod
+    def setUpClass(cls):
+        """Configuración inicial para todas las pruebas"""
+        # Asegurar que usamos una base de datos de prueba
+        os.environ["DATABASE_STRING_CONNECTION"] = "test_notifications.db"
+
+    def setUp(self):
+        """Configuración antes de cada prueba"""
+        # Limpiar todas las notificaciones antes de cada prueba
+        delete_all_notifications()
+
+    def tearDown(self):
+        """Limpieza después de cada prueba"""
+        # Limpiar todas las notificaciones después de cada prueba
+        delete_all_notifications()
+
+    @classmethod
+    def tearDownClass(cls):
+        """Limpieza final después de todas las pruebas"""
+        # Eliminar el archivo de base de datos de prueba si existe
+        db_file = "test_notifications.db"
+        if os.path.exists(db_file):
+            os.remove(db_file)
+
+    def test_generate_message_hash(self):
+        """Prueba la generación de hash para mensajes"""
+        message = "Test notification"
+        source = "test"
+        notification_type = "info"
+
+        hash1 = _generate_message_hash(message, source, notification_type)
+        hash2 = _generate_message_hash(message, source, notification_type)
+
+        # Los hashes deben ser idénticos para el mismo contenido
+        self.assertEqual(hash1, hash2)
+        self.assertEqual(len(hash1), 64)  # SHA256 produce 64 caracteres hex
+
+        # Hash diferente para mensaje diferente
+        hash3 = _generate_message_hash("Different message", source, notification_type)
+        self.assertNotEqual(hash1, hash3)
+
+    def test_add_notification(self):
+        """Prueba agregar una notificación simple"""
+        result = add_notification(
+            notification_type="info",
+            message="Test notification",
+            icon="fa-test",
+            source="test",
+        )
+
+        self.assertIsNotNone(result)
+        self.assertEqual(result["type"], "info")
+        self.assertEqual(result["message"], "Test notification")
+        self.assertEqual(result["icon"], "fa-test")
+        self.assertEqual(result["source"], "test")
+        self.assertEqual(result["count"], 1)
+        self.assertFalse(result["read"])
+
+    def test_add_notification_deduplication(self):
+        """Prueba la deduplicación de notificaciones"""
+        # Agregar la misma notificación 3 veces
+        result1 = add_notification(
+            notification_type="warning",
+            message="Duplicate test",
+            source="test",
+            deduplicate_hours=1,
+        )
+
+        result2 = add_notification(
+            notification_type="warning",
+            message="Duplicate test",
+            source="test",
+            deduplicate_hours=1,
+        )
+
+        result3 = add_notification(
+            notification_type="warning",
+            message="Duplicate test",
+            source="test",
+            deduplicate_hours=1,
+        )
+
+        # Debe haber solo 1 registro en la BD
+        all_notifs = get_all_notifications()
+        self.assertEqual(len(all_notifs["notifications"]), 1)
+
+        # El count debe ser 3
+        self.assertEqual(result3["count"], 3)
+
+        # Los IDs deben ser el mismo
+        self.assertEqual(result1["id"], result2["id"])
+        self.assertEqual(result2["id"], result3["id"])
+
+    def test_add_notification_different_types_no_duplicate(self):
+        """Prueba que notificaciones con diferentes tipos no se deduplican"""
+        result1 = add_notification(
+            notification_type="info",
+            message="Same message",
+            source="test",
+        )
+
+        result2 = add_notification(
+            notification_type="warning",
+            message="Same message",
+            source="test",
+        )
+
+        # Deben ser diferentes IDs
+        self.assertNotEqual(result1["id"], result2["id"])
+
+        # Debe haber 2 registros
+        all_notifs = get_all_notifications()
+        self.assertEqual(len(all_notifs["notifications"]), 2)
+
+    def test_add_notification_different_sources_no_duplicate(self):
+        """Prueba que notificaciones con diferentes fuentes no se deduplican"""
+        result1 = add_notification(
+            notification_type="info",
+            message="Same message",
+            source="system",
+        )
+
+        result2 = add_notification(
+            notification_type="info",
+            message="Same message",
+            source="squid",
+        )
+
+        # Deben ser diferentes IDs
+        self.assertNotEqual(result1["id"], result2["id"])
+
+        # Debe haber 2 registros
+        all_notifs = get_all_notifications()
+        self.assertEqual(len(all_notifs["notifications"]), 2)
+
+    def test_get_all_notifications(self):
+        """Prueba obtener todas las notificaciones"""
+        # Agregar varias notificaciones
+        add_notification("info", "Test 1", source="test")
+        add_notification("warning", "Test 2", source="test")
+        add_notification("error", "Test 3", source="test")
+
+        result = get_all_notifications()
+
+        self.assertEqual(len(result["notifications"]), 3)
+        self.assertEqual(result["unread_count"], 3)
+        self.assertIn("pagination", result)
+
+    def test_get_all_notifications_pagination(self):
+        """Prueba la paginación de notificaciones"""
+        # Agregar 25 notificaciones
+        for i in range(25):
+            add_notification("info", f"Test {i}", source="test")
+
+        # Primera página (20 por página por defecto)
+        page1 = get_all_notifications(page=1, per_page=10)
+        self.assertEqual(len(page1["notifications"]), 10)
+        self.assertEqual(page1["pagination"]["current_page"], 1)
+        self.assertEqual(page1["pagination"]["total_pages"], 3)
+        self.assertTrue(page1["pagination"]["has_next"])
+        self.assertFalse(page1["pagination"]["has_prev"])
+
+        # Segunda página
+        page2 = get_all_notifications(page=2, per_page=10)
+        self.assertEqual(len(page2["notifications"]), 10)
+        self.assertTrue(page2["pagination"]["has_next"])
+        self.assertTrue(page2["pagination"]["has_prev"])
+
+        # Tercera página
+        page3 = get_all_notifications(page=3, per_page=10)
+        self.assertEqual(len(page3["notifications"]), 5)
+        self.assertFalse(page3["pagination"]["has_next"])
+        self.assertTrue(page3["pagination"]["has_prev"])
+
+    def test_mark_notifications_read(self):
+        """Prueba marcar notificaciones como leídas"""
+        # Agregar notificaciones
+        n1 = add_notification("info", "Test 1", source="test")
+        n2 = add_notification("info", "Test 2", source="test")
+
+        # Verificar que todas están sin leer
+        result = get_all_notifications()
+        self.assertEqual(result["unread_count"], 2)
+
+        # Marcar 2 como leídas
+        marked = mark_notifications_read([n1["id"], n2["id"]])
+        self.assertEqual(marked, 2)
+
+        # Verificar contador
+        result = get_all_notifications()
+        self.assertEqual(result["unread_count"], 1)
+
+    def test_delete_notification(self):
+        """Prueba eliminar una notificación específica"""
+        # Agregar notificaciones
+        n1 = add_notification("info", "Test 1", source="test")
+        add_notification("info", "Test 2", source="test")
+
+        # Eliminar una
+        deleted = delete_notification(n1["id"])
+        self.assertTrue(deleted)
+
+        # Verificar que solo queda 1
+        result = get_all_notifications()
+        self.assertEqual(len(result["notifications"]), 1)
+
+        # Intentar eliminar una que no existe
+        deleted = delete_notification(99999)
+        self.assertFalse(deleted)
+
+    def test_delete_all_notifications(self):
+        """Prueba eliminar todas las notificaciones"""
+        # Agregar varias notificaciones
+        add_notification("info", "Test 1", source="test")
+        add_notification("info", "Test 2", source="test")
+        add_notification("info", "Test 3", source="test")
+
+        # Verificar que hay 3
+        result = get_all_notifications()
+        self.assertEqual(len(result["notifications"]), 3)
+
+        # Eliminar todas
+        deleted = delete_all_notifications()
+        self.assertEqual(deleted, 3)
+
+        # Verificar que no hay ninguna
+        result = get_all_notifications()
+        self.assertEqual(len(result["notifications"]), 0)
+
+    def test_check_duplicate_notification(self):
+        """Prueba la función de verificación de duplicados"""
+        db = get_session()
+        try:
+            message = "Test duplicate check"
+            message_hash = _generate_message_hash(message, "test", "info")
+
+            # No debe haber duplicados inicialmente
+            duplicate = _check_duplicate_notification(db, message_hash, hours=1)
+            self.assertIsNone(duplicate)
+
+            # Agregar una notificación
+            notification = Notification(
+                type="info",
+                message=message,
+                message_hash=message_hash,
+                icon="fa-test",
+                source="test",
+                read=0,
+                count=1,
+                created_at=datetime.now(),
+            )
+            db.add(notification)
+            db.commit()
+
+            # Ahora debe encontrar el duplicado
+            duplicate = _check_duplicate_notification(db, message_hash, hours=1)
+            self.assertIsNotNone(duplicate)
+            self.assertEqual(duplicate.message, message)
+
+        finally:
+            db.close()
+
+    def test_check_duplicate_notification_expired(self):
+        """Prueba que no se encuentren duplicados fuera del rango de tiempo"""
+        db = get_session()
+        try:
+            message = "Old notification"
+            message_hash = _generate_message_hash(message, "test", "info")
+
+            # Agregar una notificación antigua (más de 24 horas)
+            old_notification = Notification(
+                type="info",
+                message=message,
+                message_hash=message_hash,
+                icon="fa-test",
+                source="test",
+                read=0,
+                count=1,
+                created_at=datetime.now() - timedelta(hours=25),
+            )
+            db.add(old_notification)
+            db.commit()
+
+            # No debe encontrar duplicados en las últimas 24 horas
+            duplicate = _check_duplicate_notification(db, message_hash, hours=24)
+            self.assertIsNone(duplicate)
+
+            # Pero sí debe encontrarlo en las últimas 48 horas
+            duplicate = _check_duplicate_notification(db, message_hash, hours=48)
+            self.assertIsNotNone(duplicate)
+
+        finally:
+            db.close()
+
+    def test_get_unread_count(self):
+        """Prueba obtener el contador de notificaciones sin leer"""
+        db = get_session()
+        try:
+            # Inicialmente debe ser 0
+            count = _get_unread_count(db)
+            self.assertEqual(count, 0)
+
+            # Agregar notificaciones sin leer
+            for i in range(5):
+                notification = Notification(
+                    type="info",
+                    message=f"Test {i}",
+                    message_hash=_generate_message_hash(f"Test {i}", "test", "info"),
+                    icon="fa-test",
+                    source="test",
+                    read=0,
+                    count=1,
+                    created_at=datetime.now(),
+                )
+                db.add(notification)
+            db.commit()
+
+            # Debe haber 5 sin leer
+            count = _get_unread_count(db)
+            self.assertEqual(count, 5)
+
+            # Marcar 2 como leídas
+            db.query(Notification).filter(
+                Notification.message.in_(["Test 0", "Test 1"])
+            ).update({"read": 1}, synchronize_session=False)
+            db.commit()
+
+            # Debe haber 3 sin leer
+            count = _get_unread_count(db)
+            self.assertEqual(count, 3)
+
+        finally:
+            db.close()
+
+    def test_notification_ordering(self):
+        """Prueba que las notificaciones se ordenen por fecha de creación descendente"""
+        # Agregar notificaciones con pequeños retrasos
+        add_notification("info", "First", source="test")
+        add_notification("info", "Second", source="test")
+        add_notification("info", "Third", source="test")
+
+        result = get_all_notifications()
+        notifications = result["notifications"]
+
+        # La más reciente debe ser "Third"
+        self.assertEqual(notifications[0]["message"], "Third")
+        self.assertEqual(notifications[1]["message"], "Second")
+        self.assertEqual(notifications[2]["message"], "First")
+
+    def test_notification_sources(self):
+        """Prueba diferentes fuentes de notificaciones"""
+        sources = ["system", "squid", "security", "users", "git"]
+
+        for source in sources:
+            add_notification("info", f"Test from {source}", source=source)
+
+        result = get_all_notifications()
+        self.assertEqual(len(result["notifications"]), len(sources))
+
+        # Verificar que todas las fuentes están presentes
+        notification_sources = [n["source"] for n in result["notifications"]]
+        for source in sources:
+            self.assertIn(source, notification_sources)
+
+    def test_notification_types(self):
+        """Prueba diferentes tipos de notificaciones"""
+        types = ["info", "warning", "error", "success"]
+
+        for ntype in types:
+            add_notification(ntype, f"Test {ntype}", source="test")
+
+        result = get_all_notifications()
+        self.assertEqual(len(result["notifications"]), len(types))
+
+        # Verificar que todos los tipos están presentes
+        notification_types = [n["type"] for n in result["notifications"]]
+        for ntype in types:
+            self.assertIn(ntype, notification_types)
+
+    @patch("services.notifications.socketio")
+    def test_socketio_emission_new_notification(self, mock_socketio):
+        """Prueba que se emita evento de Socket.IO para nueva notificación"""
+        add_notification("info", "Test socketio", source="test")
+
+        # Debe haber emitido el evento
+        mock_socketio.emit.assert_called_once()
+        args = mock_socketio.emit.call_args
+
+        self.assertEqual(args[0][0], "new_notification")
+        self.assertIn("notification", args[0][1])
+        self.assertIn("unread_count", args[0][1])
+
+    @patch("services.notifications.socketio")
+    def test_socketio_emission_updated_notification(self, mock_socketio):
+        """Prueba que se emita evento de Socket.IO para notificación actualizada"""
+        # Primera notificación
+        add_notification("info", "Test update", source="test")
+        mock_socketio.reset_mock()
+
+        # Duplicado (debe actualizar)
+        add_notification("info", "Test update", source="test")
+
+        # Debe haber emitido evento de actualización
+        mock_socketio.emit.assert_called_once()
+        args = mock_socketio.emit.call_args
+
+        self.assertEqual(args[0][0], "notification_updated")
+        self.assertIn("notification", args[0][1])
+        self.assertIn("unread_count", args[0][1])
+
+
+class TestNotificationHelpers(unittest.TestCase):
+    """Pruebas para funciones auxiliares de notificaciones"""
+
+    def test_default_icon_assignment(self):
+        """Prueba que se asignen iconos por defecto según el tipo"""
+        from services.notifications import get_default_icon
+
+        self.assertEqual(get_default_icon("info"), "fa-info-circle")
+        self.assertEqual(get_default_icon("warning"), "fa-exclamation-triangle")
+        self.assertEqual(get_default_icon("error"), "fa-times-circle")
+        self.assertEqual(get_default_icon("success"), "fa-check-circle")
+        self.assertEqual(get_default_icon("unknown"), "fa-bell")
+
+
+if __name__ == "__main__":
+    unittest.main(verbosity=2)

+ 10 - 0
utils/e2guardian.conf

@@ -0,0 +1,10 @@
+filterports = 8080  
+proxyport = 3128
+filtergroups = 1
+
+
+logfileformat = 8  # Formato Protex con campos extras
+loglevel = 3  # Log completo
+logclienthostnames = on  # Resuelve nombres DNS
+loguseragent = on  # Registra navegadores
+showweightedfound = on  # Muestra frases detectadas