# 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/.env`) **al repo**: `scripts/entornos.env` > mapea `slug=prefijo`. El workflow de deploy la aplica al build y `deploy.sh` > la materializa como `/.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.**