Просмотр исходного кода

feat(integrations): support password authentication in ssh mode (#1708) (#1716)

Nacho 1 месяц назад
Родитель
Сommit
fe25ba27f1

+ 4 - 0
CHANGELOG.md

@@ -9,6 +9,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- Integrations in ssh mode accept password authentication (#1708): when the optional companion file `<data-dir>/integrations/<slug>.sshpass` (0600, same discipline as the environment file) exists, the server signs in to the router with the integration username and password; without it the server key stays the default and preferred path. The create and edit forms reuse the same password field for it (empty on edit keeps the current one), the password never reaches the database or any API response, deleting the integration removes the file, and an authentication rejection reports its own `ssh_auth_failed` code instead of the generic `ssh_failed`. Stock Asuswrt (dropbear with password auth only) now works with no manual key setup.
+
+### Fixed
+
 - `NETPULSE_DB_ROLLBACK_JOURNAL=1` restores the previous on-box SQLite journal engine (DELETE + synchronous FULL) after the #1700 default change; `NETPULSE_DB_TEMP_STORE` (`memory` | `file` | `default`) controls where SQLite aggregation spills go, and is also settable on-box via the new `db_rollback_journal` / `db_temp_store` UCI options.
 
 ### Fixed

+ 8 - 0
README.es.md

@@ -268,6 +268,14 @@ El pusher usa las sondas portables para sistema, WiFi, DHCP, FDB del bridge,
 ARP y LLDP. Lo que necesita `ubus` o servicios de GL.iNet sigue ausente, y las
 acciones de upgrade y reinstall del agente nativo no están disponibles.
 
+Desde la sección Integraciones la app también puede instalar el pusher por
+SSH. La llave del servidor autorizada sigue siendo lo preferente: cuando el
+router solo acepta contraseña, como el dropbear de un Asuswrt de fábrica,
+indica la contraseña en el formulario y el servidor conecta con ella. La
+contraseña se guarda en un fichero compañero 0600 junto al de entorno de la
+integración, nunca en la base de datos, y una contraseña equivocada se
+reporta como `ssh_auth_failed` en vez de un fallo genérico de SSH.
+
 **Sidecar de latencia.** Sondeos TCP de latencia por router a largo plazo,
 opcionales:
 

+ 8 - 0
README.md

@@ -259,6 +259,14 @@ The pusher uses the portable probes for system data, wireless, DHCP, bridge
 FDB, ARP and LLDP. Features that require `ubus` or GL.iNet services remain
 absent, and the native agent upgrade and reinstall actions are not available.
 
+From the Integrations section the app can also install the pusher for you
+over SSH. An authorized server key is still the preferred path; when the
+router only accepts passwords, like the dropbear of a stock Asuswrt, set the
+password in the form and the server signs in with it. The password is stored
+in a 0600 companion file next to the integration environment file, never in
+the database, and a wrong password reports `ssh_auth_failed` instead of a
+generic SSH failure.
+
 **Latency sidecar.** Optional long-term TCP latency probes per router:
 
 ```bash

+ 3 - 0
app/public/locales/en/translation.json

@@ -752,6 +752,7 @@
       "fieldHostPlaceholder": "192.168.1.1",
       "fieldUsername": "Username",
       "fieldPassword": "Password",
+      "fieldPasswordSshHint": "The password signs in to the router over SSH for the install and later actions. An authorized key stays the preferred path: use this when the router only accepts passwords, like stock Asuswrt.",
       "fieldInterval": "Interval (seconds)",
       "fieldIntervalInvalid": "Interval must be between 10 and 86400 seconds",
       "fieldArch": "Architecture",
@@ -788,6 +789,7 @@
       "download_failed": "Download failed.",
       "start_failed": "Could not start the pusher.",
       "ssh_failed": "SSH connection failed.",
+      "ssh_auth_failed": "SSH authentication failed: check the router username and password.",
       "ssh_unavailable": "SSH is not available for this vendor.",
       "router_error": "The router reported an error.",
       "not_found": "Integration not found.",
@@ -799,6 +801,7 @@
       "title": "Edit integration",
       "fieldPassword": "Password",
       "fieldPasswordKeep": "Leave blank to keep the current one",
+      "fieldPasswordSshHint": "Also updates the SSH password the server uses to reach the router. Leave blank to keep both.",
       "save": "Save and restart",
       "saving": "Saving",
       "restartHint": "Saving rewrites the pusher environment and restarts it, so the new values take effect at once."

+ 3 - 0
app/public/locales/es/translation.json

@@ -752,6 +752,7 @@
       "fieldHostPlaceholder": "192.168.1.1",
       "fieldUsername": "Usuario",
       "fieldPassword": "Contraseña",
+      "fieldPasswordSshHint": "La contraseña inicia sesión SSH en el router para instalar el pusher y para las acciones posteriores. La llave autorizada sigue siendo lo preferente: usa este campo cuando el router solo acepte contraseña, como un Asuswrt de fábrica.",
       "fieldInterval": "Intervalo (segundos)",
       "fieldIntervalInvalid": "El intervalo debe estar entre 10 y 86400 segundos",
       "fieldArch": "Arquitectura",
@@ -788,6 +789,7 @@
       "download_failed": "Falló la descarga.",
       "start_failed": "No se pudo arrancar el pusher.",
       "ssh_failed": "Falló la conexión SSH.",
+      "ssh_auth_failed": "Autenticación SSH rechazada: revisa el usuario y la contraseña del router.",
       "ssh_unavailable": "SSH no está disponible para este proveedor.",
       "router_error": "El router devolvió un error.",
       "not_found": "Integración no encontrada.",
@@ -799,6 +801,7 @@
       "title": "Editar integración",
       "fieldPassword": "Contraseña",
       "fieldPasswordKeep": "En blanco conserva la actual",
+      "fieldPasswordSshHint": "También actualiza la contraseña SSH que el servidor usa para conectar al router. En blanco conserva ambas.",
       "save": "Guardar y reiniciar",
       "saving": "Guardando",
       "restartHint": "Al guardar se reescribe el entorno del pusher y se reinicia, así que los valores nuevos entran en vigor al momento."

+ 7 - 1
app/src/pages/Integrations.tsx

@@ -177,7 +177,7 @@ export default function Integrations() {
   const submit = async (e: React.FormEvent) => {
     e.preventDefault()
     if (submitting) return
-    if (!vendorId || !host.trim() || !SLUG_RE.test(slug.trim()) || intervalInvalid) return
+    if (!vendorId || !host.trim() || !SLUG_RE.test(slug.trim()) || intervalInvalid || password === '') return
     setSubmitting(true)
     setError('')
     try {
@@ -438,6 +438,9 @@ export default function Integrations() {
                 autoComplete="new-password"
                 className="mt-1 w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
               />
+              {selectedVendor && selectedVendor.mode === 'ssh' && (
+                <span className="mt-1 block text-xs text-text-muted">{t('integrations.form.fieldPasswordSshHint')}</span>
+              )}
             </label>
             <label className="block">
               <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldInterval')}</span>
@@ -672,6 +675,9 @@ export default function Integrations() {
                           placeholder={t('integrations.edit.fieldPasswordKeep')}
                           className="mt-1 w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
                         />
+                        {editing && editing.mode === 'ssh' && (
+                          <span className="mt-1 block text-xs text-text-muted">{t('integrations.edit.fieldPasswordSshHint')}</span>
+                        )}
                       </label>
                       <label className="block">
                         <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldInterval')}</span>

+ 81 - 0
server-go/internal/adapters/sshpool.go

@@ -50,12 +50,22 @@ type SSHPool struct {
 
 	mu     sync.Mutex
 	conns  map[string]*sshConn
+	creds  map[string]sshCred
 	closed bool
 
 	dialTCP     func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
 	closeClient func(*ssh.Client) error
 }
 
+// sshCred es la credencial de contraseña registrada para un host
+// (#1708): las integraciones ssh con fichero compañero <slug>.sshpass
+// conectan por contraseña mientras la credencial esté registrada; el resto
+// de destinos siguen con la llave del servidor.
+type sshCred struct {
+	user     string
+	password string
+}
+
 func (p *SSHPool) closeSSHClient(c *ssh.Client) error {
 	if c == nil {
 		return nil
@@ -88,10 +98,45 @@ func NewSSHPool(keyPath string) (*SSHPool, error) {
 		signer:  signer,
 		khPath:  sshkey.KnownHostsPath(keyPath),
 		conns:   map[string]*sshConn{},
+		creds:   map[string]sshCred{},
 		dialTCP: ssh.Dial,
 	}, nil
 }
 
+// SetPassword registra (o borra, con password vacía) la credencial de
+// contraseña de un host (#1708). Mientras haya credencial, el dial de ese
+// host autentica por contraseña con el usuario dado y la llave del servidor
+// queda aparcada. Un cambio de credencial tira la conexión cacheada y el
+// backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
+// esperar el enfriamiento de un fallo ya resuelto.
+func (p *SSHPool) SetPassword(host, user, password string) {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	old, had := p.creds[host]
+	if password == "" {
+		if !had {
+			return
+		}
+		delete(p.creds, host)
+	} else {
+		if had && old.user == user && old.password == password {
+			return
+		}
+		if p.creds == nil {
+			p.creds = map[string]sshCred{}
+		}
+		p.creds[host] = sshCred{user: user, password: password}
+	}
+	if e := p.conns[host]; e != nil {
+		if e.client != nil {
+			_ = p.closeSSHClient(e.client)
+			e.client = nil
+		}
+		e.failures = 0
+		e.notUntil = time.Time{}
+	}
+}
+
 // hostKeyCallback implementa accept-new sobre el known_hosts propio.
 func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 	if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
@@ -148,6 +193,28 @@ func (e *HostKeyChangedError) Error() string {
 	return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
 }
 
+// SSHAuthError: el host rechazó la autenticación SSH (contraseña o llave
+// rechazadas por el servidor). Va con código de error propio en la API
+// (ssh_auth_failed, #1708) para que la UI pida revisar la contraseña en vez
+// de un fallo genérico de conexión.
+type SSHAuthError struct {
+	Host string
+	Err  error
+}
+
+func (e *SSHAuthError) Error() string {
+	return "ssh " + e.Host + ": authentication rejected: " + e.Err.Error()
+}
+
+func (e *SSHAuthError) Unwrap() error { return e.Err }
+
+// isSSHAuthError reconoce el rechazo de autenticación del handshake. La
+// librería no exporta un tipo para esto y el texto es estable en x/crypto
+// ("ssh: unable to authenticate, attempted methods ...").
+func isSSHAuthError(err error) bool {
+	return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate")
+}
+
 // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
 // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
 // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
@@ -236,12 +303,23 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 		p.mu.Unlock()
 		return nil, err
 	}
+	// Credencial registrada para este host (#1708): contraseña con el
+	// usuario de la integración en vez de la llave del servidor. Se lee bajo
+	// lock para no competir con SetPassword.
+	p.mu.Lock()
+	cred, hasCred := p.creds[host]
+	p.mu.Unlock()
+
 	cfg := &ssh.ClientConfig{
 		User:            "root",
 		Auth:            []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
 		HostKeyCallback: cb,
 		Timeout:         sshDialTimeout,
 	}
+	if hasCred {
+		cfg.User = cred.user
+		cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
+	}
 	client, err := p.dialTCP("tcp", addrOf(host), cfg)
 
 	p.mu.Lock()
@@ -255,6 +333,9 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 		}
 		entry.notUntil = time.Now().Add(backoff)
 		p.mu.Unlock()
+		if isSSHAuthError(err) {
+			return nil, &SSHAuthError{Host: host, Err: err}
+		}
 		return nil, fmt.Errorf("ssh %s: %w", host, err)
 	}
 	if p.closed {

+ 215 - 0
server-go/internal/adapters/sshpool_password_test.go

@@ -0,0 +1,215 @@
+package adapters
+
+import (
+	"crypto/ed25519"
+	"crypto/rand"
+	"errors"
+	"fmt"
+	"net"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"golang.org/x/crypto/ssh"
+)
+
+// startPasswordOnlySSHServer levanta un servidor SSH real en memoria que
+// solo acepta la contraseña dada para el usuario dado (dropbear de un
+// asuswrt de fábrica: sin llaves). Devuelve la dirección escuchando.
+func startPasswordOnlySSHServer(t *testing.T, user, acceptPassword string, seenUser *atomic.Value) net.Addr {
+	t.Helper()
+	_, priv, err := ed25519.GenerateKey(rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	signer, err := ssh.NewSignerFromKey(priv)
+	if err != nil {
+		t.Fatal(err)
+	}
+	config := &ssh.ServerConfig{
+		PasswordCallback: func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
+			if seenUser != nil {
+				seenUser.Store(conn.User())
+			}
+			if conn.User() == user && string(password) == acceptPassword {
+				return &ssh.Permissions{}, nil
+			}
+			return nil, fmt.Errorf("password rejected for %q", conn.User())
+		},
+	}
+	config.AddHostKey(signer)
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { _ = ln.Close() })
+	go func() {
+		for {
+			conn, err := ln.Accept()
+			if err != nil {
+				return
+			}
+			// El pool solo necesita el handshake: la conexión se cierra al
+			// terminar el test sin llegar a abrir sesiones.
+			go func() {
+				_, _, reqs, _ := ssh.NewServerConn(conn, config)
+				go ssh.DiscardRequests(reqs)
+			}()
+		}
+	}()
+	return ln.Addr()
+}
+
+// TestSSHPoolPasswordAuthRealHandshake (#1708): con credencial registrada el
+// dial completa un handshake SSH real contra un servidor solo-contraseña
+// (dropbear de fábrica); con la contraseña equivocada el fallo sale como
+// SSHAuthError, que la API convierte en ssh_auth_failed.
+func TestSSHPoolPasswordAuthRealHandshake(t *testing.T) {
+	var seenUser atomic.Value
+	addr := startPasswordOnlySSHServer(t, "admin", "s3cret", &seenUser)
+	host := addr.String()
+
+	pool := newTestPool(t)
+	pool.SetPassword(host, "admin", "s3cret")
+	client, err := pool.dial(host)
+	if err != nil {
+		t.Fatalf("dial con la contraseña correcta: %v", err)
+	}
+	if client == nil {
+		t.Fatal("dial sin cliente")
+	}
+	if got := seenUser.Load(); got != "admin" {
+		t.Fatalf("el servidor vio al usuario %q, quiero admin", got)
+	}
+	_ = pool.closeSSHClient(client)
+
+	// Contraseña equivocada: rechazo de autenticación tipado.
+	pool.SetPassword(host, "admin", "mala")
+	_, err = pool.dial(host)
+	var ae *SSHAuthError
+	if err == nil || !errors.As(err, &ae) {
+		t.Fatalf("la contraseña equivocada debe dar SSHAuthError, obtuve %T: %v", err, err)
+	}
+}
+
+// TestSSHPoolDialUsesRegisteredPasswordUser (#1708): con credencial el dial
+// usa el usuario registrado (no root); sin credencial vuelve a root y a la
+// llave del servidor. Con fakes de dialTCP (sin handshake real).
+func TestSSHPoolDialUsesRegisteredPasswordUser(t *testing.T) {
+	pool := newTestPool(t)
+	var lastUser atomic.Value
+	lastUser.Store("")
+
+	pool.dialTCP = func(_ string, _ string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
+		lastUser.Store(cfg.User)
+		return &ssh.Client{}, nil
+	}
+
+	pool.SetPassword("10.0.0.9", "admin", "pw")
+	if _, err := pool.dial("10.0.0.9"); err != nil {
+		t.Fatalf("dial con credencial: %v", err)
+	}
+	if got := lastUser.Load().(string); got != "admin" {
+		t.Fatalf("usuario con credencial = %q, quiero admin", got)
+	}
+
+	// Same-value SetPassword no reinicia nada (la conexión cacheada queda).
+	if e := pool.conns["10.0.0.9"]; e == nil || e.client == nil {
+		t.Fatal("SetPassword con el mismo valor no debe tirar la conexión cacheada")
+	}
+}
+
+// TestSSHPoolPasswordChangeDropsConnAndBackoff (#1708): cambiar la
+// credencial tira la conexión cacheada y limpia el backoff, de modo que un
+// fallo de contraseña corregido no hereda el enfriamiento.
+func TestSSHPoolPasswordChangeDropsConnAndBackoff(t *testing.T) {
+	pool := newTestPool(t)
+	// Los clientes del fake son valores cero: el cierre va por el hook.
+	pool.closeClient = func(*ssh.Client) error { return nil }
+	var dials atomic.Int32
+	authErr := errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain")
+
+	pool.dialTCP = func(_ string, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+		dials.Add(1)
+		if dials.Load() == 1 {
+			return nil, authErr
+		}
+		return &ssh.Client{}, nil
+	}
+
+	pool.SetPassword("10.0.0.9", "admin", "mala")
+	if _, err := pool.dial("10.0.0.9"); err == nil {
+		t.Fatal("el dial con contraseña mala debía fallar")
+	} else {
+		var ae *SSHAuthError
+		if !errors.As(err, &ae) {
+			t.Fatalf("el fallo de autenticación debe salir como SSHAuthError, obtuve %T: %v", err, err)
+		}
+	}
+	if e := pool.conns["10.0.0.9"]; e == nil || !time.Now().Before(e.notUntil) {
+		t.Fatal("el fallo debe dejar backoff en el host")
+	}
+
+	pool.SetPassword("10.0.0.9", "admin", "buena")
+	if e := pool.conns["10.0.0.9"]; e != nil && time.Now().Before(e.notUntil) {
+		t.Fatal("el cambio de credencial debe limpiar el backoff")
+	}
+	if _, err := pool.dial("10.0.0.9"); err != nil {
+		t.Fatalf("dial con la credencial corregida: %v", err)
+	}
+	if dials.Load() != 2 {
+		t.Fatalf("dials = %d, quiero 2 (el fallo inicial y la reconexión)", dials.Load())
+	}
+}
+
+// TestSSHPoolPasswordClearFallsBackToKey (#1708): borrar la credencial
+// devuelve el dial a la llave (usuario root) y tira la conexión establecida
+// con contraseña.
+func TestSSHPoolPasswordClearFallsBackToKey(t *testing.T) {
+	pool := newTestPool(t)
+	// Los clientes del fake son valores cero: el cierre va por el hook.
+	pool.closeClient = func(*ssh.Client) error { return nil }
+	var dials atomic.Int32
+	var lastUser atomic.Value
+	lastUser.Store("")
+
+	pool.dialTCP = func(_ string, _ string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
+		dials.Add(1)
+		lastUser.Store(cfg.User)
+		return &ssh.Client{}, nil
+	}
+
+	pool.SetPassword("10.0.0.9", "admin", "pw")
+	if _, err := pool.dial("10.0.0.9"); err != nil {
+		t.Fatalf("dial: %v", err)
+	}
+	if lastUser.Load().(string) != "admin" {
+		t.Fatal("el primer dial debía ir con el usuario de la credencial")
+	}
+
+	pool.SetPassword("10.0.0.9", "", "")
+	if _, err := pool.dial("10.0.0.9"); err != nil {
+		t.Fatalf("dial tras limpiar: %v", err)
+	}
+	if dials.Load() != 2 {
+		t.Fatalf("dials = %d, quiero 2 (la credencial limpiada tira la conexión)", dials.Load())
+	}
+	if lastUser.Load().(string) != "root" {
+		t.Fatal("tras limpiar la credencial el dial debe volver a root con la llave")
+	}
+}
+
+// TestSSHPoolAuthErrorNotClassifiedForOtherFailures: un fallo de red no es
+// un rechazo de autenticación (código ssh_failed en la API, no
+// ssh_auth_failed).
+func TestSSHPoolAuthErrorNotClassifiedForOtherFailures(t *testing.T) {
+	pool := newTestPool(t)
+	pool.dialTCP = func(_ string, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+		return nil, &net.OpError{Op: "dial", Err: errors.New("connection refused")}
+	}
+	_, err := pool.dial("10.0.0.9")
+	var ae *SSHAuthError
+	if errors.As(err, &ae) {
+		t.Fatalf("un fallo de red no debe clasificar como SSHAuthError: %v", err)
+	}
+}

+ 103 - 12
server-go/internal/httpapi/integrations.go

@@ -7,6 +7,7 @@ package httpapi
 
 import (
 	"context"
+	"errors"
 	"fmt"
 	"log"
 	"net/http"
@@ -16,6 +17,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/rintegration"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
@@ -365,6 +367,17 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 		return
 	}
 
+	// #1708: en modo ssh la misma contraseña del formulario es la credencial
+	// SSH del alta y de las acciones posteriores: se guarda en el fichero
+	// compañero (0600) antes de conectar, nunca en la base de datos.
+	if vendor.Mode == "ssh" && s.integrations != nil {
+		if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
+			_ = store.Delete(body.Slug)
+			writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
+			return
+		}
+	}
+
 	// Router external cuyo id es el slug (push autenticado por token de
 	// agente, agent.token.<slug>).
 	router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
@@ -382,6 +395,9 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 			_ = s.integrations.Stop(body.Slug)
 			_ = s.integrations.Cleanup(body.Slug)
 		}
+		if vendor.Mode == "ssh" && s.integrations != nil {
+			_ = s.integrations.RemoveSSHPassword(body.Slug)
+		}
 		_ = routerstore.RemoveRouter(s.db.DB, body.Slug)
 		s.syncRouters()
 		_ = store.Delete(body.Slug)
@@ -396,7 +412,7 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 	})
 	if err != nil {
 		rollback()
-		writeError(w, http.StatusBadGateway, "start_failed", err.Error())
+		writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
 		return
 	}
 
@@ -457,10 +473,66 @@ func healPusherPin(env map[string]string, serverURL string) map[string]string {
 }
 
 func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
-	_, err := s.pool.Run(row.Host, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
+	_, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
 	return err
 }
 
+// sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
+// contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
+// solo implementan Run no, y en ese caso el pool queda como esté.
+type sshPasswordSetter interface {
+	SetPassword(host, user, password string)
+}
+
+// applyIntegrationSSHAuth aplica al pool la credencial SSH de la
+// integración (#1708): si existe el fichero compañero <slug>.sshpass la
+// conexión va por contraseña con el usuario de la fila (gana sobre la llave
+// del servidor); si no, la credencial se limpia y el dial usa la llave como
+// siempre. Un fichero ilegible cae a llave con aviso en el log.
+func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
+	if s.pool == nil || s.integrations == nil {
+		return
+	}
+	setter, ok := s.pool.(sshPasswordSetter)
+	if !ok {
+		return
+	}
+	pass, err := s.integrations.ReadSSHPassword(row.Slug)
+	if err != nil {
+		log.Printf("[netpulse] aviso: integración %s: no se pudo leer el fichero de contraseña SSH (%v); conecto con llave", row.Slug, err)
+		pass = ""
+	}
+	setter.SetPassword(row.Host, row.Username, pass)
+}
+
+// runIntegrationSSH ejecuta un comando en el router de la integración
+// aplicando antes la credencial SSH del fichero compañero (#1708).
+func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
+	s.applyIntegrationSSHAuth(row)
+	return s.pool.Run(row.Host, cmd, timeout)
+}
+
+// sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
+// autenticación es su propio código (ssh_auth_failed) frente al fallo
+// genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
+// la contraseña.
+func sshErrorCode(err error) string {
+	var ae *adapters.SSHAuthError
+	if errors.As(err, &ae) {
+		return "ssh_auth_failed"
+	}
+	return "ssh_failed"
+}
+
+// sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
+// autenticación SSH y fallback para cualquier otro error.
+func sshErrorOr(err error, fallback string) string {
+	if sshErrorCode(err) == "ssh_auth_failed" {
+		return "ssh_auth_failed"
+	}
+	return fallback
+}
+
 func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
 	slug := r.PathValue("slug")
 	row, ok := s.getIntegrationRow(slug)
@@ -491,8 +563,8 @@ func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request)
 			writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
 			return
 		}
-		if _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
-			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+		if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
+			writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
 			return
 		}
 	}
@@ -520,7 +592,7 @@ func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
 			_ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
 		}
 	} else if s.pool != nil {
-		_, _ = s.pool.Run(row.Host, sshServiceScript(vendor, "stop"), 60*time.Second)
+		_, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
 	}
 	_ = s.integrationsStore().SetState(slug, "stopped", "")
 	s.broadcastIntegrations()
@@ -544,7 +616,7 @@ func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request)
 	if vendor.Mode == "local" {
 		running = s.integrations != nil && s.integrations.Running(slug)
 	} else if s.pool != nil {
-		_, err := s.pool.Run(row.Host, sshServiceScript(vendor, "check"), 30*time.Second)
+		_, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
 		running = err == nil
 	}
 	// #1696: un check verificado reconcilia el estado guardado: el unverified
@@ -618,7 +690,7 @@ func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request)
 		}
 		env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
 		if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
-			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+			writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
 			return
 		}
 	}
@@ -740,9 +812,19 @@ func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
 			writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
 			return
 		}
-		raw, err := s.pool.Run(row.Host, sshEnvReadScript(vendor), 30*time.Second)
+		// #1708: la contraseña nueva del formulario es también la credencial
+		// SSH: guardarla en el fichero compañero ANTES de conectar, porque si
+		// el usuario ya cambió la contraseña en el router, la conexión de
+		// este mismo guardado necesita la nueva.
+		if password != "" && s.integrations != nil {
+			if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
+				writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
+				return
+			}
+		}
+		raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
 		if err != nil {
-			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+			writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
 			return
 		}
 		env := rintegration.ParseEnv(raw)
@@ -753,10 +835,10 @@ func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
 		}
 		env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
 		healPusherPin(env, s.agentBaseURL(r))
-		if _, err := s.pool.Run(row.Host, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
+		if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
 			_ = store.SetState(slug, "error", err.Error())
 			s.broadcastIntegrations()
-			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+			writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
 			return
 		}
 	}
@@ -786,7 +868,16 @@ func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request)
 			_ = s.integrations.Cleanup(slug)
 		}
 	} else if s.pool != nil {
-		_, _ = s.pool.Run(row.Host, sshUninstallScript(vendor), 60*time.Second)
+		_, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
+	}
+	// #1708: la contraseña SSH del fichero compañero muere con la
+	// integración y el pool pierde la credencial (la conexión cacheada se
+	// tira y el siguiente dial vuelve a la llave).
+	if s.integrations != nil {
+		_ = s.integrations.RemoveSSHPassword(slug)
+	}
+	if setter, ok := s.pool.(sshPasswordSetter); ok {
+		setter.SetPassword(row.Host, "", "")
 	}
 	_ = s.integrationsStore().Delete(slug)
 	_ = routerstore.RemoveRouter(s.db.DB, slug)

+ 10 - 4
server-go/internal/httpapi/integrations_boot_test.go

@@ -37,8 +37,10 @@ func makeIntegrationsTestServerSeeded(t *testing.T, seed func(d *db.DB, mgr *rin
 
 // makeIntegrationsTestServerFull es la variante con catálogo de vendors
 // inyectable (#1697): catFn construye el VendorCatalog con la base ya abierta
-// (nil → fallback de NewHandler: semilla embebida sin red).
-func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager), catFn func(d *db.DB) *rintegration.Catalog) (*testServer, *rintegration.Manager) {
+// (nil → fallback de NewHandler: semilla embebida sin red). El parámetro
+// variadic pool permite inyectar un SSHRunner fake (#1708): sin él el
+// servidor no tiene pool, igual que el resto de harnesses de la app.
+func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager), catFn func(d *db.DB) *rintegration.Catalog, pool ...httpapi.SSHRunner) (*testServer, *rintegration.Manager) {
 	t.Helper()
 	auth.SetTrustProxy(true)
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
@@ -77,7 +79,7 @@ func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rinte
 	if catFn != nil {
 		cat = catFn(d)
 	}
-	handler := httpapi.NewHandler(httpapi.Deps{
+	deps := httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
 		Started:       time.Now(),
 		TokenStore:    apitoken.NewStore(d, secret),
@@ -87,7 +89,11 @@ func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rinte
 		ChannelPlan:   channelplan.NewStore(d.DB),
 		Integrations:  mgr,
 		VendorCatalog: cat,
-	})
+	}
+	if len(pool) > 0 {
+		deps.Pool = pool[0]
+	}
+	handler := httpapi.NewHandler(deps)
 	srv := httptest.NewServer(handler)
 	ts := &testServer{Server: srv, db: d, secret: secret}
 	t.Cleanup(func() {

+ 39 - 0
server-go/internal/httpapi/integrations_sshpass_internal_test.go

@@ -0,0 +1,39 @@
+// integrations_sshpass_internal_test.go - #1708: applyIntegrationSSHAuth con
+// un pool que solo implementa Run (los fakes clásicos de la app): la
+// aplicación de credencial es opcional y no debe romper el camino SSH.
+package httpapi
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+type runOnlyPool struct {
+	runs int
+}
+
+func (p *runOnlyPool) Run(host, cmd string, _ time.Duration) (string, error) {
+	p.runs++
+	return "", nil
+}
+
+// TestApplyIntegrationSSHAuthWithoutSetter: sin capacidad de contraseña en
+// el pool, el comando SSH sigue ejecutándose con la llave de siempre.
+func TestApplyIntegrationSSHAuthWithoutSetter(t *testing.T) {
+	pool := &runOnlyPool{}
+	mgr := rintegration.NewManager(t.TempDir())
+	s := &server{pool: pool, integrations: mgr}
+	if err := mgr.WriteSSHPassword("wrt", "pw"); err != nil {
+		t.Fatal(err)
+	}
+	row := rintegration.Row{Slug: "wrt", Host: "10.0.0.9", Username: "admin"}
+
+	if _, err := s.runIntegrationSSH(row, "true", time.Second); err != nil {
+		t.Fatalf("runIntegrationSSH: %v", err)
+	}
+	if pool.runs != 1 {
+		t.Fatalf("runs = %d, quiero 1", pool.runs)
+	}
+}

+ 187 - 0
server-go/internal/httpapi/integrations_sshpass_test.go

@@ -0,0 +1,187 @@
+// integrations_sshpass_test.go - #1708: el fichero compañero de contraseña
+// SSH (<slug>.sshpass) del modo ssh: se escribe al editar con contraseña,
+// se conserva al editar sin ella, muere con la integración y su fallo de
+// autenticación sale con código propio (ssh_auth_failed).
+package httpapi_test
+
+import (
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+// sshPassFakePool registra la secuencia de eventos (set/run) para poder
+// afirmar el orden: la credencial se aplica ANTES de cada comando SSH.
+type sshPassFakePool struct {
+	mu     sync.Mutex
+	events []string
+	runs   int
+	fail   bool
+}
+
+func (f *sshPassFakePool) Run(host, cmd string, _ time.Duration) (string, error) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.runs++
+	if f.runs == 1 {
+		f.events = append(f.events, "run:read")
+	} else {
+		f.events = append(f.events, fmt.Sprintf("run:call-%d", f.runs))
+	}
+	if f.fail {
+		return "", &adapters.SSHAuthError{
+			Host: host,
+			Err:  errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain"),
+		}
+	}
+	if f.runs == 1 {
+		return "ASUSWRT_HOST=127.0.0.1\nASUSWRT_USER=admin\nASUSWRT_PASS=old\nNETPULSE_INTERVAL=45s\n", nil
+	}
+	return "", nil
+}
+
+func (f *sshPassFakePool) SetPassword(host, user, password string) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.events = append(f.events, fmt.Sprintf("set:%s:%s", user, password))
+}
+
+func (f *sshPassFakePool) recorded() []string {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	return append([]string{}, f.events...)
+}
+
+func seedSSHIntegration(t *testing.T, d *db.DB, mgr *rintegration.Manager) {
+	t.Helper()
+	store := rintegration.NewStore(d.DB)
+	row := bootIntegrationRow("wrt-pass", "asuswrt", "ssh", true, "running")
+	if err := store.Upsert(row); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// TestIntegrationEditWritesSSHPassFile: editar con contraseña reescribe el
+// fichero compañero y aplica la credencial al pool antes de conectar.
+func TestIntegrationEditWritesSSHPassFile(t *testing.T) {
+	pool := &sshPassFakePool{}
+	ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
+		seedSSHIntegration(t, d, mgr)
+		if err := mgr.WriteSSHPassword("wrt-pass", "old"); err != nil {
+			t.Fatal(err)
+		}
+	}, nil, pool)
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"password":"nueva","intervalS":45}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT con password: status %d (%v)", res.StatusCode, body)
+	}
+
+	pass, err := mgr.ReadSSHPassword("wrt-pass")
+	if err != nil || pass != "nueva" {
+		t.Fatalf("fichero tras editar = %q (err %v), quiero \"nueva\"", pass, err)
+	}
+	events := pool.recorded()
+	if len(events) < 3 {
+		t.Fatalf("secuencia corta: %v", events)
+	}
+	if events[0] != "set:admin:nueva" {
+		t.Fatalf("la credencial debe aplicarse antes de conectar: %v", events)
+	}
+	if events[1] != "run:read" {
+		t.Fatalf("la edición debe leer el env remoto tras aplicar la credencial: %v", events)
+	}
+	if events[len(events)-1] != "run:call-2" {
+		t.Fatalf("la edición debe reescribir el env en una segunda llamada: %v", events)
+	}
+}
+
+// TestIntegrationEditKeepsSSHPassWhenEmpty: editar sin contraseña conserva
+// la guardada y la sigue aplicando al pool (la conexión sigue siendo por
+// contraseña).
+func TestIntegrationEditKeepsSSHPassWhenEmpty(t *testing.T) {
+	pool := &sshPassFakePool{}
+	ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
+		seedSSHIntegration(t, d, mgr)
+		if err := mgr.WriteSSHPassword("wrt-pass", "guardada"); err != nil {
+			t.Fatal(err)
+		}
+	}, nil, pool)
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"intervalS":60}`, cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT sin password: status %d", res.StatusCode)
+	}
+
+	pass, err := mgr.ReadSSHPassword("wrt-pass")
+	if err != nil || pass != "guardada" {
+		t.Fatalf("el fichero debe conservarse: %q (err %v)", pass, err)
+	}
+	for _, ev := range pool.recorded() {
+		if ev == "set:admin:guardada" {
+			return
+		}
+	}
+	t.Fatalf("el pool debe recibir la credencial conservada: %v", pool.recorded())
+}
+
+// TestIntegrationDeleteRemovesSSHPassFile: borrar la integración quita el
+// fichero compañero y limpia la credencial del pool.
+func TestIntegrationDeleteRemovesSSHPassFile(t *testing.T) {
+	pool := &sshPassFakePool{}
+	ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
+		seedSSHIntegration(t, d, mgr)
+		if err := mgr.WriteSSHPassword("wrt-pass", "old"); err != nil {
+			t.Fatal(err)
+		}
+	}, nil, pool)
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := deleteJSONPath(t, ts.URL, "/api/integrations/wrt-pass", cookie)
+	if res.StatusCode != http.StatusNoContent {
+		t.Fatalf("DELETE: status %d", res.StatusCode)
+	}
+
+	if pass, err := mgr.ReadSSHPassword("wrt-pass"); err != nil || pass != "" {
+		t.Fatalf("el fichero debe desaparecer con la integración: %q (err %v)", pass, err)
+	}
+	for _, ev := range pool.recorded() {
+		if ev == "set::" {
+			return
+		}
+	}
+	t.Fatalf("la credencial del pool debe limpiarse al borrar: %v", pool.recorded())
+}
+
+// TestIntegrationSSHAuthErrorIsItsOwnCode: el rechazo de autenticación
+// reporta ssh_auth_failed, no ssh_failed, para que la UI pida revisar la
+// contraseña.
+func TestIntegrationSSHAuthErrorIsItsOwnCode(t *testing.T) {
+	pool := &sshPassFakePool{fail: true}
+	ts, _ := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
+		seedSSHIntegration(t, d, mgr)
+		if err := mgr.WriteSSHPassword("wrt-pass", "mala"); err != nil {
+			t.Fatal(err)
+		}
+	}, nil, pool)
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"intervalS":60}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusBadGateway {
+		t.Fatalf("status = %d, quiero 502 (%v)", res.StatusCode, body)
+	}
+	if body["error"] != "ssh_auth_failed" {
+		t.Fatalf("código de error = %v, quiero ssh_auth_failed", body["error"])
+	}
+}

+ 40 - 0
server-go/internal/rintegration/manager.go

@@ -63,6 +63,46 @@ func (m *Manager) WriteEnv(slug string, env map[string]string) error {
 	return writeEnvFile(filepath.Join(m.dir, slug+".env"), env)
 }
 
+// SSHPasswordPath returns the companion SSH password file of a slug
+// (<dir>/<slug>.sshpass, #1708). Same discipline as the env file: 0600,
+// owned by the service user, never in the database and never in an API
+// response.
+func (m *Manager) SSHPasswordPath(slug string) string {
+	return filepath.Join(m.dir, slug+".sshpass")
+}
+
+// ReadSSHPassword returns the SSH password stored for slug, or "" when the
+// companion file does not exist (the server key stays the auth method). A
+// trailing newline (hand-written files) is tolerated.
+func (m *Manager) ReadSSHPassword(slug string) (string, error) {
+	data, err := os.ReadFile(m.SSHPasswordPath(slug))
+	if os.IsNotExist(err) {
+		return "", nil
+	}
+	if err != nil {
+		return "", err
+	}
+	return strings.TrimRight(string(data), "\n"), nil
+}
+
+// WriteSSHPassword stores the SSH password of slug in the companion file
+// with mode 0600.
+func (m *Manager) WriteSSHPassword(slug, password string) error {
+	if err := os.MkdirAll(m.dir, 0o755); err != nil {
+		return err
+	}
+	return os.WriteFile(m.SSHPasswordPath(slug), []byte(password), 0o600)
+}
+
+// RemoveSSHPassword deletes the companion SSH password file. Removing a
+// missing file is a no-op.
+func (m *Manager) RemoveSSHPassword(slug string) error {
+	if err := os.Remove(m.SSHPasswordPath(slug)); err != nil && !os.IsNotExist(err) {
+		return err
+	}
+	return nil
+}
+
 // SetOnExit registers the callback invoked when a process exits unexpectedly
 // (a crash). Intentional stops do not fire it: the caller owns that state.
 func (m *Manager) SetOnExit(fn func(slug string, err error)) {

+ 62 - 0
server-go/internal/rintegration/manager_sshpass_test.go

@@ -0,0 +1,62 @@
+package rintegration
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// TestSSHPasswordFilePlumbing (#1708): el fichero compañero <slug>.sshpass
+// vive junto al env del pusher, va a 0600, se lee sin salto final y su
+// borrado es idempotente. Sin fichero la lectura devuelve "" sin error: la
+// llave sigue siendo el método de autenticación por defecto.
+func TestSSHPasswordFilePlumbing(t *testing.T) {
+	mgr := NewManager(t.TempDir())
+
+	if pass, err := mgr.ReadSSHPassword("lab"); err != nil || pass != "" {
+		t.Fatalf("sin fichero: pass=%q err=%v, quiero \"\" y nil", pass, err)
+	}
+
+	if err := mgr.WriteSSHPassword("lab", "s3cret"); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	info, err := os.Stat(mgr.SSHPasswordPath("lab"))
+	if err != nil {
+		t.Fatalf("stat: %v", err)
+	}
+	if got := info.Mode().Perm(); got != 0o600 {
+		t.Fatalf("modo del fichero = %o, quiero 600", got)
+	}
+	if filepath.Base(mgr.SSHPasswordPath("lab")) != "lab.sshpass" {
+		t.Fatalf("nombre del fichero = %s, quiero lab.sshpass", filepath.Base(mgr.SSHPasswordPath("lab")))
+	}
+	if pass, err := mgr.ReadSSHPassword("lab"); err != nil || pass != "s3cret" {
+		t.Fatalf("read: pass=%q err=%v", pass, err)
+	}
+
+	// Un salto final de un fichero escrito a mano no entra en la contraseña.
+	if err := os.WriteFile(mgr.SSHPasswordPath("lab"), []byte("s3cret\n"), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	if pass, _ := mgr.ReadSSHPassword("lab"); pass != "s3cret" {
+		t.Fatalf("read con salto final: pass=%q, quiero sin salto", pass)
+	}
+
+	// Reescribir cambia el valor sin dejar el viejo.
+	if err := mgr.WriteSSHPassword("lab", "nueva"); err != nil {
+		t.Fatal(err)
+	}
+	if pass, _ := mgr.ReadSSHPassword("lab"); pass != "nueva" {
+		t.Fatalf("read tras reescribir: pass=%q", pass)
+	}
+
+	if err := mgr.RemoveSSHPassword("lab"); err != nil {
+		t.Fatalf("remove: %v", err)
+	}
+	if _, err := os.Stat(mgr.SSHPasswordPath("lab")); !os.IsNotExist(err) {
+		t.Fatalf("el fichero sigue ahí: %v", err)
+	}
+	if err := mgr.RemoveSSHPassword("lab"); err != nil {
+		t.Fatalf("remove idempotente: %v", err)
+	}
+}

+ 3 - 3
web/src/i18n.ts

@@ -1368,7 +1368,7 @@ const I18N_EXTRA = {
       mkL2: 'WiFi and clients per band, CPU, memory and temperature',
       mkL3: 'Router identity and RouterOS version',
       asusTitle: 'Asuswrt and Asuswrt-Merlin',
-      asusP: 'It reuses the portable probes from the NetPulse agent (iw, iwinfo and, on Broadcom models, wl) to read what the firmware does not publish over an API.',
+      asusP: 'It reuses the portable probes from the NetPulse agent (iw, iwinfo and, on Broadcom models, wl) to read what the firmware does not publish over an API. NetPulse can install it from the Integrations section: with an authorized key when possible, or with the router password on a stock Asuswrt, whose dropbear only accepts passwords.',
       asusL1: 'Clients per band, radios, channels and utilisation',
       asusL2: 'Ethernet ports with their real operational state',
       asusL3: 'Broadcom models: the wl tier when nl80211 lists no stations',
@@ -1639,7 +1639,7 @@ const I18N_EXTRA = {
       mkL2: 'WiFi y clientes por banda, CPU, memoria y temperatura',
       mkL3: 'Identidad del router y versión de RouterOS',
       asusTitle: 'Asuswrt y Asuswrt-Merlin',
-      asusP: 'Reutiliza las sondas portables del agente de NetPulse (iw, iwinfo y, en los modelos Broadcom, wl) para leer lo que el firmware no publica por API.',
+      asusP: 'Reutiliza las sondas portables del agente de NetPulse (iw, iwinfo y, en los modelos Broadcom, wl) para leer lo que el firmware no publica por API. NetPulse puede instalarlo desde la sección Integraciones: con llave autorizada cuando sea posible, o con la contraseña del router en un Asuswrt de fábrica, cuyo dropbear solo acepta contraseña.',
       asusL1: 'Clientes por banda, radios, canales y utilización',
       asusL2: 'Puertos Ethernet con su estado operativo real',
       asusL3: 'Modelos Broadcom: tier wl cuando nl80211 no lista estaciones',
@@ -2394,7 +2394,7 @@ const I18N_FILL = {
       mkL2: 'WiFi 与每个频段的客户端、CPU、内存和温度',
       mkL3: '路由器标识和 RouterOS 版本',
       asusTitle: 'Asuswrt 与 Asuswrt-Merlin',
-      asusP: '复用 NetPulse 代理的可移植探测(iw、iwinfo,Broadcom 机型上的 wl),读取固件不通过 API 公开的数据。',
+      asusP: '复用 NetPulse 代理的可移植探测(iw、iwinfo,Broadcom 机型上的 wl),读取固件不通过 API 公开的数据。NetPulse 可以在“集成”页面直接安装:优先使用已授权的密钥,原厂 Asuswrt 的 dropbear 仅接受密码时也可以用密码安装。',
       asusL1: '每个频段的客户端、射频、信道和利用率',
       asusL2: '以太网端口的真实运行状态',
       asusL3: 'Broadcom 机型:nl80211 未列出客户端时使用 wl 层',