App QR de checada Taboada (Python/Tkinter, PyInstaller)
Contrato identico al verificador de Node: contador = floor(unix_utc/45) codigo = HMAC-SHA256(SEMILLA, 'q1|'+contador)[0..15] base64url sin padding token = q1.<base36(contador)>.<codigo> Vector canonico verificado: q1.md56o.Jo2Q_p4tq_sTY9A9YGj-7A Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
dd8eb0b0f8
8 files changed
+470
No files matched your search
+14
@@ -0,0 +1,14 @@
|
||||
# Secreto: NUNCA subir la semilla
|
||||
semilla.key
|
||||
|
||||
# Entornos y artefactos de build
|
||||
.venv/
|
||||
venv/
|
||||
build/
|
||||
dist/
|
||||
*.spec.bak
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Sistema
|
||||
.DS_Store
|
||||
@@ -0,0 +1,75 @@
|
||||
# Checada Taboada — QR rotativo (app de escritorio)
|
||||
|
||||
App offline que muestra un QR de checada que rota cada **45 s**. El QR codifica:
|
||||
|
||||
```
|
||||
https://taboada.collinasystems.com.mx/checada.html?t=<token>
|
||||
```
|
||||
|
||||
con el **mismo contrato** que el verificador de Node (`SEMILLA_QR`):
|
||||
|
||||
```
|
||||
contador = floor(unix_utc / 45) # UTC, NO hora local
|
||||
codigo = HMAC-SHA256(SEMILLA, "q1|" + contador)[0..15] base64url sin padding
|
||||
token = "q1." + base36(contador) + "." + codigo
|
||||
```
|
||||
|
||||
Vector canónico verificado contra Node ✅:
|
||||
|
||||
```
|
||||
SEMILLA hex = 000102...1e1f contador = 37564800
|
||||
token = q1.md56o.Jo2Q_p4tq_sTY9A9YGj-7A
|
||||
```
|
||||
|
||||
## Archivos
|
||||
|
||||
| Archivo | Qué es |
|
||||
|---|---|
|
||||
| `qr_contract.py` | Lógica del contrato (token, HMAC, base36, semilla). |
|
||||
| `app.py` | UI Tkinter: QR grande + hora UTC/contador + botón semilla. |
|
||||
| `test_contrato.py` | Test del vector canónico. `python test_contrato.py` |
|
||||
| `checada.spec` | Config de PyInstaller (un solo `.exe`, sin consola). |
|
||||
| `build.bat` | Build del `.exe` en Windows (doble clic). |
|
||||
| `requirements.txt` | `qrcode`, `pillow`, `pyinstaller`. |
|
||||
|
||||
## La semilla
|
||||
|
||||
- Se lee de `semilla.key` (32 bytes en **hex**) **junto al `.exe`**.
|
||||
- El botón **«Crear semilla nueva»** genera 32 bytes aleatorios, los guarda en
|
||||
`semilla.key` y muestra el **hex** en pantalla.
|
||||
- **Un solo origen de la verdad:** copia ese hex a la variable `SEMILLA_QR` del
|
||||
servidor. Si cambias la semilla de un lado, cámbiala en el otro o las checadas
|
||||
dejan de validar.
|
||||
|
||||
## Generar el `.exe` (en Windows)
|
||||
|
||||
> ⚠️ **PyInstaller NO compila cruzado.** El `.exe` de Windows hay que generarlo
|
||||
> **en una máquina Windows** (no sale desde Mac/Linux). El código es idéntico en
|
||||
> todos lados; solo el empaquetado depende del sistema.
|
||||
|
||||
En Windows con Python 3.9+ instalado (marca *Add Python to PATH*):
|
||||
|
||||
```bat
|
||||
build.bat
|
||||
```
|
||||
|
||||
Queda en `dist\ChecadaTaboada.exe`. Cópialo a su carpeta; al abrirlo, si no hay
|
||||
`semilla.key`, pulsa «Crear semilla nueva».
|
||||
|
||||
## Correr en desarrollo (cualquier SO)
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
python test_contrato.py # debe salir todo verde
|
||||
python app.py
|
||||
```
|
||||
|
||||
## Nota sobre `dist/ChecadaTaboada`
|
||||
|
||||
El binario que hay en `dist/` es la **compilación de prueba para macOS** (se hizo
|
||||
aquí para verificar que empaqueta y arranca). **No es el `.exe`**: para Windows,
|
||||
ejecuta `build.bat` en Windows.
|
||||
```
|
||||
```
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
App de escritorio (Windows / macOS) que muestra el QR de checada de Taboada.
|
||||
|
||||
- QR grande centrado, rota cada 45 s (mismo contrato que el verificador de Node).
|
||||
- Offline: solo necesita semilla.key junto al ejecutable.
|
||||
- Esquina: hora UTC + contador, para verificar sincronia contra el servidor de un vistazo.
|
||||
- Boton "Crear semilla nueva": genera 32 bytes, los guarda y muestra el hex para pegar
|
||||
en SEMILLA_QR del servidor.
|
||||
"""
|
||||
|
||||
import time
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, scrolledtext
|
||||
|
||||
import qrcode
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
import qr_contract as qc
|
||||
|
||||
INTERVALO_MS = 200 # cada cuanto revisamos el reloj
|
||||
FONDO = "#0f172a" # slate-900
|
||||
FONDO_QR = "#ffffff"
|
||||
TEXTO = "#e2e8f0" # slate-200
|
||||
ACENTO = "#38bdf8" # sky-400
|
||||
|
||||
|
||||
class AppQR(tk.Tk):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.title("Checada Taboada — QR rotativo")
|
||||
self.configure(bg=FONDO)
|
||||
self.geometry("720x820")
|
||||
self.minsize(480, 620)
|
||||
|
||||
self.semilla = None
|
||||
self._contador_dibujado = None
|
||||
self._qr_tk = None
|
||||
self._lado_qr_dibujado = 0
|
||||
|
||||
self._construir_ui()
|
||||
self._cargar_semilla_inicial()
|
||||
|
||||
self.bind("<Configure>", self._on_resize)
|
||||
self._tick()
|
||||
|
||||
# ------------------------------------------------------------------ UI
|
||||
def _construir_ui(self):
|
||||
# Zona del QR (centro, se expande)
|
||||
self.marco_qr = tk.Frame(self, bg=FONDO)
|
||||
self.marco_qr.pack(fill="both", expand=True, padx=24, pady=(24, 8))
|
||||
|
||||
self.lbl_qr = tk.Label(self.marco_qr, bg=FONDO)
|
||||
self.lbl_qr.place(relx=0.5, rely=0.5, anchor="center")
|
||||
|
||||
# Barra inferior: estado UTC/contador + boton
|
||||
barra = tk.Frame(self, bg=FONDO)
|
||||
barra.pack(fill="x", padx=24, pady=(0, 20))
|
||||
|
||||
self.lbl_estado = tk.Label(
|
||||
barra, text="", bg=FONDO, fg=TEXTO,
|
||||
font=("Menlo", 13), justify="left", anchor="w",
|
||||
)
|
||||
self.lbl_estado.pack(side="left")
|
||||
|
||||
self.btn_semilla = tk.Button(
|
||||
barra, text="Crear semilla nueva", command=self._crear_semilla,
|
||||
bg=ACENTO, fg="#082f49", activebackground="#7dd3fc",
|
||||
relief="flat", font=("Helvetica", 12, "bold"),
|
||||
padx=14, pady=8, cursor="hand2",
|
||||
)
|
||||
self.btn_semilla.pack(side="right")
|
||||
|
||||
def _cargar_semilla_inicial(self):
|
||||
try:
|
||||
self.semilla = qc.cargar_semilla()
|
||||
except FileNotFoundError:
|
||||
self.semilla = None
|
||||
self._mostrar_mensaje_qr("No hay semilla.key\n\nPulsa «Crear semilla nueva»\npara generarla.")
|
||||
except Exception as e:
|
||||
self.semilla = None
|
||||
self._mostrar_mensaje_qr("semilla.key invalida:\n%s" % e)
|
||||
|
||||
# -------------------------------------------------------------- reloj
|
||||
def _tick(self):
|
||||
ahora = time.time()
|
||||
contador = qc.contador_actual(ahora)
|
||||
utc = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ahora))
|
||||
restante = qc.PERIODO - int(ahora % qc.PERIODO)
|
||||
|
||||
estado = "UTC %s\nContador %d (rota en %ds)" % (utc, contador, restante)
|
||||
self.lbl_estado.config(text=estado)
|
||||
|
||||
if self.semilla is not None and contador != self._contador_dibujado:
|
||||
self._dibujar_qr(contador)
|
||||
self._contador_dibujado = contador
|
||||
|
||||
self.after(INTERVALO_MS, self._tick)
|
||||
|
||||
# ---------------------------------------------------------------- QR
|
||||
def _lado_disponible(self) -> int:
|
||||
self.marco_qr.update_idletasks()
|
||||
w = self.marco_qr.winfo_width()
|
||||
h = self.marco_qr.winfo_height()
|
||||
return max(160, min(w, h) - 20)
|
||||
|
||||
def _dibujar_qr(self, contador: int):
|
||||
url = qc.calcular_url(self.semilla, contador)
|
||||
lado = self._lado_disponible()
|
||||
|
||||
qr = qrcode.QRCode(
|
||||
error_correction=qrcode.constants.ERROR_CORRECT_M,
|
||||
box_size=10, border=2,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
img = qr.make_image(fill_color="black", back_color="white").convert("RGB")
|
||||
img = img.resize((lado, lado), Image.NEAREST)
|
||||
|
||||
self._qr_tk = ImageTk.PhotoImage(img)
|
||||
self.lbl_qr.config(image=self._qr_tk, text="")
|
||||
self._lado_qr_dibujado = lado
|
||||
|
||||
def _mostrar_mensaje_qr(self, texto: str):
|
||||
self.lbl_qr.config(
|
||||
image="", text=texto, fg=TEXTO, bg=FONDO,
|
||||
font=("Helvetica", 16), justify="center",
|
||||
)
|
||||
self._qr_tk = None
|
||||
|
||||
def _on_resize(self, event):
|
||||
# Redibuja si el tamano cambio de forma apreciable
|
||||
if self.semilla is None or self._contador_dibujado is None:
|
||||
return
|
||||
if abs(self._lado_disponible() - self._lado_qr_dibujado) > 12:
|
||||
self._dibujar_qr(self._contador_dibujado)
|
||||
|
||||
# ------------------------------------------------------------ semilla
|
||||
def _crear_semilla(self):
|
||||
if self.semilla is not None:
|
||||
ok = messagebox.askyesno(
|
||||
"Crear semilla nueva",
|
||||
"Ya existe una semilla.\n\n"
|
||||
"Si creas una nueva, DEBES pegar el hex en SEMILLA_QR del servidor "
|
||||
"o las checadas dejaran de validar.\n\n¿Continuar?",
|
||||
)
|
||||
if not ok:
|
||||
return
|
||||
|
||||
self.semilla = qc.crear_semilla_nueva()
|
||||
self._contador_dibujado = None # fuerza redibujo
|
||||
self._mostrar_hex(self.semilla.hex())
|
||||
|
||||
def _mostrar_hex(self, hexdata: str):
|
||||
top = tk.Toplevel(self)
|
||||
top.title("Semilla nueva — pegar en el servidor")
|
||||
top.configure(bg=FONDO)
|
||||
top.geometry("560x260")
|
||||
top.transient(self)
|
||||
top.grab_set()
|
||||
|
||||
tk.Label(
|
||||
top, bg=FONDO, fg=TEXTO, justify="left", font=("Helvetica", 12),
|
||||
text="Guardada en semilla.key.\nPega este hex en la variable SEMILLA_QR del servidor:",
|
||||
).pack(anchor="w", padx=18, pady=(16, 8))
|
||||
|
||||
caja = scrolledtext.ScrolledText(top, height=4, wrap="char",
|
||||
font=("Menlo", 13), bg="#1e293b", fg=ACENTO)
|
||||
caja.insert("1.0", hexdata)
|
||||
caja.configure(state="normal")
|
||||
caja.pack(fill="x", padx=18)
|
||||
|
||||
def copiar():
|
||||
self.clipboard_clear()
|
||||
self.clipboard_append(hexdata)
|
||||
btn.config(text="¡Copiado!")
|
||||
|
||||
btn = tk.Button(top, text="Copiar al portapapeles", command=copiar,
|
||||
bg=ACENTO, fg="#082f49", relief="flat",
|
||||
font=("Helvetica", 12, "bold"), padx=14, pady=8, cursor="hand2")
|
||||
btn.pack(pady=16)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
AppQR().mainloop()
|
||||
@@ -0,0 +1,14 @@
|
||||
@echo off
|
||||
REM Build del .exe en Windows. Doble clic o ejecutar en cmd.
|
||||
REM Requiere Python 3.9+ instalado (marca "Add Python to PATH" al instalarlo).
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
python -m PyInstaller --clean --noconfirm checada.spec
|
||||
|
||||
echo.
|
||||
echo ==========================================================
|
||||
echo Listo: dist\ChecadaTaboada.exe
|
||||
echo Copia el .exe a su carpeta y crea la semilla desde la app.
|
||||
echo ==========================================================
|
||||
pause
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
# PyInstaller spec. Genera un unico ejecutable, sin consola.
|
||||
# pyinstaller checada.spec
|
||||
# En Windows produce ChecadaTaboada.exe; en macOS un binario Mach-O del mismo nombre.
|
||||
# NOTA: semilla.key NO se empaqueta a proposito; vive junto al .exe y se puede regenerar.
|
||||
|
||||
block_cipher = None
|
||||
|
||||
a = Analysis(
|
||||
['app.py'],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
hiddenimports=['qrcode', 'PIL', 'PIL._tkinter_finder'],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
win_no_prefer_redirects=False,
|
||||
win_private_assemblies=False,
|
||||
cipher=block_cipher,
|
||||
noarchive=False,
|
||||
)
|
||||
|
||||
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
[],
|
||||
name='ChecadaTaboada',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
runtime_tmpdir=None,
|
||||
console=False, # sin ventana de consola
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
Contrato criptografico del QR de checada.
|
||||
|
||||
DEBE ser identico, byte a byte, al verificador de Node (SEMILLA_QR):
|
||||
contador = floor(unix_utc / 45) # UTC, NO hora local
|
||||
codigo = HMAC-SHA256(SEMILLA, "q1|" + contador)[0..15] en base64url sin padding
|
||||
token = "q1." + base36(contador) + "." + codigo
|
||||
url = https://taboada.collinasystems.com.mx/checada.html?t=<token>
|
||||
|
||||
Vector canonico (no tocar, es el que valida contra Node):
|
||||
SEMILLA hex = 000102...1e1f contador = 37564800
|
||||
token = q1.md56o.Jo2Q_p4tq_sTY9A9YGj-7A
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
PERIODO = 45 # segundos por rotacion
|
||||
NAMESPACE = "q1"
|
||||
BASE_URL = "https://taboada.collinasystems.com.mx/checada.html"
|
||||
SEMILLA_ARCHIVO = "semilla.key"
|
||||
|
||||
|
||||
def base36(n: int) -> str:
|
||||
"""Entero >= 0 a base36 (0-9a-z), igual que Number.prototype.toString(36) de JS."""
|
||||
if n < 0:
|
||||
raise ValueError("contador negativo")
|
||||
if n == 0:
|
||||
return "0"
|
||||
digitos = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
s = ""
|
||||
while n > 0:
|
||||
s = digitos[n % 36] + s
|
||||
n //= 36
|
||||
return s
|
||||
|
||||
|
||||
def contador_actual(ahora: float = None) -> int:
|
||||
"""floor(unix_utc / 45). time.time() ya es epoch UTC, sin importar la zona local."""
|
||||
if ahora is None:
|
||||
ahora = time.time()
|
||||
return int(ahora // PERIODO)
|
||||
|
||||
|
||||
def calcular_codigo(semilla: bytes, contador: int) -> str:
|
||||
mensaje = ("%s|%d" % (NAMESPACE, contador)).encode("ascii")
|
||||
digest = hmac.new(semilla, mensaje, hashlib.sha256).digest()
|
||||
return base64.urlsafe_b64encode(digest[:16]).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def calcular_token(semilla: bytes, contador: int) -> str:
|
||||
return "%s.%s.%s" % (NAMESPACE, base36(contador), calcular_codigo(semilla, contador))
|
||||
|
||||
|
||||
def calcular_url(semilla: bytes, contador: int) -> str:
|
||||
return "%s?t=%s" % (BASE_URL, calcular_token(semilla, contador))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Manejo de la semilla (junto al .exe)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def directorio_base() -> str:
|
||||
"""Carpeta donde vive el .exe (o el script en desarrollo)."""
|
||||
if getattr(sys, "frozen", False):
|
||||
return os.path.dirname(sys.executable)
|
||||
return os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def ruta_semilla() -> str:
|
||||
return os.path.join(directorio_base(), SEMILLA_ARCHIVO)
|
||||
|
||||
|
||||
def cargar_semilla() -> bytes:
|
||||
"""Lee semilla.key (32 bytes en hex). Lanza excepcion si no existe o es invalida."""
|
||||
ruta = ruta_semilla()
|
||||
with open(ruta, "r", encoding="ascii") as f:
|
||||
hexdata = f.read().strip()
|
||||
semilla = bytes.fromhex(hexdata)
|
||||
if len(semilla) != 32:
|
||||
raise ValueError("La semilla debe ser de 32 bytes (64 caracteres hex); son %d bytes" % len(semilla))
|
||||
return semilla
|
||||
|
||||
|
||||
def crear_semilla_nueva() -> bytes:
|
||||
"""Genera 32 bytes aleatorios, los guarda en semilla.key y devuelve la semilla."""
|
||||
semilla = os.urandom(32)
|
||||
with open(ruta_semilla(), "w", encoding="ascii") as f:
|
||||
f.write(semilla.hex())
|
||||
return semilla
|
||||
@@ -0,0 +1,3 @@
|
||||
qrcode>=7.4
|
||||
pillow>=9.0
|
||||
pyinstaller>=6.0
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
Test del vector canonico. Debe dar EXACTAMENTE el mismo token que el verificador de Node.
|
||||
Ejecutar: python3 test_contrato.py
|
||||
"""
|
||||
|
||||
import qr_contract as qc
|
||||
|
||||
SEMILLA_HEX = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
|
||||
CONTADOR = 37564800
|
||||
TOKEN_ESPERADO = "q1.md56o.Jo2Q_p4tq_sTY9A9YGj-7A"
|
||||
|
||||
|
||||
def test_vector_canonico():
|
||||
semilla = bytes.fromhex(SEMILLA_HEX)
|
||||
token = qc.calcular_token(semilla, CONTADOR)
|
||||
assert token == TOKEN_ESPERADO, "\n esperado: %s\n obtenido: %s" % (TOKEN_ESPERADO, token)
|
||||
|
||||
|
||||
def test_base36():
|
||||
assert qc.base36(0) == "0"
|
||||
assert qc.base36(37564800) == "md56o"
|
||||
assert qc.base36(35) == "z"
|
||||
assert qc.base36(36) == "10"
|
||||
|
||||
|
||||
def test_contador_utc():
|
||||
# 37564800 * 45 = 1690416000 (epoch UTC exacto al inicio del periodo)
|
||||
assert qc.contador_actual(1690416000) == 37564800
|
||||
assert qc.contador_actual(1690416044) == 37564800 # aun mismo periodo
|
||||
assert qc.contador_actual(1690416045) == 37564801 # siguiente periodo
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for nombre, fn in sorted(globals().items()):
|
||||
if nombre.startswith("test_") and callable(fn):
|
||||
fn()
|
||||
print("OK %s" % nombre)
|
||||
print("\nToken canonico:", qc.calcular_token(bytes.fromhex(SEMILLA_HEX), CONTADOR))
|
||||
print("Todo verde: el .exe dara el codigo identico a Node.")
|
||||
Reference in new issue
Block a user