feat(seguridad): rutas admin bajo prefijo configurable obligatorio
deploy-branch / deploy (push) Failing after 3m7s
deploy-branch / teardown (push) Skipped
tests / Unitarias + componente + build (push) Failing after 3m17s
tests / Integración (Nominatim real, opt-in) (push) Skipped
tests / Unitarias + componente + build (pull_request) Failing after 3m10s
tests / Integración (Nominatim real, opt-in) (pull_request) Skipped
deploy-branch / deploy (push) Failing after 3m7s
deploy-branch / teardown (push) Skipped
tests / Unitarias + componente + build (push) Failing after 3m17s
tests / Integración (Nominatim real, opt-in) (push) Skipped
tests / Unitarias + componente + build (pull_request) Failing after 3m10s
tests / Integración (Nominatim real, opt-in) (pull_request) Skipped
Cambio openspec hide-admin-route: las rutas de administración se montan bajo LOCALESP_ADMIN_PREFIX (única variable, obligatoria, sin valor por defecto) y las rutas históricas /api/... dejan de existir (404 natural). - server: autocarga de .env (sin pisar el entorno) y fail-fast claro si falta LOCALESP_ADMIN_PREFIX; reportar/confirmar siguen públicas - frontend: src/api.js usa el prefijo expuesto por Vite (envPrefix); npm run build falla sin la variable; proxy de dev la lee vía loadEnv - .env.example como template único de configuración - tests: 109/109 en verde (rutas bajo prefijo, 404s históricos y fail-fast sin configurar) - openspec: artefactos del cambio sincronizados (design/spec/tasks)
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
# Configuración de LocalESP — copia este fichero a `.env` y rellena los valores.
|
||||||
|
# cp .env.example .env
|
||||||
|
#
|
||||||
|
# El servidor carga `.env` automáticamente al arrancar (no sobrescribe
|
||||||
|
# variables ya presentes en el entorno) y Vite lo lee en dev y build.
|
||||||
|
|
||||||
|
# Prefijo bajo el que se sirven las rutas de administración (OBLIGATORIO,
|
||||||
|
# sin valor por defecto: servidor y build fallan si no está configurada).
|
||||||
|
#
|
||||||
|
# - Es la ÚNICA variable: servidor (`node server/index.js`), proxy de
|
||||||
|
# desarrollo (`npm run dev`) y frontend (`npm run build`) leen esta misma.
|
||||||
|
# - Empieza por "/" y no lo publiques: es lo que oculta /admin de la
|
||||||
|
# enumeración de rutas. Usa algo difícil de adivinar, p. ej. /gestion-x7k2
|
||||||
|
# - Las rutas históricas (/api/pendientes, /api/reportes, ...) dejan de
|
||||||
|
# existir; el panel /admin llama a `$LOCALESP_ADMIN_PREFIX/...`
|
||||||
|
LOCALESP_ADMIN_PREFIX=
|
||||||
|
|
||||||
|
# Opcional: ruta de la base de datos SQLite (por defecto localesp.db del
|
||||||
|
# repo; en pruebas se usa ":memory:").
|
||||||
|
# LOCALESP_DB=
|
||||||
@@ -1,2 +1,48 @@
|
|||||||
# LocalESP
|
# LocalESP
|
||||||
Registro colaborativo de negocios españoles
|
|
||||||
|
Registro colaborativo de negocios españoles.
|
||||||
|
|
||||||
|
## Rutas de administración (prefijo configurable)
|
||||||
|
|
||||||
|
Las rutas de administración **solo se sirven bajo un prefijo configurable**;
|
||||||
|
las rutas históricas (`/api/pendientes`, `/api/reportes`, `/api/aprobar/:id`,
|
||||||
|
`/api/rechazar/:id`, `DELETE /api/locales/:id`, `/api/reportes/:id/descartar`)
|
||||||
|
dejan de existir y devuelven 404. Esto oculta la superficie admin de la
|
||||||
|
enumeración de rutas sin añadir autenticación (ocultación, no seguridad real).
|
||||||
|
|
||||||
|
| Ruta admin | Método |
|
||||||
|
|---|---|
|
||||||
|
| `$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 |
|
||||||
|
|
||||||
|
Siguen siendo públicas (las usa la web): `GET /api/locales`,
|
||||||
|
`POST /api/propuestas`, `POST /api/check-duplicado`,
|
||||||
|
`POST /api/locales/:id/confirmar`, `POST /api/locales/:id/reportar` y
|
||||||
|
`GET/POST /api/config/filtro_palabras`.
|
||||||
|
|
||||||
|
### Configuración
|
||||||
|
|
||||||
|
`LOCALESP_ADMIN_PREFIX` es **obligatoria, sin valor por defecto y la única
|
||||||
|
variable necesaria**: servidor, proxy de desarrollo y build del frontend
|
||||||
|
leen la misma. Sin ella, `node server/index.js` y `npm run build` fallan con
|
||||||
|
un error claro. La forma más cómoda de configurarla es copiar el template:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env # y rellena LOCALESP_ADMIN_PREFIX
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Servidor:** lee `LOCALESP_ADMIN_PREFIX` del entorno y de `.env` (el
|
||||||
|
fichero no sobrescribe variables ya presentes).
|
||||||
|
- **Frontend:** Vite expone `LOCALESP_ADMIN_PREFIX` al código cliente vía
|
||||||
|
`envPrefix` (`.env` o entorno en dev/build); `npm run build` falla si falta.
|
||||||
|
- **Desarrollo:** `npm run dev` proxya `/api` y el prefijo admin al backend
|
||||||
|
en `localhost:3000`, leyendo ambos del entorno o de `.env`.
|
||||||
|
|
||||||
|
> Nota: sin prefijo configurado el servidor no arranca (no existe modo sin
|
||||||
|
> ocultación). El prefijo viaja en el bundle del frontend, así que esto es
|
||||||
|
> ocultación básica frente a enumeración, no un mecanismo de seguridad; la
|
||||||
|
> autenticación real queda como trabajo futuro.
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-09-30
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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,86 @@
|
|||||||
|
# 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 `/admin`; its API calls go to
|
||||||
|
the configured prefix — the same single `LOCALESP_ADMIN_PREFIX` variable at build time
|
||||||
|
|
||||||
|
## 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 `/admin`
|
||||||
|
- **THEN** the panel fetches `$ADMIN_PREFIX/pendientes` (compiled with
|
||||||
|
`LOCALESP_ADMIN_PREFIX`) and renders the list exactly as before
|
||||||
|
|
||||||
|
**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,129 @@
|
|||||||
|
# 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).
|
||||||
|
|
||||||
|
## 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)
|
||||||
+70
-27
@@ -1,12 +1,55 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { fileURLToPath, pathToFileURL } from "url";
|
import { fileURLToPath, pathToFileURL } from "url";
|
||||||
import { dirname, join } from "path";
|
import { dirname, join } from "path";
|
||||||
|
import { readFileSync } from "fs";
|
||||||
import db from "./db.js";
|
import db from "./db.js";
|
||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
|
// Carga mínima de `.env` (repo raíz): KEY=valor, ignora comentarios y líneas
|
||||||
|
// vacías, admite comillas y `export`, y NO sobrescribe variables ya presentes
|
||||||
|
// en el entorno (las de pruebas/despliegue mandan sobre el fichero).
|
||||||
|
function cargarDotEnv(ruta) {
|
||||||
|
let contenido;
|
||||||
|
try {
|
||||||
|
contenido = readFileSync(ruta, "utf8");
|
||||||
|
} catch {
|
||||||
|
return; // sin .env: se usan solo las variables del entorno
|
||||||
|
}
|
||||||
|
for (const linea of contenido.split("\n")) {
|
||||||
|
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(linea);
|
||||||
|
if (!m) continue;
|
||||||
|
let valor = m[2].trim();
|
||||||
|
if ((valor.startsWith('"') && valor.endsWith('"')) || (valor.startsWith("'") && valor.endsWith("'"))) {
|
||||||
|
valor = valor.slice(1, -1);
|
||||||
|
}
|
||||||
|
if (!(m[1] in process.env)) process.env[m[1]] = valor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cargarDotEnv(join(__dirname, "../.env"));
|
||||||
|
|
||||||
|
// Prefijo de las rutas de administración (ocultación por ruta no obvia): las
|
||||||
|
// rutas admin solo se sirven bajo este prefijo y las históricas /api/... dejan
|
||||||
|
// de existir (404). OBLIGATORIO y SIN valor por defecto: es la única variable
|
||||||
|
// y también la usa el frontend (Vite la expone vía envPrefix; el build falla si
|
||||||
|
// falta). Ver .env.example.
|
||||||
|
function normalizarPrefijo(valor) {
|
||||||
|
const limpio = (valor || "").trim().replace(/\/+$/, "");
|
||||||
|
if (!limpio || limpio === "") return null;
|
||||||
|
return limpio.startsWith("/") ? limpio : `/${limpio}`;
|
||||||
|
}
|
||||||
|
const ADMIN_PREFIX = normalizarPrefijo(process.env.LOCALESP_ADMIN_PREFIX);
|
||||||
|
if (!ADMIN_PREFIX || ADMIN_PREFIX === "/") {
|
||||||
|
console.error(
|
||||||
|
"[config] Falta LOCALESP_ADMIN_PREFIX (obligatorio, sin valor por defecto)." +
|
||||||
|
" Copia .env.example a .env y asigna el prefijo de administración," +
|
||||||
|
" p. ej. LOCALESP_ADMIN_PREFIX=/gestion-x7k2",
|
||||||
|
);
|
||||||
|
throw new Error("LOCALESP_ADMIN_PREFIX no configurado");
|
||||||
|
}
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(express.static(join(__dirname, "../dist")));
|
app.use(express.static(join(__dirname, "../dist")));
|
||||||
|
|
||||||
@@ -16,12 +59,6 @@ app.get("/api/locales", (_req, res) => {
|
|||||||
res.json(locales);
|
res.json(locales);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Pendientes (admin)
|
|
||||||
app.get("/api/pendientes", (_req, res) => {
|
|
||||||
const pendientes = db.prepare("SELECT * FROM pendientes ORDER BY fechaPropuesta DESC").all();
|
|
||||||
res.json(pendientes);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Utilidades para detectar duplicados
|
// Utilidades para detectar duplicados
|
||||||
function normaliza(s) {
|
function normaliza(s) {
|
||||||
return (s || "").toString().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim();
|
return (s || "").toString().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim();
|
||||||
@@ -71,8 +108,14 @@ app.post("/api/propuestas", (req, res) => {
|
|||||||
res.status(201).json({ id, nombre, descripcion, provincia, subcategoria, direccion, enlaceGoogleMaps, puntuacion: puntuacion ?? 0, categoria, estado: "pendiente", fechaPropuesta, lat, lng });
|
res.status(201).json({ id, nombre, descripcion, provincia, subcategoria, direccion, enlaceGoogleMaps, puntuacion: puntuacion ?? 0, categoria, estado: "pendiente", fechaPropuesta, lat, lng });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Pendientes (admin, bajo prefijo configurable)
|
||||||
|
app.get(`${ADMIN_PREFIX}/pendientes`, (_req, res) => {
|
||||||
|
const pendientes = db.prepare("SELECT * FROM pendientes ORDER BY fechaPropuesta DESC").all();
|
||||||
|
res.json(pendientes);
|
||||||
|
});
|
||||||
|
|
||||||
// Aprobar propuesta
|
// Aprobar propuesta
|
||||||
app.post("/api/aprobar/:id", (req, res) => {
|
app.post(`${ADMIN_PREFIX}/aprobar/:id`, (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const propuesta = db.prepare("SELECT * FROM pendientes WHERE id = ?").get(id);
|
const propuesta = db.prepare("SELECT * FROM pendientes WHERE id = ?").get(id);
|
||||||
|
|
||||||
@@ -92,20 +135,38 @@ app.post("/api/aprobar/:id", (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Rechazar propuesta
|
// Rechazar propuesta
|
||||||
app.post("/api/rechazar/:id", (req, res) => {
|
app.post(`${ADMIN_PREFIX}/rechazar/:id`, (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
db.prepare("DELETE FROM pendientes WHERE id = ?").run(id);
|
db.prepare("DELETE FROM pendientes WHERE id = ?").run(id);
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Eliminar local
|
// Eliminar local
|
||||||
app.delete("/api/locales/:id", (req, res) => {
|
app.delete(`${ADMIN_PREFIX}/locales/:id`, (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
db.prepare("DELETE FROM locales WHERE id = ?").run(id);
|
db.prepare("DELETE FROM locales WHERE id = ?").run(id);
|
||||||
db.prepare("DELETE FROM reportes WHERE localId = ?").run(id);
|
db.prepare("DELETE FROM reportes WHERE localId = ?").run(id);
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Reportes (admin, bajo prefijo configurable)
|
||||||
|
app.get(`${ADMIN_PREFIX}/reportes`, (_req, res) => {
|
||||||
|
const reportes = db.prepare(`
|
||||||
|
SELECT r.*, l.nombre AS localNombre, l.provincia AS localProvincia, l.direccion AS localDireccion
|
||||||
|
FROM reportes r LEFT JOIN locales l ON l.id = r.localId
|
||||||
|
WHERE r.estado = 'pendiente'
|
||||||
|
ORDER BY r.fecha DESC
|
||||||
|
`).all();
|
||||||
|
res.json(reportes);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Descartar un reporte (el admin revisó y no hace falta actuar)
|
||||||
|
app.post(`${ADMIN_PREFIX}/reportes/:id/descartar`, (req, res) => {
|
||||||
|
const { id } = req.params;
|
||||||
|
db.prepare("UPDATE reportes SET estado = 'descartado' WHERE id = ?").run(id);
|
||||||
|
res.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
// Confirmar que un local sigue activo (renueva fechaConfirmacion)
|
// Confirmar que un local sigue activo (renueva fechaConfirmacion)
|
||||||
app.post("/api/locales/:id/confirmar", (req, res) => {
|
app.post("/api/locales/:id/confirmar", (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
@@ -130,24 +191,6 @@ app.post("/api/locales/:id/reportar", (req, res) => {
|
|||||||
res.status(201).json({ ok: true, id: reporteId });
|
res.status(201).json({ ok: true, id: reporteId });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Reportes (admin)
|
|
||||||
app.get("/api/reportes", (_req, res) => {
|
|
||||||
const reportes = db.prepare(`
|
|
||||||
SELECT r.*, l.nombre AS localNombre, l.provincia AS localProvincia, l.direccion AS localDireccion
|
|
||||||
FROM reportes r LEFT JOIN locales l ON l.id = r.localId
|
|
||||||
WHERE r.estado = 'pendiente'
|
|
||||||
ORDER BY r.fecha DESC
|
|
||||||
`).all();
|
|
||||||
res.json(reportes);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Descartar un reporte (el admin revisó y no hace falta actuar)
|
|
||||||
app.post("/api/reportes/:id/descartar", (req, res) => {
|
|
||||||
const { id } = req.params;
|
|
||||||
db.prepare("UPDATE reportes SET estado = 'descartado' WHERE id = ?").run(id);
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Config (palabras filtradas)
|
// Config (palabras filtradas)
|
||||||
app.get("/api/config/filtro_palabras", (_req, res) => {
|
app.get("/api/config/filtro_palabras", (_req, res) => {
|
||||||
const config = db.prepare("SELECT datos FROM config WHERE id = ?").get("filtro_palabras");
|
const config = db.prepare("SELECT datos FROM config WHERE id = ?").get("filtro_palabras");
|
||||||
|
|||||||
+13
-7
@@ -1,6 +1,12 @@
|
|||||||
// Local SQLite API instead of Firebase
|
// Local SQLite API instead of Firebase
|
||||||
|
|
||||||
const API_URL = "/api";
|
const API_URL = "/api";
|
||||||
|
// Prefijo de las rutas de administración: la MISMA variable que usa el
|
||||||
|
// servidor (LOCALESP_ADMIN_PREFIX), expuesta al frontend por Vite mediante
|
||||||
|
// `envPrefix` (dev/build la recogen de .env o del entorno; el build falla si
|
||||||
|
// falta). El fallback "/api" solo aplica fuera de un build real (p. ej. tests).
|
||||||
|
const rawAdmin = String(import.meta.env.LOCALESP_ADMIN_PREFIX || "").trim().replace(/\/+$/, "");
|
||||||
|
const ADMIN_URL = rawAdmin ? (rawAdmin.startsWith("/") ? rawAdmin : `/${rawAdmin}`) : "/api";
|
||||||
|
|
||||||
export async function suscribirLocales(onData, onError) {
|
export async function suscribirLocales(onData, onError) {
|
||||||
try {
|
try {
|
||||||
@@ -25,13 +31,13 @@ export async function suscribirLocales(onData, onError) {
|
|||||||
|
|
||||||
export async function suscribirPendientes(onData, onError) {
|
export async function suscribirPendientes(onData, onError) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/pendientes`);
|
const response = await fetch(`${ADMIN_URL}/pendientes`);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
onData(data);
|
onData(data);
|
||||||
// Simulate real-time by polling every 5 seconds
|
// Simulate real-time by polling every 5 seconds
|
||||||
const interval = setInterval(async () => {
|
const interval = setInterval(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/pendientes`);
|
const res = await fetch(`${ADMIN_URL}/pendientes`);
|
||||||
const newData = await res.json();
|
const newData = await res.json();
|
||||||
onData(newData);
|
onData(newData);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -64,7 +70,7 @@ export async function comprobarDuplicado({ nombre, provincia, lat, lng }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function aprobarPropuesta(p) {
|
export async function aprobarPropuesta(p) {
|
||||||
const response = await fetch(`${API_URL}/aprobar/${p.id}`, {
|
const response = await fetch(`${ADMIN_URL}/aprobar/${p.id}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
});
|
});
|
||||||
@@ -72,7 +78,7 @@ export async function aprobarPropuesta(p) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function rechazarPropuesta(id) {
|
export async function rechazarPropuesta(id) {
|
||||||
const response = await fetch(`${API_URL}/rechazar/${id}`, {
|
const response = await fetch(`${ADMIN_URL}/rechazar/${id}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
});
|
});
|
||||||
@@ -80,7 +86,7 @@ export async function rechazarPropuesta(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteLocal(id) {
|
export async function deleteLocal(id) {
|
||||||
const response = await fetch(`${API_URL}/locales/${id}`, {
|
const response = await fetch(`${ADMIN_URL}/locales/${id}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
return response.json();
|
return response.json();
|
||||||
@@ -101,12 +107,12 @@ export async function reportarLocal(id, motivo, comentario) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function obtenerReportes() {
|
export async function obtenerReportes() {
|
||||||
const response = await fetch(`${API_URL}/reportes`);
|
const response = await fetch(`${ADMIN_URL}/reportes`);
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function descartarReporte(id) {
|
export async function descartarReporte(id) {
|
||||||
const response = await fetch(`${API_URL}/reportes/${id}/descartar`, { method: "POST" });
|
const response = await fetch(`${ADMIN_URL}/reportes/${id}/descartar`, { method: "POST" });
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import request from "supertest";
|
||||||
|
|
||||||
|
// Sin LOCALESP_ADMIN_PREFIX el servidor debe negarse a arrancar (fail-fast,
|
||||||
|
// sin valor por defecto). Se fija la cadena vacía en el entorno para que el
|
||||||
|
// test sea hermético aunque exista un `.env` configurado en el repo.
|
||||||
|
process.env.LOCALESP_DB = ":memory:";
|
||||||
|
process.env.LOCALESP_ADMIN_PREFIX = "";
|
||||||
|
|
||||||
|
describe("LOCALESP_ADMIN_PREFIX obligatorio — fail-fast sin configurar", () => {
|
||||||
|
it("importar el servidor sin prefijo configurado lanza error", async () => {
|
||||||
|
await expect(import("../../server/index.js")).rejects.toThrow(
|
||||||
|
"LOCALESP_ADMIN_PREFIX no configurado",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import request from "supertest";
|
||||||
|
|
||||||
|
// BD en memoria y prefijo admin de prueba: deben configurarse ANTES de
|
||||||
|
// importar la app (server/db.js y server/index.js los leen al cargarse).
|
||||||
|
process.env.LOCALESP_DB = ":memory:";
|
||||||
|
process.env.LOCALESP_ADMIN_PREFIX = "/prefijo-admin-test";
|
||||||
|
|
||||||
|
// Se importa después de fijar las variables de entorno.
|
||||||
|
const server = (await import("../../server/index.js")).default;
|
||||||
|
|
||||||
|
const PREFIX = "/prefijo-admin-test";
|
||||||
|
|
||||||
|
describe("Rutas públicas — funcionan sin cambios (sección 5.1)", () => {
|
||||||
|
it("GET /api/locales → 200 con lista", async () => {
|
||||||
|
const res = await request(server).get("/api/locales").expect(200);
|
||||||
|
expect(Array.isArray(res.body)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/propuestas → 201 con la propuesta creada", async () => {
|
||||||
|
const res = await request(server)
|
||||||
|
.post("/api/propuestas")
|
||||||
|
.send({ nombre: "Cafetería Única Test", provincia: "Madrid", categoria: "Cafetería" })
|
||||||
|
.expect(201);
|
||||||
|
expect(res.body.nombre).toBe("Cafetería Única Test");
|
||||||
|
expect(res.body.estado).toBe("pendiente");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET / sirve el fallback SPA (dist/index.html)", async () => {
|
||||||
|
const res = await request(server).get("/").expect(200);
|
||||||
|
// El build emite `<!doctype html>` en minúscula: comparar sin distinción.
|
||||||
|
expect(res.text.toLowerCase()).toContain("<!doctype html>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Rutas admin conocidas — ya no existen bajo /api (404)", () => {
|
||||||
|
it("GET /api/pendientes → 404", async () => {
|
||||||
|
await request(server).get("/api/pendientes").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET /api/reportes → 404", async () => {
|
||||||
|
await request(server).get("/api/reportes").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/aprobar/:id → 404 (la acción no se ejecuta)", async () => {
|
||||||
|
await request(server).post("/api/aprobar/123").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/rechazar/:id → 404", async () => {
|
||||||
|
await request(server).post("/api/rechazar/123").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("DELETE /api/locales/:id → 404", async () => {
|
||||||
|
await request(server).delete("/api/locales/123").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/reportes/:id/descartar → 404", async () => {
|
||||||
|
await request(server).post("/api/reportes/1/descartar").expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("variantes de enumeración → sin fuga de datos", async () => {
|
||||||
|
await request(server).get("/api/pendientes.json").expect(404);
|
||||||
|
await request(server).get("/api/xpendientes").expect(404);
|
||||||
|
// Con prefijo configurado, las variantes de caja no tienen handler API y
|
||||||
|
// caen al fallback SPA (HTML genérico, sin datos).
|
||||||
|
const res = await request(server).get("/API/PENDIENTES");
|
||||||
|
expect([200, 404]).toContain(res.status);
|
||||||
|
expect(res.body).toEqual({});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Rutas admin bajo el prefijo configurable — funcionan", () => {
|
||||||
|
it("GET $PREFIX/pendientes → 200 con la propuesta pendiente", async () => {
|
||||||
|
const res = await request(server).get(`${PREFIX}/pendientes`).expect(200);
|
||||||
|
expect(Array.isArray(res.body)).toBe(true);
|
||||||
|
expect(res.body.some((p) => p.nombre === "Cafetería Única Test")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST $PREFIX/aprobar/:id → mueve la propuesta a locales", async () => {
|
||||||
|
const pendientes = (await request(server).get(`${PREFIX}/pendientes`)).body;
|
||||||
|
const propuesta = pendientes.find((p) => p.nombre === "Cafetería Única Test");
|
||||||
|
expect(propuesta).toBeDefined();
|
||||||
|
|
||||||
|
await request(server).post(`${PREFIX}/aprobar/${propuesta.id}`).expect(200);
|
||||||
|
|
||||||
|
const locales = (await request(server).get("/api/locales")).body;
|
||||||
|
expect(locales.some((l) => l.nombre === "Cafetería Única Test")).toBe(true);
|
||||||
|
|
||||||
|
const despues = (await request(server).get(`${PREFIX}/pendientes`)).body;
|
||||||
|
expect(despues.some((p) => p.id === propuesta.id)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST $PREFIX/rechazar/:id → elimina la propuesta pendiente", async () => {
|
||||||
|
const creada = await request(server)
|
||||||
|
.post("/api/propuestas")
|
||||||
|
.send({ nombre: "Propuesta Rechazable", provincia: "Cádiz" })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(server).post(`${PREFIX}/rechazar/${creada.body.id}`).expect(200);
|
||||||
|
|
||||||
|
const pendientes = (await request(server).get(`${PREFIX}/pendientes`)).body;
|
||||||
|
expect(pendientes.some((p) => p.id === creada.body.id)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ciclo de reportes: reportar (público) → listar y descartar (admin)", async () => {
|
||||||
|
const locales = (await request(server).get("/api/locales")).body;
|
||||||
|
const local = locales.find((l) => l.nombre === "Cafetería Única Test");
|
||||||
|
expect(local).toBeDefined();
|
||||||
|
|
||||||
|
// El reporte lo envía cualquier usuario desde la web pública.
|
||||||
|
const reporte = await request(server)
|
||||||
|
.post(`/api/locales/${local.id}/reportar`)
|
||||||
|
.send({ motivo: "cerrado", comentario: "prueba" })
|
||||||
|
.expect(201);
|
||||||
|
expect(reporte.body.ok).toBe(true);
|
||||||
|
|
||||||
|
const reportes = (await request(server).get(`${PREFIX}/reportes`).expect(200)).body;
|
||||||
|
const creado = reportes.find((r) => r.id === reporte.body.id);
|
||||||
|
expect(creado).toBeDefined();
|
||||||
|
expect(creado.localNombre).toBe("Cafetería Única Test");
|
||||||
|
|
||||||
|
await request(server).post(`${PREFIX}/reportes/${creado.id}/descartar`).expect(200);
|
||||||
|
const despues = (await request(server).get(`${PREFIX}/reportes`)).body;
|
||||||
|
expect(despues.some((r) => r.id === creado.id)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/locales/:id/confirmar (público) → renueva fechaConfirmacion", async () => {
|
||||||
|
const locales = (await request(server).get("/api/locales")).body;
|
||||||
|
const local = locales.find((l) => l.nombre === "Cafetería Única Test");
|
||||||
|
const res = await request(server).post(`/api/locales/${local.id}/confirmar`).expect(200);
|
||||||
|
expect(res.body.fechaConfirmacion).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("DELETE $PREFIX/locales/:id → borra el local y sus reportes", async () => {
|
||||||
|
const locales = (await request(server).get("/api/locales")).body;
|
||||||
|
const local = locales.find((l) => l.nombre === "Cafetería Única Test");
|
||||||
|
await request(server).delete(`${PREFIX}/locales/${local.id}`).expect(200);
|
||||||
|
|
||||||
|
const despues = (await request(server).get("/api/locales")).body;
|
||||||
|
expect(despues.some((l) => l.id === local.id)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /api/check-duplicado → contrato `coincidencias` intacto", async () => {
|
||||||
|
await request(server)
|
||||||
|
.post("/api/propuestas")
|
||||||
|
.send({ nombre: "Bar Duplicado", provincia: "Sevilla", lat: 37.39, lng: -5.99 })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const res = await request(server)
|
||||||
|
.post("/api/check-duplicado")
|
||||||
|
.send({ nombre: "bar duplicado", provincia: "Sevilla" })
|
||||||
|
.expect(200);
|
||||||
|
expect(res.body.duplicado).toBe(true);
|
||||||
|
expect(Array.isArray(res.body.coincidencias)).toBe(true);
|
||||||
|
expect(res.body.coincidencias.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET /api/config/filtro_palabras → 200", async () => {
|
||||||
|
const res = await request(server).get("/api/config/filtro_palabras").expect(200);
|
||||||
|
expect(res.body.palabras).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+29
-2
@@ -1,13 +1,40 @@
|
|||||||
import { defineConfig } from 'vite'
|
import { defineConfig, loadEnv } from 'vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
export default defineConfig({
|
// Una sola variable de configuración: LOCALESP_ADMIN_PREFIX (ver .env.example).
|
||||||
|
// - El servidor la lee en arranque (obligatoria, fail-fast).
|
||||||
|
// - Vite la expone al frontend vía envPrefix (dev y build la recogen de .env
|
||||||
|
// o del entorno) y la usa aquí para proxyar el prefijo al backend.
|
||||||
|
export default defineConfig(({ mode, command }) => {
|
||||||
|
const env = loadEnv(mode, process.cwd(), '')
|
||||||
|
const raw = (env.LOCALESP_ADMIN_PREFIX || process.env.LOCALESP_ADMIN_PREFIX || '').trim()
|
||||||
|
const adminPrefix = raw ? (raw.startsWith('/') ? raw : `/${raw}`).replace(/\/+$/, '') : ''
|
||||||
|
|
||||||
|
if (!adminPrefix && command === 'build') {
|
||||||
|
throw new Error(
|
||||||
|
'[config] Falta LOCALESP_ADMIN_PREFIX (obligatoria, sin valor por defecto).' +
|
||||||
|
' Copia .env.example a .env y asigna el prefijo de administración.',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!adminPrefix) {
|
||||||
|
console.warn('[config] LOCALESP_ADMIN_PREFIX sin configurar: el proxy de desarrollo no cubrirá las rutas admin (el servidor tampoco arrancará sin ella).')
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
envPrefix: ['VITE_', 'LOCALESP_'],
|
||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://localhost:3000',
|
target: 'http://localhost:3000',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
...(adminPrefix && adminPrefix !== '/api' ? {
|
||||||
|
[adminPrefix]: {
|
||||||
|
target: 'http://localhost:3000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
} : {}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user