From a60758875d99955ba5b165b6ddf9a6cb2123e354 Mon Sep 17 00:00:00 2001 From: Ricardo Monla Date: Sun, 4 Oct 2026 16:42:13 -0300 Subject: [PATCH] =?UTF-8?q?feat(nexxa):=20NEXXA=20versionada=20en=20dtic-D?= =?UTF-8?q?IIAA=20(1.3.0):=20pools=20por=20individuo=20mente/red,=20API=20?= =?UTF-8?q?por=20rol=20y=20gesti=C3=B3n=20desde=20nexxa-web?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Base: código de producción de srvv-nexxa (1.2.1), importado y verificado por hash (P335/F3) - Pools por individuo (lib_pools): mente y red, mezclan proveedores, keys compartidas o exclusivas - API: /disponible/mente|red y /estado por rol, pool_vacio explícito, /pools (CRUD admin), liberar admin - Revertir el agotada propio + motivo y quién la agotó (de P334/F4) - nexxa-web: sección Pools, motivo y botón Liberar, provider libre con sugerencias, escape de texto externo - Convención REG002: lib_*, cli_*, tool_humo_pool; contratos externos con su nombre - Suite local sobre copia aislada: humo HTTP, pools, revertir; servidor_prueba para mirar la web Co-Authored-By: Claude Opus 5.5 Co-Authored-By: GEMMA --- servicios/nexxa/.gitignore | 12 + servicios/nexxa/README.md | 36 + servicios/nexxa/germen.md | 151 +++ servicios/nexxa/organismo/VERSION | 1 + servicios/nexxa/organismo/chat.rb | 11 + servicios/nexxa/organismo/cli_admin.rb | 47 + servicios/nexxa/organismo/cli_consumidor.rb | 37 + servicios/nexxa/organismo/cli_registrar.rb | 37 + servicios/nexxa/organismo/latido.rb | 20 + servicios/nexxa/organismo/lib_auth.rb | 202 +++ servicios/nexxa/organismo/lib_checkins.rb | 54 + servicios/nexxa/organismo/lib_cripto.rb | 74 ++ servicios/nexxa/organismo/lib_envelope.rb | 38 + servicios/nexxa/organismo/lib_pools.rb | 132 ++ servicios/nexxa/organismo/lib_registro.rb | 330 +++++ servicios/nexxa/organismo/lib_tokens.rb | 117 ++ servicios/nexxa/organismo/lib_usos.rb | 46 + servicios/nexxa/organismo/nexxa.rb | 15 + servicios/nexxa/organismo/router.rb | 44 + servicios/nexxa/organismo/server.rb | 915 +++++++++++++ servicios/nexxa/organismo/tool_humo_pool.rb | 245 ++++ servicios/nexxa/test/humo_http_test.rb | 96 ++ servicios/nexxa/test/lib_servidor_prueba.rb | 59 + servicios/nexxa/test/pools_test.rb | 106 ++ servicios/nexxa/test/revertir_test.rb | 56 + servicios/nexxa/test/servidor_prueba.rb | 16 + servicios/nexxa/web/css/estilos.css | 1046 +++++++++++++++ servicios/nexxa/web/index.html | 285 +++++ servicios/nexxa/web/js/app.js | 1274 +++++++++++++++++++ servicios/nexxa/web/js/login.js | 43 + servicios/nexxa/web/login.html | 108 ++ 31 files changed, 5653 insertions(+) create mode 100644 servicios/nexxa/.gitignore create mode 100644 servicios/nexxa/README.md create mode 100644 servicios/nexxa/germen.md create mode 100644 servicios/nexxa/organismo/VERSION create mode 100644 servicios/nexxa/organismo/chat.rb create mode 100644 servicios/nexxa/organismo/cli_admin.rb create mode 100644 servicios/nexxa/organismo/cli_consumidor.rb create mode 100644 servicios/nexxa/organismo/cli_registrar.rb create mode 100644 servicios/nexxa/organismo/latido.rb create mode 100644 servicios/nexxa/organismo/lib_auth.rb create mode 100644 servicios/nexxa/organismo/lib_checkins.rb create mode 100644 servicios/nexxa/organismo/lib_cripto.rb create mode 100644 servicios/nexxa/organismo/lib_envelope.rb create mode 100644 servicios/nexxa/organismo/lib_pools.rb create mode 100644 servicios/nexxa/organismo/lib_registro.rb create mode 100644 servicios/nexxa/organismo/lib_tokens.rb create mode 100644 servicios/nexxa/organismo/lib_usos.rb create mode 100644 servicios/nexxa/organismo/nexxa.rb create mode 100644 servicios/nexxa/organismo/router.rb create mode 100644 servicios/nexxa/organismo/server.rb create mode 100644 servicios/nexxa/organismo/tool_humo_pool.rb create mode 100644 servicios/nexxa/test/humo_http_test.rb create mode 100644 servicios/nexxa/test/lib_servidor_prueba.rb create mode 100644 servicios/nexxa/test/pools_test.rb create mode 100644 servicios/nexxa/test/revertir_test.rb create mode 100644 servicios/nexxa/test/servidor_prueba.rb create mode 100644 servicios/nexxa/web/css/estilos.css create mode 100644 servicios/nexxa/web/index.html create mode 100644 servicios/nexxa/web/js/app.js create mode 100644 servicios/nexxa/web/js/login.js create mode 100644 servicios/nexxa/web/login.html diff --git a/servicios/nexxa/.gitignore b/servicios/nexxa/.gitignore new file mode 100644 index 00000000..f318dc9e --- /dev/null +++ b/servicios/nexxa/.gitignore @@ -0,0 +1,12 @@ +# Estado y secretos de NEXXA: viven SOLO en el nodo (srvv-nexxa:/opt/nexxa), nunca en el repo (Regla de Oro 15). +.env +*.conf +organismo/.master_key +organismo/.usuarios.json +organismo/.sessions.json +organismo/registro.json +organismo/tokens.json +organismo/checkins.json +organismo/pools.json +organismo/*.log +*.bak* diff --git a/servicios/nexxa/README.md b/servicios/nexxa/README.md new file mode 100644 index 00000000..2bc26f23 --- /dev/null +++ b/servicios/nexxa/README.md @@ -0,0 +1,36 @@ +# NEXXA — broker de API keys del ecosistema (servicio DIIAA) + +NEXXA administra el pool de API keys (Gemini, DeepSeek, …) que consumen GEMMA y los individuos F1: dispensa una key +por consulta, cifrada de punta a punta para el consumidor, y recibe el reporte de salud de cada key. Se gestiona desde +**nexxa-web** (`web/`, panel con usuarios admin/operador) y se consume por su API HTTP (`organismo/server.rb`, :4568). + +## Origen y versión + +- **Versión vigente:** `organismo/VERSION` (fuente única; nexxa-web la muestra en `/version`). +- **Metamorfosis (2026-10-04, P335):** nació como el individuo `rm-apid06-nexxa` del linaje apids (repo `rm-APIDs`, + P201/P204/P205/P238). Pasa a ser el servicio `srvv-nexxa` del ámbito DIIAA: es la misma NEXXA, evolucionada. +- **Base de este repo:** el código que corría en producción el 2026-10-04 (versión 1.2.1), importado y verificado por + hash contra el nodo (`gemma git importar:verificar`, 23/23 iguales). El repo `rm-APIDs` había quedado atrasado desde + P201 (6 archivos distintos o ausentes). + +## Estructura (convención REG002, P335/Fase 9) + +- `organismo/lib_*.rb`: módulos (registro, pools, tokens, auth, usos, checkins, cripto, envelope). +- `organismo/cli_*.rb`: CLIs de emergencia en el nodo (`cli_admin`, `cli_consumidor`, `cli_registrar`). +- `organismo/tool_humo_pool.rb`: humo que corre EN el nodo contra el registro real (provider descartable). +- Contratos externos con su nombre de siempre: `server.rb` (lo arranca systemd) y el chasis F1 `chat.rb`, `latido.rb`, + `nexxa.rb`, `router.rb` (los usa `gemma individuos chat`, igual en todos los individuos). +- `test/`: suite local sobre una copia aislada con estado falso (`ruby test/_test.rb`); `test/servidor_prueba.rb` + deja un NEXXA de prueba corriendo para mirar nexxa-web en un navegador. + +## Reglas + +- **El código se cambia acá y se despliega desde acá**, nunca editando en el nodo: + `gemma nodos deploy --nodo --local-dir servicios/nexxa/organismo --remoto-dir /opt/nexxa/organismo --archivos ...` + (verifica hash local == remoto). +- **Versión semver por release:** patch (arreglo), minor (función nueva compatible), major (cambia el contrato de la API). + Se sube `organismo/VERSION` en el mismo commit del cambio. +- **Estado y secretos nunca acá** (ver `.gitignore`): `registro.json`, `tokens.json`, usuarios, sesiones, la master key y + los logs viven solo en el nodo (Regla de Oro 15). + +Plan vigente: `dtic-GEMMA/_docs/DIIAA/p_P335_nexxa-pools-por-individuo-mente-y-red-con-gestion-web.md`. diff --git a/servicios/nexxa/germen.md b/servicios/nexxa/germen.md new file mode 100644 index 00000000..9578f78c --- /dev/null +++ b/servicios/nexxa/germen.md @@ -0,0 +1,151 @@ +# Germen — Individuo Circulatorio (rm-apid06-nexxa) + +## Entregar este archivo como primer mensaje a la IA ejecutora del nacimiento + +> Este germen NO es el de OpenClaw (Miguel, r-WEBs, PEGGY, ABBY). Aquellos hacen +> nacer un agente LLM-céntrico con gateway y canal conversacional. **Tampoco es** +> el de RUBBY, que aunque es chasis F1 nativo determinístico en runtime, sí lleva +> un Arquitecto (LLM) para génesis offline de piezas nuevas. **NEXXA nace sin +> ningún LLM, en ninguna capa, ni siquiera para su propia génesis** (decisión del +> Operador, P200/Fase2) — el organismo más minimalista del linaje hasta hoy. +> Reutiliza el *proceso* de nacimiento de RUBBY (checkpoints por etapa, +> separación script/individuo, secrets por env, gate entre etapas), no su +> *contenido*. + +--- + +## Tu misión + +Hacer nacer el **organismo mínimo viable** de rotación/fallback de API keys para +el equipo F1. De cara afuera, NEXXA responde consultas de sus pares vía +`apids chat` sobre qué key/provider está disponible ahora; por dentro es un +registro de estado (cuotas por provider) y una lógica de decisión puramente +determinística — sin capa de razonamiento en ningún punto del camino. + +**El diseño ya está hecho — no lo reinventes.** El delta de dominio completo +vive en `_docs/RM-LABs/rm-APIDs/D045_diseno-nexxa-f1.md` (repo dtic-GEMMA), y el +modelo F1 base en `D025`. Tu trabajo es **materializarlo**, no rediseñarlo. Si +algo del diseño no cierra contra la realidad del hábitat, lo reportás y esperás +decisión — no improvisás una variante. + +**Principio rector — diseño como objetivo, no receta:** este germen te da el *qué* +(el organismo a lograr, sus restricciones, su criterio de vida). El *cómo* +(estructura exacta de los archivos Ruby, comandos) lo investigás y resolvés vos +contra el hábitat real. + +--- + +## Etapa 1 — Relevamiento (antes de tocar nada) + +**Hábitat:** +- La LXC `rm-apid06-nexxa` en srv-pmox2 (VMID y recursos definidos en la corrida + de creación — ver Fase 3 del plan P200). Confirmá que existe, que arranca y que + tenés acceso SSH a ella. +- Ruby disponible dentro de la LXC. Es el único sustrato — no hay Node/OpenClaw + acá. +- NEXXA no necesita salida propia a internet para su función central (consulta + estado de cuotas que ya le llegaron por registro, no llama a los providers + directamente para verificar salud, al menos en el alcance mínimo de este + nacimiento — D045 §3 deja el contrato exacto a cerrar en esta misma fase). + +**Secrets — protocolo estricto, sin excepciones (ME-293):** +- NEXXA no tiene key LLM propia (no hay Arquitecto). Los secrets que sí maneja + son las **keys de terceros que registra en su base** (Gemini/Groq/… de otros + individuos) — nunca en el `.conf` versionado, siempre en `.env` o vía candados, + nunca en argv (ME-293). +- Verificás presencia de secrets contando, sin mostrar valores. + +Al cerrar el relevamiento: resumen (sin valores de secrets) y confirmación explícita +del operador antes de la Etapa 2. + +--- + +## Etapa 2 — El organismo a materializar (el objetivo, no la receta) + +Del diseño D045, dos órganos — ninguno con LLM: + +1. **Registro de cuotas** (`registro.json` o similar — nombre exacto a definir + contra el hábitat) — una sola fuente de verdad. Cada entrada: `provider`, + `email`/identificador de la key, `dueño` (individuo consumidor o + `compartida`), `disponible_desde` (mismo cálculo que `apirot.rb`, + `ultimo_uso + reset`). **Delta sobre apirot** (D045/P200 Fase2-2.3): NEXXA + nace con registro propio y limpio, inspirado en el concepto de apirot pero no + dependiente de su código ni de su archivo — apirot.rb sigue existiendo tal + cual para uso interno de GEMMA. + +2. **Router de consulta** (`maestro.rb` o equivalente mínimo) — matching exacto + `estímulo → respuesta de estado`, cero semántica en runtime, cero LLM. Ante + consulta "¿qué key uso para provider X?": busca en el registro la primera con + `disponible_desde <= ahora`; si ninguna, responde explícito y accionable (ej. + `GEMINI: agotado, próxima en 2h15m`), nunca silencioso (D045 §0, patrón ya + usado en el linaje). + +**Sin Arquitecto, sin telemetría de génesis** (a diferencia de RUBBY/D025 §5): +no hay génesis reactiva que medir — si en el futuro hace falta una pieza nueva, +la escribe GEMMA/Operador a mano (ver nota de arquitectura compartida futura, +inbox ME de P200/Fase2). + +**Restricciones heredadas del linaje (no las redescubras):** +- Gobernanza en código, nunca declarada solo en docs. +- El código del organismo vive versionado en el repo, no solo dentro del LXC + (srv-pmox2 es RAID0 sin redundancia). +- Nunca proxy/interceptor de tráfico de modelo, nunca MCP (restricciones + heredadas de P199, D045 §0). + +Presentás el plan de materialización al operador y esperás aprobación antes de ejecutar. + +--- + +## Etapa 3 — Nacimiento por checkpoints (reutiliza el patrón RUBBY/r-WEBs) + +| `STAGE` | Qué nace | Gate de la etapa | +|---------|----------|------------------| +| `esqueleto` | Registro de cuotas + router, con 0 keys cargadas | El router arranca, lee registro vacío, responde "sin datos" ante una consulta de prueba | +| `conexion` | Canal `apids chat` verificado de punta a punta (patrón ya usado con ABBY/MIGUEL/RUBBY/PEGGY) + al menos 1 key real cargada (vía candados, no génesis) | Una consulta real por `apids chat` devuelve el estado correcto de esa key | +| `servicio` | Servicio systemd + `onboot=1` — el organismo revive tras reinicio del hipervisor | El servicio levanta el router solo; sobrevive a un reinicio de la LXC | + +Secrets siempre por env exportado o candados. Al cerrar cada etapa: verificás, +registrás, y esperás OK del operador antes de la siguiente. + +--- + +## Criterio de vida (qué es "nació bien") + +El organismo está vivo cuando, sin intervención: +1. Responde una consulta real de un par (`apids chat`) sobre disponibilidad de + una key/provider, con el dato correcto. +2. Responde explícito y accionable cuando no hay ninguna key disponible (nunca + silencioso). +3. El servicio revive tras un reinicio de la LXC. + +Primer caso real de aplicación (Fase 4 del plan P200): ABBY-F1 consulta a NEXXA +para sus 3 keys de Gemini — no es parte de este nacimiento, es el smoke test +posterior. + +--- + +## individuo.conf (parámetros — el operador completa) + +```conf +# Identidad +NOMBRE=NEXXA # bautizado por el Operador (2026-08-02) — concepto de switch/conmutación +MAQUINA=rm-apid06-nexxa +VMID=(a definir en Fase 3) +IP=(a definir en Fase 3 — requiere aprobación explícita del Operador, nunca se asigna sin OK) +HABITAT=srv-pmox2 + +# Función +PROPOSITO=rotación/fallback de API keys para el equipo F1 — alcance mínimo (no el "sistema circulatorio" amplio de ME-289) + +# Sin Arquitecto — NEXXA no tiene key LLM propia, no genera piezas nuevas por su cuenta +``` + +--- + +## Referencias + +- Delta de dominio: `_docs/RM-LABs/rm-APIDs/D045_diseno-nexxa-f1.md` (dtic-GEMMA) +- Modelo F1 base: `D025_diseno-fundacional-rubby-f1.md` +- Plan: `_docs/RM-LABs/p_P200_*.md` (dtic-GEMMA) +- Precedente de proceso: `rm-apid01-rubby/germen.md` (checkpoints, etapas, gate) +- ME: 289, 292, 293, 330, 331, 335, 417, 468 diff --git a/servicios/nexxa/organismo/VERSION b/servicios/nexxa/organismo/VERSION new file mode 100644 index 00000000..f0bb29e7 --- /dev/null +++ b/servicios/nexxa/organismo/VERSION @@ -0,0 +1 @@ +1.3.0 diff --git a/servicios/nexxa/organismo/chat.rb b/servicios/nexxa/organismo/chat.rb new file mode 100644 index 00000000..2a9d4ea7 --- /dev/null +++ b/servicios/nexxa/organismo/chat.rb @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# chat.rb — Entry point invocado por 'gemma apids chat' (chasis F1 nativo) +# Contrato: recibe el mensaje completo como ARGV[0], imprime texto plano +# (sin LLM, sin JSON — D045 §1/§4, cero semántica en runtime) + +require_relative 'router' + +texto = ARGV[0].to_s +puts Nexxa::Router.procesar(texto) diff --git a/servicios/nexxa/organismo/cli_admin.rb b/servicios/nexxa/organismo/cli_admin.rb new file mode 100644 index 00000000..a7c57faa --- /dev/null +++ b/servicios/nexxa/organismo/cli_admin.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# cli_admin.rb — Bootstrap del primer usuario admin del panel web (P201/Fase4) +# Uso: ruby cli_admin.rb --usuario rmonla (crea, perfil admin) +# ruby cli_admin.rb --usuario rmonla --perfil operador +# ruby cli_admin.rb --usuario rmonla --rotar (rota su password) +# ruby cli_admin.rb --listar (metadata, sin hashes) +# +# Corre SIEMPRE en la terminal del Operador (SSH directo al nodo), nunca a +# través de GEMMA/candados ni de un agente — la password se imprime UNA vez +# acá y en ningún otro lugar (Regla 15). Una vez que existe al menos un admin, +# el alta de usuarios nuevos se hace normalmente desde el panel (sección +# Usuarios, gateada a perfil admin) — este script es solo para el bootstrap +# inicial o para recuperar acceso si quedan todos los admins bloqueados. + +require_relative 'lib_auth' + +args = ARGV.each_slice(2).to_h { |k, v| [k.sub(/^--/, ''), v] } + +if ARGV.include?('--listar') + usuarios = Nexxa::Auth.listar + if usuarios.empty? + puts 'Sin usuarios todavía.' + else + usuarios.each { |u| puts "#{u['usuario']} (#{u['perfil']}) — #{u['activo'] == false ? 'inactivo' : 'activo'}" } + end + exit +end + +usuario = args['usuario'] +abort 'Uso: ruby cli_admin.rb --usuario [--perfil admin|operador] [--rotar] | --listar' unless usuario + +password = SecureRandom.urlsafe_base64(18) + +if ARGV.include?('--rotar') + Nexxa::Auth.actualizar(usuario: usuario, password_nueva: password) + puts "Password rotada para '#{usuario}'. Nueva password (guardarla ahora, no se vuelve a mostrar):" + puts password +elsif Nexxa::Auth.existe?(usuario) + abort "Usuario '#{usuario}' ya existe — usar --rotar para cambiarle la password." +else + perfil = args['perfil'] || 'admin' + Nexxa::Auth.crear_usuario(usuario: usuario, password: password, perfil: perfil) + puts "Usuario '#{usuario}' creado (perfil #{perfil}). Password (guardarla ahora, no se vuelve a mostrar):" + puts password +end diff --git a/servicios/nexxa/organismo/cli_consumidor.rb b/servicios/nexxa/organismo/cli_consumidor.rb new file mode 100644 index 00000000..6bdf3b9c --- /dev/null +++ b/servicios/nexxa/organismo/cli_consumidor.rb @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# cli_consumidor.rb — Alta/rotación de token de consumidor sin pasar por el panel (P204) +# Uso: ruby cli_consumidor.rb --individuo gemma (genera/rota token) +# ruby cli_consumidor.rb --listar (metadata, sin hashes) +# ruby cli_consumidor.rb --revocar --individuo gemma (revoca el acceso) +# +# Corre SIEMPRE en la terminal del Operador (SSH directo al nodo), nunca a +# través de GEMMA/candados ni de un agente — el token se imprime UNA vez acá +# y en ningún otro lugar (Regla 15). + +require_relative 'lib_tokens' + +args = ARGV.each_slice(2).to_h { |k, v| [k.sub(/^--/, ''), v] } + +if ARGV.include?('--listar') + consumidores = Nexxa::Tokens.listar + if consumidores.empty? + puts 'Sin consumidores todavía.' + else + consumidores.each { |c| puts "#{c['individuo']} — creado #{c['creado']}" } + end + exit +end + +individuo = args['individuo'] +abort 'Uso: ruby cli_consumidor.rb --individuo [--revocar] | --listar' unless individuo + +if ARGV.include?('--revocar') + ok = Nexxa::Tokens.revocar(individuo) + puts(ok ? "Acceso revocado para '#{individuo}'." : "'#{individuo}' no tenía token activo.") +else + token = Nexxa::Tokens.generar(individuo) + puts "Token generado para '#{individuo}' (guardarlo ahora, no se vuelve a mostrar):" + puts token +end diff --git a/servicios/nexxa/organismo/cli_registrar.rb b/servicios/nexxa/organismo/cli_registrar.rb new file mode 100644 index 00000000..0d300cb6 --- /dev/null +++ b/servicios/nexxa/organismo/cli_registrar.rb @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# cli_registrar.rb — Alta de una key con su valor real (D045 §10/§11, P201/Fase2-3) +# Uso: ruby cli_registrar.rb +# (el valor real se lee por STDIN, nunca por argv — ME-293/296) +# +# echo -n "$VALOR" | ruby cli_registrar.rb gemini gemini-01 abby 86400 +# +# cuenta_origen: cuenta ante el proveedor que generó esta key — PERMANENTE, +# informativo, no filtro de acceso (D045 §11 — distinto de "quién la tiene +# asignada ahora", eso es ultimo_individuo/marcar_uso, efímero). +# +# NEXXA aloja ella misma el valor real, cifrado en su storage propio (D045 §10 +# — reemplaza a candados como lugar de guarda de API keys de terceros). El +# valor nunca pasa por argv/log — solo por STDIN, mismo patrón ya usado por +# GEMMA para credenciales (ME-116). + +require_relative 'lib_registro' + +provider, identificador, cuenta_origen, reset_segundos = ARGV +unless provider && identificador && cuenta_origen && reset_segundos + abort 'Uso: echo -n "$VALOR" | cli_registrar.rb ' +end + +valor = $stdin.read.strip +abort 'Valor vacío por STDIN' if valor.empty? + +Nexxa::Registro.registrar( + provider: provider, + identificador: identificador, + cuenta_origen: cuenta_origen, + reset_segundos: reset_segundos.to_i, + valor: valor +) + +puts "Registrado: #{provider} → #{identificador} (cuenta: #{cuenta_origen})" diff --git a/servicios/nexxa/organismo/latido.rb b/servicios/nexxa/organismo/latido.rb new file mode 100644 index 00000000..fafaa48d --- /dev/null +++ b/servicios/nexxa/organismo/latido.rb @@ -0,0 +1,20 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# latido.rb — Heartbeat mínimo, mantiene vivo el proceso del servicio +# ============================================================================== +# NEXXA-F1 (P200) responde a consultas puntuales vía apids chat (SSH bajo +# demanda, sin loop de decisión propio — D045 §1/§4). Este latido NO procesa +# estímulos ni carrera de era (a diferencia de RUBBY/PEGGY) — su único rol es +# marcar 'el organismo está vivo' para el criterio de vida (revive tras +# reinicio de la LXC) y dejar un heartbeat auditable en log, cadencia 300s +# (ME-435: latido ≠ conversar, nunca comparte proceso con el canal directo). +# ============================================================================== + +LOG_FILE = File.expand_path('latido.log', __dir__) +CADENCIA_SEGUNDOS = 300 + +loop do + File.open(LOG_FILE, 'a') { |f| f.puts("#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} — vivo") } + sleep CADENCIA_SEGUNDOS +end diff --git a/servicios/nexxa/organismo/lib_auth.rb b/servicios/nexxa/organismo/lib_auth.rb new file mode 100644 index 00000000..d02058c9 --- /dev/null +++ b/servicios/nexxa/organismo/lib_auth.rb @@ -0,0 +1,202 @@ +# frozen_string_literal: true + +# lib_auth.rb — Usuarios y sesiones del panel web de NEXXA (P201/Fase4) +# ============================================================================== +# Reemplaza el diseño original (nginx Basic Auth + credencial en candados de +# GEMMA) por corrección explícita del Operador: NEXXA resuelve su propia auth, +# sin dependencia de GEMMA — mismo espíritu de independencia que ya tienen +# lib_tokens.rb (individuos F1) y lib_cripto.rb (master key propia). +# +# Multi-usuario con perfil (corrección 2026-08-03 — el diseño original de un +# solo Operador binario no alcanzaba, el Operador pidió CRUD de usuarios real, +# gateado por perfil): dos perfiles, sin inventar granularidad no pedida — +# - 'admin' → todo, incluida la gestión de usuarios (crear/editar/borrar) +# - 'operador' → todo lo demás (keys, consumidores), sin gestión de usuarios +# +# No reinventa primitivas de seguridad (pedido explícito del Operador): usa +# exactamente el mismo algoritmo ya probado en producción en +# gemma/tools/candados/core/lib_cripto.rb (Armonía Integral) — PBKDF2-HMAC-SHA256, +# 100k iteraciones, salt random — en vez de SHA256 plano (adecuado para el +# token aleatorio de lib_tokens.rb, pero no para una password humana). +# +# Sesión: token aleatorio de alta entropía (mismo patrón que Tokens.generar), +# guardado server-side con expiración, entregado como cookie. HttpOnly/Secure/ +# SameSite se arman a mano en el header Set-Cookie (server.rb) porque el +# WEBrick::Cookie de esta versión de Ruby no expone esos atributos — ver +# comentario en server.rb. +# ============================================================================== + +require 'json' +require 'securerandom' +require 'openssl' +require 'base64' +require 'time' + +module Nexxa + module Auth + USERS_FILE = File.expand_path('.usuarios.json', __dir__).freeze + SESSIONS_FILE = File.expand_path('.sessions.json', __dir__).freeze + PBKDF2_ITER = 100_000 + SESSION_TTL = 8 * 3600 # 8 horas — re-login diario razonable + PERFILES_VALIDOS = %w[admin operador].freeze + + # ---------- Usuarios ---------- + + def self.leer_usuarios + return [] unless File.exist?(USERS_FILE) + + JSON.parse(File.read(USERS_FILE)) + rescue JSON::ParserError + [] + end + + def self.guardar_usuarios(lista) + File.write(USERS_FILE, JSON.pretty_generate(lista) + "\n") + File.chmod(0o600, USERS_FILE) + end + + def self.derivar(password, salt) + OpenSSL::PKCS5.pbkdf2_hmac(password, salt, PBKDF2_ITER, 32, 'SHA256') + end + + # Crea un usuario nuevo — devuelve la password EN CLARO solo si el + # caller la generó (bootstrap por cli_admin.rb), o la recibe ya elegida + # (alta vía panel por un admin). Nunca se persiste ni se loguea en claro. + # raise si el usuario ya existe o el perfil no es válido. + def self.crear_usuario(usuario:, password:, perfil:) + usuario = usuario.to_s.strip + raise 'Usuario vacío' if usuario.empty? + raise "Perfil inválido: #{perfil} (válidos: #{PERFILES_VALIDOS.join(', ')})" unless PERFILES_VALIDOS.include?(perfil) + + lista = leer_usuarios + raise "Usuario '#{usuario}' ya existe" if lista.any? { |u| u['usuario'] == usuario } + + salt = SecureRandom.random_bytes(16) + hash = derivar(password, salt) + lista << { + 'usuario' => usuario, + 'perfil' => perfil, + 'salt' => Base64.strict_encode64(salt), + 'hash' => Base64.strict_encode64(hash), + 'activo' => true, + 'creado' => Time.now.iso8601 + } + guardar_usuarios(lista) + usuario + end + + # Verifica usuario+password — devuelve el registro (sin salt/hash) si es + # válido y está activo, nil si no. Comparación de tiempo constante. + def self.autenticar(usuario:, password:) + entrada = leer_usuarios.find { |u| u['usuario'] == usuario.to_s.strip && u['activo'] != false } + return nil unless entrada + + salt = Base64.strict_decode64(entrada['salt']) + hash_guardado = Base64.strict_decode64(entrada['hash']) + hash_calculado = derivar(password.to_s, salt) + return nil unless hash_guardado.bytesize == hash_calculado.bytesize && + OpenSSL.fixed_length_secure_compare(hash_guardado, hash_calculado) + + entrada.reject { |k, _| %w[salt hash].include?(k) } + end + + # Todos los usuarios, solo metadata — NUNCA salt/hash (Regla 15). + def self.listar + leer_usuarios.map { |u| u.reject { |k, _| %w[salt hash].include?(k) } } + end + + def self.existe?(usuario) + leer_usuarios.any? { |u| u['usuario'] == usuario.to_s.strip } + end + + # Edita perfil/activo de un usuario existente. password_nueva opcional + # (rotación). raise si no existe o el perfil no es válido. + def self.actualizar(usuario:, perfil: nil, activo: nil, password_nueva: nil) + lista = leer_usuarios + entrada = lista.find { |u| u['usuario'] == usuario.to_s.strip } + raise "Usuario '#{usuario}' no encontrado" unless entrada + + if perfil + raise "Perfil inválido: #{perfil} (válidos: #{PERFILES_VALIDOS.join(', ')})" unless PERFILES_VALIDOS.include?(perfil) + entrada['perfil'] = perfil + end + entrada['activo'] = activo unless activo.nil? + if password_nueva && !password_nueva.to_s.strip.empty? + salt = SecureRandom.random_bytes(16) + entrada['salt'] = Base64.strict_encode64(salt) + entrada['hash'] = Base64.strict_encode64(derivar(password_nueva, salt)) + end + guardar_usuarios(lista) + entrada.reject { |k, _| %w[salt hash].include?(k) } + end + + # Elimina un usuario — destructivo. El caller (server.rb) es responsable + # de impedir que el último admin se borre a sí mismo (guardia de negocio, + # no de esta capa de datos). + def self.eliminar(usuario) + lista = leer_usuarios + existia = lista.reject! { |u| u['usuario'] == usuario.to_s.strip } + guardar_usuarios(lista) if existia + !existia.nil? + end + + def self.admins_activos + leer_usuarios.count { |u| u['perfil'] == 'admin' && u['activo'] != false } + end + + # ---------- Sesiones ---------- + + def self.leer_sesiones + return {} unless File.exist?(SESSIONS_FILE) + + JSON.parse(File.read(SESSIONS_FILE)) + rescue JSON::ParserError + {} + end + + def self.guardar_sesiones(sesiones) + File.write(SESSIONS_FILE, JSON.pretty_generate(sesiones) + "\n") + File.chmod(0o600, SESSIONS_FILE) + end + + def self.crear_sesion(usuario, perfil) + token = SecureRandom.hex(32) + sesiones = leer_sesiones + sesiones[token] = { + 'usuario' => usuario, + 'perfil' => perfil, + 'expira' => (Time.now + SESSION_TTL).iso8601 + } + guardar_sesiones(sesiones) + token + end + + # Devuelve {usuario, perfil} de la sesión si es válida, nil si no. + def self.sesion(token) + return nil if token.to_s.strip.empty? + + sesiones = leer_sesiones + entrada = sesiones[token] + return nil unless entrada + + if Time.parse(entrada['expira']) < Time.now + sesiones.delete(token) + guardar_sesiones(sesiones) + return nil + end + + { 'usuario' => entrada['usuario'], 'perfil' => entrada['perfil'] } + end + + def self.sesion_valida?(token) + !sesion(token).nil? + end + + def self.cerrar_sesion(token) + sesiones = leer_sesiones + existia = sesiones.delete(token) + guardar_sesiones(sesiones) if existia + !existia.nil? + end + end +end diff --git a/servicios/nexxa/organismo/lib_checkins.rb b/servicios/nexxa/organismo/lib_checkins.rb new file mode 100644 index 00000000..38461135 --- /dev/null +++ b/servicios/nexxa/organismo/lib_checkins.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +# lib_checkins.rb — Reporte proactivo de estado de individuos F1 (P216) +# ============================================================================== +# Complementa lib_tokens.rb (identidad) con un registro simple de "qué contó cada +# individuo de sí mismo la última vez" — mismo espíritu que Registro.disponible +# para keys: NEXXA solo guarda lo que le reportan, nunca sale a diagnosticar +# nada por su cuenta. Quien consulta (GEMMA, vía bandeja.rb) decide qué hacer +# con la antigüedad del último reporte. +# ============================================================================== + +require 'json' +require 'time' + +module Nexxa + module Checkins + STATE_FILE = File.expand_path('checkins.json', __dir__).freeze + + def self.leer + return {} unless File.exist?(STATE_FILE) + + JSON.parse(File.read(STATE_FILE)) + rescue JSON::ParserError + {} + end + + def self.guardar(state) + File.write(STATE_FILE, JSON.pretty_generate(state) + "\n") + File.chmod(0o600, STATE_FILE) + end + + # El individuo llega autenticado (individuo_autenticado(req) en server.rb, + # vía Nexxa::Tokens.verificar) — nunca confiar en un id que venga en el + # body, el token YA identifica quién reporta. + def self.registrar(individuo, estado:, detalle: nil) + state = leer + state[individuo] = { + 'estado' => estado.to_s, + 'detalle' => detalle, + 'ultimo_reporte' => Time.now.utc.iso8601 + } + guardar(state) + state[individuo] + end + + def self.estado(individuo) + leer[individuo] + end + + def self.listar + leer + end + end +end diff --git a/servicios/nexxa/organismo/lib_cripto.rb b/servicios/nexxa/organismo/lib_cripto.rb new file mode 100644 index 00000000..e4ae8d70 --- /dev/null +++ b/servicios/nexxa/organismo/lib_cripto.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# lib_cripto.rb — Motor criptográfico AES-256-GCM, adaptado de gemma/tools/candados/core/lib_cripto.rb +# ============================================================================== +# NEXXA-F1 (P201/Fase2) — mismo algoritmo que la bóveda de candados de GEMMA +# (Armonía Integral, no reinventar), pero SIN derivación por frase humana: NEXXA +# cifra/descifra 24/7 sin intervención (D045 §10, storage propio de la key real). +# La master key vive en un archivo local (MasterKey.cargar!), nunca en argv/log. +# ============================================================================== + +require 'openssl' +require 'base64' +require 'json' +require 'securerandom' + +module Nexxa + class Cripto + ALGORITHM = 'aes-256-gcm' + + def initialize(key_bytes) + raise 'Master key debe tener 32 bytes (256 bits)' unless key_bytes.bytesize == 32 + + @key = key_bytes + end + + def encrypt(plaintext) + cipher = OpenSSL::Cipher.new(ALGORITHM) + cipher.encrypt + cipher.key = @key + iv = cipher.random_iv + ciphertext = cipher.update(plaintext.to_s) + cipher.final + payload = { iv: b64(iv), tag: b64(cipher.auth_tag), data: b64(ciphertext) } + Base64.strict_encode64(payload.to_json) + end + + def decrypt(token) + p = JSON.parse(Base64.strict_decode64(token), symbolize_names: true) + cipher = OpenSSL::Cipher.new(ALGORITHM) + cipher.decrypt + cipher.key = @key + cipher.iv = db64(p[:iv]) + cipher.auth_tag = db64(p[:tag]) + cipher.update(db64(p[:data])) + cipher.final + rescue StandardError => e + raise "Error al descifrar: #{e.message}" + end + + private + + def b64(d) = Base64.strict_encode64(d) + def db64(d) = Base64.strict_decode64(d) + end + + module MasterKey + RUTA = File.expand_path('.master_key', __dir__) + + # Genera la master key UNA VEZ (idempotente — si ya existe, no la toca). + # Devuelve los bytes en ambos casos. El caller decide si hace backup (candados). + def self.generar_si_falta! + return File.binread(RUTA) if File.exist?(RUTA) + + bytes = SecureRandom.random_bytes(32) + File.binwrite(RUTA, bytes) + File.chmod(0o600, RUTA) + bytes + end + + def self.cargar! + raise "Master key no existe en #{RUTA} — correr MasterKey.generar_si_falta! primero" unless File.exist?(RUTA) + + File.binread(RUTA) + end + end +end diff --git a/servicios/nexxa/organismo/lib_envelope.rb b/servicios/nexxa/organismo/lib_envelope.rb new file mode 100644 index 00000000..1b3a74ce --- /dev/null +++ b/servicios/nexxa/organismo/lib_envelope.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +# lib_envelope.rb — Cifrado de punta a punta hacia el consumidor (P204, "Aplica +# Pilares" sobre la decisión previa de diferirlo) +# ============================================================================== +# Distinto de lib_cripto.rb (AES simétrico, master key propia de NEXXA, cifra EN +# REPOSO — lo que NEXXA guarda). Esto es asimétrico (RSA-OAEP), cifra PARA EL +# CONSUMIDOR — ni NEXXA ni nadie que capture el cuerpo de la respuesta HTTP +# puede leer el valor sin la clave PRIVADA del individuo, que NUNCA sale de +# ese individuo (NEXXA solo guarda la pública, ver lib_tokens.rb). +# +# RSA-OAEP directo (sin AES intermedio): las API keys son strings cortos +# (~30-60 bytes) — un RSA de 2048 bits con padding OAEP-SHA256 cifra hasta +# ~190 bytes de una, de sobra. No hace falta el patrón "envelope" clásico +# (RSA cifra una clave AES efímera, AES cifra el payload grande) porque acá +# el payload YA es chico — agregar esa capa sería complejidad sin beneficio +# real (Menos es Más). +# ============================================================================== + +require 'openssl' +require 'base64' + +module Nexxa + module Envelope + # Cifra `valor` con la clave pública PEM del consumidor — devuelve base64, + # listo para meter en un campo JSON de la respuesta HTTP. Nunca falla en + # silencio: una clave pública inválida hace que esto reviente (server.rb + # decide qué hacer, no lo traga acá). + def self.cifrar_para(clave_publica_pem, valor) + rsa = OpenSSL::PKey::RSA.new(clave_publica_pem) + Base64.strict_encode64(rsa.public_encrypt(valor.to_s, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)) + end + + # Deliberadamente NO hay Envelope.descifrar acá — descifrar es trabajo + # del CONSUMIDOR con su propia clave privada, nunca de NEXXA. Si NEXXA + # pudiera descifrar esto, no sería de punta a punta. + end +end diff --git a/servicios/nexxa/organismo/lib_pools.rb b/servicios/nexxa/organismo/lib_pools.rb new file mode 100644 index 00000000..f64d7540 --- /dev/null +++ b/servicios/nexxa/organismo/lib_pools.rb @@ -0,0 +1,132 @@ +# frozen_string_literal: true + +# lib_pools.rb — Pools de keys POR INDIVIDUO: mente y red de seguridad (P335/Fase 4, Operador 2026-10-04) +# +# Cada individuo tiene dos pools: MENTE (las keys con las que piensa y opera) y RED (solo para el aviso de batería +# baja). Un pool MEZCLA proveedores y una key puede estar en varios pools (exclusiva o compartida). Es el TERCER eje de +# una key (ME-609): `cuenta_origen` dice quién la aportó (permanente, informativo), `reservado_por` quién la tiene AHORA +# (efímero) y la asignación a pools es CONFIGURACIÓN permanente que decide un admin desde nexxa-web. +# +# Persistencia: pools.json junto a registro.json (0600). NEXXA guarda todo su estado en JSON en su hábitat y no tiene +# Postgres (REG002 R15 lo pide justificar: un individuo sin BD propia; migrarlo a BD es otra decisión). Separado de +# registro.json a propósito: lo que se edita a mano desde la web (config) no se mezcla con el estado vivo de cada key. +# +# Referencia de una key en un pool: "provider/identificador" (las dos partes juntas la identifican en registro.json). + +require 'json' + +module Nexxa + module Pools + STATE_FILE = File.expand_path('pools.json', __dir__).freeze + ROLES = %w[mente red].freeze + + module_function + + def leer + return { 'individuos' => {} } unless File.exist?(STATE_FILE) + + d = JSON.parse(File.read(STATE_FILE)) + d['individuos'] ||= {} + d + rescue JSON::ParserError + { 'individuos' => {} } + end + + def guardar(state) + tmp = "#{STATE_FILE}.tmp-#{Process.pid}" + File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |f| f.write(JSON.pretty_generate(state) + "\n") } + File.rename(tmp, STATE_FILE) + end + + def ref(provider, identificador) + "#{provider}/#{identificador}" + end + + # Refs del pool de un individuo para un rol. => ["gemini/abby", "deepseek/deepseek-01", ...] + def refs(individuo, rol) + Array(leer.dig('individuos', individuo.to_s, rol.to_s)) + end + + # Asigna una key al pool. Idempotente. Valida rol y que la key exista en el registro (inyectable para tests). + def asignar(individuo:, rol:, provider:, identificador:, existe: nil) + validar!(individuo, rol) + existe ||= ->(p, i) { Nexxa::Registro.todas.any? { |k| k['provider'] == p && k['identificador'] == i } } + raise "Key no encontrada: #{ref(provider, identificador)}" unless existe.call(provider, identificador) + + state = leer + pool = (state['individuos'][individuo] ||= {})[rol] ||= [] + r = ref(provider, identificador) + pool << r unless pool.include?(r) + guardar(state) + pool + end + + # Quita una key de un pool. => true si estaba. + def quitar(individuo:, rol:, provider:, identificador:) + validar!(individuo, rol) + state = leer + pool = state.dig('individuos', individuo, rol) + return false unless pool&.delete(ref(provider, identificador)) + + state['individuos'][individuo].delete(rol) if pool.empty? + state['individuos'].delete(individuo) if state['individuos'][individuo].empty? + guardar(state) + true + end + + # Al eliminar una key del registro, se saca de todos los pools (sin referencias colgadas). + def olvidar_key(provider:, identificador:) + state = leer + r = ref(provider, identificador) + cambio = false + state['individuos'].each_value { |roles| roles.each_value { |pool| cambio = true if pool.delete(r) } } + state['individuos'].each_value { |roles| roles.delete_if { |_, pool| pool.empty? } } + state['individuos'].delete_if { |_, roles| roles.empty? } + guardar(state) if cambio + cambio + end + + # Pools en los que está una key. => [{ 'individuo' =>, 'rol' => }] + def de_key(provider, identificador, state = leer) + r = ref(provider, identificador) + state['individuos'].flat_map do |ind, roles| + roles.select { |_, pool| pool.include?(r) }.map { |rol, _| { 'individuo' => ind, 'rol' => rol } } + end + end + + # --- Selección por NOMBRE (P335/Fase 5): el único lugar que decide si /disponible/ es un rol o un provider. + # Rol (mente|red) → el pool del individuo; si está vacío NO cae al provider (respuesta explícita 'pool_vacio'). + # Otro nombre → un provider, como antes (compatibilidad con los consumidores actuales). + def rol?(nombre) + ROLES.include?(nombre.to_s) + end + + def pool_vacio?(individuo, nombre) + rol?(nombre) && refs(individuo, nombre).empty? + end + + def disponible(individuo, nombre) + rol?(nombre) ? Nexxa::Registro.disponible_en(refs(individuo, nombre)) : Nexxa::Registro.disponible(nombre) + end + + def proxima(individuo, nombre) + rol?(nombre) ? Nexxa::Registro.proxima_en(refs(individuo, nombre)) : Nexxa::Registro.proxima(nombre) + end + + def estado(individuo, nombre) + rol?(nombre) ? Nexxa::Registro.estado_en(refs(individuo, nombre)) : Nexxa::Registro.estado_pool(nombre) + end + + # Pools completos con el estado de cada key, para nexxa-web. Nunca valores. + def con_estado + leer['individuos'].transform_values do |roles| + roles.to_h { |rol, pool| [rol, Nexxa::Registro.estado_en(pool)] } + end + end + + def validar!(individuo, rol) + raise 'Falta el individuo' if individuo.to_s.strip.empty? + raise "rol inválido: #{rol} (esperado: #{ROLES.join('|')})" unless ROLES.include?(rol.to_s) + end + end +end diff --git a/servicios/nexxa/organismo/lib_registro.rb b/servicios/nexxa/organismo/lib_registro.rb new file mode 100644 index 00000000..444a86f1 --- /dev/null +++ b/servicios/nexxa/organismo/lib_registro.rb @@ -0,0 +1,330 @@ +# frozen_string_literal: true + +# lib_registro.rb — Fuente de verdad de cuotas Y del valor real de cada key +# ============================================================================== +# NEXXA-F1 (P200, evolucionado en P201/Fase2-3 — D045 §10/§11) — registro propio, +# inspirado en apirot.rb (P121, dtic-GEMMA) pero con delta de dominio: campo +# 'provider'/'cuenta_origen' (D045 §2.3/§11) y, desde P201/Fase2, el VALOR REAL +# cifrado de cada key (D045 §10: NEXXA es la fuente de verdad, ya no candados, +# para API keys de terceros). 'identificador' es una ETIQUETA legible (ej. +# 'gemini-01'), no el secreto — el secreto vive solo en 'valor_cifrado', nunca +# en texto plano en disco ni en ningún log (ME-293/296). +# +# Dos ejes distintos, no confundir (corrección P201/Fase3, D045 §11): +# - cuenta_origen: PERMANENTE — qué cuenta ante el proveedor generó esta key. +# Informativo, nunca filtro de acceso (pool compartido, D045 §8). +# - ultimo_individuo / reservar / reportar / lib_usos.rb: EFÍMERO — qué individuo +# del ecosistema APIDs la tiene asignada ahora (o la tuvo la última vez). Una +# key se reclama y se libera — no tiene "dueño" en ese sentido. +# ============================================================================== +# NO hace: no llama a los providers externos, no valida las keys en sí — solo +# lleva el registro declarado (alta vía mini-app o cli_registrar.rb) +# ============================================================================== +# Salud real de keys (P204/Fase3, D045 §8) — el CONSUMIDOR es el árbitro del +# agotamiento, no NEXXA: solo él le pegó al proveedor real. reservar() aplica +# una reserva corta de contención al dispensar (evita doble-asignación +# concurrente, sin asumir agotamiento); reportar() recibe la señal real +# ('sana' renueva, 'liberada' suelta, 'agotada' recién ahí bloquea con +# disponible_desde). Ver registro.json: campos reservado_por/reservado_hasta. +# ============================================================================== + +require 'json' +require 'time' +require_relative 'lib_cripto' +require_relative 'lib_usos' + +module Nexxa + module Registro + STATE_FILE = File.expand_path('registro.json', __dir__).freeze + + # Reserva corta de contención (P204/Fase3, D045 §8) — no asume agotamiento, + # solo evita que 2 consumidores reciban la misma key mientras uno la está + # probando. Vence sola (evaluada en self.disponible, sin proceso de limpieza + # aparte) si nadie reporta nada; self.reportar la renueva o la libera. + RESERVA_TTL_SEGUNDOS = 600 + + def self.leer + if File.exist?(STATE_FILE) + JSON.parse(File.read(STATE_FILE)) + else + { 'keys' => [] } + end + rescue JSON::ParserError + { 'keys' => [] } + end + + def self.guardar(state) + File.write(STATE_FILE, JSON.pretty_generate(state) + "\n") + end + + # provider: "gemini"/"groq"/... ; identificador: ETIQUETA legible (ej. "gemini-01"), + # nunca el secreto ; cuenta_origen: cuenta ante el proveedor que generó la key — + # PERMANENTE, informativo, no filtro de acceso (D045 §8/§11) ; reset_segundos: + # ciclo de cuota del proveedor, se persiste para que marcar_uso pueda recalcular + # disponible_desde sin que el caller tenga que volver a pasarlo ; valor: el + # secreto en texto plano — se cifra acá mismo, nunca se persiste sin cifrar + # (nil = alta solo de metadata, compatibilidad con registros viejos aún no + # migrados, D045 §9→§10). ultimo_uso: nil (default) = key nueva/sin agotar, + # disponible YA — nunca se asume 'se usó ahora' (bug real encontrado en + # P200/Fase4: registrar una key recién creada la dejaba "agotada" 24h por + # error, ME-603). Pasar ultimo_uso explícito solo cuando se sabe que la key + # SÍ se agotó en ese momento. + def self.registrar(provider:, identificador:, cuenta_origen:, reset_segundos:, valor: nil, ultimo_uso: nil) + state = leer + ahora = Time.now + disponible_desde = ultimo_uso ? (Time.parse(ultimo_uso) + reset_segundos).iso8601(3) : ahora.iso8601(3) + ultimo_uso ||= ahora.iso8601(3) + + valor_cifrado = valor ? cifrar(valor) : nil + + existente = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + if existente + existente.merge!( + 'ultimo_uso' => ultimo_uso, + 'disponible_desde' => disponible_desde, + 'cuenta_origen' => cuenta_origen, + 'reset_segundos' => reset_segundos + ) + existente['valor_cifrado'] = valor_cifrado if valor_cifrado + else + state['keys'] << { + 'provider' => provider, + 'identificador' => identificador, + 'cuenta_origen' => cuenta_origen, + 'reset_segundos' => reset_segundos, + 'ultimo_uso' => ultimo_uso, + 'ultimo_individuo' => nil, + 'disponible_desde' => disponible_desde, + 'valor_cifrado' => valor_cifrado, + 'activo' => true, + 'reservado_por' => nil, + 'reservado_hasta' => nil + } + end + guardar(state) + state + end + + # Edita metadata de una key existente (P201/Fase3) — NUNCA el valor (eso no + # se re-muestra, se reemplaza vía 'registrar' con un valor nuevo si hace + # falta rotarlo). Cada parámetro es opcional: solo se actualiza lo pasado. + def self.actualizar(provider:, identificador:, cuenta_origen: nil, reset_segundos: nil, activo: nil) + state = leer + entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + raise "Key no encontrada: #{provider}/#{identificador}" unless entrada + + entrada['cuenta_origen'] = cuenta_origen unless cuenta_origen.nil? + entrada['reset_segundos'] = reset_segundos unless reset_segundos.nil? + entrada['activo'] = activo unless activo.nil? + guardar(state) + entrada + end + + # Elimina una key del registro — destructivo, sin deshacer (P201/Fase3). + # No borra su historial en lib_usos.rb (log append-only, queda como evidencia). + def self.eliminar(provider:, identificador:) + state = leer + existia = state['keys'].reject! { |k| k['provider'] == provider && k['identificador'] == identificador } + guardar(state) if existia + !existia.nil? + end + + # Todas las keys, solo metadata — para la vista de consulta de la mini-app + # (P201/Fase3). Nunca incluye valor_cifrado, bajo ningún caso (Regla 15). + def self.todas + leer['keys'].map { |k| k.reject { |campo, _| campo == 'valor_cifrado' } } + end + + # Descifra y devuelve el valor real de una key — SOLO para el endpoint HTTP + # autenticado (Fase 2/2.4). El router de apids chat (router.rb) nunca llama + # a esto — sigue devolviendo solo metadata, texto plano sin el secreto. + def self.revelar(provider:, identificador:) + entrada = leer['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + return nil unless entrada && entrada['valor_cifrado'] + + descifrar(entrada['valor_cifrado']) + end + + # Reserva corta de contención al dispensar (P204/Fase3, D045 §8) — reemplaza + # el bloqueo ciego de la vieja marcar_uso: NO asume agotamiento, solo evita + # que 2 consumidores reciban la misma key mientras uno la está probando. + # disponible_desde queda intacto — el agotamiento real solo lo aplica + # self.reportar(estado: 'agotada'), con la señal del consumidor. Se llama + # automático al dispensar (server.rb, GET /disponible). + def self.reservar(provider:, identificador:, individuo:) + state = leer + entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + raise "Key no encontrada: #{provider}/#{identificador}" unless entrada + + ahora = Time.now + entrada['ultimo_uso'] = ahora.iso8601(3) + entrada['ultimo_individuo'] = individuo + entrada['reservado_por'] = individuo + entrada['reservado_hasta'] = (ahora + RESERVA_TTL_SEGUNDOS).iso8601(3) + guardar(state) + + Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'dispensada') + entrada + end + + # Reporte real del consumidor sobre una key que tiene reservada (P204/Fase3, + # D045 §8) — el consumidor es el árbitro de salud, no NEXXA (solo él le pegó + # al proveedor real). Exige reservado_por == individuo — nadie reporta el + # estado de una key que no tiene reservada. + # 'sana' → renueva la reserva (sigue activo, evita que le venza en uso) + # 'liberada' → libera la reserva ya, sin tocar disponible_desde (buen + # ciudadano que terminó antes de tiempo) + # 'agotada' → recién acá se aplica el bloqueo real: disponible_desde = + # ahora + (liberar_en_segundos si el proveedor dio una pista + # real, si no el reset_segundos registrado como fallback) + # + # P334/Fase 4 (GEMMA, 2026-10-04): quien marcó una key 'agotada' puede DESHACER su propio reporte con + # 'liberada' aunque ya no la tenga reservada (agotada_por == individuo y el bloqueo sigue vigente). Caso real + # 2026-10-01 19:46: un 429 por minuto reportado como agotada bloqueó el pool compartido y el consumidor no podía + # revertirlo (409). Solo el autor del reporte: nadie libera lo que bloqueó otro. + def self.reportar(provider:, identificador:, individuo:, estado:, liberar_en_segundos: nil, motivo: nil) + state = leer + entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + raise "Key no encontrada: #{provider}/#{identificador}" unless entrada + + ahora = Time.now + if estado == 'liberada' && entrada['reservado_por'] != individuo && revertible_por?(entrada, individuo, ahora) + entrada['disponible_desde'] = ahora.iso8601(3) + entrada['agotada_por'] = nil + guardar(state) + Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'revertida') + return entrada + end + raise "Key #{provider}/#{identificador} no está reservada por #{individuo}" unless entrada['reservado_por'] == individuo + + case estado + when 'sana' + entrada['reservado_hasta'] = (ahora + RESERVA_TTL_SEGUNDOS).iso8601(3) + when 'liberada' + entrada['reservado_por'] = nil + entrada['reservado_hasta'] = nil + when 'agotada' + reset_segundos = entrada['reset_segundos'] + raise "Key #{provider}/#{identificador} sin reset_segundos persistido — no se puede reportar agotada" unless reset_segundos + + entrada['disponible_desde'] = (ahora + (liberar_en_segundos || reset_segundos)).iso8601(3) + entrada['agotada_por'] = individuo + entrada['motivo_agotada'] = motivo.to_s[0, 200] unless motivo.to_s.empty? + entrada['reservado_por'] = nil + entrada['reservado_hasta'] = nil + Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: individuo, en: ahora, evento: 'agotada') + else + raise "estado inválido: #{estado} (esperado: sana|liberada|agotada)" + end + guardar(state) + entrada + end + + # Liberación por un ADMIN desde nexxa-web (P335/Fase 7): la key queda disponible ya, sin reserva ni marca de + # agotada, sea quien sea que la bloqueó. El rastro queda en usos ('liberada-admin', con el usuario de la web). + def self.liberar_admin(provider:, identificador:, usuario:) + state = leer + entrada = state['keys'].find { |k| k['provider'] == provider && k['identificador'] == identificador } + raise "Key no encontrada: #{provider}/#{identificador}" unless entrada + + ahora = Time.now + entrada['disponible_desde'] = ahora.iso8601(3) if Time.parse(entrada['disponible_desde']) > ahora + entrada['reservado_por'] = nil + entrada['reservado_hasta'] = nil + entrada['agotada_por'] = nil + entrada['motivo_agotada'] = nil + guardar(state) + Nexxa::Usos.registrar(provider: provider, identificador: identificador, individuo: "web:#{usuario}", en: ahora, + evento: 'liberada-admin') + entrada + end + + # ¿individuo puede deshacer el 'agotada' de esta key? Solo si lo reportó él y el bloqueo sigue vigente. + def self.revertible_por?(entrada, individuo, ahora = Time.now) + entrada['agotada_por'] == individuo && Time.parse(entrada['disponible_desde']) > ahora + end + + # Estado del pool de un provider, por key, SIN el valor (P334/Fase 4): para diagnosticar desde un consumidor sin + # entrar a la mini-app. estado: inactiva | agotada | reservada | disponible. + def self.estado_pool(provider, ahora = Time.now) + estado_de(leer['keys'].select { |k| k['provider'] == provider }, ahora) + end + + # Estado de las keys de un pool (P335/Fase 5): mezcla proveedores, por eso cada fila trae su provider. + def self.estado_en(refs, ahora = Time.now) + estado_de(de_refs(refs), ahora) + end + + def self.estado_de(keys, ahora = Time.now) + keys.map do |k| + estado = if k['activo'] == false then 'inactiva' + elsif Time.parse(k['disponible_desde']) > ahora then 'agotada' + elsif k['reservado_hasta'] && Time.parse(k['reservado_hasta']) > ahora then 'reservada' + else 'disponible' + end + { 'provider' => k['provider'], 'identificador' => k['identificador'], 'estado' => estado, + 'libera_en' => (estado == 'agotada' ? k['disponible_desde'] : nil), + 'reservado_por' => (estado == 'reservada' ? k['reservado_por'] : nil), + 'agotada_por' => (estado == 'agotada' ? k['agotada_por'] : nil), + 'motivo' => (estado == 'agotada' ? k['motivo_agotada'] : nil), + 'ultimo_uso' => k['ultimo_uso'], 'ultimo_individuo' => k['ultimo_individuo'] } + end + end + + def self.cifrar(valor) + Nexxa::Cripto.new(Nexxa::MasterKey.cargar!).encrypt(valor) + end + + def self.descifrar(valor_cifrado) + Nexxa::Cripto.new(Nexxa::MasterKey.cargar!).decrypt(valor_cifrado) + end + + # Devuelve la key elegible MENOS USADA RECIENTEMENTE del provider (rotación + # del pool, P204/Fase4, propuesta del Operador) — nil si ninguna es elegible. + # Antes usaba el primer match del array: si la primera key nunca se agotaba, + # las demás no se usaban jamás y quedaban en riesgo de que el proveedor las + # diera de baja por inactividad. min_by sobre ultimo_uso rota el pool solo, + # sin estado adicional (nil = nunca usada, va primero). Elegible = 'activo' + # ausente/true (compat keys viejas), disponible_desde vencido, y + # reservado_hasta ausente/nil/vencido (compat keys pre-P204/Fase3 — la + # reserva vence sola acá, evaluada al consultar, sin limpieza aparte). + def self.disponible(provider) + elegir_libre(leer['keys'].select { |k| k['provider'] == provider }) + end + + # Igual que disponible, pero dentro de un POOL (P335/Fase 4): refs "provider/identificador" que pueden mezclar + # proveedores. La menos usada recientemente entre las libres, sin importar el proveedor. + def self.disponible_en(refs) + elegir_libre(de_refs(refs)) + end + + def self.proxima_en(refs) + de_refs(refs).select { |k| k['activo'] != false }.min_by { |k| Time.parse(k['disponible_desde']) } + end + + def self.de_refs(refs) + refs = Array(refs) + leer['keys'].select { |k| refs.include?("#{k['provider']}/#{k['identificador']}") } + end + + # Criterio ÚNICO de "libre ahora" (activa, no agotada, sin reserva vigente) y de cuál dar (la menos usada). + def self.elegir_libre(keys) + ahora = Time.now + keys + .select do |k| + k['activo'] != false && + Time.parse(k['disponible_desde']) <= ahora && + (k['reservado_hasta'].nil? || Time.parse(k['reservado_hasta']) <= ahora) + end + .min_by { |k| k['ultimo_uso'] ? Time.parse(k['ultimo_uso']) : Time.at(0) } + end + + # Próxima key de un provider a liberarse (para responder explícito, nunca + # silencioso) — también excluye desactivadas, nunca las ofrece como "próxima". + def self.proxima(provider) + leer['keys'] + .select { |k| k['provider'] == provider && k['activo'] != false } + .min_by { |k| Time.parse(k['disponible_desde']) } + end + end +end diff --git a/servicios/nexxa/organismo/lib_tokens.rb b/servicios/nexxa/organismo/lib_tokens.rb new file mode 100644 index 00000000..6f3cbf26 --- /dev/null +++ b/servicios/nexxa/organismo/lib_tokens.rb @@ -0,0 +1,117 @@ +# frozen_string_literal: true + +# lib_tokens.rb — Autenticación por-individuo (D045 §10, P201/Fase2) +# ============================================================================== +# Cada individuo F1 tiene su propio token — generado y guardado en el storage +# de NEXXA, sin dependencia de candados. Se guarda el HASH del token (SHA256), +# nunca el token en sí — mismo principio que un password: no hace falta el +# valor real para VERIFICAR posesión, solo para la emisión inicial (que se +# muestra una única vez al generarlo, nunca se vuelve a mostrar después). +# ============================================================================== + +require 'json' +require 'securerandom' +require 'digest' +require 'time' +require 'openssl' + +module Nexxa + module Tokens + STATE_FILE = File.expand_path('tokens.json', __dir__).freeze + + def self.leer + if File.exist?(STATE_FILE) + JSON.parse(File.read(STATE_FILE)) + else + { 'tokens' => [] } + end + rescue JSON::ParserError + { 'tokens' => [] } + end + + def self.guardar(state) + File.write(STATE_FILE, JSON.pretty_generate(state) + "\n") + File.chmod(0o600, STATE_FILE) + end + + # Genera un token nuevo para un individuo — devuelve el token EN CLARO, + # una única vez (el caller es responsable de entregárselo al individuo y + # nunca volver a mostrarlo). Si el individuo ya tenía token, lo reemplaza + # (rotación simple). + def self.generar(individuo) + token = SecureRandom.hex(32) + state = leer + state['tokens'].reject! { |t| t['individuo'] == individuo } + state['tokens'] << { + 'individuo' => individuo, + 'token_hash' => Digest::SHA256.hexdigest(token), + 'creado' => Time.now.iso8601 + } + guardar(state) + token + end + + # Verifica un token recibido (ej. header Authorization) — devuelve el + # nombre del individuo si es válido, nil si no. Comparación de tiempo + # constante (security-review, P201/Fase2/2.6): comparar hashes con == a + # secas es vulnerable en teoría a timing attacks — OpenSSL.fixed_length_secure_compare + # evita que el tiempo de respuesta filtre en qué byte difiere. + def self.verificar(token) + return nil if token.to_s.strip.empty? + + hash = Digest::SHA256.hexdigest(token) + entrada = leer['tokens'].find do |t| + t['token_hash'].bytesize == hash.bytesize && + OpenSSL.fixed_length_secure_compare(t['token_hash'], hash) + end + entrada && entrada['individuo'] + end + + # Todos los individuos con token registrado — solo metadata (individuo + + # fecha de creación), NUNCA el hash ni el token (P201/Fase3, mismo criterio + # que Registro.todas con valor_cifrado). + def self.listar + leer['tokens'].map { |t| { 'individuo' => t['individuo'], 'creado' => t['creado'] } } + end + + # Revoca el acceso de un individuo — borra su entrada, sin deshacer. El + # individuo necesita un token nuevo (generar) para volver a consultar NEXXA. + def self.revocar(individuo) + state = leer + existia = state['tokens'].reject! { |t| t['individuo'] == individuo } + guardar(state) if existia + !existia.nil? + end + + # Cifrado de punta a punta (P204, "Aplica Pilares" — reemplaza la + # decisión previa de diferirlo): cada individuo registra SU PROPIA clave + # pública RSA — la privada nunca sale del individuo, nunca la ve NEXXA ni + # GEMMA. Self-service: solo el individuo autenticado con SU token puede + # tocar SU propia clave (server.rb lo gatea) — ni siquiera un admin la + # puede setear por otro, porque eso rompería la propiedad de punta a + # punta (si un tercero pudiera registrar la clave pública "en nombre de" + # otro, podría sustituirla por una propia y interceptar). + def self.registrar_clave_publica(individuo:, clave_publica_pem:) + # Validar que es una clave pública RSA válida antes de guardar — falla + # rápido con un error claro en vez de guardar basura silenciosamente. + OpenSSL::PKey::RSA.new(clave_publica_pem) + + state = leer + entrada = state['tokens'].find { |t| t['individuo'] == individuo } + raise "Individuo sin token: #{individuo}" unless entrada + + entrada['clave_publica_pem'] = clave_publica_pem + guardar(state) + true + rescue OpenSSL::PKey::RSAError + raise 'Clave pública inválida — se espera PEM RSA (ej. openssl rsa -pubout)' + end + + # nil si el individuo no registró clave — server.rb cae a texto plano en + # ese caso (compatibilidad, no rompe consumidores que todavía no migraron). + def self.clave_publica(individuo) + entrada = leer['tokens'].find { |t| t['individuo'] == individuo } + entrada && entrada['clave_publica_pem'] + end + end +end diff --git a/servicios/nexxa/organismo/lib_usos.rb b/servicios/nexxa/organismo/lib_usos.rb new file mode 100644 index 00000000..cee533ff --- /dev/null +++ b/servicios/nexxa/organismo/lib_usos.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +# lib_usos.rb — Registro de uso por individuo (P201/Fase3, D045 §11, ME-605 punto 5) +# ============================================================================== +# Trazabilidad de quién recibió qué key y cuándo — separado del dato de origen +# (cuenta_origen, en lib_registro.rb) y separado de registro.json (estado actual) +# para no mezclar "foto del ahora" con "historial acumulado". Append-only, +# JSONL — mismo espíritu que un log de bitácora: se escribe, no se reescribe. +# ============================================================================== + +require 'json' +require 'time' + +module Nexxa + module Usos + LOG_FILE = File.expand_path('usos.log', __dir__).freeze + + # evento (P204/Fase3): 'dispensada' (reserva al entregar la key) o 'agotada' + # (el consumidor reportó agotamiento real) — default compat con llamadas + # previas a Fase3 (todas eran dispensas). + def self.registrar(provider:, identificador:, individuo:, en: Time.now, evento: 'dispensada') + linea = { + 'provider' => provider, + 'identificador' => identificador, + 'individuo' => individuo, + 'evento' => evento, + 'en' => en.iso8601 + } + File.open(LOG_FILE, 'a') { |f| f.puts(linea.to_json) } + end + + # Historial más reciente primero, opcionalmente filtrado por key + def self.historial(provider: nil, identificador: nil, limit: 50) + return [] unless File.exist?(LOG_FILE) + + lineas = File.readlines(LOG_FILE).filter_map do |l| + JSON.parse(l) + rescue JSON::ParserError + nil + end + lineas.select! { |l| l['provider'] == provider } if provider + lineas.select! { |l| l['identificador'] == identificador } if identificador + lineas.last(limit).reverse + end + end +end diff --git a/servicios/nexxa/organismo/nexxa.rb b/servicios/nexxa/organismo/nexxa.rb new file mode 100644 index 00000000..01250eb6 --- /dev/null +++ b/servicios/nexxa/organismo/nexxa.rb @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# nexxa.rb — Entry point del router (uso CLI y, a futuro, canal apids chat) +# Uso: ruby nexxa.rb "disponible gemini" + +require_relative 'router' + +estimulo = ARGV.join(' ') +if estimulo.empty? + puts "Uso: ruby nexxa.rb \"disponible \"" + exit 1 +end + +puts Nexxa::Router.procesar(estimulo) diff --git a/servicios/nexxa/organismo/router.rb b/servicios/nexxa/organismo/router.rb new file mode 100644 index 00000000..bc30d5c2 --- /dev/null +++ b/servicios/nexxa/organismo/router.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +# router.rb — Matching exacto estímulo → estado, cero semántica en runtime +# ============================================================================== +# NEXXA-F1 (P200) — sin LLM en ningún punto (D045 §1/§4). Responde consultas de +# pares vía apids chat con formato fijo, nunca silencioso ante agotamiento. +# ============================================================================== + +require_relative 'lib_registro' + +module Nexxa + module Router + # estimulo esperado: "disponible " (ej. "disponible gemini") + def self.procesar(estimulo) + partes = estimulo.to_s.strip.split(/\s+/) + return "ERROR: estímulo no reconocido — formato esperado: 'disponible '" unless partes[0] == 'disponible' && partes[1] + + provider = partes[1] + key = Nexxa::Registro.disponible(provider) + + if key + "#{provider.upcase}: viva (#{key['identificador']}, cuenta: #{key['cuenta_origen']})" + else + proxima = Nexxa::Registro.proxima(provider) + if proxima + restante = Time.parse(proxima['disponible_desde']) - Time.now + "#{provider.upcase}: agotado, próxima en #{formatear_tiempo(restante)}" + else + "#{provider.upcase}: sin keys registradas" + end + end + end + + def self.formatear_tiempo(segundos) + segundos = [segundos, 0].max + horas = (segundos / 3600).to_i + mins = ((segundos % 3600) / 60).to_i + partes = [] + partes << "#{horas}h" if horas > 0 + partes << "#{mins}m" if mins > 0 + partes.empty? ? '< 1m' : partes.join(' ') + end + end +end diff --git a/servicios/nexxa/organismo/server.rb b/servicios/nexxa/organismo/server.rb new file mode 100644 index 00000000..57e02ccb --- /dev/null +++ b/servicios/nexxa/organismo/server.rb @@ -0,0 +1,915 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# server.rb — Servicio HTTP/API de NEXXA (P201/Fase2-4) +# ============================================================================== +# A diferencia de gemma/tools/docs_web/server.rb y gemma/tools/sala/hub.rb +# (que corren en el MISMO host que nginx, loopback alcanza), NEXXA vive en su +# propio LXC (10.0.10.163) — srvv-proxy (10.0.10.117) le hace proxy_pass +# cross-host, así que necesita escuchar en la interfaz real, no en loopback +# (corregido P201/Fase4 tras el primer 502 real contra nexxa.frlr.utn.edu.ar). +# Sigue sin exposición directa a internet: la LAN 10.0.10.0/24 no es +# ruteable desde afuera, nginx sigue siendo el único gateway público. +# +# Dos superficies de auth, ambas resueltas por NEXXA mismo — sin nginx +# Basic Auth ni credenciales de GEMMA (corrección del Operador, P201/Fase4): +# - GET /disponible/ → individuo F1, token Bearer (lib_tokens.rb); mente|red = SU pool (P335) +# - GET /, GET /keys, GET /consumidores, GET /pools → cualquier usuario logueado (solo lectura) +# - PATCH/DELETE /keys, POST /keys/

//liberar, POST/DELETE /consumidores, POST/DELETE /pools, +# POST /alta, todo /usuarios → solo perfil 'admin' — 'operador' es +# read-only (corrección 2026-08-03: el diseño original dejaba mutar keys/ +# consumidores a cualquier logueado, error — solo /usuarios estaba bien) +# ============================================================================== + +require 'webrick' +require 'json' +require_relative 'lib_registro' +require_relative 'lib_pools' +require_relative 'lib_tokens' +require_relative 'lib_checkins' +require_relative 'lib_auth' +require_relative 'lib_envelope' + +PORT = 4568 +WEB_DIR = File.expand_path('../web', __dir__).freeze +SESSION_COOKIE = 'nexxa_session' + +# Versión semántica real (P204/Fase4, pedido del Operador: "tipo v1.0.1", el +# build stamp por timestamp no se entendía como versión) — vive en el archivo +# VERSION junto a este script, se bumpea a mano en cada deploy con cambios +# reales (mismo criterio que cualquier changelog: subir la versión es una +# decisión de quien publica). Sirve para confirmar en la mini-app que un +# deploy realmente llegó. +# +# Se lee del disco EN CADA REQUEST (self.version, no una constante cacheada +# al arrancar) — a propósito, corrección real (Operador, "hiciste cambios sin +# versionar la app"): un deploy de solo estáticos (HTML/CSS/JS) no reinicia +# el proceso, así que una constante cacheada nunca hubiera reflejado ese +# bump sin reiniciar igual — justo el caso más común. Costo despreciable +# (un archivo de una línea) frente a que el número mienta. +VERSION_FILE = File.expand_path('VERSION', __dir__).freeze +def version_actual + File.read(VERSION_FILE).strip +end + +# Cifrado de punta a punta (P204) — arma el fragmento de respuesta con el +# valor real, cifrado para EL INDIVIDUO SI tiene clave pública registrada, en +# texto plano si no (compatibilidad — un consumidor que todavía no migró a +# su propia clave sigue funcionando, protegido solo por TLS como antes). +# Un solo lugar decide esto — reusado por la dispensa normal y por +# "siguiente" en /reportar, para no repetir el criterio. +def empaquetar_valor(individuo, valor) + clave_publica = Nexxa::Tokens.clave_publica(individuo) + if clave_publica + { valor_cifrado: Nexxa::Envelope.cifrar_para(clave_publica, valor), cifrado: true } + else + { valor: valor, cifrado: false } + end +end + +# Todo reinicio del servicio invalida las sesiones activas (P204/Fase4, pedido +# del Operador) — hace el reinicio visible: quien estaba conectado tiene que +# volver a loguearse, en vez de seguir viendo el panel sin saber si el deploy +# surtió efecto. Sesiones son de por sí efímeras (SESSION_TTL=8h, lib_auth.rb) — +# perderlas en un restart no es una pérdida real, es la señal que se pidió. +Nexxa::Auth.guardar_sesiones({}) + +server = WEBrick::HTTPServer.new( + Port: PORT, + BindAddress: '0.0.0.0', + Logger: WEBrick::Log.new($stdout, WEBrick::Log::INFO), + AccessLog: [[$stdout, WEBrick::AccessLog::COMMON_LOG_FORMAT]] +) + +def individuo_autenticado(req) + auth = req['Authorization'].to_s + return nil unless auth.start_with?('Bearer ') + + Nexxa::Tokens.verificar(auth.sub('Bearer ', '').strip) +end + +# Sesión del Operador (P201/Fase4) — cookie de sesión propia de NEXXA, no +# Basic Auth de nginx. req.cookies ya viene parseado por WEBrick (stdlib). +def token_de_sesion(req) + cookie = req.cookies.find { |c| c.name == SESSION_COOKIE } + cookie&.value +end + +def sesion_actual(req) + Nexxa::Auth.sesion(token_de_sesion(req)) +end + +def operador_autenticado?(req) + !sesion_actual(req).nil? +end + +def admin_autenticado?(req) + sesion_actual(req)&.dig('perfil') == 'admin' +end + +# WEBrick::Cookie (gem webrick 1.8.1) no expone HttpOnly/SameSite — se arma +# el header Set-Cookie a mano para tener las 3 flags recomendadas (OWASP): +# HttpOnly (JS no puede leerla), Secure (solo por HTTPS — nginx termina TLS +# por delante), SameSite=Strict (mitiga CSRF). Leer sigue vía req.cookies +# (eso sí soportado), esto solo afecta cómo se escribe. +def set_cookie_sesion(res, token) + res['Set-Cookie'] = "#{SESSION_COOKIE}=#{token}; Path=/; Max-Age=#{Nexxa::Auth::SESSION_TTL}; HttpOnly; Secure; SameSite=Strict" +end + +def borrar_cookie_sesion(res) + res['Set-Cookie'] = "#{SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict" +end + +def rechazar_no_autenticado(res) + res.status = 401 + res.content_type = 'application/json' + res.body = { error: 'No autenticado' }.to_json +end + +def rechazar_no_admin(res) + res.status = 403 + res.content_type = 'application/json' + res.body = { error: 'Requiere perfil admin' }.to_json +end + +NEXXA_APP_FILE = File.expand_path('index.html', WEB_DIR).freeze +LOGIN_FILE = File.expand_path('login.html', WEB_DIR).freeze + +# GET / — sirve login.html o index.html según la sesión (P201/Fase4). Se lee +# del disco en cada request (mismo criterio que docs_web/server.rb, P164). +server.mount_proc '/' do |req, res| + res.status = 200 + res.content_type = 'text/html; charset=utf-8' + res.body = File.read(operador_autenticado?(req) ? NEXXA_APP_FILE : LOGIN_FILE) +end + +# Estáticos (css/js) — públicos a propósito: login.html los necesita antes de +# autenticar. WEBrick::HTTPServlet::FileHandler es la clase estándar de la +# stdlib para esto (no reinventar servido de estáticos). +server.mount('/css', WEBrick::HTTPServlet::FileHandler, File.join(WEB_DIR, 'css')) +server.mount('/js', WEBrick::HTTPServlet::FileHandler, File.join(WEB_DIR, 'js')) + +# POST /login — body {usuario, password}. Si matchea, crea sesión y devuelve la cookie. +server.mount_proc '/login' do |req, res| + res.content_type = 'application/json' + if req.request_method != 'POST' + res.status = 405 + res.body = { error: 'Método no permitido — usar POST' }.to_json + next + end + + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.body = { error: 'JSON inválido' }.to_json + next + end + + entrada = Nexxa::Auth.autenticar(usuario: body['usuario'], password: body['password']) + if entrada + token = Nexxa::Auth.crear_sesion(entrada['usuario'], entrada['perfil']) + set_cookie_sesion(res, token) + res.status = 200 + res.body = { ok: true, usuario: entrada['usuario'], perfil: entrada['perfil'] }.to_json + else + res.status = 401 + res.body = { error: 'Usuario o password incorrectos' }.to_json + end +end + +# POST /logout — cierra la sesión actual, si había una. +server.mount_proc '/logout' do |req, res| + res.content_type = 'application/json' + Nexxa::Auth.cerrar_sesion(token_de_sesion(req)) + borrar_cookie_sesion(res) + res.status = 200 + res.body = { ok: true }.to_json +end + +# GET /session — quién está logueado ahora (para que el frontend sepa qué +# mostrar, ej. la sección Usuarios solo si perfil admin). +# GET /version — build stamp público (P204/Fase4) — sin auth a propósito, +# mismo criterio que css/js: login.html también necesita mostrarlo, antes de +# autenticar. +server.mount_proc '/version' do |req, res| + res.status = 200 + res.content_type = 'application/json' + res.body = { version: version_actual }.to_json +end + +server.mount_proc '/session' do |req, res| + res.content_type = 'application/json' + sesion = sesion_actual(req) + if sesion + res.status = 200 + res.body = sesion.to_json + else + rechazar_no_autenticado(res) + end +end + +# GET /keys — metadata de todas las keys, NUNCA el valor +# PATCH /keys// — editar cuenta_origen/reset_segundos/activo +# DELETE /keys// — eliminar del registro (destructivo) +# (P201/Fase3-4, D045 §8/§11). Requiere sesión de Operador (lib_auth.rb). +# +# Clase de servlet, no mount_proc: WEBrick::HTTPServlet::ProcHandler (lo que +# usa mount_proc) solo define do_GET/do_POST/do_PUT (ver prochandler.rb) — +# nunca do_DELETE ni do_PATCH, así que un mount_proc con 'case request_method' +# nunca llega a ejecutarse para esos verbos (WEBrick responde 405 antes). +class KeysServlet < WEBrick::HTTPServlet::AbstractServlet + def partes_de(req) + req.path.sub(%r{\A/keys/?}, '').split('/') + end + + def do_GET(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + + res.content_type = 'application/json' + res.status = 200 + res.body = Nexxa::Registro.todas.to_json + end + + # POST /keys///liberar — admin libera una key agotada o reservada (P335/Fase 7) + def do_POST(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + partes = partes_de(req) + unless partes.size == 3 && partes[2] == 'liberar' + res.status = 400 + res.body = { error: 'Uso: POST /keys///liberar' }.to_json + return + end + + Nexxa::Registro.liberar_admin(provider: partes[0], identificador: partes[1], usuario: sesion_actual(req)['usuario']) + res.status = 200 + res.body = { ok: true, provider: partes[0], identificador: partes[1] }.to_json + rescue RuntimeError => e + res.status = 404 + res.body = { error: e.message }.to_json + end + + def do_PATCH(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + partes = partes_de(req) + if partes.size != 2 + res.status = 400 + res.body = { error: 'Uso: PATCH /keys//' }.to_json + return + end + + provider, identificador = partes + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.body = { error: 'JSON inválido' }.to_json + return + end + + begin + entrada = Nexxa::Registro.actualizar( + provider: provider, + identificador: identificador, + cuenta_origen: body['cuenta_origen'], + reset_segundos: body['reset_segundos']&.to_i, + activo: body.key?('activo') ? body['activo'] : nil + ) + res.status = 200 + res.body = entrada.reject { |k, _| k == 'valor_cifrado' }.to_json + rescue RuntimeError => e + res.status = 404 + res.body = { error: e.message }.to_json + end + end + + def do_DELETE(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + partes = partes_de(req) + if partes.size != 2 + res.status = 400 + res.body = { error: 'Uso: DELETE /keys//' }.to_json + return + end + + provider, identificador = partes + borrado = Nexxa::Registro.eliminar(provider: provider, identificador: identificador) + Nexxa::Pools.olvidar_key(provider: provider, identificador: identificador) if borrado # sin refs colgadas (P335) + if borrado + res.status = 200 + res.body = { ok: true }.to_json + else + res.status = 404 + res.body = { error: 'Key no encontrada' }.to_json + end + end +end + +server.mount '/keys', KeysServlet + +# /pools — pools por individuo (P335/Fase 5): GET para cualquier operador (estado de cada key, nunca valores); +# asignar/quitar solo admin (ME-682/ME-683, gate explícito en cada escritura). +# GET /pools +# POST /pools// body {provider, identificador} +# DELETE /pools//// +class PoolsServlet < WEBrick::HTTPServlet::AbstractServlet + def partes_de(req) + req.path.sub(%r{\A/pools/?}, '').split('/') + end + + def responder(res, status, cuerpo) + res.status = status + res.content_type = 'application/json' + res.body = cuerpo.to_json + end + + def do_GET(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + + responder(res, 200, { roles: Nexxa::Pools::ROLES, individuos: Nexxa::Pools.con_estado }) + end + + def do_POST(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + partes = partes_de(req) + return responder(res, 400, { error: 'Uso: POST /pools// {provider, identificador}' }) if partes.size != 2 + + body = begin + JSON.parse(req.body.to_s) + rescue JSON::ParserError + return responder(res, 400, { error: 'JSON inválido' }) + end + pool = Nexxa::Pools.asignar(individuo: partes[0], rol: partes[1], + provider: body['provider'].to_s, identificador: body['identificador'].to_s) + responder(res, 200, { individuo: partes[0], rol: partes[1], pool: pool }) + rescue RuntimeError => e + responder(res, 400, { error: e.message }) + end + + def do_DELETE(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + partes = partes_de(req) + return responder(res, 400, { error: 'Uso: DELETE /pools////' }) if partes.size != 4 + + quitada = Nexxa::Pools.quitar(individuo: partes[0], rol: partes[1], provider: partes[2], identificador: partes[3]) + quitada ? responder(res, 200, { ok: true }) : responder(res, 404, { error: 'La key no está en ese pool' }) + rescue RuntimeError => e + responder(res, 400, { error: e.message }) + end +end +server.mount '/pools', PoolsServlet + +# GET /usos — historial de eventos (dispensada/agotada) para la mini-app (P204/Fase4). +# Read-only, mismo criterio de auth que GET /keys (cualquier operador logueado). +# Usos.historial ya existía (P201/Fase3) — nunca se había montado por HTTP. +server.mount_proc '/usos' do |req, res| + next rechazar_no_autenticado(res) unless operador_autenticado?(req) + + res.status = 200 + res.content_type = 'application/json' + res.body = Nexxa::Usos.historial(limit: 100).to_json +end + +# GET /consumidores — individuos con token registrado (metadata) +# POST /consumidores — genera/rota token para un individuo, body +# {individuo} — el token en claro se entrega +# UNA VEZ en la respuesta (mismo criterio que +# el alta de una key: se muestra al crear, +# nunca más — el Operador lo guarda en +# candados o se lo entrega al individuo) +# DELETE /consumidores/ — revoca el acceso (destructivo) +# (P201/Fase3-4). Requiere sesión de Operador (lib_auth.rb). +class ConsumidoresServlet < WEBrick::HTTPServlet::AbstractServlet + def individuo_de(req) + req.path.sub(%r{\A/consumidores/?}, '') + end + + def do_GET(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + + res.content_type = 'application/json' + res.status = 200 + res.body = Nexxa::Tokens.listar.to_json + end + + def do_POST(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.body = { error: 'JSON inválido' }.to_json + return + end + + individuo = body['individuo'].to_s.strip + if individuo.empty? + res.status = 400 + res.body = { error: 'Falta "individuo"' }.to_json + return + end + + token = Nexxa::Tokens.generar(individuo) + res.status = 201 + res.body = { individuo: individuo, token: token }.to_json + end + + def do_DELETE(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + individuo = individuo_de(req) + if individuo.empty? + res.status = 400 + res.body = { error: 'Uso: DELETE /consumidores/' }.to_json + return + end + + revocado = Nexxa::Tokens.revocar(individuo) + if revocado + res.status = 200 + res.body = { ok: true }.to_json + else + res.status = 404 + res.body = { error: 'Individuo no encontrado' }.to_json + end + end +end + +server.mount '/consumidores', ConsumidoresServlet + +# GET /usuarios — metadata de todos los usuarios del panel +# POST /usuarios — alta, body {usuario, password, perfil} +# PATCH /usuarios/ — editar perfil/activo/password, body {perfil, activo, password} +# DELETE /usuarios/ — eliminar (destructivo) +# (P201/Fase4, corrección del Operador) — gateado a perfil 'admin', no alcanza +# con estar logueado. Guardia de negocio: nunca desactivar/degradar/borrar al +# último admin activo — dejaría el panel sin nadie que pueda gestionar usuarios. +class UsuariosServlet < WEBrick::HTTPServlet::AbstractServlet + def usuario_de(req) + req.path.sub(%r{\A/usuarios/?}, '') + end + + def do_GET(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + res.status = 200 + res.body = Nexxa::Auth.listar.to_json + end + + def do_POST(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.body = { error: 'JSON inválido' }.to_json + return + end + + faltantes = %w[usuario password perfil].reject { |k| body[k].to_s.strip != '' } + if faltantes.any? + res.status = 400 + res.body = { error: "Faltan campos: #{faltantes.join(', ')}" }.to_json + return + end + + begin + Nexxa::Auth.crear_usuario(usuario: body['usuario'], password: body['password'], perfil: body['perfil']) + res.status = 201 + res.body = { ok: true, usuario: body['usuario'], perfil: body['perfil'] }.to_json + rescue RuntimeError => e + res.status = 409 + res.body = { error: e.message }.to_json + end + end + + def do_PATCH(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + usuario = usuario_de(req) + if usuario.empty? + res.status = 400 + res.body = { error: 'Uso: PATCH /usuarios/' }.to_json + return + end + + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.body = { error: 'JSON inválido' }.to_json + return + end + + # Guardia: no degradar/desactivar al último admin activo. + degradando = (body.key?('perfil') && body['perfil'] != 'admin') || body['activo'] == false + if degradando + actual = Nexxa::Auth.listar.find { |u| u['usuario'] == usuario } + if actual && actual['perfil'] == 'admin' && actual['activo'] != false && Nexxa::Auth.admins_activos <= 1 + res.status = 409 + res.body = { error: 'No se puede desactivar/degradar al último admin activo' }.to_json + return + end + end + + begin + entrada = Nexxa::Auth.actualizar( + usuario: usuario, + perfil: body['perfil'], + activo: body.key?('activo') ? body['activo'] : nil, + password_nueva: body['password'] + ) + res.status = 200 + res.body = entrada.to_json + rescue RuntimeError => e + res.status = 404 + res.body = { error: e.message }.to_json + end + end + + def do_DELETE(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + res.content_type = 'application/json' + usuario = usuario_de(req) + if usuario.empty? + res.status = 400 + res.body = { error: 'Uso: DELETE /usuarios/' }.to_json + return + end + + actual = Nexxa::Auth.listar.find { |u| u['usuario'] == usuario } + if actual && actual['perfil'] == 'admin' && actual['activo'] != false && Nexxa::Auth.admins_activos <= 1 + res.status = 409 + res.body = { error: 'No se puede eliminar al último admin activo' }.to_json + return + end + + borrado = Nexxa::Auth.eliminar(usuario) + if borrado + res.status = 200 + res.body = { ok: true }.to_json + else + res.status = 404 + res.body = { error: 'Usuario no encontrado' }.to_json + end + end +end + +server.mount '/usuarios', UsuariosServlet + +# GET /disponible/ — entrega el valor real al individuo autenticado +# (Regla 15: sistema-a-sistema, no exposición a un humano — D045 §8/§10). +# Cifrado de punta a punta (P204, ver empaquetar_valor/lib_envelope.rb): si el +# individuo registró clave pública (POST /consumidor/clave-publica), el +# valor va cifrado con SU clave — ni TLS ni NEXXA ven el texto plano en el +# cuerpo de la respuesta, solo el individuo con su privada. Sin clave +# registrada, cae a texto plano protegido solo por TLS (compatibilidad). +# POST /disponible//reportar — salud real de keys (P204/Fase3, D045 +# §8): el consumidor, no NEXXA, reporta si la key sigue sana, si la libera +# antes de tiempo, o si se agotó de verdad contra el proveedor real. +# P335/Fase 5: puede ser un ROL (mente|red) → el pool de ESE individuo, que mezcla proveedores; si no, es un +# provider como siempre. La decisión vive en Nexxa::Pools (disponible/proxima/estado), no acá. +server.mount_proc '/disponible' do |req, res| + individuo = individuo_autenticado(req) + if individuo.nil? + res.status = 401 + res.content_type = 'application/json' + res.body = { error: 'Token inválido o ausente (header Authorization: Bearer )' }.to_json + next + end + + resto = req.path.sub(%r{\A/disponible/?}, '') + + if req.request_method == 'POST' && resto.end_with?('/reportar') + nombre = resto.sub(%r{/reportar\z}, '') + if nombre.empty? + res.status = 400 + res.content_type = 'application/json' + res.body = { error: 'Uso: POST /disponible//reportar' }.to_json + next + end + + body = begin + JSON.parse(req.body.to_s) + rescue JSON::ParserError + {} + end + identificador = body['identificador'] + estado = body['estado'] + liberar_en_segundos = body['liberar_en_segundos'] + # En un rol el pool mezcla proveedores: la key se identifica con provider + identificador (la que se recibió). + provider = Nexxa::Pools.rol?(nombre) ? body['provider'].to_s : nombre + + unless identificador && !provider.empty? && %w[sana liberada agotada].include?(estado) + res.status = 400 + res.content_type = 'application/json' + res.body = { error: 'Body esperado: {identificador, estado: sana|liberada|agotada, liberar_en_segundos?, motivo?} ' \ + '(+ provider si se reporta por rol mente|red)' }.to_json + next + end + + begin + Nexxa::Registro.reportar( + provider: provider, identificador: identificador, individuo: individuo, + estado: estado, liberar_en_segundos: liberar_en_segundos, motivo: body['motivo'] + ) + rescue StandardError => e + res.status = 409 + res.content_type = 'application/json' + res.body = { error: e.message }.to_json + next + end + + resp = { provider: provider, identificador: identificador, estado: estado } + + if estado == 'agotada' + siguiente = Nexxa::Pools.disponible(individuo, nombre) # del mismo pool (rol) o del mismo provider + if siguiente + sp = siguiente['provider'] + valor_siguiente = Nexxa::Registro.revelar(provider: sp, identificador: siguiente['identificador']) + if valor_siguiente + Nexxa::Registro.reservar(provider: sp, identificador: siguiente['identificador'], individuo: individuo) + resp[:siguiente] = { provider: sp, identificador: siguiente['identificador'] }.merge(empaquetar_valor(individuo, valor_siguiente)) + end + end + end + + res.status = 200 + res.content_type = 'application/json' + res.body = resp.to_json + next + end + + # GET /disponible//estado (P334/Fase 4): estado del pool por key, nunca el valor. Mismo gate que el + # resto de /disponible (token de individuo, ME-683): solo metadata para diagnosticar. + if req.request_method == 'GET' && resto.end_with?('/estado') + nombre = resto.sub(%r{/estado\z}, '') + res.status = nombre.empty? ? 400 : 200 + res.content_type = 'application/json' + res.body = if nombre.empty? + { error: 'Uso: GET /disponible//estado' }.to_json + elsif Nexxa::Pools.rol?(nombre) + { individuo: individuo, rol: nombre, keys: Nexxa::Pools.estado(individuo, nombre) }.to_json + else + { provider: nombre, keys: Nexxa::Pools.estado(individuo, nombre) }.to_json + end + next + end + + nombre = resto + if nombre.empty? + res.status = 400 + res.content_type = 'application/json' + res.body = { error: 'Uso: GET /disponible/' }.to_json + next + end + + # Pool vacío: explícito, nunca cae al provider (el admin todavía no le asignó keys a ese individuo en ese rol) + if Nexxa::Pools.pool_vacio?(individuo, nombre) + res.status = 404 + res.content_type = 'application/json' + res.body = { error: 'pool_vacio', individuo: individuo, rol: nombre }.to_json + next + end + + donde = Nexxa::Pools.rol?(nombre) ? { rol: nombre } : { provider: nombre } + key = Nexxa::Pools.disponible(individuo, nombre) + if key.nil? + proxima = Nexxa::Pools.proxima(individuo, nombre) + res.status = 404 + res.content_type = 'application/json' + res.body = if proxima + { error: 'agotado', proxima_disponible: proxima['disponible_desde'] }.merge(donde).to_json + else + { error: 'sin_keys_registradas' }.merge(donde).to_json + end + next + end + provider = key['provider'] + + # dry_run (P204, prp08 §"verificar sin consumir"): confirmar disponibilidad sin + # dispensar el valor ni marcar uso — nunca incluye 'valor' en la respuesta, + # pensado para health-check/verificación (evita que probar el mecanismo + # requiera recibir el secreto — ver incidente de sesión, ME-631). + if req.query['dry_run'] + res.status = 200 + res.content_type = 'application/json' + res.body = { provider: provider, identificador: key['identificador'], disponible: true }.to_json + next + end + + valor = Nexxa::Registro.revelar(provider: provider, identificador: key['identificador']) + if valor.nil? + # Key registrada solo como metadata (no migrada todavía, D045 §9→§10) — + # respuesta explícita, nunca silenciosa (mismo criterio que router.rb) + res.status = 409 + res.content_type = 'application/json' + res.body = { error: 'sin_valor_migrado', provider: provider, identificador: key['identificador'] }.to_json + next + end + + # Reserva corta de contención (P204/Fase3, D045 §8) — ya no asume agotamiento + # completo al dispensar (eso lo decide el consumidor vía POST .../reportar); + # solo evita que 2 consumidores reciban la misma key mientras uno la prueba. + Nexxa::Registro.reservar(provider: provider, identificador: key['identificador'], individuo: individuo) + + res.status = 200 + res.content_type = 'application/json' + res.body = { provider: provider, identificador: key['identificador'] }.merge(empaquetar_valor(individuo, valor)).to_json +end + +# POST /consumidor/clave-publica — cifrado de punta a punta (P204): el +# individuo registra SU PROPIA clave pública RSA (PEM), self-service — solo +# puede tocar la suya (individuo_autenticado la resuelve por su propio +# token, no hay parámetro "para quién" que alguien pueda falsear). La +# privada nunca llega a NEXXA, ni siquiera de paso — el individuo la genera +# y se la guarda él mismo, acá solo entra la mitad pública. +server.mount_proc '/consumidor/clave-publica' do |req, res| + individuo = individuo_autenticado(req) + if individuo.nil? + res.status = 401 + res.content_type = 'application/json' + res.body = { error: 'Token inválido o ausente (header Authorization: Bearer )' }.to_json + next + end + + if req.request_method != 'POST' + res.status = 405 + res.content_type = 'application/json' + res.body = { error: 'Uso: POST /consumidor/clave-publica {clave_publica: "-----BEGIN PUBLIC KEY-----..."}' }.to_json + next + end + + body = begin + JSON.parse(req.body.to_s) + rescue JSON::ParserError + {} + end + + begin + Nexxa::Tokens.registrar_clave_publica(individuo: individuo, clave_publica_pem: body['clave_publica'].to_s) + rescue StandardError => e + res.status = 400 + res.content_type = 'application/json' + res.body = { error: e.message }.to_json + next + end + + res.status = 200 + res.content_type = 'application/json' + res.body = { ok: true, individuo: individuo }.to_json +end + +# POST /alta — alta de una key nueva, JSON {provider, identificador, cuenta_origen, +# reset_segundos, valor}. Requiere perfil admin (operador es solo-lectura). +server.mount_proc '/alta' do |req, res| + if req.request_method != 'POST' + res.status = 405 + res.content_type = 'application/json' + res.body = { error: 'Método no permitido — usar POST' }.to_json + next + end + + unless operador_autenticado?(req) + rechazar_no_autenticado(res) + next + end + unless admin_autenticado?(req) + rechazar_no_admin(res) + next + end + + begin + body = JSON.parse(req.body) + rescue JSON::ParserError + res.status = 400 + res.content_type = 'application/json' + res.body = { error: 'JSON inválido' }.to_json + next + end + + faltantes = %w[provider identificador cuenta_origen reset_segundos valor].reject { |k| body[k] } + if faltantes.any? + res.status = 400 + res.content_type = 'application/json' + res.body = { error: "Faltan campos: #{faltantes.join(', ')}" }.to_json + next + end + + Nexxa::Registro.registrar( + provider: body['provider'], + identificador: body['identificador'], + cuenta_origen: body['cuenta_origen'], + reset_segundos: body['reset_segundos'].to_i, + valor: body['valor'] + ) + + res.status = 201 + res.content_type = 'application/json' + res.body = { ok: true, provider: body['provider'], identificador: body['identificador'] }.to_json +end + +# /checkin — reporte proactivo de estado de individuos F1 (P216). Mismo +# patrón de auth que /disponible: individuo_autenticado(req) — el token YA +# identifica quién reporta, nunca se confía en un id del body/path para +# escribir. Consultar (GET) exige token válido igual (cualquier consumidor +# logueado por Bearer, no solo el propio individuo) — es diagnóstico +# compartido entre el equipo F1, no un dato privado de cada uno. +server.mount_proc '/checkin' do |req, res| + individuo = individuo_autenticado(req) + if individuo.nil? + res.status = 401 + res.content_type = 'application/json' + res.body = { error: 'Token inválido o ausente (header Authorization: Bearer )' }.to_json + next + end + + resto = req.path.sub(%r{\A/checkin/?}, '') + + if req.request_method == 'POST' && resto.empty? + body = begin + JSON.parse(req.body.to_s) + rescue JSON::ParserError + {} + end + estado = body['estado'] + if estado.to_s.strip.empty? + res.status = 400 + res.content_type = 'application/json' + res.body = { error: "Uso: POST /checkin {estado: '...', detalle: '...' (opcional)}" }.to_json + next + end + + registro = Nexxa::Checkins.registrar(individuo, estado: estado, detalle: body['detalle']) + res.status = 201 + res.content_type = 'application/json' + res.body = { ok: true, individuo: individuo }.merge(registro).to_json + next + end + + if req.request_method == 'GET' && !resto.empty? + registro = Nexxa::Checkins.estado(resto) + if registro.nil? + res.status = 404 + res.content_type = 'application/json' + res.body = { error: "Sin check-in registrado para '#{resto}'" }.to_json + next + end + res.content_type = 'application/json' + res.body = { individuo: resto }.merge(registro).to_json + next + end + + res.status = 404 + res.content_type = 'application/json' + res.body = { error: 'Uso: POST /checkin (reportar propio estado) | GET /checkin/ (consultar)' }.to_json +end + +# /checkins (bulk) — P216/Fase4: todos los check-in en una sola respuesta, +# consumida por el FRONTEND del panel (cookie de sesión del Operador, mismo +# mecanismo que /consumidores — operador_autenticado?, NO individuo_autenticado +# que exige Bearer token de individuo F1). Bug real corregido en el camino: la +# primera versión exigía Bearer, el JS nunca lo manda, devolvía 401 en loop +# con el interceptor global de fetch que recarga la página en cualquier 401. +server.mount_proc '/checkins' do |req, res| + unless operador_autenticado?(req) + res.status = 401 + res.content_type = 'application/json' + res.body = { error: 'Sesión inválida o expirada' }.to_json + next + end + + res.content_type = 'application/json' + res.body = Nexxa::Checkins.listar.to_json +end + +trap('INT') { server.shutdown } +trap('TERM') { server.shutdown } +server.start diff --git a/servicios/nexxa/organismo/tool_humo_pool.rb b/servicios/nexxa/organismo/tool_humo_pool.rb new file mode 100644 index 00000000..0773d4c6 --- /dev/null +++ b/servicios/nexxa/organismo/tool_humo_pool.rb @@ -0,0 +1,245 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# tool_humo_pool.rb — Pool de tests de humo: rotación + salud + mecanismo de +# reserva/reporte (P204/Fase3-4) +# ============================================================================== +# Formaliza las verificaciones ad-hoc hechas durante P204 (pedido del Operador: +# re-correrlas cuando se toque el mecanismo de nuevo, no reinventarlas cada +# vez). Corre LOCAL contra lib_registro.rb — sin pasar por HTTP/server.rb, mismo +# criterio que las pruebas aisladas de Fase 3. +# +# Todo lo destructivo (reserva, rotación, reportar) usa un provider/keys +# DESCARTABLES ('selftest', nunca un provider real) — nunca toca keys reales +# ni su estado. La única sección de solo-lectura ("salud actual") sí lee el +# registro real, pero nunca dispensa ni reserva nada (mismo espíritu que +# dry_run) — reporta el estado tal cual está, no lo cambia. +# ============================================================================== +# Uso: ruby tool_humo_pool.rb (correr como usuario 'nexxa' — dueño de +# registro.json — o con permisos de lectura/ +# escritura sobre él) +# ============================================================================== + +require_relative 'lib_registro' +require_relative 'lib_tokens' +require_relative 'lib_envelope' +require 'openssl' +require 'base64' + +PROVIDER_TEST = 'selftest' +INDIVIDUO_TEST = 'selftest' + +$fallas = 0 +$total = 0 + +def test(nombre) + $total += 1 + yield + puts " ✅ #{nombre}" +rescue StandardError => e + $fallas += 1 + puts " ❌ #{nombre} — #{e.class}: #{e.message}" +end + +def assert(cond, msg) + raise msg unless cond +end + +def limpiar_provider_test + Nexxa::Registro.leer['keys'] + .select { |k| k['provider'] == PROVIDER_TEST } + .each { |k| Nexxa::Registro.eliminar(provider: PROVIDER_TEST, identificador: k['identificador']) } +end + +puts "\n🧪 Pool de tests NEXXA — rotación + salud + reserva/reporte (P204)\n\n" + +# ------------------------------------------------------------------ +puts '→ Salud actual (solo lectura, keys REALES — nunca dispensa)' +ahora = Time.now +providers_reales = Nexxa::Registro.leer['keys'].map { |k| k['provider'] }.uniq + +test('lee el registro real sin explotar') do + assert(Nexxa::Registro.leer.is_a?(Hash), 'leer() no devolvió un Hash') +end + +providers_reales.each do |provider| + keys = Nexxa::Registro.leer['keys'].select { |k| k['provider'] == provider } + keys.each do |k| + agotada = Time.parse(k['disponible_desde']) > ahora + reservada = !agotada && k['reservado_hasta'] && Time.parse(k['reservado_hasta']) > ahora + estado = if k['activo'] == false then 'desactivada' + elsif agotada then 'agotada' + elsif reservada then 'reservada' + else 'disponible' + end + icono = { 'disponible' => '🟢', 'reservada' => '🔵', 'agotada' => '🔴', 'desactivada' => '⚪' }[estado] + puts " #{icono} #{provider}/#{k['identificador']}: #{estado}" + end +end + +# ------------------------------------------------------------------ +puts "\n→ Mecanismo de reserva/reporte (provider descartable '#{PROVIDER_TEST}')" +limpiar_provider_test + +Nexxa::Registro.registrar(provider: PROVIDER_TEST, identificador: 'k1', cuenta_origen: 'test', reset_segundos: 3) + +test('key recén registrada está disponible') do + assert(Nexxa::Registro.disponible(PROVIDER_TEST), 'no debería estar nil') +end + +test('reservar bloquea la key para otros consumidores') do + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA') + assert(Nexxa::Registro.disponible(PROVIDER_TEST).nil?, 'sigue apareciendo disponible con reserva activa') +end + +test('reportar rechaza a un individuo que no tiene la reserva') do + begin + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testB', estado: 'sana') + raise 'no lanzó excepción' + rescue RuntimeError + # esperado + end +end + +test("estado 'sana' renueva la reserva (sigue no disponible)") do + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA', estado: 'sana') + assert(Nexxa::Registro.disponible(PROVIDER_TEST).nil?, 'debería seguir reservada tras "sana"') +end + +test("estado 'liberada' libera de inmediato") do + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA', estado: 'liberada') + assert(Nexxa::Registro.disponible(PROVIDER_TEST), 'debería estar disponible tras "liberada"') +end + +test("estado 'agotada' con liberar_en_segundos aplica el valor custom, no reset_segundos") do + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA') + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA', estado: 'agotada', liberar_en_segundos: 2) + assert(Nexxa::Registro.disponible(PROVIDER_TEST).nil?, 'debería estar agotada inmediatamente después') + sleep 2.2 + assert(Nexxa::Registro.disponible(PROVIDER_TEST), 'debería liberarse tras los 2s custom') +end + +test('reserva sin ningún reporte vence sola (pasivo)') do + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: 'k1', individuo: 'testA') + state = Nexxa::Registro.leer + entrada = state['keys'].find { |k| k['identificador'] == 'k1' } + entrada['reservado_hasta'] = (Time.now - 1).iso8601(3) + Nexxa::Registro.guardar(state) + assert(Nexxa::Registro.disponible(PROVIDER_TEST), 'debería estar libre con reserva vencida') +end + +# ------------------------------------------------------------------ +puts "\n→ Rotación del pool (menos usada recientemente, no siempre la primera)" +limpiar_provider_test + +%w[k1 k2 k3].each { |id| Nexxa::Registro.registrar(provider: PROVIDER_TEST, identificador: id, cuenta_origen: 'test', reset_segundos: 100) } + +# ultimo_uso explícito y bien separado (determinismo — 3 registrar() seguidos +# pueden empatar en el mismo milisegundo según qué tan rápido corra la CPU/ +# disco, sin relación con el mecanismo real que se está probando) +state = Nexxa::Registro.leer +base = Time.now - 30 +%w[k1 k2 k3].each_with_index do |id, i| + entrada = state['keys'].find { |k| k['provider'] == PROVIDER_TEST && k['identificador'] == id } + entrada['ultimo_uso'] = (base + i).iso8601(3) +end +Nexxa::Registro.guardar(state) + +test('6 pedidos seguidos rotan k1→k2→k3→k1→k2→k3, sin repetir de corrido') do + orden = [] + 6.times do + k = Nexxa::Registro.disponible(PROVIDER_TEST) + orden << k['identificador'] + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: k['identificador'], individuo: 'rot') + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: k['identificador'], individuo: 'rot', estado: 'liberada') + # separación real entre picks — evita empates de milisegundo entre + # reservar() consecutivos en un loop apretado (nunca pasa en uso real: + # nadie dispensa+reporta 2 keys en el mismo milisegundo) + sleep 0.01 + end + esperado = %w[k1 k2 k3 k1 k2 k3] + assert(orden == esperado, "orden real: #{orden.join('→')} (esperado: #{esperado.join('→')})") +end + +test('una key agotada no entra en la rotación hasta liberarse') do + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: 'k2', individuo: 'rot') + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: 'k2', individuo: 'rot', estado: 'agotada', liberar_en_segundos: 999) + 3.times do + k = Nexxa::Registro.disponible(PROVIDER_TEST) + assert(k['identificador'] != 'k2', 'k2 no debería salir elegida estando agotada') + Nexxa::Registro.reservar(provider: PROVIDER_TEST, identificador: k['identificador'], individuo: 'rot') + Nexxa::Registro.reportar(provider: PROVIDER_TEST, identificador: k['identificador'], individuo: 'rot', estado: 'liberada') + end +end + +limpiar_provider_test + +# ------------------------------------------------------------------ +puts "\n→ Cifrado de punta a punta (P204, envelope RSA-OAEP)" + +def limpiar_individuo_test + state = Nexxa::Tokens.leer + state['tokens'].reject! { |t| t['individuo'] == INDIVIDUO_TEST } + Nexxa::Tokens.guardar(state) +end + +limpiar_individuo_test +Nexxa::Tokens.generar(INDIVIDUO_TEST) +par_test = OpenSSL::PKey::RSA.generate(2048) + +test('registrar_clave_publica guarda y releer coincide exacto') do + Nexxa::Tokens.registrar_clave_publica(individuo: INDIVIDUO_TEST, clave_publica_pem: par_test.public_key.to_pem) + assert(Nexxa::Tokens.clave_publica(INDIVIDUO_TEST) == par_test.public_key.to_pem, 'la clave releída no coincide con la guardada') +end + +test('rechaza una clave pública inválida (no PEM)') do + begin + Nexxa::Tokens.registrar_clave_publica(individuo: INDIVIDUO_TEST, clave_publica_pem: 'no es una clave') + raise 'no lanzó excepción' + rescue RuntimeError + # esperado + end +end + +test('rechaza registrar clave para un individuo sin token') do + begin + Nexxa::Tokens.registrar_clave_publica(individuo: 'no-existe-de-verdad', clave_publica_pem: par_test.public_key.to_pem) + raise 'no lanzó excepción' + rescue RuntimeError + # esperado + end +end + +test('Envelope.cifrar_para produce algo distinto del valor real') do + valor = 'valor-de-prueba-no-es-un-secreto-real' + cifrado = Nexxa::Envelope.cifrar_para(par_test.public_key.to_pem, valor) + assert(cifrado != valor, 'el cifrado es igual al valor real — no cifró nada') +end + +test('round-trip: cifrar con la pública + descifrar con la privada = valor original') do + valor = 'valor-de-prueba-no-es-un-secreto-real' + cifrado = Nexxa::Envelope.cifrar_para(par_test.public_key.to_pem, valor) + descifrado = par_test.private_decrypt(Base64.strict_decode64(cifrado), OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING) + assert(descifrado == valor, "descifrado (#{descifrado.inspect}) no coincide con el original") +end + +test('la clave pública sola NO alcanza para descifrar (asimetría real)') do + valor = 'valor-de-prueba-no-es-un-secreto-real' + cifrado = Nexxa::Envelope.cifrar_para(par_test.public_key.to_pem, valor) + begin + par_test.public_decrypt(Base64.strict_decode64(cifrado)) + raise 'se pudo descifrar solo con la pública — esto NO debería pasar' + rescue OpenSSL::PKey::RSAError + # esperado — confirma que es asimétrico de verdad + end +end + +test('sin clave pública registrada, empaquetar_valor cae a texto plano (compatibilidad)') do + assert(Nexxa::Tokens.clave_publica('individuo-sin-clave-nunca-registrada').nil?, 'debería ser nil para un individuo sin clave') +end + +limpiar_individuo_test + +# ------------------------------------------------------------------ +puts "\n#{$fallas.zero? ? '✅' : '❌'} #{$total - $fallas}/#{$total} tests OK\n\n" +exit($fallas.zero? ? 0 : 1) diff --git a/servicios/nexxa/test/humo_http_test.rb b/servicios/nexxa/test/humo_http_test.rb new file mode 100644 index 00000000..0a80dd7f --- /dev/null +++ b/servicios/nexxa/test/humo_http_test.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# humo_http_test.rb — Humo HTTP REAL del server de NEXXA sobre una copia aislada (P335/Fase 5). +# El server de prueba lo arma lib_servidor_prueba.rb (copia aislada, estado falso, 127.0.0.1). Nunca toca el nodo +# ni secretos reales. Correr después de cada cambio de la API: ruby servicios/nexxa/test/humo_http_test.rb +require 'minitest/autorun' +require 'net/http' +require 'json' +require 'time' +require_relative 'lib_servidor_prueba' + +PRUEBA = ServidorPrueba.armar(individuos: %w[gemma-humo liberar-humo]) +PUERTO = PRUEBA[:puerto] +TOKEN_IND = PRUEBA[:tokens]['gemma-humo'] +TOKEN_LIB = PRUEBA[:tokens]['liberar-humo'] # individuo propio del test de liberar: no comparte estado +PID = ServidorPrueba.arrancar(PRUEBA) +Minitest.after_run { ServidorPrueba.detener(PID, PRUEBA) } + +# El server invalida las sesiones al arrancar (P204): se entra por /login, como un usuario real. +def login(usuario) + password = ServidorPrueba::USUARIOS.fetch(usuario).first + r = Net::HTTP.post(URI("http://127.0.0.1:#{PUERTO}/login"), { usuario: usuario, password: password }.to_json, + 'Content-Type' => 'application/json') + r['Set-Cookie'].to_s[/nexxa_session=([0-9a-f]+)/, 1] or raise "login de #{usuario} falló: #{r.code} #{r.body}" +end +SES_ADMIN = login('humo-admin') +SES_OPER = login('humo-oper') + +class HumoHttpTest < Minitest::Test + def pedir(metodo, ruta, cuerpo: nil, sesion: nil, token: nil) + req = Net::HTTP.const_get(metodo.capitalize).new(ruta) + req['Cookie'] = "nexxa_session=#{sesion}" if sesion + req['Authorization'] = "Bearer #{token}" if token + if cuerpo + req['Content-Type'] = 'application/json' + req.body = cuerpo.to_json + end + r = Net::HTTP.start('127.0.0.1', PUERTO) { |h| h.request(req) } + [r.code.to_i, (JSON.parse(r.body) rescue r.body)] + end + + def test_ciclo_pools_y_disponible_por_rol + # sin pool asignado: explícito, nunca cae al provider + assert_equal [404, 'pool_vacio'], pedir('get', '/disponible/mente', token: TOKEN_IND).then { |c, b| [c, b['error']] } + # operador lee pero no asigna; admin asigna + assert_equal 403, pedir('post', '/pools/gemma-humo/mente', cuerpo: { provider: 'deepseek', identificador: 'd-01' }, sesion: SES_OPER)[0] + assert_equal 200, pedir('post', '/pools/gemma-humo/mente', cuerpo: { provider: 'deepseek', identificador: 'd-01' }, sesion: SES_ADMIN)[0] + assert_equal 200, pedir('post', '/pools/gemma-humo/red', cuerpo: { provider: 'gemini', identificador: 'g-02' }, sesion: SES_ADMIN)[0] + assert_equal 400, pedir('post', '/pools/gemma-humo/otro', cuerpo: { provider: 'gemini', identificador: 'g-02' }, sesion: SES_ADMIN)[0] + c, b = pedir('get', '/pools', sesion: SES_OPER) + assert_equal [200, ['d-01']], [c, b.dig('individuos', 'gemma-humo', 'mente').map { |f| f['identificador'] }] + + # mente y red dispensan su propia key, con el provider real + c, b = pedir('get', '/disponible/mente', token: TOKEN_IND) + assert_equal [200, 'deepseek', 'd-01'], [c, b['provider'], b['identificador']] + c, b = pedir('get', '/disponible/red?dry_run=1', token: TOKEN_IND) + assert_equal [200, 'gemini', 'g-02'], [c, b['provider'], b['identificador']] + + # reportar por rol exige provider; con provider marca agotada con motivo y el estado lo muestra + assert_equal 400, pedir('post', '/disponible/mente/reportar', cuerpo: { identificador: 'd-01', estado: 'agotada' }, token: TOKEN_IND)[0] + c, = pedir('post', '/disponible/mente/reportar', cuerpo: { provider: 'deepseek', identificador: 'd-01', estado: 'agotada', motivo: 'humo' }, token: TOKEN_IND) + assert_equal 200, c + c, b = pedir('get', '/disponible/mente/estado', token: TOKEN_IND) + assert_equal [200, 'mente', %w[agotada humo]], [c, b['rol'], b['keys'][0].values_at('estado', 'motivo')] + assert_equal 'agotado', pedir('get', '/disponible/mente', token: TOKEN_IND)[1]['error'] + + # compatibilidad: por provider sigue como antes + c, b = pedir('get', '/disponible/gemini?dry_run=1', token: TOKEN_IND) + assert_equal [200, 'gemini'], [c, b['provider']] + + # quitar (admin) y borrar una key la saca de todos los pools + assert_equal 200, pedir('delete', '/pools/gemma-humo/mente/deepseek/d-01', sesion: SES_ADMIN)[0] + assert_equal 404, pedir('delete', '/pools/gemma-humo/mente/deepseek/d-01', sesion: SES_ADMIN)[0] + assert_equal 200, pedir('delete', '/keys/gemini/g-02', sesion: SES_ADMIN)[0] + assert_equal({}, pedir('get', '/pools', sesion: SES_OPER)[1]['individuos']) + end + + def test_liberar_desde_la_web_solo_admin + # key (groq) e individuo propios: este test no toca nada de lo que usa el ciclo de pools + assert_equal 200, pedir('get', '/disponible/groq', token: TOKEN_LIB)[0] + pedir('post', '/disponible/groq/reportar', cuerpo: { identificador: 'q-lib', estado: 'agotada', motivo: 'humo-web' }, token: TOKEN_LIB) + key = -> { pedir('get', '/keys', sesion: SES_OPER)[1].find { |k| k['identificador'] == 'q-lib' } } + assert_equal %w[liberar-humo humo-web], key.call.values_at('agotada_por', 'motivo_agotada') + assert_equal 'agotado', pedir('get', '/disponible/groq', token: TOKEN_LIB)[1]['error'] + assert_equal 403, pedir('post', '/keys/groq/q-lib/liberar', sesion: SES_OPER)[0] + assert_equal 404, pedir('post', '/keys/groq/no-existe/liberar', sesion: SES_ADMIN)[0] + assert_equal 200, pedir('post', '/keys/groq/q-lib/liberar', sesion: SES_ADMIN)[0] + assert_equal [nil, nil], key.call.values_at('agotada_por', 'motivo_agotada') + assert_equal 200, pedir('get', '/disponible/groq?dry_run=1', token: TOKEN_LIB)[0] + end + + def test_sin_token_ni_sesion + assert_equal 401, pedir('get', '/disponible/mente')[0] + assert_equal 401, pedir('get', '/pools')[0] + end +end diff --git a/servicios/nexxa/test/lib_servidor_prueba.rb b/servicios/nexxa/test/lib_servidor_prueba.rb new file mode 100644 index 00000000..d807ab07 --- /dev/null +++ b/servicios/nexxa/test/lib_servidor_prueba.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +# lib_servidor_prueba.rb — NEXXA de PRUEBA sobre una copia aislada (P335/Fase 7). Fuente única para el humo HTTP y para +# mirar nexxa-web en un navegador real sin tocar el nodo ni secretos reales. +# Copia organismo/ y web/ a un directorio temporal, cambia el server a 127.0.0.1 y un puerto libre, y siembra estado +# FALSO: master key, keys con valores inventados, usuarios humo-admin/humo-oper y tokens de individuos. +require 'tmpdir' +require 'fileutils' +require 'socket' + +module ServidorPrueba + BASE = File.expand_path('..', __dir__) + USUARIOS = { 'humo-admin' => ['humo-admin-123', 'admin'], 'humo-oper' => ['humo-oper-123', 'operador'] }.freeze + KEYS = [%w[gemini g-01], %w[gemini g-02], %w[deepseek d-01], %w[groq q-lib]].freeze + + module_function + + # => { dir:, org:, puerto:, tokens: { individuo => token } } + def armar(individuos: %w[gemma-humo liberar-humo], puerto: nil) + dir = Dir.mktmpdir('nexxa-prueba') + %w[organismo web].each { |d| FileUtils.cp_r(File.join(BASE, d), dir) } + org = File.join(dir, 'organismo') + puerto ||= TCPServer.new('127.0.0.1', 0).then { |s| s.addr[1].tap { s.close } } + srv = File.read(File.join(org, 'server.rb')) + .sub(/^PORT = \d+/, "PORT = #{puerto}").sub("BindAddress: '0.0.0.0'", "BindAddress: '127.0.0.1'") + File.write(File.join(org, 'server.rb'), srv) + + %w[lib_cripto lib_registro lib_tokens lib_auth lib_pools].each { |f| require File.join(org, f) } + Nexxa::MasterKey.generar_si_falta! + KEYS.each do |p, i| + Nexxa::Registro.registrar(provider: p, identificador: i, cuenta_origen: 'prueba', reset_segundos: 86_400, valor: "falso-#{i}") + end + USUARIOS.each { |u, (pw, perfil)| Nexxa::Auth.crear_usuario(usuario: u, password: pw, perfil: perfil) } + tokens = individuos.to_h { |ind| [ind, Nexxa::Tokens.generar(ind)] } + { dir: dir, org: org, puerto: puerto, tokens: tokens } + end + + # Arranca server.rb de la copia y espera el puerto. => pid + def arrancar(prueba, log: File.join(prueba[:dir], 'server.log')) + pid = Process.spawn('ruby', 'server.rb', chdir: prueba[:org], out: File::NULL, err: log) + 60.times { abierto?(prueba[:puerto]) ? break : sleep(0.25) } + raise "El server de prueba no abrió el puerto #{prueba[:puerto]} (ver #{log})" unless abierto?(prueba[:puerto]) + + pid + end + + def detener(pid, prueba) + Process.kill('TERM', pid) rescue nil + Process.wait(pid) rescue nil + FileUtils.rm_rf(prueba[:dir]) + end + + def abierto?(puerto) + TCPSocket.new('127.0.0.1', puerto).close + true + rescue SystemCallError + false + end +end diff --git a/servicios/nexxa/test/pools_test.rb b/servicios/nexxa/test/pools_test.rb new file mode 100644 index 00000000..44e17d56 --- /dev/null +++ b/servicios/nexxa/test/pools_test.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +# pools_test.rb — Pools por individuo (P335/Fase 4). Corre sobre una COPIA de organismo/ en un directorio temporal: +# registro.json/pools.json de prueba, nunca los reales. ruby servicios/nexxa/test/pools_test.rb +require 'minitest/autorun' +require 'tmpdir' +require 'fileutils' + +DIR_PRUEBA = Dir.mktmpdir('nexxa-pools') +Dir[File.expand_path('../organismo/*.rb', __dir__)].each { |f| FileUtils.cp(f, DIR_PRUEBA) } +require File.join(DIR_PRUEBA, 'lib_registro') +require File.join(DIR_PRUEBA, 'lib_pools') +Minitest.after_run { FileUtils.rm_rf(DIR_PRUEBA) } + +class PoolsTest < Minitest::Test + R = Nexxa::Registro + P = Nexxa::Pools + + def setup + FileUtils.rm_f([R::STATE_FILE, P::STATE_FILE]) + pasado = (Time.now - 3600).iso8601(3) + key = ->(p, i, extra = {}) { { 'provider' => p, 'identificador' => i, 'disponible_desde' => pasado, 'reset_segundos' => 86_400 }.merge(extra) } + R.guardar('keys' => [key.('gemini', 'g-01', 'ultimo_uso' => (Time.now - 60).iso8601(3)), + key.('deepseek', 'd-01', 'ultimo_uso' => (Time.now - 600).iso8601(3)), + key.('gemini', 'g-red'), + key.('gemini', 'g-off', 'activo' => false)]) + end + + def asignar(ind, rol, p, i) = P.asignar(individuo: ind, rol: rol, provider: p, identificador: i) + + def test_pool_mezcla_proveedores_y_da_la_menos_usada + asignar('gemma', 'mente', 'gemini', 'g-01') + asignar('gemma', 'mente', 'deepseek', 'd-01') + k = R.disponible_en(P.refs('gemma', 'mente')) + assert_equal %w[deepseek d-01], [k['provider'], k['identificador']] + end + + def test_red_separada_de_mente_y_compartida_entre_individuos + asignar('gemma', 'mente', 'gemini', 'g-01') + asignar('gemma', 'red', 'gemini', 'g-red') + asignar('peggy', 'red', 'gemini', 'g-red') + assert_equal 'g-red', R.disponible_en(P.refs('gemma', 'red'))['identificador'] + assert_equal [{ 'individuo' => 'gemma', 'rol' => 'red' }, { 'individuo' => 'peggy', 'rol' => 'red' }], + P.de_key('gemini', 'g-red') + end + + def test_asignar_es_idempotente_y_valida + 2.times { asignar('gemma', 'mente', 'gemini', 'g-01') } + assert_equal ['gemini/g-01'], P.refs('gemma', 'mente') + assert_raises(RuntimeError) { asignar('gemma', 'otro', 'gemini', 'g-01') } + assert_raises(RuntimeError) { asignar('gemma', 'mente', 'gemini', 'no-existe') } + end + + def test_desactivada_o_reservada_no_se_da_y_proxima_responde + asignar('gemma', 'mente', 'gemini', 'g-off') + assert_nil R.disponible_en(P.refs('gemma', 'mente')) + assert_nil R.proxima_en(P.refs('gemma', 'mente')) + asignar('gemma', 'mente', 'gemini', 'g-01') + R.reservar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma') + assert_nil R.disponible_en(P.refs('gemma', 'mente')) + assert_equal 'g-01', R.proxima_en(P.refs('gemma', 'mente'))['identificador'] + end + + def test_quitar_y_olvidar_no_dejan_refs_colgadas + asignar('gemma', 'mente', 'gemini', 'g-01') + asignar('peggy', 'red', 'gemini', 'g-01') + assert P.quitar(individuo: 'gemma', rol: 'mente', provider: 'gemini', identificador: 'g-01') + refute P.quitar(individuo: 'gemma', rol: 'mente', provider: 'gemini', identificador: 'g-01') + assert P.olvidar_key(provider: 'gemini', identificador: 'g-01') + assert_equal({ 'individuos' => {} }, P.leer) + assert_equal '600', format('%o', File.stat(P::STATE_FILE).mode & 0o777) + end + + def test_pool_vacio_no_cae_al_provider + assert_nil R.disponible_en(P.refs('nadie', 'mente')) + assert P.pool_vacio?('nadie', 'mente') + assert_nil P.disponible('nadie', 'mente') + end + + # --- Fase 5: selección por nombre (rol o provider) y estado + def test_nombre_rol_usa_el_pool_y_nombre_provider_sigue_igual + asignar('gemma', 'mente', 'deepseek', 'd-01') + assert_equal 'd-01', P.disponible('gemma', 'mente')['identificador'] + assert_equal 'gemini', P.disponible('gemma', 'gemini')['provider'] # compatibilidad: por provider, sin pools + refute P.pool_vacio?('gemma', 'gemini') + refute P.rol?('gemini') + end + + def test_estado_por_rol_trae_provider_motivo_y_quien + asignar('gemma', 'mente', 'gemini', 'g-01') + asignar('gemma', 'mente', 'deepseek', 'd-01') + R.reservar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma') + R.reportar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma', estado: 'agotada', motivo: 'cuota diaria') + filas = P.estado('gemma', 'mente').to_h { |f| [f['identificador'], f] } + assert_equal %w[d-01 g-01], filas.keys.sort + assert_equal %w[agotada gemini gemma cuota\ diaria], + filas['g-01'].values_at('estado', 'provider', 'agotada_por', 'motivo') + assert_equal 'disponible', filas['d-01']['estado'] + assert_equal 'deepseek', P.disponible('gemma', 'mente')['provider'] + end + + def test_con_estado_para_la_web + asignar('gemma', 'red', 'gemini', 'g-red') + assert_equal ['g-red'], P.con_estado.dig('gemma', 'red').map { |f| f['identificador'] } + end +end diff --git a/servicios/nexxa/test/revertir_test.rb b/servicios/nexxa/test/revertir_test.rb new file mode 100644 index 00000000..bfdc002f --- /dev/null +++ b/servicios/nexxa/test/revertir_test.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +# revertir_test.rb — Revertir el 'agotada' propio y estado del pool por key (P334/Fase 4, integrado en P335/Fase 6). +# Corre sobre una COPIA de organismo/ en un directorio temporal: nunca el registro real. +# ruby servicios/nexxa/test/revertir_test.rb +require 'minitest/autorun' +require 'tmpdir' +require 'fileutils' + +DIR_REVERTIR = Dir.mktmpdir('nexxa-revertir') +Dir[File.expand_path('../organismo/*.rb', __dir__)].each { |f| FileUtils.cp(f, DIR_REVERTIR) } +require File.join(DIR_REVERTIR, 'lib_registro') +Minitest.after_run { FileUtils.rm_rf(DIR_REVERTIR) } + +class RevertirTest < Minitest::Test + R = Nexxa::Registro + def setup + FileUtils.rm_f([R::STATE_FILE, Nexxa::Usos::LOG_FILE]) + pasado = (Time.now - 3600).iso8601(3) + R.guardar('keys' => %w[g-01 g-02 g-03].map { |i| { 'provider' => 'gemini', 'identificador' => i, 'disponible_desde' => pasado, 'reset_segundos' => 86_400, 'reservado_por' => nil } } + + [{ 'provider' => 'gemini', 'identificador' => 'g-off', 'activo' => false, 'disponible_desde' => pasado }]) + end + + def test_quien_la_agoto_puede_deshacerlo_aunque_ya_no_la_tenga_reservada + R.reservar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1') + R.reportar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1', estado: 'agotada') + assert_equal 'agotada', R.estado_pool('gemini').find { |k| k['identificador'] == 'g-01' }['estado'] + R.reportar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1', estado: 'liberada') + e = R.estado_pool('gemini').find { |k| k['identificador'] == 'g-01' } + assert_equal 'disponible', e['estado'] + assert_includes File.read(Nexxa::Usos::LOG_FILE), 'revertida' + end + + def test_otro_individuo_no_puede_liberar_lo_que_agoto_otro + R.reservar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1') + R.reportar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1', estado: 'agotada') + assert_raises(RuntimeError) { R.reportar(provider: 'gemini', identificador: 'g-01', individuo: 'peggy-f1', estado: 'liberada') } + end + + def test_el_flujo_original_de_reserva_sigue_igual + R.reservar(provider: 'gemini', identificador: 'g-02', individuo: 'gemma-f1') + assert_raises(RuntimeError) { R.reportar(provider: 'gemini', identificador: 'g-02', individuo: 'otro', estado: 'sana') } + R.reportar(provider: 'gemini', identificador: 'g-02', individuo: 'gemma-f1', estado: 'liberada') + assert_equal 'disponible', R.estado_pool('gemini').find { |k| k['identificador'] == 'g-02' }['estado'] + end + + def test_estado_del_pool_sin_valores_y_con_los_cuatro_estados + R.reservar(provider: 'gemini', identificador: 'g-01', individuo: 'gemma-f1') + R.reservar(provider: 'gemini', identificador: 'g-02', individuo: 'gemma-f1') + R.reportar(provider: 'gemini', identificador: 'g-02', individuo: 'gemma-f1', estado: 'agotada', liberar_en_segundos: 60) + est = R.estado_pool('gemini').to_h { |k| [k['identificador'], k] } + assert_equal %w[reservada agotada disponible inactiva], %w[g-01 g-02 g-03 g-off].map { |i| est[i]['estado'] } + assert_equal 'gemma-f1', est['g-02']['agotada_por'] + refute est.values.any? { |k| k.key?('valor') || k.key?('valor_cifrado') } + end +end diff --git a/servicios/nexxa/test/servidor_prueba.rb b/servicios/nexxa/test/servidor_prueba.rb new file mode 100644 index 00000000..deb56975 --- /dev/null +++ b/servicios/nexxa/test/servidor_prueba.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +# servidor_prueba.rb — Deja corriendo un NEXXA de PRUEBA (copia aislada, estado falso) para mirar nexxa-web en un +# navegador real (P335/Fase 7). Ctrl+C lo detiene y borra la copia. +# ruby servicios/nexxa/test/servidor_prueba.rb [--puerto 14568] +# Entra con humo-admin / humo-admin-123 (o humo-oper / humo-oper-123): usuarios INVENTADOS de la copia, no del nodo. +require_relative 'lib_servidor_prueba' + +puerto = ARGV[ARGV.index('--puerto') + 1].to_i if ARGV.include?('--puerto') +prueba = ServidorPrueba.armar(individuos: %w[gemma-prueba peggy-prueba], puerto: puerto) +pid = ServidorPrueba.arrancar(prueba) +puts "NEXXA de prueba en http://127.0.0.1:#{prueba[:puerto]}/ (pid #{pid}) — usuarios: #{ServidorPrueba::USUARIOS.keys.join(', ')}" +$stdout.flush +trap('INT') { ServidorPrueba.detener(pid, prueba); exit } +trap('TERM') { ServidorPrueba.detener(pid, prueba); exit } +Process.wait(pid) diff --git a/servicios/nexxa/web/css/estilos.css b/servicios/nexxa/web/css/estilos.css new file mode 100644 index 00000000..66d1f54b --- /dev/null +++ b/servicios/nexxa/web/css/estilos.css @@ -0,0 +1,1046 @@ + :root { + --bg: #0e1315; + --surface: #161d20; + --surface-raised: #1c2427; + --border: #29343a; + --border-soft: #202a2f; + --text: #e7edee; + --text-dim: #8fa1a3; + --text-faint: #5c6d6f; + --accent: #57c2b7; + --accent-strong: #7fd8cd; + --accent-soft: rgba(87, 194, 183, 0.13); + --accent-border: rgba(87, 194, 183, 0.35); + --ok: #6bc084; + --ok-soft: rgba(107, 192, 132, 0.13); + --warn: #dba94a; + --warn-soft: rgba(219, 169, 74, 0.13); + --danger: #dd6f6a; + --danger-soft: rgba(221, 111, 106, 0.13); + --shadow: 0 20px 44px -20px rgba(0, 0, 0, 0.55); + } + + :root[data-theme="light"] { + --bg: #f2f5f4; + --surface: #ffffff; + --surface-raised: #ffffff; + --border: #d7e0de; + --border-soft: #e4ecea; + --text: #16201f; + --text-dim: #55696a; + --text-faint: #8b9c9c; + --accent: #17847a; + --accent-strong: #106861; + --accent-soft: rgba(23, 132, 122, 0.09); + --accent-border: rgba(23, 132, 122, 0.3); + --ok: #2f8f52; + --ok-soft: rgba(47, 143, 82, 0.1); + --warn: #a5730e; + --warn-soft: rgba(165, 115, 14, 0.1); + --danger: #b7443f; + --danger-soft: rgba(183, 68, 63, 0.09); + --shadow: 0 20px 44px -24px rgba(20, 40, 38, 0.25); + } + + @media (prefers-color-scheme: light) { + :root:not([data-theme="dark"]) { + --bg: #f2f5f4; + --surface: #ffffff; + --surface-raised: #ffffff; + --border: #d7e0de; + --border-soft: #e4ecea; + --text: #16201f; + --text-dim: #55696a; + --text-faint: #8b9c9c; + --accent: #17847a; + --accent-strong: #106861; + --accent-soft: rgba(23, 132, 122, 0.09); + --accent-border: rgba(23, 132, 122, 0.3); + --ok: #2f8f52; + --ok-soft: rgba(47, 143, 82, 0.1); + --warn: #a5730e; + --warn-soft: rgba(165, 115, 14, 0.1); + --danger: #b7443f; + --danger-soft: rgba(183, 68, 63, 0.09); + --shadow: 0 20px 44px -24px rgba(20, 40, 38, 0.25); + } + } + + * { box-sizing: border-box; } + + /* Scrollbar delgado y de la paleta del tema — el default del navegador + desentona con un panel oscuro (Firefox: scrollbar-width/color; Chrome/ + Safari/Edge: pseudo-elementos ::-webkit-scrollbar). Aplicado a cualquier + contenedor con scroll propio (.main-area, .sidebar, listas internas). */ + .main-area, .sidebar, #actividad-lista, #reportes-individuo { + scrollbar-width: thin; + scrollbar-color: var(--border) transparent; + } + + .main-area::-webkit-scrollbar, + .sidebar::-webkit-scrollbar, + #actividad-lista::-webkit-scrollbar, + #reportes-individuo::-webkit-scrollbar { + width: 8px; + } + + .main-area::-webkit-scrollbar-track, + .sidebar::-webkit-scrollbar-track, + #actividad-lista::-webkit-scrollbar-track, + #reportes-individuo::-webkit-scrollbar-track { + background: transparent; + } + + .main-area::-webkit-scrollbar-thumb, + .sidebar::-webkit-scrollbar-thumb, + #actividad-lista::-webkit-scrollbar-thumb, + #reportes-individuo::-webkit-scrollbar-thumb { + background: var(--border); + border-radius: 8px; + } + + .main-area::-webkit-scrollbar-thumb:hover, + .sidebar::-webkit-scrollbar-thumb:hover, + #actividad-lista::-webkit-scrollbar-thumb:hover, + #reportes-individuo::-webkit-scrollbar-thumb:hover { + background: var(--text-faint); + } + + html, body { + height: 100%; + } + + body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: -apple-system, "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif; + font-size: 15px; + line-height: 1.5; + -webkit-font-smoothing: antialiased; + } + + .mono { + font-family: ui-monospace, "SF Mono", "Cascadia Code", "JetBrains Mono", Consolas, monospace; + font-variant-numeric: tabular-nums; + } + + a { color: inherit; } + + /* Shell fijo (P204/Fase4, pedido del Operador): antes .app-shell usaba + min-height y toda la página scrolleaba junta — la sidebar terminaba más + alta que la pantalla y se perdía contenido abajo sin forma clara de + saberlo. Ahora la sidebar queda pinneada a 100vh y solo .main-area + scrollea — patrón estándar de "shell fijo + contenido scrolleable". + Sidebar y contenido son paneles FLOTANTES separados del fondo (.app-shell + hace de "fondo", con su propio padding/gap) — no franjas pegadas borde a + borde, patrón de dashboards reales investigado (bento/floating panels). */ + .app-shell { + display: flex; + height: 100vh; + align-items: stretch; + overflow: hidden; + background: var(--bg); + padding: 16px; + gap: 16px; + } + + .sidebar { + width: 208px; + flex-shrink: 0; + background: var(--surface); + border: 1px solid var(--border-soft); + border-radius: 14px; + display: flex; + flex-direction: column; + padding: 20px 12px; + overflow-y: auto; + transition: width 0.16s ease; + } + + .sidebar.collapsed { width: 60px; } + + .sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 26px; + padding: 0 6px; + min-height: 24px; + } + + .sidebar.collapsed .sidebar-header { justify-content: center; } + .sidebar.collapsed .sidebar-header .brand-block { display: none; } + + .sidebar-toggle-btn { + appearance: none; + border: none; + background: transparent; + color: var(--text-dim); + cursor: pointer; + font-size: 15px; + padding: 5px 7px; + border-radius: 7px; + line-height: 1; + } + + .sidebar-toggle-btn:hover { background: var(--bg); color: var(--text); } + + .sidebar-nav { + display: flex; + flex-direction: column; + gap: 3px; + } + + /* Versión visible bajo el brand mark, no al pie (P204/Fase4) — este layout no + tiene sidebar fijo (la página entera scrollea junta, .app-shell usa + min-height, no height), así que "pegado al fondo" vía margin-top:auto + terminaba en el fondo del CONTENIDO total, invisible sin scrollear todo. */ + .version-tag { + font-size: 10.5px; + color: var(--text-faint); + } + + .nav-item { + display: flex; + align-items: center; + gap: 11px; + padding: 10px 11px; + border-radius: 9px; + border: none; + background: transparent; + color: var(--text-dim); + font-size: 13.5px; + font-weight: 600; + cursor: pointer; + text-align: left; + font-family: inherit; + white-space: nowrap; + overflow: hidden; + } + + .nav-item .nav-icon { font-size: 16px; flex-shrink: 0; } + .sidebar.collapsed .nav-item { justify-content: center; padding: 10px; } + .sidebar.collapsed .nav-label { display: none; } + + .nav-item[aria-current="page"] { + background: var(--accent-soft); + color: var(--accent-strong); + } + + .nav-item:not([aria-current="page"]):hover { + background: var(--bg); + color: var(--text); + } + + /* padding-bottom era 80px — sobraba de cuando la página scrolleaba completa + (daba aire al final); con shell fijo eso solo resta espacio real y + provoca overflow innecesario. Sin max-width — el ancho fijo (980px) no + tenía motivo real más que "se veía prolijo" (corregido, Operador): con + más pantalla disponible hay lugar para más paneles por fila sin + scrollear (ver .dash-panels, auto-fit). Sin height explícito — el + align-items:stretch de .app-shell (default de flex) ya le da la altura + correcta, no hace falta duplicarla. */ + .main-area { + flex: 1; + min-width: 0; + padding: 28px 24px; + overflow-y: auto; + } + + .section { display: none; } + .section.active { display: block; } + + .topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding-bottom: 22px; + border-bottom: 1px solid var(--border-soft); + margin-bottom: 26px; + } + + .page-title { + font-size: 19px; + font-weight: 700; + margin: 0; + } + + .brand { + display: flex; + align-items: baseline; + gap: 10px; + } + + .brand-mark { + font-size: 19px; + font-weight: 700; + letter-spacing: 0.01em; + } + + .brand-sub { + font-size: 12.5px; + color: var(--text-faint); + font-family: ui-monospace, "SF Mono", Consolas, monospace; + } + + .node-pill { + display: inline-flex; + align-items: center; + gap: 7px; + padding: 6px 12px; + border: 1px solid var(--border); + border-radius: 999px; + font-size: 12.5px; + color: var(--text-dim); + background: var(--surface); + } + + .node-pill .dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--ok); + box-shadow: 0 0 0 3px var(--ok-soft); + } + + .node-pill.error .dot { background: var(--danger); box-shadow: 0 0 0 3px var(--danger-soft); } + + .tabs { + display: inline-flex; + padding: 3px; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--surface); + margin-bottom: 22px; + } + + .tab { + appearance: none; + border: none; + background: transparent; + color: var(--text-dim); + font-size: 13.5px; + font-weight: 600; + padding: 8px 16px; + border-radius: 8px; + cursor: pointer; + font-family: inherit; + transition: background 0.15s ease, color 0.15s ease; + } + + .tab[aria-selected="true"] { + background: var(--accent-soft); + color: var(--accent-strong); + } + + .tab:not([aria-selected="true"]):hover { + color: var(--text); + } + + /* Dashboard (P204/Fase4, rediseñado 2 veces con referencia a patrones + reales de dashboards — barra de métricas full-width primero, después + una grilla de tarjetas PAREJAS). auto-fit + minmax en vez de un número + fijo de columnas (corregido, Operador: "no me gusta lo fijo/rígido") — + el navegador acomoda tantas tarjetas por fila como el ancho disponible + permita, sin depender de breakpoints a mano ni de un max-width fijo en + .main-area. Con las 4 tarjetas actuales, en una pantalla de escritorio + normal entran las 4 en una sola fila; en una más angosta, el mismo grid + las acomoda en 2 filas de 2, sin JS ni media query dedicada. */ + .dash-panels { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 16px; + } + + .panel-tall { + max-height: 360px; + display: flex; + flex-direction: column; + } + + .panel-tall #actividad-lista, + .panel-tall #reportes-individuo { + overflow-y: auto; + flex: 1; + } + + .stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin-bottom: 16px; + } + + .stat { + border: 1px solid var(--border); + background: var(--surface); + border-radius: 12px; + padding: 14px 16px; + } + + .stat-label { + font-size: 11.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-faint); + margin-bottom: 6px; + } + + .stat-value { + font-size: 22px; + font-weight: 700; + font-family: ui-monospace, "SF Mono", Consolas, monospace; + } + + .stat-value.warn { color: var(--warn); } + .stat-value.info { color: var(--accent); } + + /* P204/Fase4 — gauges, gráfico de barras y actividad reciente del Dashboard */ + .panel { + border: 1px solid var(--border); + background: var(--surface); + border-radius: 12px; + padding: 14px 16px; + } + + .panel-title { + font-size: 11.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-faint); + margin-bottom: 14px; + } + + .gauge-row { + display: flex; + flex-wrap: wrap; + gap: 24px; + } + + .gauge { + width: 120px; + text-align: center; + } + + .gauge svg { width: 100%; height: auto; } + + .gauge-bg { + fill: none; + stroke: var(--border-soft); + stroke-width: 10; + } + + .gauge-fg { + fill: none; + stroke-width: 10; + stroke-linecap: round; + transition: stroke-dashoffset 0.4s ease; + } + + .gauge-pct { + font-size: 20px; + font-weight: 700; + text-anchor: middle; + fill: var(--text); + font-family: ui-monospace, "SF Mono", Consolas, monospace; + } + + .gauge-sub { + font-size: 10px; + text-anchor: middle; + fill: var(--text-dim); + } + + .gauge-label { + margin-top: 2px; + font-size: 13px; + color: var(--text-dim); + } + + .bar-chart { + display: flex; + align-items: flex-end; + gap: 10px; + height: 76px; + } + + .bar-col { + display: flex; + flex-direction: column; + align-items: center; + justify-content: flex-end; + flex: 1; + } + + .bar { + width: 100%; + max-width: 28px; + background: var(--accent); + border-radius: 3px 3px 0 0; + } + + .bar-label { + font-size: 10px; + color: var(--text-faint); + margin-top: 6px; + } + + .activity-row { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 8px 8px 0; + border-bottom: 1px solid var(--border-soft); + font-size: 13px; + } + + .activity-row:last-child { border-bottom: none; } + + .activity-text { + flex: 1; + color: var(--text-dim); + } + + .activity-text b { color: var(--text); font-weight: 600; } + + .report-row { + display: grid; + grid-template-columns: 100px 1fr 32px; + align-items: center; + gap: 12px; + padding: 7px 0; + } + + .report-label { + font-size: 12.5px; + color: var(--text-dim); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .report-bar { + display: flex; + height: 8px; + border-radius: 4px; + overflow: hidden; + background: var(--border-soft); + } + + .report-seg.ok { background: var(--ok); } + .report-seg.warn { background: var(--warn); } + + .report-count { + font-size: 12.5px; + color: var(--text-faint); + text-align: right; + } + + .notice { + display: flex; + gap: 10px; + align-items: flex-start; + border: 1px solid var(--accent-border); + background: var(--accent-soft); + border-radius: 12px; + padding: 12px 14px; + font-size: 13px; + color: var(--text-dim); + margin-bottom: 22px; + } + + .notice.error { + display: none; + border-color: var(--danger); + background: var(--danger-soft); + } + + .notice.error.visible { + display: flex; + } + + .notice strong { color: var(--text); } + + .group-title { + display: flex; + align-items: center; + gap: 8px; + font-size: 12.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-faint); + margin: 22px 0 10px; + } + + .group-title .line { + flex: 1; + height: 1px; + background: var(--border-soft); + } + + .card-list { + display: flex; + flex-direction: column; + gap: 10px; + } + + .key-card { + border: 1px solid var(--border); + background: var(--surface); + border-radius: 12px; + padding: 14px 16px; + display: grid; + grid-template-columns: 1.2fr 1fr 0.9fr 1.2fr auto; + gap: 14px; + align-items: center; + } + + .card-icon-actions { + display: flex; + gap: 6px; + justify-self: end; + } + + .icon-btn { + width: 30px; + height: 30px; + flex-shrink: 0; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text-dim); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + font-size: 14px; + padding: 0; + } + + .icon-btn:hover { color: var(--text); border-color: var(--text-faint); } + .icon-btn.danger { color: var(--danger); } + .icon-btn.danger:hover { border-color: var(--danger); background: var(--danger-soft); } + .icon-btn.primary { color: var(--accent-strong); border-color: var(--accent-border); } + .icon-btn.primary:hover { background: var(--accent-soft); } + + /* Ficha inline de alta genérica — reusada por APIs (keys) y Nodos + (consumidores, P201/Fase3): un "+" arriba de la lista despliega un + formulario con el mismo estilo visual que las fichas ya cargadas. */ + .add-trigger { + appearance: none; + width: 100%; + display: flex; + align-items: center; + gap: 10px; + border: 1px dashed var(--border); + background: transparent; + color: var(--text-dim); + font-size: 13.5px; + font-weight: 600; + font-family: inherit; + padding: 12px 16px; + border-radius: 12px; + cursor: pointer; + margin-bottom: 14px; + } + + .add-trigger:hover { + border-color: var(--accent-border); + color: var(--accent-strong); + background: var(--accent-soft); + } + + .add-plus { + font-size: 16px; + line-height: 1; + } + + /* Especificidad "div.inline-add-form" a propósito: gana el empate con + .key-card/.consumidor-card (misma especificidad de clase única) sin + depender del orden de aparición en la hoja de estilos. */ + div.inline-add-form { + display: none; + flex-direction: column; + gap: 12px; + margin-bottom: 14px; + border-color: var(--accent-border); + } + + div.inline-add-form.visible { display: flex; } + + .inline-add-row { + display: grid; + grid-template-columns: 1fr 1fr 1fr 1fr auto; + gap: 12px; + align-items: end; + } + + .inline-add-field label { + display: block; + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-faint); + margin-bottom: 5px; + } + + .inline-add-field input, .inline-add-field select { + width: 100%; + padding: 8px 10px; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text); + font-size: 13.5px; + font-family: inherit; + } + + .inline-add-field.secret-field { position: relative; } + .inline-add-field.secret-field input { padding-right: 62px; } + + .inline-add-field .secret-toggle { + position: absolute; + right: 6px; + top: 28px; + background: none; + border: none; + color: var(--text-faint); + font-size: 11.5px; + cursor: pointer; + padding: 4px 6px; + } + + .inline-add-field.has-error input { border-color: var(--danger); } + + .inline-add-hint { + font-size: 11.5px; + color: var(--text-faint); + margin: 0; + } + + @media (max-width: 640px) { + .inline-add-row { grid-template-columns: 1fr 1fr; } + } + + .key-card.is-new { + animation: pop 1.2s ease; + border-color: var(--accent-border); + } + + @keyframes pop { + 0% { background: var(--accent-soft); } + 100% { background: var(--surface); } + } + + .field-label { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-faint); + margin-bottom: 3px; + } + + .id-block .id { + font-weight: 600; + font-size: 14.5px; + } + + .id-block .provider { + color: var(--text-dim); + font-size: 12.5px; + } + + .owner { + font-size: 13.5px; + color: var(--text); + font-weight: 600; + } + + .owner.unassigned { + color: var(--text-faint); + font-weight: 400; + font-style: italic; + } + + .pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + width: fit-content; + } + + .pill .dot { width: 6px; height: 6px; border-radius: 50%; } + + .pill.ok { background: var(--ok-soft); color: var(--ok); } + .pill.ok .dot { background: var(--ok); } + + .pill.warn { background: var(--warn-soft); color: var(--warn); } + .pill.warn .dot { background: var(--warn); } + + .pill.info { background: var(--accent-soft); color: var(--accent); } + .pill.info .dot { background: var(--accent); } + + .timing { + font-size: 12.5px; + color: var(--text-dim); + } + + .timing .value { color: var(--text); } + + .timing-sub { + font-size: 11.5px; + color: var(--text-faint); + margin-top: 3px; + } + + .key-actions { + grid-column: 1 / -1; + display: flex; + gap: 8px; + padding-top: 12px; + margin-top: 2px; + border-top: 1px solid var(--border-soft); + } + + .action-btn { + appearance: none; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text-dim); + font-size: 12px; + font-weight: 600; + padding: 5px 11px; + border-radius: 7px; + cursor: pointer; + font-family: inherit; + } + + .action-btn:hover { color: var(--text); border-color: var(--text-faint); } + .action-btn.danger { color: var(--danger); } + .action-btn.danger:hover { border-color: var(--danger); background: var(--danger-soft); } + .action-btn.confirm { color: #08211e; background: var(--danger); border-color: var(--danger); } + .action-btn.primary { color: var(--accent-strong); border-color: var(--accent-border); } + + .edit-panel { + grid-column: 1 / -1; + display: flex; + gap: 10px; + align-items: flex-end; + padding-top: 12px; + margin-top: 2px; + border-top: 1px solid var(--border-soft); + flex-wrap: wrap; + } + + .edit-panel .ep-field { display: flex; flex-direction: column; gap: 4px; } + .edit-panel label { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-faint); } + .edit-panel input, .edit-panel select { + padding: 6px 9px; + border-radius: 7px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text); + font-size: 13px; + font-family: inherit; + } + + .pill.inactive { background: var(--border-soft); color: var(--text-faint); } + .pill.inactive .dot { background: var(--text-faint); } + + .empty-state { + border: 1px dashed var(--border); + border-radius: 12px; + padding: 34px 18px; + text-align: center; + color: var(--text-faint); + font-size: 13.5px; + } + + .token-banner .token-value { + display: inline-block; + background: var(--bg); + border: 1px solid var(--border); + border-radius: 7px; + padding: 6px 10px; + margin: 6px 8px 6px 0; + font-size: 13px; + word-break: break-all; + } + + .consumidor-card { + border: 1px solid var(--border); + background: var(--surface); + border-radius: 12px; + padding: 14px 16px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + margin-bottom: 10px; + flex-wrap: wrap; + } + + .consumidor-info .id { font-weight: 600; font-size: 14.5px; } + .consumidor-info .meta { color: var(--text-dim); font-size: 12.5px; margin-top: 2px; } + + /* Check-in proactivo (P216/Fase4) — badge de estado real, segunda línea de la card */ + .badge { + display: inline-block; + margin-top: 4px; + padding: 2px 8px; + border-radius: 6px; + font-size: 11.5px; + font-weight: 600; + background: var(--border-soft); + color: var(--text-faint); + } + .badge.success { background: var(--ok-soft); color: var(--ok); } + .badge.warning { background: var(--warn-soft); color: var(--warn); } + .badge.stale { background: var(--danger-soft); color: var(--danger); } + + .secret-toggle { + position: absolute; + right: 8px; + top: 32px; + background: none; + border: none; + color: var(--text-faint); + font-size: 12px; + cursor: pointer; + padding: 4px 6px; + } + + .secret-toggle:hover { color: var(--text-dim); } + + .hint-conditional { + display: none; + color: var(--danger); + } + + .hint-conditional.visible { + display: block; + } + + .confirm-banner, .error-banner { + display: none; + align-items: flex-start; + gap: 10px; + border-radius: 12px; + padding: 14px 16px; + margin-bottom: 18px; + font-size: 13.5px; + } + + .confirm-banner { + border: 1px solid var(--ok); + background: var(--ok-soft); + } + + .error-banner { + border: 1px solid var(--danger); + background: var(--danger-soft); + } + + .confirm-banner.visible, .error-banner.visible { display: flex; } + + .confirm-banner .title { font-weight: 700; color: var(--ok); display: block; margin-bottom: 3px; } + .error-banner .title { font-weight: 700; color: var(--danger); display: block; margin-bottom: 3px; } + .confirm-banner .body, .error-banner .body { color: var(--text-dim); } + + .view { display: none; } + .view.active { display: block; } + + @media (max-width: 640px) { + .key-card { grid-template-columns: 1fr 1fr; row-gap: 10px; } + .panel-tall { max-height: none; } + } + + @media (prefers-reduced-motion: reduce) { + .key-card.is-new { animation: none; } + } + + .modal-backdrop { + display: none; + position: fixed; + inset: 0; + background: rgba(4, 8, 9, 0.6); + align-items: center; + justify-content: center; + z-index: 100; + padding: 20px; + } + + .modal-backdrop.visible { display: flex; } + + .modal { + background: var(--surface-raised); + border: 1px solid var(--border); + border-radius: 14px; + padding: 26px; + max-width: 360px; + width: 100%; + box-shadow: var(--shadow); + text-align: center; + } + + .modal-icon { font-size: 30px; margin-bottom: 10px; } + .modal h3 { margin: 0 0 8px; font-size: 16px; } + .modal-body { color: var(--text-dim); font-size: 13.5px; margin: 0 0 18px; line-height: 1.5; } + .modal-body b { color: var(--text); } + + .modal-field { text-align: left; margin-bottom: 18px; } + .modal-field label { + display: block; + font-size: 11.5px; + color: var(--text-faint); + margin-bottom: 6px; + } + .modal-field input { + width: 100%; + padding: 9px 11px; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--bg); + color: var(--text); + font-size: 14px; + } + .modal-field input:focus { + outline: none; + border-color: var(--danger); + box-shadow: 0 0 0 3px var(--danger-soft); + } + + .modal-actions { display: flex; gap: 10px; justify-content: center; } + .modal-actions .action-btn { padding: 8px 16px; font-size: 13px; } + .modal-actions .action-btn.confirm:disabled { + opacity: 0.4; + cursor: not-allowed; + background: var(--border); + border-color: var(--border); + color: var(--text-faint); + } + + /* Pools por individuo: mente y red (P335/Fase 7) */ + #pools-lista { display: flex; flex-direction: column; gap: 10px; } + .key-card.pool-card { grid-template-columns: 0.8fr 1.6fr 1.6fr; align-items: start; } + .pool-col { display: flex; flex-direction: column; gap: 8px; min-width: 0; } + .pool-key { + display: grid; + grid-template-columns: 1fr auto auto; + gap: 8px; + align-items: center; + padding: 6px 8px; + border: 1px solid var(--border); + border-radius: 8px; + } + .pool-agregar { display: flex; gap: 6px; } + .pool-agregar select { flex: 1; min-width: 0; } + @media (max-width: 640px) { + .key-card.pool-card { grid-template-columns: 1fr; } + } diff --git a/servicios/nexxa/web/index.html b/servicios/nexxa/web/index.html new file mode 100644 index 00000000..44230bfa --- /dev/null +++ b/servicios/nexxa/web/index.html @@ -0,0 +1,285 @@ + + + + + +NEXXA · Panel de administración + + + +

+ + +
+
+

Dashboard

+
+ +
conectando…
+ +
+
+ +
+
+
+
Keys registradas
+
—
+
+
+
Providers
+
—
+
+
+
Agotadas ahora
+
—
+
+
+
Reservadas ahora
+
—
+
+
+
Consumidores
+
—
+
+
+ +
+
+
Distribución de APIs por proveedor
+
+
+ +
+
Dispensas por día (últimos 7 días)
+
+
+ +
+
Reportes por individuo
+
+
+ +
+
Actividad reciente
+
+
+
+
+ +
+
+ 🔒 + Solo metadata. Esta vista nunca muestra el valor de una key — ni completo, ni parcial. El valor real solo se entrega a un individuo autenticado vía GET /disponible/<provider|mente|red>. +
+ +
+ +
+ ⚠️ + + No se pudo registrar la key + + +
+ + + +
+
+
+ + + +
+
+ + + Obligatorio. + Ya existe. +
+
+ + + + Obligatorio. +
+
+ + +
+
+ + +
+
+ +
+
+ + + + Obligatorio. +
+
+ +

🛈 Se cifra al llegar a NEXXA — no se vuelve a mostrar en pantalla una vez cargada, ni en esta mini-app ni en apids chat.

+

🛈 La estimación de reset es solo un respaldo — se usa cuando un consumidor reporta "agotada" sin informar un tiempo real del proveedor. Desde P204/Fase3, dispensar la key ya NO la bloquea automáticamente: el consumidor es quien reporta salud real.

+
+ +
+
+ +
+
+ 🧩 + Pools por individuo (P335). Cada individuo piensa y opera con las keys de su pool Mente y usa las de su pool Red solo para avisar que se quedó sin batería. Un pool puede mezclar proveedores y una key puede estar en varios pools. El individuo las pide con GET /disponible/mente o /disponible/red; con un pool vacío NEXXA responde pool_vacio, nunca cae a otra key. +
+
+
+
+ +
+
+ 🔑 + Individuos con acceso. Cada uno tiene un token propio para pedir keys vía GET /disponible/<provider|mente|red>. El token se muestra en claro una única vez, al generarlo — nunca se vuelve a mostrar después. +
+ +
+ 📡 + Check-in proactivo (P216). Cada individuo reporta su propio estado — nunca deducido. El badge de abajo de cada tarjeta refleja el último reporte real, o "sin check-in" si el individuo todavía no adoptó el mecanismo. +
+ +
+ 🔑 + + + + + + + Guardalo ahora (ej. en candados) — no se vuelve a mostrar en esta pantalla. + +
+ +
+ ⚠️ + + No se pudo completar la operación + + +
+ + + +
+
+
+ + + Obligatorio. +
+
+ + +
+
+

🛈 Si el individuo ya tenía token, esto lo reemplaza (rotación) — el viejo deja de servir.

+
+ +
+
+ +
+
+ 👤 + Gestión de usuarios. Solo perfil admin puede crear, editar o eliminar usuarios del panel. El último admin activo no se puede degradar ni eliminar. +
+ +
+ ⚠️ + + No se pudo completar la operación + + +
+ + + +
+
+
+ + + Obligatorio. +
+
+ + +
+
+ + + + Obligatorio. +
+
+ + +
+
+

🛈 El usuario nuevo cambia su password desde acá mismo (editar) cuando quiera — no hay auto-reset.

+
+ +
+
+
+
+ + + + + + diff --git a/servicios/nexxa/web/js/app.js b/servicios/nexxa/web/js/app.js new file mode 100644 index 00000000..fae6ac3e --- /dev/null +++ b/servicios/nexxa/web/js/app.js @@ -0,0 +1,1274 @@ + (function () { + "use strict"; + + // Sesión: cualquier 401 (cookie vencida/inválida) recarga la página — + // server.rb decide server-side si corresponde servir login.html o + // index.html, sin lógica de auth duplicada acá (P201/Fase4). + var _fetch = window.fetch; + window.fetch = function (url, opts) { + return _fetch(url, opts).then(function (r) { + if (r.status === 401) location.reload(); + return r; + }); + }; + + document.getElementById("logout-btn").addEventListener("click", function () { + fetch("/logout", { method: "POST" }).finally(function () { location.reload(); }); + }); + + var HOUR = 3600 * 1000; + var keys = []; + var lastCreated = null; + var editing = null; + var pendingDelete = null; + var RESET_OPTIONS = [ + { value: 86400, label: "24 horas" }, + { value: 3600, label: "1 hora" }, + { value: 604800, label: "7 días" } + ]; + + var nodePill = document.getElementById("node-pill"); + var nodePillText = document.getElementById("node-pill-text"); + var loadError = document.getElementById("load-error"); + + // Navegación de la barra lateral (Dashboard / APIs / Nodos, P201/Fase3) + var sidebar = document.getElementById("sidebar"); + var sidebarToggle = document.getElementById("sidebar-toggle"); + var navItems = document.querySelectorAll(".nav-item"); + var pageTitle = document.getElementById("page-title"); + var sectionTitles = { dashboard: "Dashboard", apis: "APIs", nodos: "Individuos", pools: "Pools", usuarios: "Usuarios" }; + + function selectSection(which) { + navItems.forEach(function (item) { + var activo = item.getAttribute("data-section") === which; + if (activo) { + item.setAttribute("aria-current", "page"); + } else { + item.removeAttribute("aria-current"); + } + }); + document.getElementById("section-dashboard").classList.toggle("active", which === "dashboard"); + document.getElementById("section-apis").classList.toggle("active", which === "apis"); + document.getElementById("section-nodos").classList.toggle("active", which === "nodos"); + document.getElementById("section-pools").classList.toggle("active", which === "pools"); + document.getElementById("section-usuarios").classList.toggle("active", which === "usuarios"); + pageTitle.textContent = sectionTitles[which]; + + if (which === "nodos") { + tokenBanner.classList.remove('visible'); + consumidoresErrorBanner.classList.remove('visible'); + cargarCheckins().then(cargarConsumidores); + } else if (which === "pools") { + cargarPools(); + } else if (which === "usuarios") { + usuariosErrorBanner.classList.remove('visible'); + cargarUsuarios(); + } + } + + navItems.forEach(function (item) { + item.addEventListener("click", function () { selectSection(item.getAttribute("data-section")); }); + }); + + sidebarToggle.addEventListener("click", function () { + sidebar.classList.toggle("collapsed"); + }); + + // Sesión actual (P201/Fase4) — gatea "Usuarios" y todo el CRUD de + // keys/consumidores por perfil: 'operador' es solo-lectura (corrección + // 2026-08-03 — el diseño original lo dejaba mutar, error). esAdmin se + // resuelve ANTES del primer cargarKeys()/cargarConsumidores() para que + // los botones de escritura no aparezcan ni un instante y se oculten + // después (Advertir antes que fallar — no mostrar controles que el + // backend va a rechazar). + var esAdmin = false; + var sesionActualEl = document.getElementById("sesion-actual"); + var navUsuarios = document.getElementById("nav-usuarios"); + fetch("/session") + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (s) { + if (s) { + esAdmin = s.perfil === "admin"; + sesionActualEl.textContent = s.usuario + " · " + s.perfil; + if (esAdmin) navUsuarios.style.display = ""; + if (!esAdmin) { + document.getElementById("add-key-trigger").style.display = "none"; + document.getElementById("add-consumidor-trigger").style.display = "none"; + } + } + }) + .catch(function () {}) + .finally(function () { + cargarKeys(); + setInterval(cargarKeys, 30000); + cargarCheckins().then(cargarConsumidores); + cargarUsos(); + setInterval(cargarUsos, 30000); + cargarVersion(); + }); + + // P204/Fase4 — build stamp visible (pedido del Operador, tras confusión + // real por caché del navegador): confirma que lo que se está viendo + // corresponde al último deploy, sin adivinar por el contenido. + function cargarVersion() { + var el = document.getElementById("version-tag"); + if (!el) return; + fetch('/version') + .then(function (r) { return r.json(); }) + .then(function (d) { el.textContent = 'v' + d.version; }) + .catch(function () {}); + } + + function fmtRelative(iso) { + var ts = new Date(iso).getTime(); + var diff = ts - Date.now(); + var abs = Math.abs(diff); + var h = abs / HOUR; + var text; + if (h < 1) { + text = Math.round(abs / 60000) + "m"; + } else if (h < 48) { + text = h.toFixed(1) + "h"; + } else { + text = Math.round(h / 24) + "d"; + } + return diff <= 0 ? "hace " + text : "en " + text; + } + + // Texto que viene de afuera (motivo que manda un consumidor, nombres) nunca entra crudo al HTML (P335/Fase 7) + function esc(t) { + return String(t == null ? '' : t).replace(/[&<>"']/g, function (c) { + return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; + }); + } + + function fmtClock(iso) { + var d = new Date(iso); + return d.toLocaleString("es-AR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); + } + + function actionsHtml(k, keyId, activo, bloqueada) { + if (!esAdmin) return ''; + return '
' + + (bloqueada ? '' : '') + + '' + + '' + + '' + + '
'; + } + + function editPanelHtml(k) { + var options = RESET_OPTIONS.map(function (o) { + return ''; + }).join(''); + + return '
' + + '
' + + '' + + '' + + '
' + + '
' + + '' + + '' + + '
' + + '' + + '' + + '
'; + } + + function patchKey(provider, identificador, body) { + return fetch('/keys/' + encodeURIComponent(provider) + '/' + encodeURIComponent(identificador), { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }).then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }); + } + + function deleteKey(provider, identificador) { + return fetch('/keys/' + encodeURIComponent(provider) + '/' + encodeURIComponent(identificador), { method: 'DELETE' }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }); + } + + function mostrarErrorAccion(msg) { + loadError.textContent = msg; + loadError.classList.add('visible'); + } + + // ---------- Consumidores (individuos con token, P201/Fase3) ---------- + + var consumidores = []; + var consumidoresErrorBanner = document.getElementById("consumidores-error-banner"); + var consumidoresErrorTitle = document.getElementById("consumidores-error-title"); + var tokenBanner = document.getElementById("token-banner"); + var tokenBannerTitle = document.getElementById("token-banner-title"); + var tokenBannerValue = document.getElementById("token-banner-value"); + var tokenCopyBtn = document.getElementById("token-copy-btn"); + + function mostrarErrorConsumidores(msg) { + consumidoresErrorTitle.textContent = msg; + consumidoresErrorBanner.classList.add('visible'); + } + + // ---------- Check-in proactivo (P216/Fase4) ---------- + // Ventana de "reciente" — mismo criterio que bandeja.rb (4x una cadencia + // típica de latido ~300s). Best-effort: si /checkins falla, el resto del + // panel sigue funcionando, solo sin badges. + var checkins = {}; + var CHECKIN_VENTANA_MS = 20 * 60 * 1000; + + function cargarCheckins() { + return fetch('/checkins') + .then(function (r) { return r.ok ? r.json() : {}; }) + .then(function (data) { checkins = data || {}; }) + .catch(function () { checkins = {}; }); + } + + function checkinBadgeHtml(individuo) { + var c = checkins[individuo]; + if (!c || !c.ultimo_reporte) { + return 'sin check-in'; + } + var edad = Date.now() - new Date(c.ultimo_reporte).getTime(); + var reciente = edad <= CHECKIN_VENTANA_MS; + var clase = reciente && c.estado === 'ok' ? 'badge success' : reciente ? 'badge warning' : 'badge stale'; + var etiqueta = reciente ? c.estado : 'stale'; + var texto = etiqueta + ' · ' + fmtRelative(c.ultimo_reporte) + (c.detalle ? ' · ' + c.detalle : ''); + return '' + texto + ''; + } + + function cargarConsumidores() { + return fetch('/consumidores') + .then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }) + .then(function (data) { + consumidores = data; + renderConsumidores(); + }) + .catch(function (e) { + mostrarErrorConsumidores('No se pudo cargar la lista (' + e.message + ').'); + }); + } + + function renderConsumidores() { + document.getElementById("stat-consumidores").textContent = consumidores.length; + + var list = document.getElementById("consumidores-list"); + if (!consumidores.length) { + list.innerHTML = '
Sin individuos con token todavía. Generá el primero abajo.
'; + return; + } + + list.innerHTML = consumidores.map(function (c) { + return '
' + + '
' + + '
' + c.individuo + '
' + + '
token creado ' + fmtRelative(c.creado) + ' · ' + fmtClock(c.creado) + '
' + + '
' + checkinBadgeHtml(c.individuo) + '
' + + '
' + + (esAdmin + ? '
' + + '' + + '' + + '
' + : '') + + '
'; + }).join(''); + } + + function generarToken(individuo) { + return fetch('/consumidores', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ individuo: individuo }) + }).then(function (r) { + return r.json().then(function (data) { + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + return data; + }); + }); + } + + function mostrarTokenGenerado(individuo, token) { + tokenBannerTitle.textContent = 'Token generado para ' + individuo + '.'; + tokenBannerValue.textContent = token; + tokenBanner.classList.add('visible'); + } + + tokenCopyBtn.addEventListener("click", function () { + navigator.clipboard.writeText(tokenBannerValue.textContent).then(function () { + tokenCopyBtn.textContent = "Copiado"; + setTimeout(function () { tokenCopyBtn.textContent = "Copiar"; }, 1500); + }); + }); + + var nuevoIndividuoInput = document.getElementById("f-nuevo-individuo"); + + var addConsumidorToggler = crearTogglerInline("add-consumidor-trigger", "add-consumidor-form", "f-nuevo-individuo", function () { + nuevoIndividuoInput.value = ""; + marcarCampoRequerido("field-nuevo-individuo", "hint-individuo-required", false); + }); + + document.getElementById("add-consumidor-trigger").addEventListener("click", addConsumidorToggler.abrir); + + document.getElementById("add-consumidor-form").addEventListener("click", function (e) { + var btn = e.target.closest("[data-action]"); + if (!btn) return; + if (btn.getAttribute("data-action") === "cancel-new-consumidor") addConsumidorToggler.cerrar(); + if (btn.getAttribute("data-action") === "save-new-consumidor") guardarConsumidorNuevo(btn); + }); + + function guardarConsumidorNuevo(btn) { + var individuo = nuevoIndividuoInput.value.trim(); + var vacio = !individuo; + marcarCampoRequerido("field-nuevo-individuo", "hint-individuo-required", vacio); + if (vacio) return; + + btn.disabled = true; + + generarToken(individuo) + .then(function (data) { + addConsumidorToggler.cerrar(); + mostrarTokenGenerado(data.individuo, data.token); + return cargarConsumidores(); + }) + .catch(function (err) { mostrarErrorConsumidores('No se pudo generar el token: ' + err.message); }) + .finally(function () { btn.disabled = false; }); + } + + document.getElementById("consumidores-list").addEventListener("click", function (e) { + var btn = e.target.closest("[data-consumidor-action]"); + if (!btn) return; + var card = e.target.closest(".consumidor-card"); + var individuo = card.getAttribute("data-individuo"); + var action = btn.getAttribute("data-consumidor-action"); + + if (action === "rotar") { + generarToken(individuo) + .then(function (data) { + mostrarTokenGenerado(data.individuo, data.token); + return cargarConsumidores(); + }) + .catch(function (err) { mostrarErrorConsumidores('No se pudo rotar el token: ' + err.message); }); + } else if (action === "revocar") { + abrirModalConfirmacion({ + titulo: "Revocar acceso", + confirmValue: individuo, + accion: "Sí, revocar", + accionEnCurso: "Revocando…", + bodyHtml: '¿Revocar el acceso de ' + individuo + '? Esta acción no se puede deshacer — el individuo no va a poder pedir keys hasta que se le genere un token nuevo.', + onConfirm: function () { + return fetch('/consumidores/' + encodeURIComponent(individuo), { method: 'DELETE' }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }); + }, + onDone: cargarConsumidores + }); + } + }); + + // ---------- Usuarios (gestión del panel, P201/Fase4 — solo perfil admin) ---------- + + var usuarios = []; + var editingUsuario = null; + var usuariosErrorBanner = document.getElementById("usuarios-error-banner"); + var usuariosErrorTitle = document.getElementById("usuarios-error-title"); + + function mostrarErrorUsuarios(msg) { + usuariosErrorTitle.textContent = msg; + usuariosErrorBanner.classList.add('visible'); + } + + function cargarUsuarios() { + return fetch('/usuarios') + .then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }) + .then(function (data) { + usuarios = data; + renderUsuarios(); + }) + .catch(function (e) { + mostrarErrorUsuarios('No se pudo cargar la lista (' + e.message + ').'); + }); + } + + function actionsHtmlUsuario(u) { + var activo = u.activo !== false; + return '
' + + '' + + '' + + '' + + '
'; + } + + function editPanelHtmlUsuario(u) { + return '
' + + '
' + + '' + + '' + + '
' + + '
' + + '' + + '' + + '
' + + '' + + '' + + '
'; + } + + function renderUsuarios() { + var list = document.getElementById("usuarios-list"); + if (!usuarios.length) { + list.innerHTML = '
Sin usuarios todavía.
'; + return; + } + + list.innerHTML = usuarios.map(function (u) { + var activo = u.activo !== false; + var estadoHtml = activo + ? 'activo' + : 'inactivo'; + return '
' + + '
' + + '
Usuario
' + + '
' + u.usuario + '
' + + '
' + + '
' + + '
Perfil
' + + '
' + u.perfil + '
' + + '
' + + '
' + + '
Estado
' + + estadoHtml + + '
' + + '
' + + '
Creado
' + + '
' + fmtRelative(u.creado) + ' · ' + fmtClock(u.creado) + '
' + + '
' + + (editingUsuario === u.usuario ? editPanelHtmlUsuario(u) : actionsHtmlUsuario(u)) + + '
'; + }).join(''); + } + + document.getElementById("usuarios-list").addEventListener("click", function (e) { + var btn = e.target.closest("[data-usuario-action]"); + if (!btn) return; + var card = e.target.closest(".key-card"); + var usuario = card.getAttribute("data-usuario"); + var action = btn.getAttribute("data-usuario-action"); + var u = usuarios.find(function (uu) { return uu.usuario === usuario; }); + + if (action === "edit") { + editingUsuario = usuario; + renderUsuarios(); + } else if (action === "cancel-edit") { + editingUsuario = null; + renderUsuarios(); + } else if (action === "save-edit") { + var perfil = card.querySelector(".ep-perfil").value; + var passwordNueva = card.querySelector(".ep-password").value; + var body = { perfil: perfil }; + if (passwordNueva) body.password = passwordNueva; + fetch('/usuarios/' + encodeURIComponent(usuario), { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }) + .then(function () { editingUsuario = null; return cargarUsuarios(); }) + .catch(function (err) { mostrarErrorUsuarios('No se pudo editar: ' + err.message); }); + } else if (action === "toggle-activo") { + var nuevoActivo = !(u.activo !== false); + fetch('/usuarios/' + encodeURIComponent(usuario), { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ activo: nuevoActivo }) + }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }) + .then(function () { return cargarUsuarios(); }) + .catch(function (err) { mostrarErrorUsuarios('No se pudo cambiar el estado: ' + err.message); }); + } else if (action === "delete") { + abrirModalConfirmacion({ + titulo: "Eliminar usuario", + confirmValue: usuario, + accion: "Sí, eliminar", + accionEnCurso: "Eliminando…", + bodyHtml: '¿Eliminar el usuario ' + usuario + '? Esta acción no se puede deshacer — pierde acceso al panel inmediatamente.', + onConfirm: function () { + return fetch('/usuarios/' + encodeURIComponent(usuario), { method: 'DELETE' }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return r.json(); + }); + }, + onDone: cargarUsuarios + }); + } + }); + + var nuevoUsuarioInput = document.getElementById("f-nuevo-usuario"); + var nuevoUsuarioPasswordInput = document.getElementById("f-nuevo-usuario-password"); + var toggleNuevoUsuarioPassword = document.getElementById("toggle-nuevo-usuario-password"); + + toggleNuevoUsuarioPassword.addEventListener("click", function () { + var showing = nuevoUsuarioPasswordInput.type === "text"; + nuevoUsuarioPasswordInput.type = showing ? "password" : "text"; + toggleNuevoUsuarioPassword.textContent = showing ? "mostrar" : "ocultar"; + }); + + var addUsuarioToggler = crearTogglerInline("add-usuario-trigger", "add-usuario-form", "f-nuevo-usuario", function () { + nuevoUsuarioInput.value = ""; + nuevoUsuarioPasswordInput.value = ""; + nuevoUsuarioPasswordInput.type = "password"; + toggleNuevoUsuarioPassword.textContent = "mostrar"; + marcarCampoRequerido("field-nuevo-usuario", "hint-usuario-required", false); + marcarCampoRequerido("field-nuevo-usuario-password", "hint-usuario-password-required", false); + }); + + document.getElementById("add-usuario-trigger").addEventListener("click", addUsuarioToggler.abrir); + + document.getElementById("add-usuario-form").addEventListener("click", function (e) { + var btn = e.target.closest("[data-action]"); + if (!btn) return; + if (btn.getAttribute("data-action") === "cancel-new-usuario") addUsuarioToggler.cerrar(); + if (btn.getAttribute("data-action") === "save-new-usuario") guardarUsuarioNuevo(btn); + }); + + function guardarUsuarioNuevo(btn) { + var usuario = nuevoUsuarioInput.value.trim(); + var perfil = document.getElementById("f-nuevo-perfil").value; + var password = nuevoUsuarioPasswordInput.value; + + var usuarioVacio = !usuario; + var passwordVacia = !password; + marcarCampoRequerido("field-nuevo-usuario", "hint-usuario-required", usuarioVacio); + marcarCampoRequerido("field-nuevo-usuario-password", "hint-usuario-password-required", passwordVacia); + if (usuarioVacio || passwordVacia) return; + + btn.disabled = true; + + fetch('/usuarios', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ usuario: usuario, perfil: perfil, password: password }) + }) + .then(function (r) { + return r.json().then(function (data) { return { ok: r.ok, data: data }; }); + }) + .then(function (result) { + if (!result.ok) throw new Error(result.data.error || ('HTTP ' + result.status)); + addUsuarioToggler.cerrar(); + return cargarUsuarios(); + }) + .catch(function (e) { mostrarErrorUsuarios(e.message); }) + .finally(function () { btn.disabled = false; }); + } + + document.getElementById("groups").addEventListener("click", function (e) { + var btn = e.target.closest("[data-action]"); + if (!btn) return; + + var card = e.target.closest(".key-card"); + var provider = card.getAttribute("data-provider"); + var identificador = card.getAttribute("data-identificador"); + var action = btn.getAttribute("data-action"); + + if (action === "edit") { + editing = provider + '/' + identificador; + render(); + } else if (action === "cancel-edit") { + editing = null; + render(); + } else if (action === "save-edit") { + var cuenta = card.querySelector(".ep-cuenta").value.trim(); + var reset = card.querySelector(".ep-reset").value; + patchKey(provider, identificador, { cuenta_origen: cuenta, reset_segundos: reset }) + .then(function () { editing = null; return cargarKeys(); }) + .catch(function (err) { mostrarErrorAccion('No se pudo editar: ' + err.message); }); + } else if (action === "toggle-activo") { + var k = keys.find(function (kk) { return kk.provider === provider && kk.identificador === identificador; }); + var nuevoActivo = !(k.activo !== false); + patchKey(provider, identificador, { activo: nuevoActivo }) + .then(function () { return cargarKeys(); }) + .catch(function (err) { mostrarErrorAccion('No se pudo cambiar el estado: ' + err.message); }); + } else if (action === "delete") { + abrirModalEliminar(provider, identificador); + } else if (action === "liberar") { + fetch('/keys/' + encodeURIComponent(provider) + '/' + encodeURIComponent(identificador) + '/liberar', { method: 'POST' }) + .then(function (r) { + if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || ('HTTP ' + r.status)); }); + return cargarKeys(); + }) + .catch(function (err) { mostrarErrorAccion('No se pudo liberar: ' + err.message); }); + } + }); + + var deleteModalBackdrop = document.getElementById("delete-modal-backdrop"); + var deleteModalTitle = document.getElementById("delete-modal-title"); + var deleteModalBody = document.getElementById("delete-modal-body"); + var deleteModalLabel = document.getElementById("delete-modal-label"); + var deleteModalInput = document.getElementById("delete-modal-input"); + var deleteModalCancel = document.getElementById("delete-modal-cancel"); + var deleteModalConfirm = document.getElementById("delete-modal-confirm"); + + // Modal genérico de confirmación destructiva — "type to confirm" (pedido + // del Operador). Usado tanto para eliminar keys como revocar consumidores: + // pendingDelete = { confirmValue, accion, onConfirm, onDone }. + function abrirModalConfirmacion(opts) { + pendingDelete = opts; + deleteModalTitle.textContent = opts.titulo || "Confirmar"; + deleteModalBody.innerHTML = opts.bodyHtml; + deleteModalLabel.textContent = 'Escribí "' + opts.confirmValue + '" para confirmar'; + deleteModalInput.value = ""; + deleteModalBackdrop.classList.add("visible"); + deleteModalConfirm.textContent = opts.accion; + deleteModalConfirm.disabled = true; + deleteModalInput.focus(); + } + + function abrirModalEliminar(provider, identificador) { + abrirModalConfirmacion({ + titulo: "Eliminar key", + confirmValue: identificador, + accion: "Sí, eliminar", + accionEnCurso: "Eliminando…", + bodyHtml: '¿Eliminar ' + identificador + ' (' + provider + ')? Esta acción no se puede deshacer — el historial de uso en usos.log se conserva, pero la key deja de existir en el registro.', + onConfirm: function () { return deleteKey(provider, identificador); }, + onDone: cargarKeys + }); + } + + function cerrarModalEliminar() { + pendingDelete = null; + deleteModalInput.value = ""; + deleteModalBackdrop.classList.remove("visible"); + } + + deleteModalInput.addEventListener("input", function () { + deleteModalConfirm.disabled = !pendingDelete || deleteModalInput.value !== pendingDelete.confirmValue; + }); + + deleteModalCancel.addEventListener("click", cerrarModalEliminar); + + deleteModalBackdrop.addEventListener("click", function (e) { + if (e.target === deleteModalBackdrop) cerrarModalEliminar(); + }); + + document.addEventListener("keydown", function (e) { + if (e.key === "Escape" && deleteModalBackdrop.classList.contains("visible")) cerrarModalEliminar(); + }); + + deleteModalConfirm.addEventListener("click", function () { + if (!pendingDelete) return; + var accionTexto = pendingDelete.accion; + var onDone = pendingDelete.onDone; + deleteModalConfirm.disabled = true; + deleteModalConfirm.textContent = pendingDelete.accionEnCurso; + pendingDelete.onConfirm() + .then(function () { + cerrarModalEliminar(); + return onDone(); + }) + .catch(function (err) { + deleteModalConfirm.disabled = false; + deleteModalConfirm.textContent = accionTexto; + mostrarErrorAccion('No se pudo completar: ' + err.message); + }); + }); + + function render() { + var groups = document.getElementById("groups"); + groups.innerHTML = ""; + + var byProvider = {}; + keys.forEach(function (k) { + (byProvider[k.provider] = byProvider[k.provider] || []).push(k); + }); + + var providers = Object.keys(byProvider).sort(); + var ahora = Date.now(); + // P204/Fase3: agotada = disponible_desde en el futuro (agotamiento REAL, + // reportado por el consumidor) — reservada = bajo reserva corta de + // contención (reservado_hasta en el futuro), no es lo mismo. + var agotadas = keys.filter(function (k) { return new Date(k.disponible_desde).getTime() > ahora; }).length; + var reservadas = keys.filter(function (k) { + return k.reservado_hasta && new Date(k.reservado_hasta).getTime() > ahora; + }).length; + + document.getElementById("stat-total").textContent = keys.length; + document.getElementById("stat-providers").textContent = providers.length; + document.getElementById("stat-agotadas").textContent = agotadas; + document.getElementById("stat-reservadas").textContent = reservadas; + + renderGauges(byProvider); + + // Autocompletar "Cuenta de origen" con las ya cargadas (P204/Fase4, + // pedido del Operador) — evita retipear siempre desde cero. + // nativo, sin JS de más: el navegador ya sabe filtrar/sugerir solo. + var cuentasList = document.getElementById("cuentas-origen-conocidas"); + if (cuentasList) { + var cuentas = Array.from(new Set(keys.map(function (k) { return k.cuenta_origen; }).filter(Boolean))).sort(); + cuentasList.innerHTML = cuentas.map(function (c) { return ''; }).join(''); + } + + if (!keys.length) { + groups.innerHTML = '
Sin keys registradas todavía. Usá la pestaña «Alta de key» para cargar la primera.
'; + return; + } + + providers.forEach(function (provider) { + var title = document.createElement("div"); + title.className = "group-title"; + title.innerHTML = '' + provider + '' + byProvider[provider].length + ''; + groups.appendChild(title); + + var list = document.createElement("div"); + list.className = "card-list"; + + byProvider[provider] + .slice() + // Orden por último uso, no por disponible_desde (P204/Fase4, pedido + // del Operador: la vista tiene que reflejar cómo se CONSUME el pool, + // no un campo administrativo) — la que menos se usó recientemente + // aparece primero, mismo criterio que Registro.disponible en el + // backend (rotación) — así la lista muestra literalmente "quién + // sigue" en el orden real de reparto. + .sort(function (a, b) { + var uaA = a.ultimo_uso ? new Date(a.ultimo_uso).getTime() : 0; + var uaB = b.ultimo_uso ? new Date(b.ultimo_uso).getTime() : 0; + return uaA - uaB; + }) + .forEach(function (k) { + var keyId = k.provider + '/' + k.identificador; + var activo = k.activo !== false; + // P204/Fase3: agotada (disponible_desde futuro, agotamiento real + // reportado por el consumidor) y reservada (reservado_hasta futuro, + // contención corta al dispensar) son estados distintos — una key + // puede estar reservada sin estar agotada, y viceversa nunca (agotada + // siempre libera la reserva). Reflejar exactamente el mismo filtro + // que usa Registro.disponible en el backend (Armonía Integral). + var agotada = new Date(k.disponible_desde).getTime() > ahora; + var reservada = !agotada && k.reservado_hasta && new Date(k.reservado_hasta).getTime() > ahora; + var disponible = activo && !agotada && !reservada; + var isNew = lastCreated && lastCreated.provider === k.provider && lastCreated.identificador === k.identificador; + var card = document.createElement("div"); + card.className = "key-card" + (isNew ? " is-new" : ""); + card.setAttribute("data-provider", k.provider); + card.setAttribute("data-identificador", k.identificador); + + // Estado + su timing van juntos (P204/Fase4, rediseño de columnas + // por propósito real — el timing es una aclaración del estado, no + // un dato independiente) — pill arriba, "vence en X"/"libera en X" + // como subtexto, sin ocupar una columna propia. + var estadoHtml, timingSub; + if (!activo) { + estadoHtml = 'desactivada'; + timingSub = ''; + } else if (disponible) { + estadoHtml = 'disponible'; + timingSub = ''; + } else if (reservada) { + estadoHtml = 'reservada'; + timingSub = 'vence ' + fmtRelative(k.reservado_hasta); + } else { + estadoHtml = 'agotada'; + timingSub = 'libera ' + fmtRelative(k.disponible_desde) + + (k.agotada_por ? ' · por ' + esc(k.agotada_por) : '') + + (k.motivo_agotada ? ' · ' + esc(k.motivo_agotada) : ''); + } + + var asignadaHtml; + if (reservada && k.reservado_por) { + asignadaHtml = '
' + esc(k.reservado_por) + '
'; + } else if (k.ultimo_individuo) { + asignadaHtml = '
último: ' + esc(k.ultimo_individuo) + '
'; + } else { + asignadaHtml = '
— libre —
'; + } + + // Último uso (P204/Fase4, pedido del Operador): NEXXA sirve keys — + // el dato que más importa operativamente es cuándo se dispensó por + // última vez, no cuándo "vence" algo. Es también la señal visual + // de que la rotación (Fase4/4.6) funciona: ninguna key debería + // quedar mucho más atrás que las demás del mismo provider. + var ultimoUsoHtml = k.ultimo_uso + ? '' + fmtRelative(k.ultimo_uso) + ' · ' + fmtClock(k.ultimo_uso) + : 'nunca'; + + card.innerHTML = + '
' + + '
Identificador
' + + '
' + esc(k.identificador) + '
' + + '
' + esc(k.provider) + ' · cuenta: ' + esc(k.cuenta_origen) + '
' + + '
' + + '
' + + '
Estado
' + + estadoHtml + + (timingSub ? '
' + timingSub + '
' : '') + + '
' + + '
' + + '
Último uso
' + + '
' + ultimoUsoHtml + '
' + + '
' + + '
' + + '
Asignada a
' + + asignadaHtml + + '
' + + (editing === keyId ? editPanelHtml(k) : actionsHtml(k, keyId, activo, activo && (agotada || reservada))); + + list.appendChild(card); + }); + + groups.appendChild(list); + }); + } + + // Gauges circulares por provider (P204/Fase4, estilo resumen de Proxmox) — + // distribución real del pool: qué % de las APIs registradas es de cada + // proveedor (no "% en uso", que confundía — un gauge de uso solo tiene + // sentido comparado contra el resto del mismo provider, no como % del + // total, y con un solo provider siempre daba una lectura rara). Se + // calcula de los datos ya cargados de /keys, sin fetch propio. + function renderGauges(byProvider) { + var el = document.getElementById("gauges"); + if (!el) return; + + var providers = Object.keys(byProvider).sort(); + if (!providers.length) { + el.innerHTML = ''; + return; + } + + var totalKeys = providers.reduce(function (sum, p) { + return sum + byProvider[p].filter(function (k) { return k.activo !== false; }).length; + }, 0); + + el.innerHTML = providers.map(function (provider) { + var count = byProvider[provider].filter(function (k) { return k.activo !== false; }).length; + var pct = totalKeys ? Math.round((count / totalKeys) * 100) : 0; + return gaugeHtml(pct, provider, count + '/' + totalKeys); + }).join(''); + } + + function gaugeHtml(pct, label, sub) { + var r = 46, c = Math.round(2 * Math.PI * r); + var offset = Math.round(c - (pct / 100) * c); + // Distribución, no alerta — a diferencia de un gauge de "% en uso", acá + // un valor alto no es malo (un solo provider = 100%, es normal), así + // que no escala a rojo/naranja como si fuera una advertencia. + var color = 'var(--accent)'; + return ( + '
' + + '' + + '' + + '' + + '' + pct + '%' + + '' + sub + '' + + '' + + '
' + label + '
' + + '
' + ); + } + + // Actividad reciente + gráfico de dispensas por día (P204/Fase4) — ambos + // proporcionados al volumen real de usos.log (hoy escaso): la lista muestra + // lo que hay sin inventar agregados, el gráfico crece solo con el uso real. + function renderActividad(usos) { + var el = document.getElementById("actividad-lista"); + if (!el) return; + + if (!usos.length) { + el.innerHTML = '
Sin actividad registrada todavía.
'; + return; + } + + el.innerHTML = usos.slice(0, 15).map(function (u) { + var agotada = u.evento === 'agotada'; + var icon = agotada ? '🔴' : '🟢'; + var accion = agotada ? 'reportó agotada' : 'pidió'; + return ( + '
' + + '' + icon + '' + + '' + u.individuo + ' ' + accion + ' ' + u.provider + '/' + u.identificador + '' + + '' + fmtRelative(u.en) + '' + + '
' + ); + }).join(''); + } + + function renderBarChart(usos) { + var el = document.getElementById("bar-chart"); + if (!el) return; + + var dias = []; + for (var i = 6; i >= 0; i--) { + var d = new Date(); + d.setDate(d.getDate() - i); + dias.push(d.toISOString().slice(0, 10)); + } + var counts = {}; + dias.forEach(function (d) { counts[d] = 0; }); + usos.forEach(function (u) { + var d = String(u.en).slice(0, 10); + if (counts.hasOwnProperty(d)) counts[d]++; + }); + var max = Math.max.apply(null, dias.map(function (d) { return counts[d]; }).concat([1])); + + el.innerHTML = dias.map(function (d) { + var h = Math.max(2, Math.round((counts[d] / max) * 60)); + return ( + '
' + + '
' + + '
' + d.slice(5) + '
' + + '
' + ); + }).join(''); + } + + // Reportes por individuo (P204/Fase4, pedido del Operador) — mismo /usos, + // otra lectura: no "cuándo" sino "quién reporta qué" — barra apilada + // sana+liberada (verde) vs agotada (naranja) por individuo, ordenado por + // volumen total. + function renderReportesPorIndividuo(usos) { + var el = document.getElementById("reportes-individuo"); + if (!el) return; + + var counts = {}; + usos.forEach(function (u) { + counts[u.individuo] = counts[u.individuo] || { ok: 0, agotada: 0 }; + if (u.evento === 'agotada') counts[u.individuo].agotada++; + else counts[u.individuo].ok++; + }); + + var individuos = Object.keys(counts).sort(function (a, b) { + var totalA = counts[a].ok + counts[a].agotada; + var totalB = counts[b].ok + counts[b].agotada; + return totalB - totalA; + }); + + if (!individuos.length) { + el.innerHTML = '
Sin reportes todavía.
'; + return; + } + + var max = Math.max.apply(null, individuos.map(function (i) { return counts[i].ok + counts[i].agotada; })); + + el.innerHTML = individuos.map(function (ind) { + var c = counts[ind]; + var total = c.ok + c.agotada; + var pctOk = max ? (c.ok / max) * 100 : 0; + var pctAgotada = max ? (c.agotada / max) * 100 : 0; + return ( + '
' + + '
' + ind + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + total + '
' + + '
' + ); + }).join(''); + } + + function cargarUsos() { + return fetch('/usos') + .then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }) + .then(function (usos) { + renderActividad(usos); + renderBarChart(usos); + renderReportesPorIndividuo(usos); + }) + .catch(function () { + // Silencioso a propósito — cargarKeys ya reporta problemas de conexión + // en el banner principal, no hace falta duplicar el aviso acá. + }); + } + + function cargarKeys() { + return fetch('/keys') + .then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }) + .then(function (data) { + keys = data; + actualizarProvidersConocidos(); + loadError.classList.remove('visible'); + nodePill.classList.remove('error'); + nodePillText.textContent = 'servicio activo · puerto 4568'; + render(); + }) + .catch(function (e) { + loadError.textContent = 'No se pudo cargar el estado de las keys (' + e.message + ').'; + loadError.classList.add('visible'); + nodePill.classList.add('error'); + nodePillText.textContent = 'sin conexión'; + }); + } + + // Sugerencias de provider para el alta (P335/Fase 7): los que ya tienen keys + los habituales, sin lista fija + var PROVIDERS_HABITUALES = ["gemini", "deepseek", "groq", "openai", "anthropic"]; + function actualizarProvidersConocidos() { + var vistos = {}; + PROVIDERS_HABITUALES.concat(keys.map(function (k) { return k.provider; })).forEach(function (p) { vistos[p] = true; }); + document.getElementById("providers-conocidos").innerHTML = Object.keys(vistos).sort().map(function (p) { + return ''; + }).join(''); + } + + var toggleValor = document.getElementById("toggle-valor"); + var valorInput = document.getElementById("f-valor"); + toggleValor.addEventListener("click", function () { + var showing = valorInput.type === "text"; + valorInput.type = showing ? "password" : "text"; + toggleValor.textContent = showing ? "mostrar" : "ocultar"; + }); + + // Fichas inline de alta ("+" sobre la lista, P201/Fase3 — reemplazan las + // pestañas separadas de alta: mismo estilo visual que las fichas ya + // cargadas, se abren/cierran in-place). abrir/cerrar es el mismo + // mecanismo para keys y consumidores — un solo helper, no duplicado. + function crearTogglerInline(triggerId, formId, primerCampoId, limpiarFn) { + var trigger = document.getElementById(triggerId); + var form = document.getElementById(formId); + return { + abrir: function () { + trigger.style.display = "none"; + form.classList.add("visible"); + document.getElementById(primerCampoId).focus(); + }, + cerrar: function () { + if (limpiarFn) limpiarFn(); + form.classList.remove("visible"); + trigger.style.display = ""; + } + }; + } + + // Toggle de error+hint de un campo requerido — mismo patrón repetido en + // el alta de keys y en el alta de consumidores, extraído una sola vez. + function marcarCampoRequerido(fieldId, hintId, vacio) { + document.getElementById(fieldId).classList.toggle("has-error", vacio); + document.getElementById(hintId).classList.toggle("visible", vacio); + } + + var addKeyErrorBanner = document.getElementById("add-key-error-banner"); + var addKeyErrorTitle = document.getElementById("add-key-error-title"); + + function limpiarAddKeyForm() { + document.getElementById("f-identificador").value = ""; + document.getElementById("f-cuenta-origen").value = ""; + valorInput.value = ""; + valorInput.type = "password"; + toggleValor.textContent = "mostrar"; + marcarCampoRequerido("field-identificador", "hint-id-required", false); + document.getElementById("hint-id-taken").classList.remove("visible"); + marcarCampoRequerido("field-cuenta-origen", "hint-cuenta-required", false); + marcarCampoRequerido("field-valor", "hint-valor-required", false); + addKeyErrorBanner.classList.remove("visible"); + } + + var addKeyToggler = crearTogglerInline("add-key-trigger", "add-key-form", "f-identificador", limpiarAddKeyForm); + + document.getElementById("add-key-trigger").addEventListener("click", addKeyToggler.abrir); + + document.getElementById("add-key-form").addEventListener("click", function (e) { + var btn = e.target.closest("[data-action]"); + if (!btn) return; + if (btn.getAttribute("data-action") === "cancel-new") addKeyToggler.cerrar(); + if (btn.getAttribute("data-action") === "save-new") guardarKeyNueva(btn); + }); + + function guardarKeyNueva(btn) { + var identificador = document.getElementById("f-identificador").value.trim(); + var cuentaOrigen = document.getElementById("f-cuenta-origen").value.trim(); + var valor = valorInput.value; + var provider = document.getElementById("f-provider").value.trim().toLowerCase(); + var resetSegundos = document.getElementById("f-reset").value; + + var idVacio = !identificador; + var idTaken = !idVacio && keys.some(function (k) { return k.provider === provider && k.identificador === identificador; }); + + marcarCampoRequerido("field-identificador", "hint-id-required", idVacio); + document.getElementById("hint-id-taken").classList.toggle("visible", idTaken); + document.getElementById("field-identificador").classList.toggle("has-error", idVacio || idTaken); + marcarCampoRequerido("field-cuenta-origen", "hint-cuenta-required", !cuentaOrigen); + marcarCampoRequerido("field-valor", "hint-valor-required", !valor); + addKeyErrorBanner.classList.remove("visible"); + + if (!provider) { + addKeyErrorTitle.textContent = 'Falta el provider (ej. gemini, deepseek).'; + addKeyErrorBanner.classList.add("visible"); + } + if (!provider || idVacio || idTaken || !cuentaOrigen || !valor) return; + + btn.disabled = true; + + fetch('/alta', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + provider: provider, + identificador: identificador, + cuenta_origen: cuentaOrigen, + reset_segundos: resetSegundos, + valor: valor + }) + }) + .then(function (r) { + return r.json().then(function (data) { return { ok: r.ok, status: r.status, data: data }; }); + }) + .then(function (result) { + if (!result.ok) { + throw new Error(result.data.error || ('HTTP ' + result.status)); + } + + lastCreated = { provider: provider, identificador: identificador }; + addKeyToggler.cerrar(); + return cargarKeys(); + }) + .catch(function (e) { + addKeyErrorTitle.textContent = e.message; + addKeyErrorBanner.classList.add("visible"); + }) + .finally(function () { + btn.disabled = false; + }); + } + + // ---------- Pools por individuo: mente y red (P335/Fase 7) ---------- + // Lee /pools (estado de cada key de cada pool, nunca valores) y /consumidores (individuos con token: aparecen + // aunque todavía no tengan pool). Asignar/quitar solo admin; el backend lo valida igual (ME-683). + var poolsError = document.getElementById("pools-error"); + var poolsLista = document.getElementById("pools-lista"); + var ROLES_POOL = [ + { rol: "mente", titulo: "🧠 Mente", ayuda: "piensa y opera" }, + { rol: "red", titulo: "🪫 Red", ayuda: "solo aviso de batería baja" } + ]; + + function pedirJson(url, opts) { + return fetch(url, opts).then(function (r) { + return r.json().then(function (d) { + if (!r.ok) throw new Error(d.error || ('HTTP ' + r.status)); + return d; + }); + }); + } + + function cargarPools() { + poolsError.classList.remove('visible'); + return Promise.all([pedirJson('/pools'), pedirJson('/consumidores')]) + .then(function (res) { renderPools(res[0].individuos || {}, res[1] || []); }) + .catch(function (e) { + poolsError.textContent = 'No se pudieron cargar los pools (' + e.message + ').'; + poolsError.classList.add('visible'); + }); + } + + function pillEstado(f) { + var clase = { disponible: 'ok', reservada: 'info', agotada: 'warn', inactiva: 'inactive' }[f.estado] || 'inactive'; + var detalle = f.estado === 'agotada' + ? (f.libera_en ? ' · libera ' + fmtRelative(f.libera_en) : '') + (f.agotada_por ? ' · por ' + esc(f.agotada_por) : '') + + (f.motivo ? ' · ' + esc(f.motivo) : '') + : (f.estado === 'reservada' && f.reservado_por ? ' · ' + esc(f.reservado_por) : ''); + return '' + esc(f.estado) + '' + + (detalle ? '
' + detalle + '
' : ''); + } + + function renderPools(pools, consumidoresLista) { + var nombres = {}; + consumidoresLista.forEach(function (c) { nombres[c.individuo] = true; }); + Object.keys(pools).forEach(function (n) { nombres[n] = true; }); + var lista = Object.keys(nombres).sort(); + if (!lista.length) { + poolsLista.innerHTML = '
Sin individuos con token todavía. Dalos de alta en «Individuos».
'; + return; + } + + poolsLista.innerHTML = lista.map(function (ind) { + var columnas = ROLES_POOL.map(function (r) { + var filas = (pools[ind] && pools[ind][r.rol]) || []; + var enPool = {}; + filas.forEach(function (f) { enPool[f.provider + '/' + f.identificador] = true; }); + var items = filas.length ? filas.map(function (f) { + return '
' + + '
' + esc(f.identificador) + ' ' + esc(f.provider) + '
' + + '
' + pillEstado(f) + '
' + + (esAdmin ? '' : '') + + '
'; + }).join('') : '
— vacío: NEXXA responde pool_vacio —
'; + var opciones = keys.filter(function (k) { return !enPool[k.provider + '/' + k.identificador]; }) + .map(function (k) { + var v = esc(k.provider + '/' + k.identificador); + return ''; + }).join(''); + var agregar = esAdmin && opciones + ? '
' + + '
' + : ''; + return '
' + + '
' + r.titulo + ' · ' + r.ayuda + '
' + + items + agregar + '
'; + }).join(''); + return '
' + + '
Individuo
' + esc(ind) + '
' + + columnas + '
'; + }).join(''); + } + + poolsLista.addEventListener("click", function (e) { + var btn = e.target.closest("[data-action]"); + if (!btn) return; + var card = btn.closest(".pool-card"); + var col = btn.closest(".pool-col"); + var base = '/pools/' + encodeURIComponent(card.getAttribute("data-individuo")) + '/' + col.getAttribute("data-rol"); + var accion; + if (btn.getAttribute("data-action") === "pool-agregar") { + var ref = col.querySelector("select").value.split('/'); + accion = pedirJson(base, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ provider: ref[0], identificador: ref.slice(1).join('/') }) + }); + } else if (btn.getAttribute("data-action") === "pool-quitar") { + var item = btn.closest(".pool-key"); + accion = pedirJson(base + '/' + encodeURIComponent(item.getAttribute("data-provider")) + '/' + + encodeURIComponent(item.getAttribute("data-identificador")), { method: 'DELETE' }); + } else { + return; + } + btn.disabled = true; + accion.then(cargarPools).catch(function (err) { + btn.disabled = false; + poolsError.textContent = 'No se pudo cambiar el pool: ' + err.message; + poolsError.classList.add('visible'); + }); + }); + })(); diff --git a/servicios/nexxa/web/js/login.js b/servicios/nexxa/web/js/login.js new file mode 100644 index 00000000..0c91d9e5 --- /dev/null +++ b/servicios/nexxa/web/js/login.js @@ -0,0 +1,43 @@ +(function () { + "use strict"; + + var form = document.getElementById("login-form"); + var usuarioInput = document.getElementById("f-usuario"); + var passwordInput = document.getElementById("f-password"); + var submitBtn = document.getElementById("login-submit"); + var errorEl = document.getElementById("login-error"); + var versionEl = document.getElementById("version-tag"); + + if (versionEl) { + fetch("/version") + .then(function (r) { return r.json(); }) + .then(function (d) { versionEl.textContent = "v" + d.version; }) + .catch(function () {}); + } + + form.addEventListener("submit", function (e) { + e.preventDefault(); + errorEl.classList.remove("visible"); + submitBtn.disabled = true; + + fetch("/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ usuario: usuarioInput.value, password: passwordInput.value }) + }) + .then(function (r) { + return r.json().then(function (data) { return { ok: r.ok, data: data }; }); + }) + .then(function (result) { + if (!result.ok) throw new Error(result.data.error || "Usuario o password incorrectos"); + location.reload(); + }) + .catch(function (err) { + errorEl.textContent = err.message; + errorEl.classList.add("visible"); + passwordInput.value = ""; + passwordInput.focus(); + submitBtn.disabled = false; + }); + }); +})(); diff --git a/servicios/nexxa/web/login.html b/servicios/nexxa/web/login.html new file mode 100644 index 00000000..3abb7a7d --- /dev/null +++ b/servicios/nexxa/web/login.html @@ -0,0 +1,108 @@ + + + + + +NEXXA · Ingresar + + + + + + + +