Browse Source

feat(ui): ring overflow chip interactive, pull-to-refresh, demo read-only (#117 #139 #118) (#148)

#117 — ring-overflow '+N' chip interactive:
- RingOverflowChip now carries the resolved hidden devices (derived with
  hubOf/isVisibleInRing next to the existing overflow count).
- TopologyMap: ring-overflow chip is now role=button + tabindex (keyboard
  accessible) mirroring peers-overflow; clicking/hovering opens a tooltip
  listing the hidden clients (icon, name, band, IP).
- i18n es/en overflowTitle.

#139 — pull-to-refresh on mobile:
- PullToRefresh component (from Keynest pattern) wrapping the Layout
  Outlet: touch pull from scrollY<=0 reloads the page to pick up new
  deploys; passive listeners, no interference with native overscroll or
  desktop.

#118 — demo mode read-only + compact admin-bar toggle:
- Backend: demoReadOnly middleware rejects non-GET/HEAD mutations with
  409 demo_read_only when cfg.DemoMode, except allowlist (auth/*,
  demo/enable, refresh, push/*, users/me/*). Wired inside RequireAuth.
- Frontend: DemoCard is now a compact switch in the admin bar (was a full
  Settings card); keeps the enable/disable + restart flow.
- Tests: TestDemoReadOnly (mutations blocked, allowlist works); test
  helpers split into makeTestServer (DEMO_MODE=0, CRUD tests) and
  makeDemoTestServer (DEMO_MODE=1).

#141 (layout tuning) left pending for visual review on the live map.
Verified in production (CT 226): pull-to-refresh doesn't break mobile
render, demo toggle switch present in admin bar. Go suite + frontend
build/lint green.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 months ago
parent
commit
bfe7ae3919

+ 2 - 1
app/public/locales/en/translation.json

@@ -640,7 +640,8 @@
       "overflowAria": "{{count}} additional WireGuard peers"
     },
     "ring": {
-      "overflowAria": "{{count}} more clients on {{router}}"
+      "overflowAria": "{{count}} more clients on {{router}}",
+      "overflowTitle": "{{count}} more clients on {{router}}"
     }
   },
   "settings": {

+ 2 - 1
app/public/locales/es/translation.json

@@ -640,7 +640,8 @@
       "overflowAria": "{{count}} peers WireGuard adicionales"
     },
     "ring": {
-      "overflowAria": "{{count}} clientes más en {{router}}"
+      "overflowAria": "{{count}} clientes más en {{router}}",
+      "overflowTitle": "{{count}} clientes más en {{router}}"
     }
   },
   "settings": {

+ 17 - 11
app/src/components/Layout.tsx

@@ -2,6 +2,7 @@ import { useMemo, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router'
 import { AnimatePresence, motion } from 'framer-motion'
+import PullToRefresh from '@/components/PullToRefresh'
 import {
   BarChart3,
   Bell,
@@ -636,17 +637,22 @@ function Shell() {
         <main className="mx-auto w-full max-w-[1400px] px-4 pb-24 pt-4 md:px-6 md:pb-10 md:pt-6">
           {isDemo && <DemoBanner />}
           <UpdateBanner />
-          <AnimatePresence mode="wait">
-            <motion.div
-              key={key}
-              initial={{ opacity: 0, y: 8 }}
-              animate={{ opacity: 1, y: 0 }}
-              exit={{ opacity: 0, y: -4 }}
-              transition={{ duration: 0.2, ease: 'easeOut' }}
-            >
-              <Outlet />
-            </motion.div>
-          </AnimatePresence>
+          {/* Pull-to-refresh (issue #139): gesto móvil recarga la vista para
+              coger un deploy nuevo sin reabrir la app. Solo actúa en touch y
+              con scroll arriba; no interfiere con carruseles/tablas. */}
+          <PullToRefresh>
+            <AnimatePresence mode="wait">
+              <motion.div
+                key={key}
+                initial={{ opacity: 0, y: 8 }}
+                animate={{ opacity: 1, y: 0 }}
+                exit={{ opacity: 0, y: -4 }}
+                transition={{ duration: 0.2, ease: 'easeOut' }}
+              >
+                <Outlet />
+              </motion.div>
+            </AnimatePresence>
+          </PullToRefresh>
         </main>
       </div>
       <TabBar />

+ 85 - 0
app/src/components/PullToRefresh.tsx

@@ -0,0 +1,85 @@
+/**
+ * Pull-to-refresh móvil (issue #139): al tirar hacia abajo desde el top de la
+ * página, recarga la vista (permite coger un deploy nuevo sin cerrar y reabrir
+ * la app). Solo actúa cuando window.scrollY <= 0 y el gesto es un pull vertical.
+ * En desktop no aporta (Ctrl+R existe) y no interfiere con scroll nativo.
+ */
+import { useEffect, useRef, useState } from 'react'
+import type { ReactNode } from 'react'
+import { RefreshCw } from 'lucide-react'
+import { cn } from '@/lib/utils'
+
+const THRESHOLD = 70
+
+export default function PullToRefresh({ children }: { children: ReactNode }) {
+  const startY = useRef<number | null>(null)
+  const pullRef = useRef(0)
+  const [pull, setPull] = useState(0)
+  const [refreshing, setRefreshing] = useState(false)
+
+  useEffect(() => {
+    const onTouchStart = (e: TouchEvent) => {
+      if (window.scrollY <= 0 && e.touches.length === 1) {
+        startY.current = e.touches[0].clientY
+      } else {
+        startY.current = null
+      }
+    }
+    const onTouchMove = (e: TouchEvent) => {
+      if (startY.current === null) return
+      const dy = e.touches[0].clientY - startY.current
+      if (dy > 0) {
+        const v = Math.min(dy * 0.5, 120)
+        pullRef.current = v
+        setPull(v)
+      } else {
+        pullRef.current = 0
+        setPull(0)
+      }
+    }
+    const onTouchEnd = () => {
+      if (startY.current === null) return
+      startY.current = null
+      if (pullRef.current >= THRESHOLD) {
+        setRefreshing(true)
+        window.location.reload()
+        return
+      }
+      pullRef.current = 0
+      setPull(0)
+    }
+    window.addEventListener('touchstart', onTouchStart, { passive: true })
+    window.addEventListener('touchmove', onTouchMove, { passive: true })
+    window.addEventListener('touchend', onTouchEnd, { passive: true })
+    return () => {
+      window.removeEventListener('touchstart', onTouchStart)
+      window.removeEventListener('touchmove', onTouchMove)
+      window.removeEventListener('touchend', onTouchEnd)
+    }
+  }, [])
+
+  return (
+    <div className="relative">
+      <div
+        className="pointer-events-none absolute inset-x-0 top-0 z-50 flex items-center justify-center overflow-hidden"
+        style={{
+          height: Math.max(pull, refreshing ? 28 : 0),
+          transition: refreshing ? 'height 0.2s' : 'none',
+        }}
+      >
+        <RefreshCw
+          className={cn('h-5 w-5', (pull > 0 || refreshing) && 'animate-spin')}
+          style={{ color: 'rgb(var(--text-muted))' }}
+        />
+      </div>
+      <div
+        style={{
+          transform: pull > 0 ? `translateY(${pull}px)` : undefined,
+          transition: pull > 0 ? 'none' : 'transform 0.2s',
+        }}
+      >
+        {children}
+      </div>
+    </div>
+  )
+}

+ 51 - 2
app/src/components/topology/TopologyMap.tsx

@@ -69,6 +69,7 @@ type TooltipData =
   | { kind: 'internet'; id: string; x: number; y: number }
   | { kind: 'peer'; id: string; peer: WGPeer; x: number; y: number }
   | { kind: 'peersOverflow'; id: string; peers: WGPeer[]; x: number; y: number }
+  | { kind: 'ringOverflow'; id: string; routerName: string; devices: Device[]; x: number; y: number }
   | {
       kind: 'chip'
       id: string
@@ -185,6 +186,33 @@ function TooltipCard({
           </div>
         </div>
       )}
+      {tip.kind === 'ringOverflow' && (
+        <div>
+          <div className="flex items-center justify-between gap-2">
+            <span className="font-display text-sm font-semibold text-text-primary">
+              {t('topology.ring.overflowTitle', { count: tip.devices.length, router: tip.routerName })}
+            </span>
+            <StatusPill tone="accent" label="+N" />
+          </div>
+          <div className="mt-2 max-h-48 space-y-1.5 overflow-y-auto">
+            {tip.devices.length === 0 && <div className="text-caption text-text-muted">—</div>}
+            {tip.devices.map((d) => {
+              const Icon = DEVICE_ICONS[d.type] ?? Laptop
+              return (
+                <div key={d.id} className="flex items-center gap-2 text-caption">
+                  <Icon className="h-3.5 w-3.5 shrink-0 text-text-muted" strokeWidth={1.75} />
+                  <span className="min-w-0 flex-1 truncate font-semibold text-text-primary">{d.name}</span>
+                  <span className="shrink-0 text-text-muted">{d.band === 'cable' ? t('common.cable') : d.band}</span>
+                  {d.ip && <span className="shrink-0 font-mono text-text-muted">{d.ip}</span>}
+                </div>
+              )
+            })}
+          </div>
+          <div className="mt-2 border-t border-border pt-1.5 text-caption font-semibold text-accent">
+            {touch ? t('topology.tapAgainDetail') : t('topology.clickDetail')}
+          </div>
+        </div>
+      )}
       {tip.kind === 'chip' && (
         <ChipTooltip chip={tip.chip} touch={touch} hostCtCount={tip.hostCtCount} ctHost={tip.ctHost} />
       )}
@@ -1027,6 +1055,14 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
         {/* --------- Clientes ocultos del anillo ("+N", semántica server) ------ */}
         {ringOverflowChips.map((chip, i) => {
           const routerName = routerNodes.find((n) => n.id === chip.routerId)?.router.name ?? chip.routerId
+          const tip: Extract<TooltipData, { kind: 'ringOverflow' }> = {
+            kind: 'ringOverflow',
+            id: `ring-overflow-${chip.routerId}`,
+            routerName,
+            devices: chip.devices,
+            x: chip.x,
+            y: chip.y + 30,
+          }
           return (
             <g key={`ring-overflow-${chip.routerId}`} transform={`translate(${chip.x} ${chip.y})`}>
               <motion.g
@@ -1035,8 +1071,21 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                 transition={reduce ? { duration: 0 } : { delay: (2.2 + i * 0.1) * T, duration: 0.35 }}
                 style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
               >
-                <g role="img" aria-label={t('topology.ring.overflowAria', { count: chip.count, router: routerName })}>
-                  <title>{t('topology.ring.overflowAria', { count: chip.count, router: routerName })}</title>
+                <g
+                  className="cursor-pointer outline-none"
+                  role="button"
+                  tabIndex={0}
+                  aria-label={t('topology.ring.overflowAria', { count: chip.count, router: routerName })}
+                  onPointerEnter={(e) => handleNodeHover(tip, e)}
+                  onPointerLeave={closeHover}
+                  onClick={(e) => nodeClick(e, tip)}
+                  onKeyDown={(e) => {
+                    if (e.key === 'Enter' || e.key === ' ') {
+                      e.preventDefault()
+                      handleNodeClick(tip)
+                    }
+                  }}
+                >
                   <rect x={-15} y={-11} width={30} height={22} rx={8} fill="rgb(var(--elevated))" stroke={COLOR.accent} strokeWidth={1.5} />
                   <text x={0} y={3.5} textAnchor="middle" fontSize={9.5} fontWeight={700} fill={COLOR.accent}>
                     +{chip.count}

+ 8 - 2
app/src/components/topology/model.ts

@@ -128,10 +128,13 @@ export interface TopologyInput {
   vm?: number
 }
 
-/** Chip "+N" de un anillo desbordado (posición ya calculada, geometría local). */
+/** Chip "+N" de un anillo desbordado (posición ya calculada, geometría local).
+ *  `devices` = clientes ocultos del anillo (los que el "+N" resume), para que
+ *  el chip sea interactivo y los liste (issue #117). */
 export interface RingOverflowChip {
   routerId: string
   count: number
+  devices: Device[]
   x: number
   y: number
 }
@@ -956,7 +959,10 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const radii = ringRadii.get(routerId)
     const isGw = routerId === gatewayNode?.id
     const r = radii?.[radii.length - 1] ?? (isGw ? GATEWAY_RINGS : AP_RINGS)[(isGw ? GATEWAY_RINGS : AP_RINGS).length - 1].r
-    ringOverflowChips.push({ routerId, count, ...pos(node.x, node.y, isGw ? 60 : 250, r) })
+    // Clientes ocultos = miembros del anillo que exceden el aforo visible
+    // (issue #117: el chip "+N" los lista al hacer clic, como peers-overflow).
+    const hidden = online.filter((d) => hubOf(d) === routerId && !isVisibleInRing(d))
+    ringOverflowChips.push({ routerId, count, devices: hidden, ...pos(node.x, node.y, isGw ? 60 : 250, r) })
   }
 
   // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------

+ 23 - 28
app/src/pages/Settings.tsx

@@ -1589,7 +1589,7 @@ function PushNotificationsCard({ reduce, onSaved }: { reduce: boolean; onSaved:
 // vía de explorarla después. Solo visible para admin con backend real (en el
 // demo local sin backend no hay .env que tocar).
 // ---------------------------------------------------------------------------
-function DemoCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
+function DemoCard({ onSaved }: { reduce?: boolean; onSaved: () => void }) {
   const { t } = useTranslation()
   const [serverMode, setServerMode] = useState<'demo' | 'live' | null>(null)
   const [busy, setBusy] = useState(false)
@@ -1639,33 +1639,28 @@ function DemoCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => void })
 
   if (serverMode === null) return null
 
-  const enabling = serverMode === 'live'
+  // Switch compacto de la AdminBar (issue #118): el checkbox de la tarjeta
+  // grande se sustituye por este toggle de una línea.
   return (
-    <Card title={t('settings.demo.title')} caption={t('settings.demo.caption')} index={5} reduce={reduce}>
-      <div className="flex flex-col gap-3">
-        <p className="text-caption leading-relaxed text-text-muted">
-          {enabling ? t('settings.demo.enableDesc') : t('settings.demo.disableDesc')}
-        </p>
-        {busy ? (
-          <div className="flex items-center gap-2 rounded-xl bg-elevated px-3.5 py-2.5 text-caption text-text-secondary">
-            <span className="relative flex h-2 w-2">
-              <span className="absolute inline-flex h-full w-full animate-ping-soft rounded-full bg-accent opacity-75" />
-              <span className="relative inline-flex h-2 w-2 rounded-full bg-accent" />
-            </span>
-            {t('settings.demo.restarting')}
-          </div>
-        ) : (
-          <button
-            onClick={() => void switchMode(enabling)}
-            className="inline-flex w-fit items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
-          >
-            <FlaskConical className="h-4 w-4" strokeWidth={1.75} />
-            {enabling ? t('settings.demo.enable') : t('settings.demo.disable')}
-          </button>
-        )}
-        {error && <p className="text-caption text-red-500">{error}</p>}
-      </div>
-    </Card>
+    <label
+      className="inline-flex h-9 shrink-0 cursor-pointer items-center gap-2 rounded-xl border border-border bg-elevated px-3 text-[13px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+      title={t('settings.demo.caption')}
+    >
+      <FlaskConical className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+      <span className="hidden sm:inline">{t('settings.demo.title')}</span>
+      <Switch
+        checked={serverMode === 'demo'}
+        onCheckedChange={(v) => void switchMode(v)}
+        disabled={busy}
+        aria-label={t('settings.demo.title')}
+      />
+      {busy && <span className="h-2 w-2 animate-ping-soft rounded-full bg-accent" aria-hidden="true" />}
+      {error && (
+        <span role="alert" className="text-caption text-danger">
+          {error}
+        </span>
+      )}
+    </label>
   )
 }
 
@@ -2642,7 +2637,7 @@ export default function Settings() {
 
                 {/* 4. Modo demo a la derecha */}
                 <div className="ml-auto">
-                  <DemoCard reduce={reduce} onSaved={notify} />
+                  <DemoCard onSaved={notify} />
                 </div>
               </div>
 

+ 1 - 1
server-go/internal/httpapi/agent_api_test.go

@@ -43,7 +43,7 @@ func makeAgentTestServer(t *testing.T) *agentTestServer {
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
 		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
-		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
 		t.Fatalf("config: %v", err)

+ 1 - 1
server-go/internal/httpapi/demo_test.go

@@ -35,7 +35,7 @@ func TestDemoEnable401SinSesion(t *testing.T) {
 }
 
 func TestDemoEnable409CuandoYaDemo(t *testing.T) {
-	ts := makeTestServer(t) // DEMO_MODE=1
+	ts := makeDemoTestServer(t) // DEMO_MODE=1
 	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
 	res := do(t, "POST", ts.URL, "/api/demo/enable", adminCookie)
 	if res.StatusCode != http.StatusConflict {

+ 54 - 0
server-go/internal/httpapi/demoreadonly.go

@@ -0,0 +1,54 @@
+// demoreadonly.go — Guard de modo demo read-only (issue #118). En modo demo
+// (DEMO_MODE=1) el dataset canónico vive en memoria y la BD debe quedar
+// pristina: cualquier mutación HTTP (no GET/HEAD) se rechaza con 409
+// "demo_read_only" salvo una allowlist mínima.
+package httpapi
+
+import (
+	"net/http"
+	"strings"
+)
+
+// demoReadOnlyNext permite pasar al siguiente handler.
+// demoAllowlist: rutas de mutación que SÍ deben funcionar en modo demo.
+//   - /api/auth/* : login/logout (ciclo de vida de sesión; sin login no hay demo)
+//   - /api/demo/enable : la única vía de SALIR del demo (si se bloquea, el
+//     admin queda atrapado en demo para siempre)
+//   - /api/refresh : no escribe en BD; el botón "Refrescar" sigue vivo
+//   - /api/push/* y /api/users/me/* : preferencias de usuario/UI (idioma,
+//     nombre, push), no tocan el dataset canónico
+func demoAllowlist(path string) bool {
+	if strings.HasPrefix(path, "/api/auth/") {
+		return true
+	}
+	switch path {
+	case "/api/demo/enable", "/api/refresh":
+		return true
+	}
+	if strings.HasPrefix(path, "/api/push/") || strings.HasPrefix(path, "/api/users/me/") {
+		return true
+	}
+	return false
+}
+
+// demoReadOnly envuelve el mux de API: en modo demo, rechaza mutaciones fuera
+// de la allowlist. Ubicado DENTRO de RequireAuth (ve el User del contexto) y
+// ANTES de noStoreMux. Los endpoints de agente (Bearer) también lo atraviesan,
+// pero en demo no hay agentes reales.
+//
+// Fuente de verdad: cfg.DemoMode (lo que declara el operador en DEMO_MODE).
+// En producción, DEMO_MODE=1 → adapter NewDemo (coinciden). En el fallback de
+// arranque sin clave SSH el adapter cae a demo pero cfg sigue live: las
+// mutaciones de BD/UI permanecen operativas (no hay red que gestionar de todos
+// modos). Los tests de mutación usan DEMO_MODE=0 sin depender de adapter.
+func (s *server) demoReadOnly(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if s.cfg != nil && s.cfg.DemoMode && r.Method != http.MethodGet && r.Method != http.MethodHead {
+			if !demoAllowlist(r.URL.Path) {
+				writeError(w, http.StatusConflict, "demo_read_only", "Modo demo: las escrituras están deshabilitadas para preservar el dataset de ejemplo.")
+				return
+			}
+		}
+		next.ServeHTTP(w, r)
+	})
+}

+ 80 - 0
server-go/internal/httpapi/demoreadonly_test.go

@@ -0,0 +1,80 @@
+package httpapi_test
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// demoReadOnly (issue #118): en modo demo las mutaciones fuera de la allowlist
+// se rechazan con 409 demo_read_only; la allowlist (login, demo/enable,
+// refresh, push, users/me) sigue funcionando.
+func TestDemoReadOnly(t *testing.T) {
+	ts := makeDemoTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	if cookie == "" {
+		t.Fatal("login no devolvió cookie")
+	}
+
+	do := func(method, path, body string) (int, string) {
+		t.Helper()
+		var req *http.Request
+		if body != "" {
+			req, _ = http.NewRequest(method, ts.URL+path, strings.NewReader(body))
+			req.Header.Set("Content-Type", "application/json")
+		} else {
+			req, _ = http.NewRequest(method, ts.URL+path, nil)
+		}
+		req.Header.Set("Cookie", "session="+cookie)
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatalf("%s %s: %v", method, path, err)
+		}
+		defer res.Body.Close()
+		buf := new(strings.Builder)
+		_, _ = io.Copy(buf, res.Body)
+		return res.StatusCode, buf.String()
+	}
+
+	// Mutación bloqueada: crear un override de topología en demo
+	status, bodyStr := do("POST", "/api/topology/overrides", `{"mac":"aa:bb:cc:dd:ee:ff","kind":"hypervisor"}`)
+	if status != http.StatusConflict {
+		t.Errorf("POST override en demo: status %d, esperado 409", status)
+	}
+	var body struct {
+		Error string `json:"error"`
+	}
+	if err := json.Unmarshal([]byte(bodyStr), &body); err != nil {
+		t.Fatalf("decode: %v", err)
+	}
+	if body.Error != "demo_read_only" {
+		t.Errorf("error=%q, esperado demo_read_only", body.Error)
+	}
+
+	// Mutación bloqueada: añadir router
+	if status, _ := do("POST", "/api/config/routers", `{"host":"10.0.0.9","name":"r9"}`); status != http.StatusConflict {
+		t.Errorf("POST router en demo: status %d, esperado 409", status)
+	}
+
+	// Mutación bloqueada: plan de orquestación
+	if status, _ := do("POST", "/api/plans", `{"router_id":"r1","resource":"x","desired":"y"}`); status != http.StatusConflict {
+		t.Errorf("POST plan en demo: status %d, esperado 409", status)
+	}
+
+	// Allowlist: refresh (no escribe) debe funcionar
+	if status, _ := do("POST", "/api/refresh", ""); status != http.StatusNoContent && status != http.StatusAccepted && status != http.StatusTooManyRequests {
+		t.Errorf("POST refresh en demo: status %d, no esperado", status)
+	}
+
+	// Allowlist: preferencia de idioma (users/me) debe funcionar
+	if status, _ := do("PUT", "/api/users/me/language", `{"language":"es"}`); status != http.StatusOK && status != http.StatusNoContent {
+		t.Errorf("PUT language en demo: status %d, esperado 2xx", status)
+	}
+
+	// GET sigue funcionando (solo lectura)
+	if status, _ := do("GET", "/api/topology/overrides", ""); status != http.StatusOK {
+		t.Errorf("GET overrides en demo: status %d, esperado 200", status)
+	}
+}

+ 21 - 2
server-go/internal/httpapi/httpapi_test.go

@@ -27,17 +27,36 @@ type testServer struct {
 }
 
 // makeTestServer replica tests/helpers.js: app real con adapter demo stub y
-// DB temporal, config AUTH_USER=admin AUTH_PASS=test1234 DEMO_MODE=1.
+// DB temporal. DEMO_MODE=0 → la API permite mutaciones (tests de CRUD de
+// users/routers/agents). Para probar el modo demo read-only (issue #118) usar
+// makeDemoTestServer. El adapter sigue siendo NewDemo: /api/health y /api/auth/me
+// reportan mode:"demo" como esperan algunos tests de contrato.
 func makeTestServer(t *testing.T) *testServer {
+	t.Helper()
+	return makeTestServerWithMode(t, false)
+}
+
+// makeDemoTestServer: igual que makeTestServer pero con DEMO_MODE=1 (issue
+// #118) — las mutaciones fuera de la allowlist se rechazan con 409.
+func makeDemoTestServer(t *testing.T) *testServer {
+	t.Helper()
+	return makeTestServerWithMode(t, true)
+}
+
+func makeTestServerWithMode(t *testing.T, demoMode bool) *testServer {
 	t.Helper()
 	// Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
 	// limit); por defecto en producción NO se confía en XFF (auditoría #1).
 	auth.SetTrustProxy(true)
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
+	demo := "0"
+	if demoMode {
+		demo = "1"
+	}
 	cfg, err := config.Load(map[string]string{
 		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
-		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+		"DEMO_MODE": demo, "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
 		t.Fatalf("config: %v", err)

+ 1 - 1
server-go/internal/httpapi/rearm_api_test.go

@@ -74,7 +74,7 @@ func makeRearmTestServer(t *testing.T, pool *fakeSSH, pollWait time.Duration) *r
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
 		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
-		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
 		t.Fatalf("config: %v", err)

+ 1 - 1
server-go/internal/httpapi/server.go

@@ -254,7 +254,7 @@ func NewHandler(d Deps) http.Handler {
 		mux.Handle("/", static)
 	}
 
-	return requestID(security.Middleware(auth.RequireAuth(s.db, s.secret, noStoreMux(mux))))
+	return requestID(security.Middleware(auth.RequireAuth(s.db, s.secret, s.demoReadOnly(noStoreMux(mux)))))
 }
 
 // requestID lee o genera un x-request-id para cada petición y lo expone en