La config de prefijo admin pasa del host (/etc/localesp/<slug>.env) al repo, para que viaje con el código que despliega y se revise en PRs: - scripts/entornos.env: mapping <slug>=<prefijo> (prototipo-yb01= /administrador; master y prototipo-yb01-ef como plantilla comentada) - env.sh: servicio Config::admin_prefix lee el mapping; require_config falla con mensaje claro si la rama no tiene entrada; Env::deploy regenera <dest>/.env desde el repo (el servidor lo autocarga) - deploy.yml: el build exporta el prefijo del mapping antes de compilar
7.2 KiB
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_PREFIXen el servidor,VITE_ADMIN_PREFIXal 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/confirmarsiguen públicas (las usa la web) yDELETE /api/locales/:idpasa 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_PREFIXpasa a ser obligatoria y sin valor por defecto: sin ella el servidor hace fail-fast al arrancar. Se añade.env.examplecomo template y el servidor carga.envautomáticamente (sin sobrescribir variables del entorno). Se elimina el escenario de compatibilidad con prefijo/apipor 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 medianteenvPrefix: ["VITE_", "LOCALESP_"]ynpm run buildtambié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/adminpasa 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.envmapeaslug=prefijo. El workflow de deploy la aplica al build ydeploy.shla 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?
- Minimal friction — existing admin users who know the URL still get the data
- No auth required — avoids adding another layer of complexity
- No breaking changes — authenticated users are unaffected
- 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:
- Check the request path against the admin route list
- If matched: return
404with a generic message - 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_ROUTESlist - Returns
404for 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/pendientesreturns JSON - Authenticated users see the routes in some admin dashboard (likely on the frontend)
Revised approach:
- Add a middleware that logs and alerts when
/api/pendientesor/api/reportesis accessed - Return 404 with a message for unauthenticated requests that triggers the middleware
- 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
- Add the middleware to
server/index.js - Add
ADMIN_ROUTESconstant with patterns to protect - Deploy to production
- Share the new route patterns (or keep them secret — the point is obscurity)
Open Questions
- Should we also protect
/api/aprobarand/api/rechazareven 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.