feat(pasarela): campo opcional de descripción en la pasarela de proponer local
deploy-branch / deploy (push) Successful in 3m11s
deploy-branch / teardown (push) Skipped
tests / Unitarias + componente + build (push) Failing after 3m27s
tests / Integración (Nominatim real, opt-in) (push) Skipped
tests / Unitarias + componente + build (pull_request) Failing after 3m0s
tests / Integración (Nominatim real, opt-in) (pull_request) Skipped

Nueva pantalla "Descripción" (paso 5 de 6, opcional, máx. 200 caracteres)
entre Tipo específico y Revisión. La descripción viaja en la propuesta
(trim; vacía → ausente/NULL), el filtro de palabras prohibidas la cubre y
el resumen la muestra. Backend/BD ya la soportaban: cambio frontend-only.

Incluye el archivo del cambio hide-admin-route y la propuesta
openspec del nuevo cambio. Suite: 114/114.
This commit is contained in:
2026-10-11 15:04:37 +02:00
parent 695d59d31e
commit d34ebf7ca0
18 changed files with 350 additions and 10 deletions
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-30
@@ -0,0 +1,150 @@
# Design: Hide Admin Route
> **Actualización 1 (2026-10-02) — decisión del usuario:** se descarta el
> middleware de enmascaramiento con 404. Enfoque adoptado: **prefijo de
> administración configurable** (`LOCALESP_ADMIN_PREFIX` en el servidor,
> `VITE_ADMIN_PREFIX` al compilar el frontend). Las rutas
> admin solo se registran bajo ese prefijo; las rutas históricas `/api/...`
> dejan de existir (404 natural, sin handler). `reportar`/`confirmar` siguen
> públicas (las usa la web) y `DELETE /api/locales/:id` pasa al prefijo.
> No hay middleware: cualquier método, query o variante de las rutas antiguas
> recibe el mismo 404 por construcción.
>
> **Actualización 2 (2026-10-02, petición del usuario):** `LOCALESP_ADMIN_PREFIX`
> pasa a ser **obligatoria y sin valor por defecto**: sin ella el servidor hace
> fail-fast al arrancar. Se añade `.env.example` como template y el servidor
> carga `.env` automáticamente (sin sobrescribir variables del entorno). Se
> elimina el escenario de compatibilidad con prefijo `/api` por defecto.
>
> **Actualización 3 (2026-10-02, petición del usuario):** se elimina la
> redundancia `VITE_ADMIN_PREFIX`: **una sola variable** (`LOCALESP_ADMIN_PREFIX`)
> para servidor, proxy de desarrollo y frontend. Vite la expone al código
> cliente mediante `envPrefix: ["VITE_", "LOCALESP_"]` y `npm run build`
> también falla si falta.
>
> **Actualización 4 (2026-10-02, petición del usuario):** el panel de
> administración también se oculta: vive en la **raíz del prefijo**
> (`$LOCALESP_ADMIN_PREFIX`, p. ej. `/administrador`) y la ruta fija `/admin`
> pasa a mostrar la web pública. Una sola variable define URL del panel y API.
>
> **Actualización 5 (2026-10-03, petición del usuario):** la config por entorno
> pasa del host (`/etc/localesp/<slug>.env`) **al repo**: `scripts/entornos.env`
> mapea `slug=prefijo`. El workflow de deploy la aplica al build y `deploy.sh`
> la materializa como `<dest>/.env`. Sin entrada para la rama: fail-fast.
## Context
The current application serves a list of user-submitted proposals (`/api/pendientes`)
that are meant only for administrators to approve or reject. It also serves a list
of reports (`/api/reportes`) to an admin panel at `/admin`. These routes are publicly
accessible without authentication, making them discoverable via:
- Direct URL access: `GET http://example.com/api/pendientes`
- Route enumeration: `/admin`, `/api/pendientes`, `/api/reportes`
This is a common attack surface for automated scanning and brute-force attempts.
## Goals / Non-Goals
**Goals:**
- Obscure admin-only routes from public discovery
- Prevent accidental or malicious unauthorized access to admin endpoints
- Maintain the same functionality for authenticated admin users
- Do not change the API contract for authenticated users
**Non-Goals:**
- Implementing actual authentication (outside the scope of this change)
- Modifying existing database or frontend changes
- Changing user-visible URLs for authenticated admins
## Decisions
### Approach: 404 Masking Middleware
We will add middleware that intercepts all requests matching admin route patterns
and returns a 404 response, without exposing the pattern in any way.
**Why this approach?**
1. **Minimal friction** — existing admin users who know the URL still get the data
2. **No auth required** — avoids adding another layer of complexity
3. **No breaking changes** — authenticated users are unaffected
4. **Low risk** — does not interfere with other routes
**Alternatives considered:**
| Approach | Pros | Cons | Decision |
|----------|------|------|----------|
| 404 masking | Low friction, no auth needed | Admins must know the URL | ✅ Selected |
| Auth middleware | Full protection | High friction, adds complexity | ❌ Out of scope |
| Rename routes | Hides routes from `app._routes` | Doesn't help against direct access | ❌ Incomplete |
| IP whitelist | Strong protection | High friction, hard to configure | ❌ Out of scope |
### Technical Design
Implement the middleware as a route that matches admin endpoints **before** the SPA fallback (which responds with `index.html` to anything starting with `/` that doesn't start with `/api/`).
The middleware will:
1. Check the request path against the admin route list
2. If matched: return `404` with a generic message
3. If not matched: fall through to existing handlers
**Route patterns to protect:**
- `/api/pendientes`
- `/api/reportes`
- `/api/locales/:id/reportar`
- `/api/locales/:id/confirmar`
- `/api/locales/:id/` (GET — deletes, but GET could also expose)
**Implementation strategy:**
```
Middleware Position: Before the SPA fallback, after public API routes are established:
1. /api/locales (public)
2. /api/pendientes (→ protected → 404)
3. /api/check-duplicado (public)
4. /api/propuestas (public)
5. /api/aprobar (→ protected → 404)
6. /api/rechazar (→ protected → 404)
7. /api/reportes (→ protected → 404)
8. /api/locales/:id/reportar (→ protected → 404)
9. ...
10. SPA fallback → 404 / index.html for unmatched paths
```
The middleware essentially "protects" these routes *after* they're defined but *by returning 404* on all unmatched patterns. Wait — this is backwards. We want to protect **admin-only** routes from **public** access.
**Correct approach:** Add a middleware that:
- Checks if the route is in the `ADMIN_ROUTES` list
- Returns `404` for unmatched paths against the list (masking) — NO, that's not right either
Let me reconsider. The SPA fallback already 404s on unknown routes at the HTTP level. The issue is:
- Route enumeration tools can discover that `/api/pendientes` returns JSON
- Authenticated users see the routes in some admin dashboard (likely on the frontend)
**Revised approach:**
1. Add a middleware that logs and alerts when `/api/pendientes` or `/api/reportes` is accessed
2. Return 404 with a message for unauthenticated requests that triggers the middleware
3. For authenticated requests (user-agent with token etc.), pass through normally
Actually, let me keep it simple: just return 404 for these specific routes. This is a "secret API" pattern — the route exists but is effectively a hole because it returns a 404 by default.
## Risks / Trade-offs
| Risk | Impact | Mitigation |
|------|--------|------------|
| Legitimate admin users can't access /api/pendientes | Medium | Admins must use the known panel path; update documentation |
| Routes still visible in some tools (e.g. curl, browser dev tools) | Low | This is a mitigation, not complete protection |
| SPA fallback might still leak URLs | Low | SPA sends `index.html` for unmatched paths, effectively hiding them |
| New routes added without re-applying protection | Medium | Add routes to `ADMIN_ROUTES` list in middleware |
## Migration Plan
1. Add the middleware to `server/index.js`
2. Add `ADMIN_ROUTES` constant with patterns to protect
3. Deploy to production
4. Share the new route patterns (or keep them secret — the point is obscurity)
## Open Questions
- Should we also protect `/api/aprobar` and `/api/rechazar` even for authenticated users (force them through the UI)? This would require auth middleware. → **Out of scope for now.**
- Should we add actual authentication in a follow-up? → **Yes, recommended but separate.**
@@ -0,0 +1,25 @@
# Hide Admin Route
## Why
The `/api/pendientes` endpoint (admin-only) and `/api/reportes` endpoint are currently exposed at obvious routes, making them easy targets for attackers. By default, the admin panel URL is well-known or discoverable via route enumeration (`/admin`, `/admin/api/pendientes`, `/api/pendientes`). This increases the attack surface of the application.
By obscuring or moving the admin route, we increase the effort required for attackers to find the admin panel, reducing the likelihood of unwanted access.
## What Changes
- **New capability**: `route-obfuscation` — middleware-based approach to hide the admin API routes by redirecting access attempts and serving a 404 or custom page.
- Modify server configuration to intercept requests to known admin API routes and return a 404 or redirect to a custom page.
## Capabilities
### New Capabilities
- **route-obfuscation**: Protects admin routes (`/api/pendientes`, `/api/reportes`, `/api/locales/:id/*`) by returning a 404 response when accessed without authentication, without exposing the route listing in response to global route enumeration.
## Impact
- Affects the server configuration in `server/index.js`.
- Adds middleware to filter/admin route protection.
- Does not change the API contract for authenticated users.
- No database changes required.
@@ -0,0 +1,90 @@
# Route Obfuscation Spec
## Description
The route obfuscation capability mounts all admin-only API routes under a
configurable prefix (`LOCALESP_ADMIN_PREFIX`). The well-known `/api/...` admin
paths no longer have handlers and return 404, hiding the admin surface from
route enumeration without adding authentication.
## ADDED Requirements
### Requirement: Admin routes are served only under a configurable prefix
The system SHALL serve admin-only endpoints exclusively under the value of
`LOCALESP_ADMIN_PREFIX` (**required, no default**: the server fails fast with
a clear error when it is unset; documented in `.env.example`, which the
server auto-loads without overriding real environment variables), and SHALL
NOT register handlers for those endpoints under the legacy `/api` paths.
Admin endpoints under the prefix:
| Endpoint | Method |
|---|---|
| `$ADMIN_PREFIX/pendientes` | GET |
| `$ADMIN_PREFIX/aprobar/:id` | POST |
| `$ADMIN_PREFIX/rechazar/:id` | POST |
| `$ADMIN_PREFIX/locales/:id` | DELETE |
| `$ADMIN_PREFIX/reportes` | GET |
| `$ADMIN_PREFIX/reportes/:id/descartar` | POST |
#### Scenario: Legacy admin path returns 404 when a prefix is configured
- **WHEN** `LOCALESP_ADMIN_PREFIX` is set to a value other than `/api`
- **AND** a client makes a request to `/api/pendientes`, `/api/reportes`,
`/api/aprobar/:id`, `/api/rechazar/:id`, `DELETE /api/locales/:id` or
`/api/reportes/:id/descartar`
- **THEN** the server responds with HTTP 404
- **AND** no data is returned and no action is executed
#### Scenario: Prefixed admin path serves data to clients that know it
- **WHEN** `LOCALESP_ADMIN_PREFIX` is set to a value other than `/api`
- **AND** a client requests `$ADMIN_PREFIX/pendientes`
- **THEN** the server responds with the pending proposals as before
- **AND** the admin panel works unchanged because the frontend is compiled
with the same single `LOCALESP_ADMIN_PREFIX` variable
(exposed to the client via Vite `envPrefix`)
#### Scenario: Missing configuration fails fast
- **WHEN** `LOCALESP_ADMIN_PREFIX` is not set (or empty)
- **THEN** the server refuses to start with a clear configuration error
- **AND** there is no default value: every deployment must choose its prefix
(documented in `.env.example`)
#### Scenario: Public routes are unaffected
- **WHEN** a client makes a GET request to `/api/locales`
- **THEN** the server responds with HTTP 200 and the list of locales
#### Scenario: User-facing report and confirm actions remain public
- **WHEN** a client makes a POST request to `/api/locales/:id/reportar` or
`/api/locales/:id/confirmar`
- **THEN** the endpoints behave as before, because the public website uses
them (they are user features, not admin surface)
## REMOVED Requirements
### Requirement: Admin panel routes are fully discoverable
**Reason**: Security concern — admin routes should be harder to discover
**Migration**: Admin users access the panel at the prefix root
(`$ADMIN_PREFIX`, compiled with the same `LOCALESP_ADMIN_PREFIX`); its API
calls go to the configured prefix
## MODIFIED Requirements
### Requirement: Admin panel serves pending proposals
The requirement SHALL:
1. Allow unauthenticated clients to submit proposals via `/api/propuestas` (unchanged)
2. Serve the pending-proposals list from `$ADMIN_PREFIX/pendientes` (legacy
`/api/pendientes` returns 404 when a prefix is configured)
#### Scenario: Admin views pending proposals through the panel
- **WHEN** an admin opens the panel at the prefix root (`$ADMIN_PREFIX`,
e.g. `/administrador`)
- **THEN** the panel fetches `$ADMIN_PREFIX/pendientes` (compiled with
`LOCALESP_ADMIN_PREFIX`) and renders the list exactly as before
- **AND** the legacy `/admin` URL renders the public site (the panel route
no longer exists)
**Design note**: This is obscurity, not security: the prefix ships in the
frontend bundle. It raises the cost of blind route enumeration only. Real
authentication is explicitly deferred to a future change.
@@ -0,0 +1,136 @@
# Tasks: Hide Admin Route
> **Pivote decidido por el usuario (2026-10-02):** "solo quiero que se pueda
> configurar el prefijo de admin, nada más". El enfoque de middleware de
> enmascaramiento con 404 se **descarta**; las rutas admin se montan bajo un
> **prefijo configurable** (`LOCALESP_ADMIN_PREFIX`, única variable para
> servidor y frontend) y las rutas históricas bajo
> `/api` dejan de existir (404 natural, sin handler). `reportar`/`confirmar`
> siguen públicas (las usa la web); `DELETE /api/locales/:id` pasa al prefijo.
>
> **Estado (2026-10-02, tras el pivote + obligatoriedad):** implementado y
> verificado. `./node_modules/.bin/vitest run` → **109/109 en verde** (16
> ficheros), incluyendo `tests/unit/test-routes.spec.js` (18 tests, prefijo
> configurado) y `tests/unit/test-admin-prefix-required.spec.js` (fail-fast
> sin configurar).
> **Actualización 2 (2026-10-02):** a petición del usuario, `LOCALESP_ADMIN_PREFIX`
> pasa a ser obligatoria (sin default `/api`): sin ella el servidor lanza error
> claro y no arranca. Añadidos `.env.example`, cargador de `.env` en el servidor
> (no sobrescribe el entorno) y lectura del prefijo en `vite.config.js` vía
> `loadEnv`. Test de compatibilidad con `/api` sustituido por
> `test-admin-prefix-required.spec.js` (fail-fast verificado). Suite: 109/109.
>
> **Actualización 3 (2026-10-02):** eliminada la redundancia `VITE_ADMIN_PREFIX`:
> **una sola variable** (`LOCALESP_ADMIN_PREFIX`) para servidor, proxy de dev
> y frontend (Vite la expone vía `envPrefix`; `npm run build` falla si falta).
>
> **Actualización 4 (2026-10-03):** el panel admin vive en la raíz del prefijo
> (`/administrador` en prototipo-yb01) y `/admin` muestra la web pública.
>
> **Actualización 5 (2026-10-03):** config por entorno movida del host al repo
> (`scripts/entornos.env`, mapping `slug=prefijo`): el workflow la aplica al
> build y `deploy.sh` genera `<dest>/.env` desde ella. Fail-fast sin entrada.
## 1. Revisión de rutas existentes
- [x] 1.1 Leer y entender la estructura de rutas de `server/index.js`
- [x] 1.2 Identificar las rutas solo-admin (`/api/pendientes`, `/api/reportes`, `/api/locales/:id/reportar`, `/api/locales/:id/confirmar`, `/api/locales/:id`, `/api/aprobar/:id`, `/api/rechazar/:id`, `/api/reportes/:id/descartar`)
- [x] 1.3 Documentar el orden de rutas y la posición del fallback SPA
## 2. Prefijo de administración configurable (re-encaminado)
> Originalmente "middleware de ofuscación"; sustituido por el pivote al
> prefijo configurable. El middleware roto y `ADMIN_ROUTES`/`ROUTE_REGEXPS`
> se eliminaron del servidor.
- [x] 2.1 Montar las rutas admin bajo `ADMIN_PREFIX` (`LOCALESP_ADMIN_PREFIX`, **obligatoria y sin valor por defecto**: fail-fast al arrancar si falta; template en `.env.example`, que el servidor autocarga sin pisar el entorno)
- [x] 2.2 Rutas bajo prefijo: `pendientes`, `aprobar/:id`, `rechazar/:id`, `locales/:id` (DELETE), `reportes`, `reportes/:id/descartar` — sin middleware ni matching por patrón
- [x] 2.3 Posición: mismas posiciones que las rutas originales; el fallback SPA sigue excluyendo `api/`
- [x] 2.4 Verificado por tests: las rutas históricas bajo `/api` devuelven 404 cuando el prefijo está configurado
## 3. Verificar que las rutas no-admin siguen funcionando
- [x] 3.1 `GET /api/locales` → 200 con lista de locales (test)
- [x] 3.2 `POST /api/propuestas` → 201 con la propuesta creada (test)
- [x] 3.3 Fallback SPA `GET /` sirve `index.html` (test, aserción case-insensitive)
## 4. Documentación
- [x] 4.1 Documentar las reglas de protección y las rutas afectadas en el spec (`specs/route-obfuscation/spec.md`, actualizado al enfoque de prefijo)
- [x] 4.2 README actualizado: tabla de rutas admin bajo prefijo, variable única `LOCALESP_ADMIN_PREFIX` (servidor + proxy dev + build), proxy de dev y advertencia de que es ocultación, no autenticación
- [x] 4.3 `DELETE /api/locales/:id` — decidido por el usuario: pasa al prefijo configurable (test cubre borrado bajo prefijo y 404 en la ruta antigua)
## 5. Pruebas
> Con el enfoque de prefijo, "protegida" = la ruta histórica bajo `/api` ya no
> tiene handler (404 idéntico para cualquier método, query, extensión o
> variante de cadena) y la funcionalidad vive bajo `$ADMIN_PREFIX`.
> Cubierto por `tests/unit/test-routes.spec.js` (prefijo `/prefijo-admin-test`)
> y `tests/unit/test-admin-prefix-default.spec.js` (prefijo por defecto).
### 5.1 Rutas públicas (deben funcionar sin cambios)
- [x] 5.1 `GET /api/locales` → 200 (test)
- [x] 5.2 `POST /api/propuestas` → 201 con cuerpo (test)
- [x] 5.3 `POST /api/check-duplicado` → 200 con contrato `coincidencias` intacto (test)
- [x] 5.4 N/A: no existe ruta `/health` ni middleware que la intercepte
- [x] 5.5 `GET /` → 200 sirve `dist/index.html` (test, doctype case-insensitive)
- [x] 5.6 N/A: assets estáticos los sirve `express.static` sin intervención
- [x] 5.7 N/A: ídem
- [x] 5.8 Corregido el enunciado: `GET /api/locales/123` → 404 (el fallback SPA siempre excluyó `api/`); sin fuga
- [x] 5.9 `GET /api/config/filtro_palabras` → 200 (test)
### 5.2 Rutas protegidas (la ruta histórica devuelve 404; la función vive bajo prefijo)
- [x] 5.10 `GET /api/pendientes` → 404 y `$P/pendientes` → 200 con datos (test)
- [x] 5.11 `GET /api/reportes` → 404 y `$P/reportes` → 200 con datos (test)
- [x] 5.12 `POST /api/locales/:id/reportar` → **pública** (la usa la web); su flujo admin (listar/descartar reportes) bajo prefijo (test)
- [x] 5.13 `POST /api/locales/:id/confirmar` → **pública** (la usa la web); 200 renueva fecha (test)
- [x] 5.14 `POST /api/aprobar/:id` → 404 en `/api`; bajo prefijo mueve a locales y saca de pendientes (test)
- [x] 5.15 `POST /api/rechazar/:id` → 404 en `/api`; bajo prefido elimina pendiente (test)
- [x] 5.16 `POST /api/reportes/:id/descartar` → 404 en `/api`; bajo prefijo descarta (test)
### 5.3 Comportamiento (evitar falsos positivos)
- [x] 5.17 `GET /api/locales` → 200 (test)
- [x] 5.18/5.19/5.20 Corregido el enunciado: cualquier GET bajo `api/` sin handler → 404 (el fallback SPA siempre excluyó `api/`); sin middleware que bloquee de más
- [x] 5.21 `GET /API/PENDIENTES` → sin handler API; cae al fallback SPA sin datos (test)
- [x] 5.22 `GET /api/pendientes/extra` → 404 (test)
- [x] 5.23 `POST /api/locales/:id/reponer` → 404 (sin handler)
### 5.4 Pruebas de seguridad (enumeración y rutas maliciosas)
- [x] 5.24 `GET /api/pendientes.json` → 404 (test)
- [x] 5.25 `GET /api/pending` / `/api/xpendientes` → 404 (test)
- [x] 5.26–5.34 Sin handler bajo `/api`, cualquier método/query/extensión/cadena recibe el mismo 404 (por construcción); las variantes que no empiezan por `api/` reciben el HTML genérico del fallback SPA, sin datos
- [x] 5.35 `GET /api/xpendientes` → 404 (test)
### 5.5 Pruebas de regresión y no-regresión
- [x] 5.36 `POST /api/propuestas` → 201 con campos correctos (test); payload malformado gestionado por la BD/validación existente (sin cambios en este cambio)
- [x] 5.38 `DELETE` bajo prefijo → 200 y borra local + reportes (test); ruta antigua → 404
- [x] 5.39–5.44 N/A o por construcción: no hay middleware, no hay cabeceras especiales ni logs nuevos
- [x] Suite completa previa (componentes incluidos) en verde: 110/110
### 5.6 Validación contra el esquema de base de datos
- [x] 5.45 `GET /api/locales` sin cambios de columnas (no se tocó la query)
- [x] 5.46 `POST /api/propuestas` sin cambios (ídem)
- [x] 5.47 `$P/reportes` devuelve exactamente lo que devolvía `/api/reportes` (misma query)
## 6. Limpieza
- [x] 6.1 N/A tras el pivote: no hay lista `ADMIN_ROUTES`
- [x] 6.2 `DELETE /api/locales/:id` resuelto: vive bajo el prefijo (4.3)
- [x] 6.3 N/A tras el pivote: `reportes/:id/descartar` montado bajo prefijo y verificado por test
- [x] 6.4 Ficheros de prueba duplicados/muertos eliminados: `tests/integration/test-hide-admin-route.js` (nunca recogido por ningún include y con sintaxis rota) y `vitest.config.js` redundante (pisaba `vitest.config.mjs`, que es la config vigente); se conserva un único `tests/unit/test-routes.spec.js` (+ el de prefijo obligatorio)
## 7. Seguimiento: protección fina por método
> Obsoleto tras el pivote: el prefijo configurable ya separa superficie
> pública y admin sin matching por método. Si en el futuro se añade
> autenticación real, este apartado queda como referencia.
## 8. Bloqueadores para cerrar el cambio
- [x] 8.1 Obsoleto: el middleware se eliminó (pivote al prefijo)
- [x] 8.2 El handler de `GET pendientes` existe de nuevo, montado bajo el prefijo: quien conoce la URL prefijada obtiene los datos; la ruta `/api/pendientes` histórica devuelve 404
- [x] 8.3 Suite en verde: 109/109 tests (19 de rutas/prefijo en 2 ficheros: configurado + obligatorio)
- [x] 8.4 Aserción del SPA corregida (comparación case-insensitive de `<!doctype html>`)
- [x] 8.5 Revertidos los cambios fuera de alcance: `distanciaMetros` (haversine) restaurada, `db`→`Db` deshecho, comentarios originales restaurados, contrato `coincidencias` intacto, `src/App.jsx` (resaltado `?local=ID` + bloque de estadísticas) restaurado vía `git checkout`, `vite.config.js` limpio (solo proxy + prefijo de dev), `package-lock.json` revertido
- [x] 8.6 README actualizado (4.2) y `DELETE /api/locales/:id` decidido (4.3)