Sfoglia il codice sorgente

feat(https): serve NetPulse over HTTPS with a private certificate authority (#937) (#942)

* fix(fork): send HSTS only on secure responses

Strict-Transport-Security was set on every response, plain HTTP included.
Browsers ignore it there (RFC 6797 section 8.1), so it only misstated
what the server offers. It is now sent when the request was secure - a
TLS connection, or a TLS-terminating proxy the server trusts - by the
same rule that decides the session cookie's Secure flag.

includeSubDomains is dropped: nothing lives under the server's own name,
and the flag would pin every host below it to HTTPS for a year, making
HTTPS much harder to turn off again.

(cherry picked from commit 71e63575adb7294527a501378aea0e80c93b33aa)

* fix(fork): give the update stream the SSE write timeout

/api/update/stream is an SSE stream, but it was not in isSSEStreamPath,
so the server's normal write timeout cut it every time and the update
dialog fell back to polling.

(cherry picked from commit 2258f7e92c921f4945595bd30fb593652b444224)

* fix(fork): hand out the server fingerprint with the extra TLS listener

With NETPULSE_TLS_ENABLED the extra listener's fingerprint was only
logged: Deps.ServerFP stayed empty, /fingerprint was served on-box only,
and pairing returned an empty server_fp, so no agent could be paired to
pin it.

The self-signed certificate's fingerprint is now passed on. A
user-supplied certificate's is read live through the reloader
(Deps.ServerFPFunc), because a renewal can change the key - certbot does
unless told --reuse-key - and a value captured at start-up would hand
agents a stale pin. /fingerprint is served whenever any TLS listener is
up. On-box, PORT's own certificate stays the one agents pin.

(cherry picked from commit c627210d0bb6bf35d5e81534972601892491288f)

* fix(fork): download firmware from a mirror with normal CA checks

The agent fetched the admin-configured firmware image through the
transport pinned to its own server. That transport accepts only the
server's key, so with the server on HTTPS every download from a vendor
mirror was refused. Only an image on the server itself keeps the pinned
transport now; anything else is checked against the system's CAs. The
image checksum is verified either way.

(cherry picked from commit c5d240e91751a2f2bc5697bd3561857013a62c00)

* feat(fork): let an agent pin its server's CA, and more than one key

NETPULSE_SERVER_FP pinned the server's own key, so a server whose
certificate is renewed with a new key - or re-issued by its own CA - left
every agent unable to connect.

A pin may now also name a CA in the chain the server presents. That pin
accepts the connection only if the CA really is one and signed a leaf
that is valid now, for server authentication, for the host the agent
dialled - so pinning a CA does not mean trusting anything it ever signed.
A pin on the server's own key keeps its old meaning. The setting takes a
comma-separated list, which is what lets a server move to a new CA with
no window in which its agents cannot reach it, and a malformed pin is now
an error rather than a pin that silently never matches.

The check moves to VerifyConnection, which also runs on resumed sessions.

(cherry picked from commit 4d1990f891e34946d6f74dd13b94b3048b5e4b3a)

* feat(fork): prove the server's key to an agent at pairing

An agent given a pairing token but no pin could not pair with an HTTPS
server at all: the pin had to be supplied beforehand, and the pin a
pairing reply carries arrives over the very connection it should
authenticate.

POST /api/agents/pair/hello closes that gap without trust on first use.
The agent sends a nonce; the server answers with its key's fingerprint
and an HMAC over both, keyed with the admin pairing token
(agent/pairproof). The agent accepts the fingerprint only if the MAC is
right and the key is one the connection actually presented, then pairs
over a connection pinned to it and writes the pin next to its new token.
The pairing token itself is never sent before the key is proven, and a
relayed proof fails because it names the real server's key, not the
relay's. The autoenroll token, handed out over UDP to anyone who asks,
proves nothing and is not used.

runtime.ProveServerKey and runtime.ServerTransport are exported for
embedders such as NetGrip, whose own requests to the server should pin
the same way.

(cherry picked from commit 97ef031832caa4f2db84f67131d7be6e300c7473)

* feat(fork): a private certificate authority for the server

Browsers only register a service worker - Web Push, installing the PWA -
on a certificate they trust outright; an exception accepted for a
self-signed one is not enough. tlscert.CA gives the server its own root,
which the admin installs once on their devices, and a leaf it signs.
Agents pin the root, so the leaf can be re-issued without breaking them.

The root is bounded three ways:
- Name Constraints: private address ranges and local names only
  (lan, home.arpa, internal, local, the host's own names, that host under
  each search domain - never the whole domain - and NETPULSE_TLS_NAMES,
  with a warning for a name that is not local), so a copy of its key
  cannot impersonate a public site to a device that trusts it;
- its key lives in a 0700 directory in a 0600 file owned by the service
  user, and the server refuses to start if either has been opened up;
- it is created once and never replaced implicitly: half a pair is an
  error, not a reason to mint a root no device trusts. It is backdated a
  year, so one created while the clock ran fast is not left "not yet
  valid".

The leaf names every private address and local name the host has, drops
the rest with one log line per change, lasts 90 days and is re-issued 30
days before expiry or when the addresses change - with the same key, so
leaf pins survive too. Writes are atomic and a failed re-issue keeps the
leaf being served. The chain served is leaf plus root, which an agent
pinning the root needs to verify it. TLS 1.2 is limited to forward-secret
AEAD suites.

The constraints are not marked critical: mbedTLS, OpenWrt's TLS library
behind its wget and curl, refuses a certificate with a critical extension
it does not implement, so routers could not verify the server. Go,
OpenSSL, Chrome and Firefox enforce them either way.

(cherry picked from commit 80f9724aea621f6e7b2a32cbde1e3c2b18050c9c)

* feat(fork): turn HTTPS on and retire plain HTTP from Settings

internal/tlsmode runs HTTPS with the private CA as settings an admin
changes from the web UI, live, without a restart:

- Enabling only adds the TLS listener (NETPULSE_TLS_PORT). Plain HTTP
  keeps serving everything ("full"), so enabling cannot lock anyone out.
- "migrate": plain HTTP refuses sign-ins, sessions, API tokens and the
  admin pairing token - a redirect cannot protect a secret already sent
  in clear - sends page loads to HTTPS, and still serves agents
  (auth.IsAgentRequest) until each has moved. Settings lists the agents
  still reporting over HTTP; the list is kept in kv, so a restart does
  not forget them, and drops agents deleted or silent for a day.
- "redirect": plain HTTP only redirects, serves the root certificate,
  and answers health checks from loopback (update.sh keeps working).
  Refused while agents are still on HTTP unless forced.

A stricter mode only takes effect once confirmed from a page loaded over
HTTPS within five minutes: the admin has then proved HTTPS works for them
before plain HTTP stops taking logins. Going back to full is immediate.
HTTPS can only be turned off from full, and not while agents report over
it unless forced; the listener stops after answering that request. Every
change asks for the admin's password again, counts towards the sign-in
lockout, and is logged. A TLS-terminating proxy the server trusts counts
as HTTPS throughout, as it does for the session cookie.

Redirects go only to a name the certificate carries - the browser's own,
else the address the request arrived on, the public URL's host, or an
address the certificate names - so a forged Host header cannot send a
browser elsewhere.

HSTS is per host, not per port. The manager sends max-age=0 in full and
with HTTPS off (it clears any policy a stricter mode left), a day in
migrate and a year in redirect. Once the CA exists, the plain port also
answers TLS (first-byte sniffing) in every mode, so a browser holding a
policy for the name, which rewrites http://name:3000 to
https://name:3000, still gets in and can be told to drop it. A temporary
accept error no longer stops the plain port for good. Without the
manager, HSTS is no longer sent from the extra TLS listener while PORT
serves plain HTTP - a policy from it made browsers rewrite
http://name:PORT to https://name:PORT, where nothing spoke TLS.

NETPULSE_TLS_ENABLED=1 with the new NETPULSE_TLS_CA=1 turns it on from
the environment and locks the switch; NETPULSE_HTTP_MODE locks the mode
and is the way back over SSH. NETPULSE_TLS_ENABLED=0, as .env.example
ships, locks nothing. NETPULSE_TLS_NAMES adds names to the certificate.
On-box, and with a certificate of the admin's own, HTTPS stays as it
was. The root is served at /netpulse-ca.crt (DER, which phones install)
and /netpulse-ca.pem, and pairing hands agents its pin.

(cherry picked from commit 2479c4f1f9a1696dd65da0a578d44e0650a29865)

* feat(fork): the HTTPS card in Settings

Settings > HTTPS (admin, live mode) turns HTTPS on, offers the root
certificate for download with the fingerprint to check it against, shows
the pin agents use, and lets the admin choose what plain HTTP may still
do - listing the agents still reporting over it. Every change asks for
the password; a stricter mode shows the HTTPS link to confirm it from,
and the card confirms on arrival there. Settings fixed in the server's
environment are shown as locked. English and Spanish strings.

(cherry picked from commit 92e83d3377f3302ef169ec878bfa9e81238b005e)

* fix(fork): keep HTTP and HTTPS sign-ins in separate cookies

Cookies are shared by every port and scheme of a host. Once a sign-in
over HTTPS set the session cookie with Secure, a sign-in over plain HTTP
on the same host could neither replace it nor use it - the browser
refuses to overwrite a Secure cookie from an insecure origin and does not
send it there - so signing in over plain HTTP looped while both were in
use, which is exactly the window HTTPS is being rolled out in.

A Secure session cookie is now called __Host-session (the prefix makes
browsers insist it is Secure, host-only and for Path=/), and a request
is authenticated by whichever of the two cookies it carries is valid,
the Secure one first. Signing out ends every session the request
carries and, over HTTPS, clears the Secure cookie too. A sign-in over
plain HTTP is unchanged.

(cherry picked from commit bdc6860cc5ef18905e71d5bf64f1548431a6795a)

* feat(fork): move agents to HTTPS wherever they are installed

With HTTPS and the private CA on, every path that installs or
reconfigures an agent now moves it there (tlsmode.AgentTrust):

- Reinstall, manual or by the rearmer: the script points the agent at
  the HTTPS address, writes NETPULSE_SERVER_FP, and first writes the
  root to the router - over the SSH session, whose host key the server
  checks - so the binary download, agent token included, is verified
  against it. The self-heal verifies with the same root. Without HTTPS
  the script behaves as before; an https server URL of another kind
  still gets its pin written.
- The install command carries the root and --server-fp, so the
  download on the admin's machine is verified too.
- The discovery reply adds url_https and server_fp - as hints: nothing
  in a UDP reply is authenticated.
- deploy/switch-scraper.sh takes NETPULSE_CA for pushing over HTTPS.

An agent is never handed a loopback address: when the address the admin
browsed to is loopback, or one the certificate does not name, the
server's own reachable address is used instead.

docs/https.md describes the whole thing for admins: turning it on,
installing and checking the root on each platform, moving agents,
retiring plain HTTP, getting back in, backups and starting over.
.env.example documents NETPULSE_TLS_CA, NETPULSE_TLS_NAMES and
NETPULSE_HTTP_MODE.

(cherry picked from commit ad05674f2868ebf29a6b98457a5ff64a64f048ed)

* fix(fork): drop the plain session cookie once plain HTTP is retired

A browser sends the session cookie of a sign-in made over plain HTTP
with every http:// request - an old bookmark, access by address, which
HSTS never covers - in clear, until it expires. In migrate and redirect,
where plain HTTP is no longer for people, the answers it gives them now
delete that cookie. Agents' requests are left alone.

(cherry picked from commit 403c1b18799cabad5528056e8a8d51c957ccdccf)

* fix(fork): the HTTPS card no longer takes Settings down

With HTTPS on and no agent reporting over plain HTTP, the settings API
sent the list of such agents as null. The card read its length while
rendering, the error unmounted the whole app, and the page showed the
boot watchdog's "the app could not load" instead of Settings - over
HTTP and HTTPS alike. The list is now always an array, and the card
treats a missing one as empty.

(cherry picked from commit 989de5263f581f9e9500229591155d4d72a101c3)

* fix(fork): keep live streams alive and the server up over HTTPS

Two faults in the SSE hubs, found loading the app over HTTPS:

- A browser leaving /api/stream while a broadcast was on its way to it
  got the write after its handler had returned. net/http panics on a
  write to a finished response, and the whole server went down. The
  same could happen to an agent's command stream in Send. Each stream
  is now marked finished, under its write lock, before its handler
  returns, and a write to it is refused.
- Every write set a 10 s write deadline and left it in place. Over
  HTTP/1.1 that only bounds the write, but over HTTP/2 a deadline that
  passes resets the stream even when nothing is being written: every
  stream served over HTTPS died 10 s after its last event, and the page
  lost its live updates. After a write the deadline now moves to three
  heartbeats ahead, which still ends a stream nobody reads.

The first is upstream's too; the second only shows once HTTPS is in
use.

(cherry picked from commit ceb5ef698a1a1582df927cedc8fb2059c48a7daf)

* fix(fork): let downloads through the service worker

The service worker answered every navigation with the app shell, so a
link to something the server itself serves - the root certificate on
Settings > HTTPS, and upstream's CSV export and backup download - opened
the app's "page not found" instead of downloading the file, on any
device where the app had loaded before. Navigations to /api/,
/netpulse-ca.*, /fingerprint and /health now go to the server. The
certificate links are also marked as downloads.

(cherry picked from commit 2f95bd646137dbebbe31c834c8ee2b42f054a04b)

* feat(fork): renew the certificate on demand from Settings > HTTPS

The certificate already follows the server's addresses and names by
itself, re-checked every ten minutes. "Renew now" does that check at
once - useful right after an address or name changes - and says
whether a new certificate was issued. It keeps the same root, so
nothing is reinstalled on any device and no agent's pin changes; no
password is asked, since it changes nothing the periodic check would
not.

The card now also lists any of the server's addresses or names the root
may not vouch for, and why: reaching the server under one of those needs
a new root, installed again on every device.

(cherry picked from commit 201eff912bc45c1ca5d48c67ecc8ad8c6c5c7ffe)

* fix(fork): give push notifications their own card in Settings

The Web Push switch was a small unlabelled button in the About card, and
over plain HTTP it rendered nothing at all - the "requires a secure
context" state had text but no markup - so the option looked missing.

It is now a full card under Notifications, with its title, what it does,
and the note on which alerts arrive; over plain HTTP it says that push
needs HTTPS and where an admin turns that on. The app install button
stays in About.

(cherry picked from commit b0810c57840965c79f6995b681feb90036784dde)

* test(reinstall): restore the os/exec import the HTTPS trust test needs

The fork's 27aaa8f (token rotation) introduced the os/exec import, but
that commit is redundant with upstream's own #851 FP-preservation work and
was skipped. ad05674's TestScriptWithTrust still relies on exec.Command,
so restore just the import.

* test(httpapi): add the minimal panelTestServer helper the HTTPS tests reuse

The HTTPS-series tests (server_fp_test.go, https_transport_test.go) share
the panelTestServer helper defined in the fork's netgrip_panel_test.go.
The NetGrip-panel integration itself is a separate feature and was left
out, so carry only this minimal db+registry helper.

---------

Co-authored-by: borky-git <borky-git@protonmail.com>
Nacho 2 mesi fa
parent
commit
73710954b8
53 ha cambiato i file con 6113 aggiunte e 63 eliminazioni
  1. 142 10
      agent/internal/tlspin/tlspin.go
  2. 269 0
      agent/internal/tlspin/tlspin_ca_test.go
  3. 25 0
      agent/pairproof/pairproof.go
  4. 31 1
      agent/runtime/firmware.go
  5. 34 0
      agent/runtime/firmware_transport_test.go
  6. 26 3
      agent/runtime/pairing.go
  7. 141 0
      agent/runtime/prove.go
  8. 2 2
      agent/runtime/runtime_test.go
  9. 51 1
      app/public/locales/en/translation.json
  10. 51 1
      app/public/locales/es/translation.json
  11. 405 0
      app/src/components/HttpsCard.tsx
  12. 27 2
      app/src/pages/Settings.tsx
  13. 8 1
      app/src/sw.ts
  14. 8 0
      deploy/switch-scraper.env.example
  15. 6 1
      deploy/switch-scraper.sh
  16. 207 0
      docs/https.md
  17. 16 0
      server-go/.env.example
  18. 99 9
      server-go/cmd/netpulse/main.go
  19. 2 0
      server-go/cmd/netpulse/main_test.go
  20. 52 9
      server-go/internal/auth/auth.go
  21. 13 0
      server-go/internal/auth/middleware.go
  22. 44 0
      server-go/internal/config/config.go
  23. 37 0
      server-go/internal/config/config_test.go
  24. 23 8
      server-go/internal/httpapi/agent.go
  25. 4 0
      server-go/internal/httpapi/auth.go
  26. 10 0
      server-go/internal/httpapi/discovery.go
  27. 47 0
      server-go/internal/httpapi/discovery_test.go
  28. 23 1
      server-go/internal/httpapi/httpapi_test.go
  29. 341 0
      server-go/internal/httpapi/https_settings.go
  30. 445 0
      server-go/internal/httpapi/https_settings_test.go
  31. 67 0
      server-go/internal/httpapi/https_transport_test.go
  32. 235 0
      server-go/internal/httpapi/pair_hello_test.go
  33. 68 2
      server-go/internal/httpapi/pairing.go
  34. 29 1
      server-go/internal/httpapi/server.go
  35. 45 0
      server-go/internal/httpapi/server_fp_test.go
  36. 13 1
      server-go/internal/rearmer/rearmer.go
  37. 59 6
      server-go/internal/reinstall/reinstall.go
  38. 49 0
      server-go/internal/reinstall/script_test.go
  39. 21 4
      server-go/internal/security/security.go
  40. 13 0
      server-go/internal/sse/agenthub.go
  41. 71 0
      server-go/internal/sse/h2_idle_test.go
  42. 28 0
      server-go/internal/sse/hub.go
  43. 75 0
      server-go/internal/sse/hub_finish_test.go
  44. 711 0
      server-go/internal/tlscert/ca.go
  45. 343 0
      server-go/internal/tlscert/ca_test.go
  46. 8 0
      server-go/internal/tlscert/owner_other.go
  47. 15 0
      server-go/internal/tlscert/owner_unix.go
  48. 21 0
      server-go/internal/tlscert/reloader.go
  49. 35 0
      server-go/internal/tlscert/reloader_test.go
  50. 658 0
      server-go/internal/tlsmode/manager.go
  51. 622 0
      server-go/internal/tlsmode/manager_test.go
  52. 276 0
      server-go/internal/tlsmode/plain.go
  53. 62 0
      server-go/internal/tlsmode/trust.go

+ 142 - 10
agent/internal/tlspin/tlspin.go

@@ -11,49 +11,181 @@ import (
 	"crypto/tls"
 	"crypto/x509"
 	"encoding/hex"
+	"errors"
 	"fmt"
 	"net/http"
 	"net/url"
+	"slices"
 	"strings"
+	"time"
 )
 
 // Normalize limpia un fingerprint: quita prefijo "sha256/", dos-puntos y
 // espacios, y lo pasa a minúsculas. Formato esperado: 64 hex chars.
 func Normalize(s string) string {
-	s = strings.NewReplacer("sha256/", "", ":", "", " ", "").Replace(s)
-	return strings.ToLower(strings.TrimSpace(s))
+	// Lower-cased first, so "SHA256/" is stripped as well as "sha256/".
+	s = strings.ToLower(strings.TrimSpace(s))
+	return strings.NewReplacer("sha256/", "", ":", "", " ", "").Replace(s)
 }
 
 // BuildTransport crea un *http.Transport con la validación TLS adecuada:
 //   - HTTP: transporte por defecto (sin TLS).
-//   - HTTPS con fp: TLS con pinning SPKI (VerifyPeerCertificate).
+//   - HTTPS con fp: TLS con pinning SPKI (VerifyConnection).
 //   - HTTPS sin fp: error (fail-closed).
-func BuildTransport(serverURL, fp string) (*http.Transport, error) {
+//
+// FORK: fps may hold several comma-separated pins, and a pin may name either
+// the server's own key (as before) or a CA in the chain the server presents;
+// see Verify. More than one pin is what lets the server move to a new CA
+// without a window in which its agents cannot reach it.
+func BuildTransport(serverURL, fps string) (*http.Transport, error) {
 	t := http.DefaultTransport.(*http.Transport).Clone()
 	if !strings.HasPrefix(serverURL, "https://") {
 		return t, nil // HTTP plano: sin TLS
 	}
-	fp = Normalize(fp)
-	if fp == "" {
+	pins, err := ParsePins(fps)
+	if err != nil {
+		return nil, err
+	}
+	if len(pins) == 0 {
 		host := serverURL
 		if u, err := url.Parse(serverURL); err == nil && u.Host != "" {
 			host = u.Host
 		}
 		return nil, fmt.Errorf("HTTPS requiere NETPULSE_SERVER_FP (pinning SPKI, sin InsecureSkipVerify); consíguelo con install-agent.sh (lo deriva del certificado automáticamente) o con: openssl s_client -connect %s </dev/null 2>/dev/null | openssl x509 -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum", host)
 	}
-	want := fp
+	u, err := url.Parse(serverURL)
+	if err != nil {
+		return nil, fmt.Errorf("server URL: %w", err)
+	}
+	host := u.Hostname()
+	if host == "" {
+		// Without a host there is nothing to check the certificate's names
+		// against, and a CA pin would accept any name the CA signed.
+		return nil, fmt.Errorf("server URL %q has no host", serverURL)
+	}
 	t.TLSClientConfig = &tls.Config{
 		// InsecureSkipVerify salta la verificación normal de CA; la decisión
-		// final la toma VerifyPeerCertificate contra el SPKI pineado.
+		// final la toma VerifyConnection contra el SPKI pineado.
 		InsecureSkipVerify: true, //nolint:gosec // pinning deliberado por SPKI
-		VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
-			return VerifySPKI(rawCerts, want)
+		// VerifyConnection rather than VerifyPeerCertificate: it also runs on
+		// resumed sessions, so a session cache added later cannot let a
+		// connection skip the pin.
+		VerifyConnection: func(cs tls.ConnectionState) error {
+			return Verify(cs.PeerCertificates, host, pins, time.Now())
 		},
 		MinVersion: tls.VersionTLS12,
 	}
 	return t, nil
 }
 
+// ParsePins splits a comma-separated list of fingerprints, normalizing each.
+// A pin that is not a SHA-256 in hex is an error rather than a pin that can
+// never match: a typo in the env file should say so, not look like an
+// impostor server.
+func ParsePins(fps string) ([]string, error) {
+	var pins []string
+	for _, p := range strings.Split(Normalize(fps), ",") {
+		if p == "" {
+			continue
+		}
+		if b, err := hex.DecodeString(p); err != nil || len(b) != sha256.Size {
+			return nil, fmt.Errorf("NETPULSE_SERVER_FP: %q is not a SHA-256 fingerprint (64 hex characters)", p)
+		}
+		pins = append(pins, p)
+	}
+	return pins, nil
+}
+
+// Verify decides whether the chain a server presented matches one of pins.
+//
+// A pin on the leaf's own key accepts the connection outright - the original
+// behaviour, which checks neither name nor dates: the key is the identity.
+//
+// A pin on a CA accepts it only if the pinned key signed a leaf that is valid
+// now, for server authentication, for host. Pinning a CA hands it the power
+// to vouch for other keys, so those checks are what keeps "signed by our CA"
+// from meaning "any certificate our CA ever signed, for any name, at any
+// time".
+//
+// What is enforced is the leaf's signature by the pinned key. The CA
+// certificate itself, as the server sends it, is not signed by anything this
+// check trusts - anyone can present a copy of its key with other fields - so
+// its own dates and name constraints cannot be relied on here, and its CA
+// flags are only checked to catch a pin pointing at the wrong certificate.
+// The server must send the CA certificate in its chain: a hash cannot stand
+// in for it.
+func Verify(chain []*x509.Certificate, host string, pins []string, now time.Time) error {
+	if len(chain) == 0 {
+		return fmt.Errorf("sin certificados del peer")
+	}
+	leaf := chain[0]
+	// The handshake has already proved the peer holds the leaf's private key,
+	// so a pinned key presented as the leaf is that key's holder - even when
+	// it is a CA's key, which only its owner can present this way.
+	if slices.Contains(pins, spki(leaf)) {
+		return nil
+	}
+	var lastErr error
+	for i, c := range chain[1:] {
+		if !slices.Contains(pins, spki(c)) {
+			continue
+		}
+		// A CA without a key usage extension (OpenSSL's default for one) may
+		// sign; one that has the extension must include certificate signing.
+		if !c.IsCA || !c.BasicConstraintsValid || (c.KeyUsage != 0 && c.KeyUsage&x509.KeyUsageCertSign == 0) {
+			lastErr = fmt.Errorf("the pinned key belongs to a certificate that is not a CA")
+			continue
+		}
+		roots := x509.NewCertPool()
+		roots.AddCert(c)
+		inter := x509.NewCertPool()
+		for j, o := range chain[1:] {
+			if j != i {
+				inter.AddCert(o)
+			}
+		}
+		_, err := leaf.Verify(x509.VerifyOptions{
+			DNSName:       host,
+			Roots:         roots,
+			Intermediates: inter,
+			CurrentTime:   now,
+			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		})
+		if err == nil {
+			return nil
+		}
+		// Another pinned certificate further up the chain may still vouch
+		// for the leaf, as during a move to a new CA.
+		lastErr = explain(err, host)
+	}
+	if lastErr != nil {
+		return lastErr
+	}
+	return fmt.Errorf("SPKI mismatch: the server's key %s matches no pinned key", spki(leaf))
+}
+
+// explain turns a chain verification error into one that says what to check.
+func explain(err error, host string) error {
+	var hostErr x509.HostnameError
+	var invalid x509.CertificateInvalidError
+	switch {
+	case err == nil:
+		return nil
+	case errors.As(err, &hostErr):
+		return fmt.Errorf("the server's certificate does not name %s: %w", host, err)
+	case errors.As(err, &invalid) && invalid.Reason == x509.Expired:
+		return fmt.Errorf("the server's certificate is expired or not yet valid - "+
+			"if this device's clock is not set yet (no NTP), this clears once it is: %w", err)
+	default:
+		return fmt.Errorf("the server's certificate was not issued by the pinned CA: %w", err)
+	}
+}
+
+func spki(c *x509.Certificate) string {
+	sum := sha256.Sum256(c.RawSubjectPublicKeyInfo)
+	return hex.EncodeToString(sum[:])
+}
+
 // VerifySPKI comprueba que el SPKI hash del leaf cert coincida con el
 // fingerprint esperado (SHA-256 hex del DER del SubjectPublicKeyInfo).
 func VerifySPKI(rawCerts [][]byte, wantHex string) error {

+ 269 - 0
agent/internal/tlspin/tlspin_ca_test.go

@@ -0,0 +1,269 @@
+package tlspin
+
+// FORK: tests for CA pins and pin lists. Addresses are from the
+// documentation ranges, names invented.
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/tls"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"fmt"
+	"math/big"
+	"net"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+)
+
+type testCA struct {
+	cert *x509.Certificate
+	key  *ecdsa.PrivateKey
+}
+
+func newKey(t *testing.T) *ecdsa.PrivateKey {
+	t.Helper()
+	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return k
+}
+
+func sign(t *testing.T, tmpl, parent *x509.Certificate, pub any, signer *ecdsa.PrivateKey) *x509.Certificate {
+	t.Helper()
+	tmpl.SerialNumber, _ = rand.Int(rand.Reader, big.NewInt(1<<62))
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, pub, signer)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c, err := x509.ParseCertificate(der)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return c
+}
+
+// newCA makes a root; isCA=false makes a certificate that looks like one to a
+// careless check but is not.
+func newCA(t *testing.T, isCA bool) testCA {
+	t.Helper()
+	k := newKey(t)
+	tmpl := &x509.Certificate{
+		Subject:               pkix.Name{CommonName: "test root"},
+		NotBefore:             time.Now().Add(-time.Hour),
+		NotAfter:              time.Now().Add(24 * time.Hour),
+		BasicConstraintsValid: true,
+		IsCA:                  isCA,
+		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
+	}
+	return testCA{cert: sign(t, tmpl, tmpl, &k.PublicKey, k), key: k}
+}
+
+type leafOpts struct {
+	ips       []string
+	names     []string
+	notBefore time.Time
+	notAfter  time.Time
+	eku       []x509.ExtKeyUsage
+}
+
+func (ca testCA) leaf(t *testing.T, o leafOpts) (*x509.Certificate, *ecdsa.PrivateKey) {
+	t.Helper()
+	k := newKey(t)
+	if o.notBefore.IsZero() {
+		o.notBefore = time.Now().Add(-time.Hour)
+	}
+	if o.notAfter.IsZero() {
+		o.notAfter = time.Now().Add(time.Hour)
+	}
+	if o.eku == nil {
+		o.eku = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
+	}
+	tmpl := &x509.Certificate{
+		Subject:     pkix.Name{CommonName: "test server"},
+		NotBefore:   o.notBefore,
+		NotAfter:    o.notAfter,
+		KeyUsage:    x509.KeyUsageDigitalSignature,
+		ExtKeyUsage: o.eku,
+		DNSNames:    o.names,
+	}
+	for _, ip := range o.ips {
+		tmpl.IPAddresses = append(tmpl.IPAddresses, net.ParseIP(ip))
+	}
+	return sign(t, tmpl, ca.cert, &k.PublicKey, ca.key), k
+}
+
+func TestVerifyCAPins(t *testing.T) {
+	ca := newCA(t, true)
+	other := newCA(t, true)
+	notCA := newCA(t, false)
+	now := time.Now()
+	good, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"}, names: []string{"netpulse.lan"}})
+	byOther, _ := other.leaf(t, leafOpts{ips: []string{"192.0.2.10"}})
+	byNotCA, _ := notCA.leaf(t, leafOpts{ips: []string{"192.0.2.10"}})
+	expired, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"},
+		notBefore: now.Add(-48 * time.Hour), notAfter: now.Add(-24 * time.Hour)})
+	notYet, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"},
+		notBefore: now.Add(24 * time.Hour), notAfter: now.Add(48 * time.Hour)})
+	clientOnly, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"},
+		eku: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}})
+
+	for _, tc := range []struct {
+		name    string
+		chain   []*x509.Certificate
+		host    string
+		pins    []string
+		wantErr string // "" = accepted
+	}{
+		{"CA pin, by IP", []*x509.Certificate{good, ca.cert}, "192.0.2.10", []string{spki(ca.cert)}, ""},
+		{"CA pin, by name", []*x509.Certificate{good, ca.cert}, "netpulse.lan", []string{spki(ca.cert)}, ""},
+		{"a list with one match", []*x509.Certificate{good, ca.cert}, "192.0.2.10",
+			[]string{spki(other.cert), spki(ca.cert)}, ""},
+		{"leaf pin keeps its old meaning", []*x509.Certificate{good, ca.cert}, "198.51.100.1",
+			[]string{spki(good)}, ""},
+		{"wrong CA pinned", []*x509.Certificate{good, ca.cert}, "192.0.2.10", []string{spki(other.cert)}, "mismatch"},
+		{"a name the leaf does not carry", []*x509.Certificate{good, ca.cert}, "198.51.100.1",
+			[]string{spki(ca.cert)}, "does not name"},
+		{"expired leaf", []*x509.Certificate{expired, ca.cert}, "192.0.2.10", []string{spki(ca.cert)}, "clock"},
+		{"leaf not valid yet", []*x509.Certificate{notYet, ca.cert}, "192.0.2.10", []string{spki(ca.cert)}, "clock"},
+		{"pinned key on a certificate that is not a CA", []*x509.Certificate{byNotCA, notCA.cert}, "192.0.2.10",
+			[]string{spki(notCA.cert)}, "not a CA"},
+		// Our root is public: an impostor can send it along with a leaf of
+		// its own. The leaf must still have been signed by the pinned key.
+		{"an impostor's leaf sent with our root", []*x509.Certificate{byOther, ca.cert}, "192.0.2.10",
+			[]string{spki(ca.cert)}, "not issued"},
+		{"a leaf not meant for servers", []*x509.Certificate{clientOnly, ca.cert}, "192.0.2.10",
+			[]string{spki(ca.cert)}, "not issued"},
+		{"no certificate", nil, "192.0.2.10", []string{spki(ca.cert)}, "sin certificados"},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			err := Verify(tc.chain, tc.host, tc.pins, now)
+			switch {
+			case tc.wantErr == "" && err != nil:
+				t.Fatalf("refused: %v", err)
+			case tc.wantErr != "" && err == nil:
+				t.Fatal("accepted")
+			case tc.wantErr != "" && !strings.Contains(err.Error(), tc.wantErr):
+				t.Fatalf("error %q does not say %q", err, tc.wantErr)
+			}
+		})
+	}
+}
+
+// End to end: an agent pinning the CA reaches a server that presents a leaf
+// the CA signed, and refuses the same server when it presents a leaf signed
+// by another CA - even with the pinned root attached to the chain.
+func TestCAPinOverARealConnection(t *testing.T) {
+	ca := newCA(t, true)
+	other := newCA(t, true)
+	for _, tc := range []struct {
+		name   string
+		signer testCA
+		wantOK bool
+	}{
+		{"leaf signed by the pinned CA", ca, true},
+		{"leaf signed by another CA", other, false},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			leaf, key := tc.signer.leaf(t, leafOpts{ips: []string{"127.0.0.1"}})
+			ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+				fmt.Fprint(w, "ok")
+			}))
+			ts.TLS = &tls.Config{Certificates: []tls.Certificate{{
+				Certificate: [][]byte{leaf.Raw, ca.cert.Raw},
+				PrivateKey:  key,
+			}}}
+			ts.StartTLS()
+			defer ts.Close()
+
+			tr, err := BuildTransport(ts.URL, spki(ca.cert))
+			if err != nil {
+				t.Fatal(err)
+			}
+			res, err := (&http.Client{Transport: tr, Timeout: 5 * time.Second}).Get(ts.URL)
+			if err == nil {
+				res.Body.Close()
+			}
+			if (err == nil) != tc.wantOK {
+				t.Fatalf("connected = %v, want %v (err %v)", err == nil, tc.wantOK, err)
+			}
+		})
+	}
+}
+
+func TestBuildTransportRefusesAMalformedPin(t *testing.T) {
+	good := strings.Repeat("ab", 32)
+	for _, fps := range []string{"abcd", good + ",zz", good + "," + good[:62]} {
+		if _, err := BuildTransport("https://192.0.2.10:3443", fps); err == nil {
+			t.Errorf("BuildTransport accepted pins %q", fps)
+		}
+	}
+	if _, err := BuildTransport("https://192.0.2.10:3443", "sha256/"+good+", "+strings.ToUpper(good)); err != nil {
+		t.Errorf("a normalizable list was refused: %v", err)
+	}
+}
+
+// The check must sit in VerifyConnection, which also runs on resumed
+// sessions; VerifyPeerCertificate does not.
+func TestThePinIsCheckedOnEveryConnection(t *testing.T) {
+	tr, err := BuildTransport("https://192.0.2.10:3443", strings.Repeat("ab", 32))
+	if err != nil {
+		t.Fatal(err)
+	}
+	c := tr.TLSClientConfig
+	if c.VerifyConnection == nil || c.VerifyPeerCertificate != nil {
+		t.Fatal("the pin must be checked in VerifyConnection")
+	}
+}
+
+// A CA made the way OpenSSL makes one by default has no key usage extension.
+// It may sign, and must be accepted.
+func TestACAWithoutKeyUsageIsAccepted(t *testing.T) {
+	k := newKey(t)
+	tmpl := &x509.Certificate{
+		Subject:               pkix.Name{CommonName: "openssl-style root"},
+		NotBefore:             time.Now().Add(-time.Hour),
+		NotAfter:              time.Now().Add(24 * time.Hour),
+		BasicConstraintsValid: true,
+		IsCA:                  true,
+	}
+	ca := testCA{cert: sign(t, tmpl, tmpl, &k.PublicKey, k), key: k}
+	if ca.cert.KeyUsage != 0 {
+		t.Fatal("test root unexpectedly has a key usage")
+	}
+	leaf, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"}})
+	if err := Verify([]*x509.Certificate{leaf, ca.cert}, "192.0.2.10", []string{spki(ca.cert)}, time.Now()); err != nil {
+		t.Fatalf("refused: %v", err)
+	}
+}
+
+// One pinned certificate that cannot vouch for the leaf does not stop another
+// pinned one further up the chain from doing so.
+func TestEveryPinnedCertificateInTheChainIsTried(t *testing.T) {
+	ca := newCA(t, true)
+	notCA := newCA(t, false)
+	leaf, _ := ca.leaf(t, leafOpts{ips: []string{"192.0.2.10"}})
+	chain := []*x509.Certificate{leaf, notCA.cert, ca.cert}
+	if err := Verify(chain, "192.0.2.10", []string{spki(notCA.cert), spki(ca.cert)}, time.Now()); err != nil {
+		t.Fatalf("refused: %v", err)
+	}
+}
+
+func TestBuildTransportRefusesAURLWithoutAHost(t *testing.T) {
+	if _, err := BuildTransport("https://:3443", strings.Repeat("ab", 32)); err == nil {
+		t.Fatal("a URL with no host was accepted: nothing to check the certificate's names against")
+	}
+}
+
+func TestNormalizeStripsAnUpperCasePrefix(t *testing.T) {
+	good := strings.Repeat("ab", 32)
+	pins, err := ParsePins("SHA256/" + strings.ToUpper(good))
+	if err != nil || len(pins) != 1 || pins[0] != good {
+		t.Fatalf("ParsePins = %v, %v", pins, err)
+	}
+}

+ 25 - 0
agent/pairproof/pairproof.go

@@ -0,0 +1,25 @@
+// Package pairproof is the proof a NetPulse server gives, at pairing, that
+// the key it serves is the real server's: an HMAC keyed with the pairing
+// token, which only the server and the admin who copied it know. The agent
+// and the server both compute it here, so the two cannot drift apart.
+//
+// FORK: see runtime.ProveServerKey for the exchange.
+package pairproof
+
+import (
+	"crypto/hmac"
+	"crypto/sha256"
+	"encoding/hex"
+	"fmt"
+)
+
+// Label separates this MAC from any other use of the pairing token.
+const Label = "netpulse-pair-v1"
+
+// MAC is HMAC-SHA256 keyed with the pairing token over the label, the
+// agent's nonce and the server's key fingerprint, in hex.
+func MAC(pairingToken, nonce, serverFP string) string {
+	m := hmac.New(sha256.New, []byte(pairingToken))
+	fmt.Fprintf(m, "%s\n%s\n%s", Label, nonce, serverFP)
+	return hex.EncodeToString(m.Sum(nil))
+}

+ 31 - 1
agent/runtime/firmware.go

@@ -15,6 +15,7 @@ import (
 	"fmt"
 	"io"
 	"net/http"
+	"net/url"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -61,7 +62,7 @@ func handleFirmwareUpgrade(opts Options, transport http.RoundTripper, data strin
 	}
 
 	log.Info("[netpulse-agent] firmware_upgrade iniciado", "upgrade_id", cmd.UpgradeID, "url", cmd.TargetURL)
-	hc := &http.Client{Transport: transport, Timeout: 5 * time.Minute}
+	hc := &http.Client{Transport: firmwareTransport(opts.Server, cmd.TargetURL, transport), Timeout: 5 * time.Minute}
 
 	dest := filepath.Join(firmwareTmpDir, fmt.Sprintf("firmware-%d.bin", cmd.UpgradeID))
 
@@ -266,3 +267,32 @@ func readPendingFirmware() (*pendingFirmware, error) {
 func clearPendingFirmware() error {
 	return os.Remove(firmwarePendingFile)
 }
+
+// firmwareTransport is the transport to download a firmware image with.
+//
+// The image URL is whatever the admin configured, usually a vendor mirror on
+// the public internet. The transport pinned to this agent's server only
+// accepts the server's own key, so once the server is reached over HTTPS it
+// refused every such mirror. Only a URL on the server itself keeps the pinned
+// transport; anything else is checked against the system's CAs. The image's
+// checksum is verified after download either way.
+func firmwareTransport(server, target string, serverTransport http.RoundTripper) http.RoundTripper {
+	su, err1 := url.Parse(server)
+	tu, err2 := url.Parse(target)
+	if err1 == nil && err2 == nil && su.Scheme == tu.Scheme &&
+		strings.EqualFold(su.Hostname(), tu.Hostname()) && effectivePort(su) == effectivePort(tu) {
+		return serverTransport
+	}
+	return http.DefaultTransport.(*http.Transport).Clone()
+}
+
+// effectivePort is u's port, or the scheme's default when it has none.
+func effectivePort(u *url.URL) string {
+	if p := u.Port(); p != "" {
+		return p
+	}
+	if u.Scheme == "https" {
+		return "443"
+	}
+	return "80"
+}

+ 34 - 0
agent/runtime/firmware_transport_test.go

@@ -0,0 +1,34 @@
+package runtime
+
+// FORK: tests for firmwareTransport. Addresses are from the documentation
+// ranges.
+
+import (
+	"net/http"
+	"testing"
+)
+
+// The pinned transport accepts only the server's own key, so it is kept for
+// an image on the server itself and never used for a mirror.
+func TestFirmwareTransportKeepsThePinOnlyForTheServer(t *testing.T) {
+	pinned := &http.Transport{}
+	for _, tc := range []struct {
+		server  string
+		target  string
+		wantPin bool
+	}{
+		{"https://192.0.2.10:3443", "https://192.0.2.10:3443/firmware/image.bin", true},
+		{"https://192.0.2.10:3443", "https://downloads.example.org/releases/image.bin", false},
+		{"https://192.0.2.10:3443", "https://192.0.2.10:8443/image.bin", false},
+		{"https://192.0.2.10:3443", "http://192.0.2.10:3443/image.bin", false},
+		// The default port, written out or not, is the same server.
+		{"https://192.0.2.10", "https://192.0.2.10:443/image.bin", true},
+		{"https://192.0.2.10:443", "https://192.0.2.10/image.bin", true},
+	} {
+		got := firmwareTransport(tc.server, tc.target, pinned)
+		if (got == http.RoundTripper(pinned)) != tc.wantPin {
+			t.Errorf("server %s, image %s: pinned transport used = %v, want %v",
+				tc.server, tc.target, got == http.RoundTripper(pinned), tc.wantPin)
+		}
+	}
+}

+ 26 - 3
agent/runtime/pairing.go

@@ -19,6 +19,16 @@ import (
 // server_fp para validar TLS (el admin lo proporciona junto con el
 // pairing token).
 func pairWithServer(opts Options) error {
+	// FORK: over https with no pin, prove the server's key with the pairing
+	// token first, then pair over a connection pinned to it.
+	learnedFP := ""
+	if strings.HasPrefix(opts.Server, "https://") && opts.ServerFP == "" {
+		fp, err := ProveServerKey(opts.Server, opts.PairingToken)
+		if err != nil {
+			return err
+		}
+		opts.ServerFP, learnedFP = fp, fp
+	}
 	transport, err := buildTransport(opts)
 	if err != nil {
 		return err
@@ -58,7 +68,7 @@ func pairWithServer(opts Options) error {
 	}
 
 	// Escribir el token real al env file (reemplaza PAIRING_TOKEN por TOKEN).
-	if err := writePairedToken(opts.EnvFile, pr.Token); err != nil {
+	if err := writePairedToken(opts.EnvFile, pr.Token, learnedFP); err != nil {
 		return fmt.Errorf("escribir token al env file: %w", err)
 	}
 
@@ -70,11 +80,18 @@ func pairWithServer(opts Options) error {
 
 // writePairedToken reescribe el env file: quita NETPULSE_PAIRING_TOKEN y
 // añade/actualiza NETPULSE_TOKEN. Conserva el resto de líneas.
-func writePairedToken(path, token string) error {
+//
+// FORK: fp, when not empty, is a pin proven during pairing and is written as
+// NETPULSE_SERVER_FP, so the agent keeps pinning it after the restart.
+func writePairedToken(path, token, fp string) error {
 	data, err := os.ReadFile(path)
 	if err != nil {
 		// Si no existe, crear uno nuevo con el token.
-		return os.WriteFile(path, []byte("NETPULSE_TOKEN="+token+"\n"), 0o600)
+		out := "NETPULSE_TOKEN=" + token + "\n"
+		if fp != "" {
+			out += "NETPULSE_SERVER_FP=" + fp + "\n"
+		}
+		return os.WriteFile(path, []byte(out), 0o600)
 	}
 	var out []string
 	haveToken := false
@@ -98,10 +115,16 @@ func writePairedToken(path, token string) error {
 			haveToken = true
 			continue
 		}
+		if key == "NETPULSE_SERVER_FP" && fp != "" {
+			continue // replaced by the proven pin below
+		}
 		out = append(out, line)
 	}
 	if !haveToken {
 		out = append(out, "NETPULSE_TOKEN="+token)
 	}
+	if fp != "" {
+		out = append(out, "NETPULSE_SERVER_FP="+fp)
+	}
 	return os.WriteFile(path, []byte(strings.Join(out, "\n")+"\n"), 0o600)
 }

+ 141 - 0
agent/runtime/prove.go

@@ -0,0 +1,141 @@
+package runtime
+
+// FORK: learning the server's key at pairing without trusting whoever
+// answers first.
+//
+// An agent given a pairing token but no pin used to have no way to reach an
+// HTTPS server at all: the pin had to be supplied beforehand. ProveServerKey
+// closes that gap without falling back to trust on first use. The pairing
+// token is a secret the admin copies from the server, so the server can prove
+// it knows the token - and bind that proof to the key it is serving - while
+// the token itself never travels on the not-yet-authenticated connection:
+//
+//	agent -> POST /api/agents/pair/hello {nonce}
+//	server -> {server_fp, mac = pairproof.MAC(token, nonce, server_fp)}
+//
+// The agent accepts server_fp only if the MAC is right AND server_fp is the
+// key of a certificate in the chain it was actually shown. A man in the
+// middle can relay the hello and obtain the real server's MAC, but for the
+// real server's key, which is not in the chain the middle presented.
+
+import (
+	"crypto/hmac"
+	"crypto/rand"
+	"crypto/tls"
+	"crypto/x509"
+	"encoding/hex"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/internal/tlspin"
+	"github.com/gnacho/netpulse/agent/pairproof"
+)
+
+// ServerTransport is the transport an embedder should use for its own
+// requests to the NetPulse server: the same pinning the agent uses. fps is
+// NETPULSE_SERVER_FP - one or more comma-separated pins.
+func ServerTransport(serverURL, fps string) (*http.Transport, error) {
+	return tlspin.BuildTransport(serverURL, fps)
+}
+
+// ValidatePins checks a NETPULSE_SERVER_FP value - one or more
+// comma-separated SHA-256 fingerprints - as the agent will read it, so a
+// setting can be refused when it is entered rather than when the agent
+// starts.
+func ValidatePins(fps string) error {
+	_, err := tlspin.ParsePins(fps)
+	return err
+}
+
+// ProveServerKey learns which key the HTTPS server at serverURL serves and
+// checks, with the pairing token, that it is the real server's. It returns
+// the fingerprint to pin. It never sends the pairing token.
+func ProveServerKey(serverURL, pairingToken string) (string, error) {
+	if !strings.HasPrefix(serverURL, "https://") {
+		return "", errors.New("the server's key can only be proven over https")
+	}
+	if pairingToken == "" {
+		return "", errors.New("proving the server's key needs the pairing token")
+	}
+	var (
+		mu   sync.Mutex
+		seen []*x509.Certificate
+	)
+	t := http.DefaultTransport.(*http.Transport).Clone()
+	t.DisableKeepAlives = true
+	t.TLSClientConfig = &tls.Config{
+		// Nothing is trusted on this connection: it only records the chain,
+		// and what the server says over it is checked against that chain.
+		InsecureSkipVerify: true, //nolint:gosec // the chain is checked below, against the MAC
+		MinVersion:         tls.VersionTLS12,
+		VerifyConnection: func(cs tls.ConnectionState) error {
+			mu.Lock()
+			seen = cs.PeerCertificates
+			mu.Unlock()
+			return nil
+		},
+	}
+	nonceBytes := make([]byte, 32)
+	if _, err := rand.Read(nonceBytes); err != nil {
+		return "", err
+	}
+	nonce := hex.EncodeToString(nonceBytes)
+	body := fmt.Sprintf(`{"nonce":%q}`, nonce)
+	req, err := http.NewRequest("POST", strings.TrimRight(serverURL, "/")+"/api/agents/pair/hello", strings.NewReader(body))
+	if err != nil {
+		return "", err
+	}
+	req.Header.Set("Content-Type", "application/json")
+	hc := &http.Client{
+		Transport: t,
+		Timeout:   15 * time.Second,
+		// A redirect would move the request to another connection, whose
+		// chain is not the one recorded.
+		CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+	}
+	res, err := hc.Do(req)
+	if err != nil {
+		return "", fmt.Errorf("pair hello: %w", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		b, _ := io.ReadAll(io.LimitReader(res.Body, 512))
+		return "", fmt.Errorf("pair hello: HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(b)))
+	}
+	var hello struct {
+		ServerFP string `json:"server_fp"`
+		MAC      string `json:"mac"`
+	}
+	if err := json.NewDecoder(io.LimitReader(res.Body, 4096)).Decode(&hello); err != nil {
+		return "", fmt.Errorf("pair hello: %w", err)
+	}
+	fp := tlspin.Normalize(hello.ServerFP)
+	want := pairproof.MAC(pairingToken, nonce, fp)
+	if !hmac.Equal([]byte(strings.ToLower(hello.MAC)), []byte(want)) {
+		return "", errors.New("pair hello: the server could not prove it holds the pairing token; " +
+			"this is not the server the token came from, or the token is wrong")
+	}
+	mu.Lock()
+	chain := seen
+	mu.Unlock()
+	// The proven key must be the one this connection authenticated with: the
+	// leaf's own key, or a CA key that signed the leaf for this host. Merely
+	// appearing in the chain is not enough - a relay can attach the real
+	// server's certificate to its own.
+	u, err := url.Parse(serverURL)
+	if err != nil {
+		return "", err
+	}
+	if err := tlspin.Verify(chain, u.Hostname(), []string{fp}, time.Now()); err != nil {
+		return "", fmt.Errorf("pair hello: the proven key is not the one this connection authenticated with; "+
+			"something between this device and the server is intercepting the connection (%v)", err)
+	}
+	return fp, nil
+}

+ 2 - 2
agent/runtime/runtime_test.go

@@ -233,7 +233,7 @@ func TestWritePairedToken(t *testing.T) {
 	env := filepath.Join(dir, "agent.env")
 	writeFile(t, env, "NETPULSE_SERVER=http://s\nNETPULSE_PAIRING_TOKEN=pt\nNETPULSE_SLUG=s\n")
 
-	if err := writePairedToken(env, "real-token"); err != nil {
+	if err := writePairedToken(env, "real-token", ""); err != nil {
 		t.Fatalf("writePairedToken: %v", err)
 	}
 	data, err := os.ReadFile(env)
@@ -257,7 +257,7 @@ func TestWritePairedToken(t *testing.T) {
 
 	// Env file inexistente: se crea solo con el token.
 	env2 := filepath.Join(dir, "nuevo.env")
-	if err := writePairedToken(env2, "tk"); err != nil {
+	if err := writePairedToken(env2, "tk", ""); err != nil {
 		t.Fatalf("writePairedToken nuevo: %v", err)
 	}
 	data2, _ := os.ReadFile(env2)

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

@@ -1324,7 +1324,7 @@
       "stateOffCaption": "Get urgent alerts on this device even when the app is not open.",
       "denied": "Permission denied in the browser. To re-enable it: click the lock (or tune) icon in the address bar → Permissions → Notifications → Allow, then reload the page.",
       "unsupported": "This browser does not support push notifications (it needs Service Worker, the Push API and the Notifications API).",
-      "insecure": "Push notifications require a secure context (HTTPS). On the local network they only work via localhost; over http://<lan-ip> the browser blocks them.",
+      "insecure": "Push notifications need HTTPS, and this page is open over plain HTTP. Open NetPulse at its HTTPS address to enable them on this device - an admin turns HTTPS on in Settings > HTTPS (port 3443 by default).",
       "demoNote": "Not available in the local demo: push notifications need the NetPulse backend (without a server, a subscription would never receive anything).",
       "errorServer": "Could not reach the push server. Please try again.",
       "errorGeneric": "Push notifications could not be enabled on this device.",
@@ -1730,6 +1730,56 @@
       "title": "Notification language",
       "description": "Language used for ntfy, Telegram and webhook alerts (alerts are composed in Spanish and translated when published).",
       "label": "Alert language"
+    },
+        "https": {
+      "title": "HTTPS",
+      "caption": "Serve NetPulse over HTTPS with its own certificate authority, and retire plain HTTP step by step.",
+      "loadError": "Could not load the HTTPS settings.",
+      "unavailable": "HTTPS is managed outside this page: {{reason}}.",
+      "enabled": "HTTPS on port {{port}}",
+      "enabledHint": "Only adds the HTTPS port. Plain HTTP keeps working until you choose a stricter mode below.",
+      "locked": "Fixed in the server's environment file; change it there.",
+      "rootTitle": "Root certificate",
+      "rootHint": "Install it once on each phone and computer you use NetPulse from. Before trusting it, check that the fingerprint your device shows matches this one, and the one in the server's log.",
+      "names": "The certificate covers {{names}} and renews itself (current one valid until {{until}}).",
+      "agentPin": "Agent pin (NETPULSE_SERVER_FP)",
+      "agentPinHint": "Agents and NetGrip pin this key when they reach the server at https://…:{{port}}. It stays the same when the certificate renews.",
+      "copy": "Copy",
+      "modeTitle": "What plain HTTP may still do",
+      "current": "current",
+      "modes": {
+        "full": {
+          "title": "Everything (as before)",
+          "hint": "Plain HTTP serves everything. Safe while you install the root certificate and move agents."
+        },
+        "migrate": {
+          "title": "Agents only",
+          "hint": "Browsers are sent to HTTPS; sign-ins and API calls over plain HTTP are refused. Agents keep reporting over plain HTTP until each one has moved."
+        },
+        "redirect": {
+          "title": "Nothing",
+          "hint": "Plain HTTP only redirects to HTTPS and hands out the root certificate. Agents still on plain HTTP stop reporting."
+        }
+      },
+      "agentsOnHttp": "Still reporting over plain HTTP",
+      "pending": "{{mode}} is waiting for confirmation until {{until}}. It only takes effect once confirmed from a page loaded over HTTPS; otherwise nothing changes.",
+      "confirmLink": "Open over HTTPS and confirm",
+      "confirmHint": "If the browser warns about the certificate, install the root certificate first.",
+      "confirmFailed": "The change could not be confirmed; it may have expired. Choose the mode again.",
+      "password": "Your password, to confirm",
+      "badPassword": "The password is not correct.",
+      "applyFailed": "The change could not be applied.",
+      "blocked": "These agents still report over plain HTTP and would stop reporting: {{agents}}.",
+      "switchAnyway": "Switch anyway",
+      "apply": "Apply",
+      "blockedOff": "These agents already report over HTTPS and would stop reporting: {{agents}}. Move them back first, or switch anyway.",
+      "rateLimited": "Too many wrong passwords. Try again in {{seconds}} s.",
+      "notFull": "Choose \"Everything\" first, and leave it on for a while: browsers told to always use HTTPS need it answering to be told to stop.",
+      "renew": "Renew now",
+      "renewHint": "Checked by itself every 10 minutes: after the server's address or name changes, a new certificate follows. Same root - nothing to reinstall.",
+      "renewed": "A new certificate was issued for the server's current addresses and names.",
+      "renewUnchanged": "Nothing changed: the certificate already covers the server's addresses and names.",
+      "uncovered": "Not covered: {{names}}. This root may only vouch for private addresses and the local names it was created with, so reaching the server under these needs a new root, installed again on every device (docs/https.md, \"Starting over\")."
     }
   },
   "statcard": {

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

@@ -1324,7 +1324,7 @@
       "stateOffCaption": "Recibe las alertas urgentes en este dispositivo aunque no tengas la app abierta.",
       "denied": "Permiso denegado en el navegador. Para reactivarlo: pulsa el candado (o el icono de ajustes) de la barra de direcciones → Permisos → Notificaciones → Permitir, y recarga la página.",
       "unsupported": "Este navegador no admite notificaciones push (hacen falta Service Worker, Push API y la API de notificaciones).",
-      "insecure": "Las notificaciones push exigen un contexto seguro (HTTPS). En la red local solo funcionan accediendo por localhost; desde http://<ip-de-la-lan> el navegador las bloquea.",
+      "insecure": "Las notificaciones push necesitan HTTPS, y esta página está abierta por HTTP. Abre NetPulse en su dirección HTTPS para activarlas en este dispositivo; un administrador activa HTTPS en Ajustes > HTTPS (puerto 3443 por defecto).",
       "demoNote": "No disponible en la demo local: las notificaciones push necesitan el backend de NetPulse (sin servidor, una suscripción nunca recibiría nada).",
       "errorServer": "No se pudo contactar con el servidor push. Inténtalo de nuevo.",
       "errorGeneric": "No se pudieron activar las notificaciones push en este dispositivo.",
@@ -1730,6 +1730,56 @@
       "title": "Idioma de las notificaciones",
       "description": "Idioma en que se envían los avisos de ntfy, Telegram y webhook (las alertas se componen en español y se traducen al publicar).",
       "label": "Idioma de los avisos"
+    },
+        "https": {
+      "title": "HTTPS",
+      "caption": "Sirve NetPulse por HTTPS con su propia autoridad de certificación y retira el HTTP plano paso a paso.",
+      "loadError": "No se pudieron cargar los ajustes de HTTPS.",
+      "unavailable": "HTTPS se gestiona fuera de esta página: {{reason}}.",
+      "enabled": "HTTPS en el puerto {{port}}",
+      "enabledHint": "Solo añade el puerto HTTPS. El HTTP plano sigue funcionando hasta que elijas un modo más estricto abajo.",
+      "locked": "Fijado en el archivo de entorno del servidor; cámbialo allí.",
+      "rootTitle": "Certificado raíz",
+      "rootHint": "Instálalo una vez en cada móvil y ordenador desde el que uses NetPulse. Antes de confiar en él, comprueba que la huella que muestra tu dispositivo coincide con esta y con la del log del servidor.",
+      "names": "El certificado cubre {{names}} y se renueva solo (el actual vale hasta {{until}}).",
+      "agentPin": "Pin para agentes (NETPULSE_SERVER_FP)",
+      "agentPinHint": "Los agentes y NetGrip fijan esta clave al conectar con el servidor en https://…:{{port}}. No cambia cuando el certificado se renueva.",
+      "copy": "Copiar",
+      "modeTitle": "Qué puede seguir haciendo el HTTP plano",
+      "current": "actual",
+      "modes": {
+        "full": {
+          "title": "Todo (como antes)",
+          "hint": "El HTTP plano lo sirve todo. Seguro mientras instalas el certificado raíz y mueves los agentes."
+        },
+        "migrate": {
+          "title": "Solo agentes",
+          "hint": "Los navegadores van a HTTPS; los inicios de sesión y las llamadas a la API por HTTP plano se rechazan. Los agentes siguen reportando por HTTP plano hasta que cada uno se mueva."
+        },
+        "redirect": {
+          "title": "Nada",
+          "hint": "El HTTP plano solo redirige a HTTPS y entrega el certificado raíz. Los agentes que sigan en HTTP plano dejan de reportar."
+        }
+      },
+      "agentsOnHttp": "Siguen reportando por HTTP plano",
+      "pending": "{{mode}} espera confirmación hasta las {{until}}. Solo se aplica al confirmarlo desde una página cargada por HTTPS; si no, no cambia nada.",
+      "confirmLink": "Abrir por HTTPS y confirmar",
+      "confirmHint": "Si el navegador avisa del certificado, instala antes el certificado raíz.",
+      "confirmFailed": "No se pudo confirmar el cambio; puede haber caducado. Vuelve a elegir el modo.",
+      "password": "Tu contraseña, para confirmar",
+      "badPassword": "La contraseña no es correcta.",
+      "applyFailed": "No se pudo aplicar el cambio.",
+      "blocked": "Estos agentes siguen reportando por HTTP plano y dejarían de reportar: {{agents}}.",
+      "switchAnyway": "Cambiar de todos modos",
+      "apply": "Aplicar",
+      "blockedOff": "Estos agentes ya reportan por HTTPS y dejarían de reportar: {{agents}}. Devuélvelos antes a HTTP, o cambia de todos modos.",
+      "rateLimited": "Demasiadas contraseñas erróneas. Vuelve a intentarlo en {{seconds}} s.",
+      "notFull": "Elige antes \"Todo\" y déjalo un tiempo: los navegadores a los que se dijo que usaran siempre HTTPS necesitan que responda para dejar de hacerlo.",
+      "renew": "Renovar ahora",
+      "renewHint": "Se comprueba solo cada 10 minutos: si cambia la dirección o el nombre del servidor, el certificado se renueva. Misma raíz: no hay que reinstalar nada.",
+      "renewed": "Se emitió un certificado nuevo para las direcciones y nombres actuales del servidor.",
+      "renewUnchanged": "Sin cambios: el certificado ya cubre las direcciones y nombres del servidor.",
+      "uncovered": "Sin cubrir: {{names}}. Esta raíz solo puede avalar direcciones privadas y los nombres locales con los que se creó; para llegar al servidor con estos hace falta una raíz nueva, instalada de nuevo en cada dispositivo (docs/https.md, \"Starting over\")."
     }
   },
   "statcard": {

+ 405 - 0
app/src/components/HttpsCard.tsx

@@ -0,0 +1,405 @@
+import { useState, useEffect, useCallback, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSearchParams } from 'react-router'
+import { Loader2, Check, Lock, Download, Copy, ShieldCheck, TriangleAlert, ExternalLink, RefreshCw } from 'lucide-react'
+import { Switch } from '@/components/ui/switch'
+
+// FORK: Settings > HTTPS (server: internal/httpapi/https_settings.go).
+//
+// Turning HTTPS on only adds the HTTPS port; plain HTTP keeps working until a
+// stricter mode is chosen - and that only takes effect once confirmed from a
+// page loaded over HTTPS, so a change here cannot lock the admin out. Every
+// change asks for the admin's password again.
+
+type Mode = 'full' | 'migrate' | 'redirect'
+
+interface HttpsStatus {
+  available: boolean
+  unavailable?: string
+  enabled: boolean
+  enabledLocked: boolean
+  mode: Mode
+  modeLocked: boolean
+  port: number
+  rootSha256?: string
+  fingerprint?: string
+  names?: string[]
+  uncovered?: string[]
+  validUntil?: string
+  pending?: Mode
+  pendingUntil?: string
+  error?: string
+  agentsOnHttp?: { slug: string; lastSeen: string }[] | null
+}
+
+type Change = { enabled?: boolean; mode?: Mode; force?: boolean }
+
+const MODES: Mode[] = ['full', 'migrate', 'redirect']
+
+export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
+  const { t } = useTranslation()
+  const [params, setParams] = useSearchParams()
+  const [st, setSt] = useState<HttpsStatus | null>(null)
+  const [loadError, setLoadError] = useState('')
+  const [change, setChange] = useState<Change | null>(null)
+  const [password, setPassword] = useState('')
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState('')
+  const [blocked, setBlocked] = useState<{ kind: 'http' | 'https'; agents: { slug: string }[] } | null>(null)
+  const [confirmUrl, setConfirmUrl] = useState('')
+  const [copied, setCopied] = useState(false)
+  const [renewing, setRenewing] = useState(false)
+  const [renewNote, setRenewNote] = useState('')
+  const confirming = useRef(false)
+
+  const load = useCallback(async () => {
+    try {
+      const r = await fetch('/api/settings/https')
+      if (!r.ok) {
+        setLoadError(r.status === 404 ? '' : t('settings.https.loadError'))
+        return
+      }
+      const d = (await r.json()) as HttpsStatus
+      setSt({ ...d, agentsOnHttp: d.agentsOnHttp ?? [], names: d.names ?? [] })
+    } catch {
+      setLoadError(t('settings.https.loadError'))
+    }
+  }, [t])
+
+  useEffect(() => {
+    void load()
+  }, [load])
+
+  // Arriving from the confirmation link: confirm once, then drop the code
+  // from the address so a reload does not try again.
+  useEffect(() => {
+    const code = params.get('confirm')
+    if (!code || confirming.current) return
+    confirming.current = true
+    void (async () => {
+      try {
+        const r = await fetch('/api/settings/https/confirm', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ code }),
+        })
+        const next = new URLSearchParams(params)
+        next.delete('confirm')
+        setParams(next, { replace: true })
+        if (r.ok) {
+          onSaved()
+        } else {
+          setError(t('settings.https.confirmFailed'))
+        }
+        await load()
+      } catch {
+        // A network error: keep the code in the address and allow a retry.
+        confirming.current = false
+        setError(t('settings.https.confirmFailed'))
+      }
+    })()
+  }, [params, setParams, load, onSaved, t])
+
+  const apply = useCallback(async () => {
+    if (!change) return
+    setBusy(true)
+    setError('')
+    setBlocked(null)
+    try {
+      const r = await fetch('/api/settings/https', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ ...change, password }),
+      })
+      const d = await r.json().catch(() => ({}))
+      if (r.status === 409 && (d.error === 'agents_on_http' || d.error === 'agents_on_https')) {
+        setBlocked({ kind: d.error === 'agents_on_http' ? 'http' : 'https', agents: d.agents ?? [] })
+        return
+      }
+      if (!r.ok) {
+        setError(
+          r.status === 401
+            ? t('settings.https.badPassword')
+            : r.status === 429
+              ? t('settings.https.rateLimited', { seconds: d.retryAfterSec ?? 60 })
+              : r.status === 409 && d.error === 'not_full'
+                ? t('settings.https.notFull')
+                : d.message || t('settings.https.applyFailed'),
+        )
+        return
+      }
+      setConfirmUrl(d.confirmUrl ?? '')
+      setChange(null)
+      setPassword('')
+      onSaved()
+      await load()
+    } catch {
+      setError(t('settings.https.applyFailed'))
+    } finally {
+      setBusy(false)
+    }
+  }, [change, password, load, onSaved, t])
+
+  // Re-checks the certificate against the server's addresses and names now,
+  // rather than at the next periodic check. Same root: nothing to reinstall.
+  const renew = async () => {
+    setRenewing(true)
+    setRenewNote('')
+    try {
+      const r = await fetch('/api/settings/https/renew', { method: 'POST' })
+      const d = await r.json().catch(() => ({}))
+      if (!r.ok) {
+        setRenewNote(d.message || t('settings.https.applyFailed'))
+        return
+      }
+      setRenewNote(t(d.issued ? 'settings.https.renewed' : 'settings.https.renewUnchanged'))
+      await load()
+    } catch {
+      setRenewNote(t('settings.https.applyFailed'))
+    } finally {
+      setRenewing(false)
+    }
+  }
+
+  if (loadError) return <p className="text-caption text-danger">{loadError}</p>
+  if (!st) return <p className="text-caption text-text-muted">{t('common.loading')}</p>
+
+  if (!st.available) {
+    return (
+      <p className="flex items-start gap-2 text-xs text-text-secondary">
+        <Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" strokeWidth={2} />
+        {t('settings.https.unavailable', { reason: st.unavailable })}
+      </p>
+    )
+  }
+
+  const inputCls =
+    'w-full rounded-md border border-border bg-elevated px-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none'
+  const onHttps = window.location.protocol === 'https:'
+
+  return (
+    <div className="space-y-4">
+      {/* On / off */}
+      <div className="flex items-center justify-between gap-4">
+        <div>
+          <div className="text-sm font-medium text-text-primary">{t('settings.https.enabled', { port: st.port })}</div>
+          <p className="text-[11px] text-text-muted">{t('settings.https.enabledHint')}</p>
+        </div>
+        <Switch
+          checked={change?.enabled ?? st.enabled}
+          disabled={st.enabledLocked || busy}
+          onCheckedChange={(v) => setChange(v === st.enabled ? null : { enabled: v })}
+          aria-label={t('settings.https.enabled', { port: st.port })}
+        />
+      </div>
+      {st.enabledLocked && <p className="text-[11px] text-text-muted">{t('settings.https.locked')}</p>}
+      {st.error && <p className="text-xs text-danger">{st.error}</p>}
+
+      {st.enabled && (
+        <>
+          {/* The root, for devices to install */}
+          <div className="rounded-lg border border-border bg-elevated p-3">
+            <div className="mb-1 flex items-center gap-2 text-sm font-medium text-text-primary">
+              <ShieldCheck className="h-4 w-4 text-accent" strokeWidth={2} />
+              {t('settings.https.rootTitle')}
+            </div>
+            <p className="mb-2 text-[11px] leading-relaxed text-text-secondary">{t('settings.https.rootHint')}</p>
+            <div className="mb-2 break-all font-mono text-[11px] text-text-primary">{st.rootSha256}</div>
+            <div className="flex flex-wrap gap-2">
+              <a
+                href="/netpulse-ca.crt"
+                download
+                className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 text-xs font-medium text-text-primary hover:bg-hover"
+              >
+                <Download className="h-3.5 w-3.5" /> netpulse-ca.crt
+              </a>
+              <a
+                href="/netpulse-ca.pem"
+                download
+                className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 text-xs font-medium text-text-primary hover:bg-hover"
+              >
+                <Download className="h-3.5 w-3.5" /> netpulse-ca.pem
+              </a>
+            </div>
+            {st.names && st.names.length > 0 && (
+              <p className="mt-2 text-[11px] text-text-muted">
+                {t('settings.https.names', {
+                  names: st.names.join(', '),
+                  until: st.validUntil ? new Date(st.validUntil).toLocaleDateString() : '',
+                })}
+              </p>
+            )}
+            {st.uncovered && st.uncovered.length > 0 && (
+              <p className="mt-2 text-[11px] leading-relaxed text-warn">
+                {t('settings.https.uncovered', { names: st.uncovered.join(', ') })}
+              </p>
+            )}
+            <div className="mt-2 flex flex-wrap items-center gap-2">
+              <button
+                type="button"
+                onClick={() => void renew()}
+                disabled={renewing}
+                className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 text-xs font-medium text-text-primary hover:bg-hover disabled:opacity-50"
+              >
+                {renewing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
+                {t('settings.https.renew')}
+              </button>
+              <span className="text-[11px] text-text-muted">{renewNote || t('settings.https.renewHint')}</span>
+            </div>
+          </div>
+
+          {/* The pin for agents */}
+          <div>
+            <div className="text-[11px] font-medium uppercase tracking-wider text-text-muted">{t('settings.https.agentPin')}</div>
+            <div className="mt-1 flex items-center gap-2">
+              <code className="flex-1 break-all rounded-md border border-border bg-elevated px-2 py-1 font-mono text-[11px] text-text-primary">
+                {st.fingerprint}
+              </code>
+              <button
+                type="button"
+                onClick={() => {
+                  void navigator.clipboard?.writeText(st.fingerprint ?? '')
+                  setCopied(true)
+                  setTimeout(() => setCopied(false), 1500)
+                }}
+                className="rounded-md border border-border p-1.5 text-text-muted hover:text-text-primary"
+                title={t('settings.https.copy')}
+              >
+                {copied ? <Check className="h-3.5 w-3.5 text-ok" /> : <Copy className="h-3.5 w-3.5" />}
+              </button>
+            </div>
+            <p className="mt-1 text-[11px] text-text-muted">{t('settings.https.agentPinHint', { port: st.port })}</p>
+          </div>
+
+          {/* What plain HTTP may still do */}
+          <div>
+            <div className="text-sm font-medium text-text-primary">{t('settings.https.modeTitle')}</div>
+            <div className="mt-2 space-y-2">
+              {MODES.map((m) => (
+                <label
+                  key={m}
+                  className={`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 ${
+                    (change?.mode ?? st.mode) === m ? 'border-accent bg-accent/[0.04]' : 'border-border'
+                  } ${st.modeLocked ? 'cursor-not-allowed opacity-60' : ''}`}
+                >
+                  <input
+                    type="radio"
+                    name="https-mode"
+                    className="mt-0.5"
+                    checked={(change?.mode ?? st.mode) === m}
+                    disabled={st.modeLocked || busy}
+                    onChange={() => setChange(m === st.mode ? null : { mode: m })}
+                  />
+                  <span>
+                    <span className="block text-xs font-semibold text-text-primary">
+                      {t(`settings.https.modes.${m}.title`)}
+                      {st.mode === m && <span className="ml-1.5 font-normal text-ok">{t('settings.https.current')}</span>}
+                    </span>
+                    <span className="block text-[11px] leading-relaxed text-text-secondary">
+                      {t(`settings.https.modes.${m}.hint`)}
+                    </span>
+                  </span>
+                </label>
+              ))}
+            </div>
+            {st.modeLocked && <p className="mt-1 text-[11px] text-text-muted">{t('settings.https.locked')}</p>}
+          </div>
+
+          {/* Agents that would stop reporting */}
+          {(st.agentsOnHttp ?? []).length > 0 && (
+            <div className="rounded-lg border border-warn/30 bg-warn/10 p-3 text-[11px] text-warn">
+              <div className="mb-1 flex items-center gap-1.5 font-semibold">
+                <TriangleAlert className="h-3.5 w-3.5" /> {t('settings.https.agentsOnHttp')}
+              </div>
+              <ul className="space-y-0.5">
+                {(st.agentsOnHttp ?? []).map((a) => (
+                  <li key={a.slug}>
+                    {a.slug} · {new Date(a.lastSeen).toLocaleString()}
+                  </li>
+                ))}
+              </ul>
+            </div>
+          )}
+        </>
+      )}
+
+      {/* A staged change waiting for confirmation over HTTPS */}
+      {(confirmUrl || st.pending) && (
+        <div className="rounded-lg border border-accent/40 bg-accent/[0.05] p-3 text-xs text-text-primary">
+          <p className="mb-2">
+            {t('settings.https.pending', {
+              mode: t(`settings.https.modes.${st.pending ?? 'migrate'}.title`),
+              until: st.pendingUntil ? new Date(st.pendingUntil).toLocaleTimeString() : '',
+            })}
+          </p>
+          {confirmUrl && (
+            <a
+              href={confirmUrl}
+              className="inline-flex items-center gap-1.5 font-semibold text-accent hover:underline"
+            >
+              <ExternalLink className="h-3.5 w-3.5" /> {t('settings.https.confirmLink')}
+            </a>
+          )}
+          {!onHttps && <p className="mt-2 text-[11px] text-text-muted">{t('settings.https.confirmHint')}</p>}
+        </div>
+      )}
+
+      {/* Password, for any change */}
+      {change && (
+        <div className="rounded-lg border border-border p-3">
+          <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+            {t('settings.https.password')}
+          </label>
+          <input
+            type="password"
+            value={password}
+            onChange={(e) => setPassword(e.target.value)}
+            autoComplete="current-password"
+            className={inputCls}
+          />
+          {blocked && (
+            <div className="mt-2 text-[11px] text-warn">
+              <p>
+                {t(blocked.kind === 'http' ? 'settings.https.blocked' : 'settings.https.blockedOff', {
+                  agents: blocked.agents.map((a) => a.slug).join(', '),
+                })}
+              </p>
+              <button
+                type="button"
+                className="mt-1 font-semibold underline"
+                onClick={() => setChange((c) => (c ? { ...c, force: true } : c))}
+              >
+                {t('settings.https.switchAnyway')}
+              </button>
+            </div>
+          )}
+          {error && <p className="mt-2 text-xs text-danger">{error}</p>}
+          <div className="mt-2 flex gap-2">
+            <button
+              type="button"
+              onClick={() => void apply()}
+              disabled={busy || !password}
+              className="inline-flex h-9 items-center gap-1.5 rounded-xl bg-accent px-3 text-[13px] font-semibold text-canvas hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
+            >
+              {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" strokeWidth={2.5} />}
+              {t('settings.https.apply')}
+            </button>
+            <button
+              type="button"
+              onClick={() => {
+                setChange(null)
+                setPassword('')
+                setError('')
+                setBlocked(null)
+              }}
+              className="inline-flex h-9 items-center rounded-xl border border-border px-3 text-[13px] text-text-primary hover:bg-hover"
+            >
+              {t('common.cancel')}
+            </button>
+          </div>
+        </div>
+      )}
+      {!change && error && <p className="text-xs text-danger">{error}</p>}
+    </div>
+  )
+}

+ 27 - 2
app/src/pages/Settings.tsx

@@ -74,6 +74,7 @@ import { PALETTES, type PaletteId, type ThemeMode } from '@/lib/theme-boot'
 import TelegramCard from '@/components/TelegramCard'
 import NtfyCard from '@/components/NtfyCard'
 import MqttCard from '@/components/MqttCard'
+import HttpsCard from '@/components/HttpsCard'
 import pkg from '../../package.json'
 
 // ---------------------------------------------------------------------------
@@ -3517,6 +3518,14 @@ function PushNotificationsCard({ reduce, onSaved, compact }: { reduce: boolean;
         </p>
       )}
 
+      {/* FORK: said, not left blank - over plain HTTP the card used to show
+          nothing at all, and the option looked missing. */}
+      {state === 'insecure' && (
+        <p className="rounded-xl bg-elevated px-3 py-2 text-caption leading-relaxed text-text-muted">
+          {t('settings.push.insecure')}
+        </p>
+      )}
+
       {state === 'demo' && (
         <p className="rounded-xl bg-elevated px-3 py-2 text-caption leading-relaxed text-text-muted">
           {t('settings.push.demoNote')}
@@ -5118,6 +5127,12 @@ export default function Settings() {
           </Card>
         </div>
 
+        {/* FORK: Web Push as its own card in Notifications. It was only a
+            small unlabelled button in About, and absent over plain HTTP. */}
+        <div className="order-61">
+          <PushNotificationsCard reduce={reduce} onSaved={notify} />
+        </div>
+
         {/* Idioma de las notificaciones push (#889): server-wide */}
         {!isDemo && (
           <div className="order-69">
@@ -5309,6 +5324,16 @@ export default function Settings() {
           </div>
         )}
 
+        {/* FORK: HTTPS with the server's private CA, and what plain HTTP may
+            still do (HttpsCard). Admin only, live mode. */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="order-121" id="https">
+            <Card title={t('settings.https.title')} caption={t('settings.https.caption')} index={5} reduce={reduce}>
+              <HttpsCard onSaved={notify} />
+            </Card>
+          </div>
+        )}
+
         {/* AdGuard Home (GL.iNet) — solo admin, modo live y servicio visible */}
         {!isDemo && auth?.role === 'admin' && services.adguard && (
           <div className="order-140">
@@ -5587,9 +5612,9 @@ export default function Settings() {
                   })}
                 </div>
 
-                {/* Push + PWA compactos (issue #156) */}
+                {/* Push + PWA compactos (issue #156). FORK: push moved to its own
+                    card under Notifications; the app install stays here. */}
                 <div className="mt-4 flex flex-wrap items-center gap-2">
-                  <PushNotificationsCard reduce={reduce} onSaved={notify} compact />
                   {!installed && (
                     <Confetti burstKey={confettiKey} reduce={reduce} />
                   )}

+ 8 - 1
app/src/sw.ts

@@ -32,8 +32,15 @@ cleanupOutdatedCaches()
 // App-shell offline para navegaciones (equivale a `navigateFallback:
 // 'index.html'` de generateSW). En dev NO se registra: el SW de desarrollo
 // no precachea index.html y esta ruta serviría un HTML congelado.
+// FORK: except where a navigation is meant to reach the server itself - the
+// root certificate, the fingerprint, and API downloads (CSV exports, the
+// backup). Served from here they turned into the app's "page not found".
 if (!import.meta.env.DEV) {
-  registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html')))
+  registerRoute(
+    new NavigationRoute(createHandlerBoundToURL('/index.html'), {
+      denylist: [/^\/api\//, /^\/netpulse-ca\./, /^\/fingerprint$/, /^\/health$/],
+    }),
+  )
 }
 
 // ---------------------------------------------------------------------------

+ 8 - 0
deploy/switch-scraper.env.example

@@ -14,3 +14,11 @@ AGENT_SLUG="switch16"
 # Servidor NetPulse y cadencia de push (segundos)
 NETPULSE_URL="http://127.0.0.1:3000"
 INTERVAL=300
+
+# FORK: with HTTPS on (Settings > HTTPS), push over it instead - required once
+# plain HTTP is set to "redirect". Fetch the root once into a file this
+# script's user can read (the server's own copy is private to it), and check
+# its fingerprint against Settings > HTTPS:
+#   curl -fsS http://127.0.0.1:3000/netpulse-ca.pem -o /opt/netpulse/netpulse-ca.pem
+# NETPULSE_URL="https://127.0.0.1:3443"
+# NETPULSE_CA="/opt/netpulse/netpulse-ca.pem"

+ 6 - 1
deploy/switch-scraper.sh

@@ -31,6 +31,11 @@ fi
 : "${AGENT_SLUG:?AGENT_SLUG no definido en $ENV_FILE}"
 : "${NETPULSE_URL:=http://127.0.0.1:3000}"
 : "${INTERVAL:=300}"
+# FORK: with NETPULSE_URL on https, the server's root to verify it against
+# (DATA_DIR/tls/ca.pem on the server itself). Never skip verification: the
+# push carries the agent token.
+CA_ARG=""
+[ -n "${NETPULSE_CA:-}" ] && CA_ARG="--cacert ${NETPULSE_CA}"
 TOKEN_FILE="${TOKEN_FILE:-/opt/netpulse/${AGENT_SLUG}.token}"
 
 TOKEN="$(cat "$TOKEN_FILE")"
@@ -104,7 +109,7 @@ PAYLOAD="{\"router\":\"${AGENT_SLUG}\",\"ts\":${TS},\"version\":\"scraper-2.0\",
 
 SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "$TOKEN" 2>/dev/null | awk '{print $NF}')
 
-HTTP_CODE=$(curl -s -o /tmp/${AGENT_SLUG}-response -w '%{http_code}' -m 10 -X POST "${NETPULSE_URL}/api/ingest/agent" \
+HTTP_CODE=$(curl -s $CA_ARG -o /tmp/${AGENT_SLUG}-response -w '%{http_code}' -m 10 -X POST "${NETPULSE_URL}/api/ingest/agent" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${TOKEN}" \
     -H "X-Agent-Signature: ${SIG}" \

+ 207 - 0
docs/https.md

@@ -0,0 +1,207 @@
+# HTTPS with NetPulse's own certificate authority
+
+NetPulse can serve its web UI and its agent API over HTTPS with a certificate
+signed by its **own private certificate authority (CA)**. You install that
+CA's root certificate once on each device you use NetPulse from; after that
+browsers trust the server without warnings. That is also what lets the PWA
+be installed and Web Push work: browsers do not allow them over a
+certificate you have only clicked through a warning for.
+
+Agents pin the root rather than the server's certificate, so the certificate
+can renew itself, or follow a change of the server's address, without any
+agent noticing.
+
+Nothing changes until an admin turns it on.
+
+## Turning it on
+
+In **Settings → HTTPS** (admins only), switch on **HTTPS on port 3443**.
+Every change on that card asks for your password again.
+
+Turning HTTPS on only **adds** the HTTPS port. Plain HTTP on the usual port
+keeps working exactly as before, so turning it on cannot lock you out.
+
+The first time, the server creates its CA in `DATA_DIR/tls/` and logs the
+root's fingerprint:
+
+```
+[netpulse] TLS: root certificate SHA-256 AB:CD:…
+[netpulse] TLS: agents pin 1f2e…
+```
+
+The port is `NETPULSE_TLS_PORT` (3443 by default).
+
+## Installing the root certificate
+
+The HTTPS card links the root as `netpulse-ca.crt` (for phones) and
+`netpulse-ca.pem`. Anyone can download it, since devices need it before they
+can trust the server. It lists the names it may vouch for (see below), so it
+tells whoever downloads it the server's host name and local domains.
+
+**Before trusting it, compare fingerprints.** Your device shows the
+certificate's SHA-256 fingerprint when installing it. It must match both the
+one on the HTTPS card and the one in the server's log. Read the log over SSH,
+not over the network you are securing:
+
+```
+journalctl -u netpulse | grep 'root certificate SHA-256'
+```
+
+- **Android:** open `netpulse-ca.crt`, or install it from Settings → Security →
+  Encryption & credentials → Install a certificate → CA certificate.
+- **iPhone / iPad:** open `netpulse-ca.crt` and allow the profile download.
+  Then install it in Settings → General → VPN & Device Management, and turn
+  on full trust in Settings → General → About → Certificate Trust Settings.
+- **Windows:** open `netpulse-ca.crt` → Install Certificate → Local Machine →
+  "Trusted Root Certification Authorities".
+- **macOS:** open `netpulse-ca.crt` in Keychain Access, add it to the System
+  keychain, and set "When using this certificate" to Always Trust.
+- **Linux:** copy `netpulse-ca.pem` to
+  `/usr/local/share/ca-certificates/netpulse-ca.crt` and run
+  `update-ca-certificates` (Debian, Ubuntu). Chrome and Chromium use this store.
+- **Firefox** keeps its own store: Settings → Privacy & Security → View
+  Certificates → Authorities → Import, then tick "Trust this CA to identify
+  websites".
+
+Then open `https://<server>:3443`.
+
+### What the root can and cannot vouch for
+
+The root carries **name constraints**. It can only vouch for:
+
+- private addresses: 10/8, 172.16/12, 192.168/16, 100.64/10, loopback, and
+  IPv6 fc00::/7;
+- local names: `lan`, `home.arpa`, `internal`, `local`, the server's own
+  host name, that name under each of its search domains, and anything in
+  `NETPULSE_TLS_NAMES` when the CA was created. A name there covers
+  everything below it, so the server logs a warning for one that is not a
+  local name.
+
+A device that enforces these constraints therefore cannot be fooled by it for
+a public site, even if someone copied the CA's key - short of a public name
+you added through `NETPULSE_TLS_NAMES` or `NETPULSE_PUBLIC_URL`. Chrome,
+Firefox and desktop systems enforce them; check your phones before relying
+on it.
+
+The certificate the server serves covers every private address and local
+name the host has. It lasts 90 days, is renewed automatically 30 days before
+it expires, and is re-issued within minutes when the server's addresses
+change.
+
+**Renew now** on the HTTPS card does that check at once, instead of at the
+next one within ten minutes: useful right after the server's address or name
+changes. It keeps the same root, so nothing is reinstalled anywhere. The card
+also lists any of the server's names or addresses the root cannot cover.
+
+To reach the server under a name outside those constraints, the CA has to
+be created again with that name in `NETPULSE_TLS_NAMES`. See "Starting over"
+below.
+
+## Moving agents to HTTPS
+
+Settings → HTTPS lists the agents still reporting over plain HTTP. Each
+moves in one of these ways:
+
+- **Reinstall from NetPulse** (Agents → Reinstall, or the automatic
+  reinstall). The agent is moved to HTTPS, pins the root, and verifies its
+  downloads against it. The root reaches the router over the SSH session,
+  whose host key NetPulse checks.
+- **The install command** shown when adding an agent. Once HTTPS is on, it
+  carries the root and the pin.
+- **NetGrip:** in its NetPulse settings, set the server to
+  `https://<server>:3443` and the server fingerprint to the **agent pin**
+  shown on the HTTPS card.
+- **Any other agent:** set `NETPULSE_SERVER=https://<server>:3443` and
+  `NETPULSE_SERVER_FP=<agent pin>` in its env file.
+- **Pairing with the pairing token:** an agent given only an https server URL
+  and the pairing token proves the server's key with that token before
+  trusting it. The token is never sent before the key is proven.
+- **`deploy/switch-scraper.sh`:** fetch the root once into a file its user
+  can read (`curl -fsS http://127.0.0.1:3000/netpulse-ca.pem -o …`; the
+  server's own copy is private to it), then set
+  `NETPULSE_URL=https://127.0.0.1:3443` and `NETPULSE_CA` to that file.
+
+Zero-touch enrolment (`AGENT_AUTOENROLL`) hands its token to anyone who asks
+over UDP, so it cannot prove anything. An agent enrolled that way trusts
+whichever server answered first. Prefer the pairing token when that matters.
+
+## Retiring plain HTTP
+
+The same card sets what plain HTTP may still do:
+
+| Mode | Plain HTTP |
+|---|---|
+| **Everything** (`full`) | serves everything, as before |
+| **Agents only** (`migrate`) | page loads are redirected to HTTPS; sign-ins, sessions and API tokens are refused; agents keep reporting until each one has moved |
+| **Nothing** (`redirect`) | only redirects to HTTPS and serves the root certificate; `/api/health` answers the server itself |
+
+A stricter mode **does not take effect when you click it.** The card shows a
+link to the HTTPS address. The mode only applies once you open that link,
+signed in, within five minutes. That way you have proved HTTPS works for you
+before plain HTTP stops taking sign-ins. If you do not confirm, nothing
+changes. Going back to **Everything** is immediate. If the HTTPS page asks
+you to sign in first, sign in and open the link again.
+
+**Nothing** is refused while agents are still on plain HTTP, unless you choose
+"Switch anyway". The list comes from each agent's last report in the past
+day, and survives a restart of the server.
+
+HTTPS can only be turned off from **Everything**. Browsers told to always use
+HTTPS in a stricter mode need it answering, on either port, to be told to
+stop. Turning it off is also refused while agents report over HTTPS, since
+they would stop reporting, unless you choose "Switch anyway".
+
+Once the CA exists, the plain port also answers HTTPS. A browser that learned
+to always use HTTPS for the server's name (HSTS) still reaches it on either
+port, in any mode.
+
+## If you cannot get in
+
+Over SSH, add to the server's env file (`/var/lib/netpulse/.env` on a
+standard install) and restart:
+
+```
+NETPULSE_HTTP_MODE=full
+```
+
+Plain HTTP serves everything again, and the mode is locked until you remove
+the line. Settings the environment fixes appear locked on the card.
+
+To manage HTTPS from the environment instead of the UI, set
+`NETPULSE_TLS_ENABLED=1` and `NETPULSE_TLS_CA=1`. `NETPULSE_TLS_ENABLED=0`, as
+in `.env.example`, does not lock anything.
+
+## Backups
+
+`DATA_DIR/tls/ca-key.pem` is the key every device you installed the root on
+trusts. Anything that backs up `DATA_DIR` holds it, just as it already holds
+the agents' tokens. Keep such backups as private as the server itself.
+
+If the key file or its directory can be read by other users, HTTPS does not
+start: turned on from the environment, the server refuses to start at all;
+turned on from the UI, the card shows the error and plain HTTP keeps
+working.
+
+## Starting over
+
+To create a new CA, for example to cover a new name:
+
+1. Choose **Everything**.
+2. Stop the server and move `DATA_DIR/tls` away.
+3. Start the server again.
+4. Install the new root on your devices, and move each agent to the new pin
+   (reinstalling does it).
+
+Removing only one of `ca.pem` and `ca-key.pem` is refused: a lost half is
+restored from a backup, never silently replaced.
+
+## Other HTTPS set-ups
+
+- **On-box** (`NETPULSE_ONBOX=1`) keeps its own HTTPS on the server's port.
+- **A certificate of your own** (`NETPULSE_TLS_CERT` / `NETPULSE_TLS_KEY`)
+  keeps working as before. If agents pin its key, renew it keeping the same
+  key (for example `certbot --reuse-key`). Agents pinning a CA need that CA's
+  certificate in the chain the server sends.
+- **Behind a TLS-terminating proxy**, agents see the proxy's certificate. Set
+  `NETPULSE_SERVER_FP` on them by hand; pairing cannot prove a key the server
+  does not hold.

+ 16 - 0
server-go/.env.example

@@ -72,3 +72,19 @@ NETPULSE_TLS_PORT=3443
 # arrancar (con el aviso del navegador, sin validez de PWA).
 #NETPULSE_TLS_CERT=/ruta/a/fullchain.pem
 #NETPULSE_TLS_KEY=/ruta/a/privkey.pem
+
+# --- FORK: HTTPS with the server's own private CA (docs/https.md) ---
+# Usually turned on from Settings > HTTPS, with no restart; these only
+# matter to fix it here instead. With NETPULSE_TLS_ENABLED=1 and
+# NETPULSE_TLS_CA=1 the extra listener serves a certificate signed by the
+# server's own CA (DATA_DIR/tls), which you install once on your devices;
+# the switch in Settings is then locked on.
+#NETPULSE_TLS_CA=1
+# Extra names or addresses the certificate should cover, comma-separated
+# (the host's own addresses and names are found by themselves). Only
+# private addresses and local names can be covered.
+#NETPULSE_TLS_NAMES=
+# What plain HTTP on PORT may still do: full | migrate | redirect. Set it
+# to lock the mode - and set it to "full" to get plain HTTP back if HTTPS
+# ever becomes unreachable.
+#NETPULSE_HTTP_MODE=

+ 99 - 9
server-go/cmd/netpulse/main.go

@@ -20,6 +20,7 @@ import (
 	"errors"
 	"fmt"
 	"log"
+	"net"
 	"net/http"
 	"net/url"
 	"os"
@@ -51,6 +52,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/poller"
 	"github.com/gnacho/netpulse/server-go/internal/push"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 	"github.com/gnacho/netpulse/server-go/internal/roamevents"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
@@ -61,6 +63,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/telegram"
 	"github.com/gnacho/netpulse/server-go/internal/telemetry"
 	"github.com/gnacho/netpulse/server-go/internal/tlscert"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
 	"github.com/gnacho/netpulse/server-go/internal/webhook"
 	"github.com/gnacho/netpulse/server-go/internal/wifisle"
@@ -80,7 +83,10 @@ const (
 
 // isSSEStreamPath devuelve true para los endpoints SSE de larga duración.
 func isSSEStreamPath(p string) bool {
-	if p == "/api/stream" {
+	// FORK: /api/update/stream is an SSE stream too; with the normal write
+	// timeout it was cut every time and the update dialog fell back to
+	// polling.
+	if p == "/api/stream" || p == "/api/update/stream" {
 		return true
 	}
 	return strings.HasPrefix(p, "/api/agents/") && strings.HasSuffix(p, "/stream")
@@ -506,7 +512,13 @@ func run() error {
 	// certs del usuario (NETPULSE_TLS_CERT/NETPULSE_TLS_KEY) se cargan; si no,
 	// se genera un autofirmado en DATA_DIR.
 	var extraTLSConf *tls.Config
-	if cfg.TLSEnabled {
+	// FORK: the fingerprint of a user-supplied certificate, read live (it can
+	// change key on renewal). Set only when the extra listener is the one
+	// agents reach over TLS, i.e. not on-box, where PORT's own certificate is
+	// the one they pin.
+	var serverFPFunc func() string
+	// FORK: with NETPULSE_TLS_CA the extra listener belongs to tlsmode below.
+	if cfg.TLSEnabled && !cfg.TLSCA {
 		certPath := cfg.TLSCert
 		keyPath := cfg.TLSKey
 		userCerts := certPath != "" && keyPath != ""
@@ -525,6 +537,10 @@ func run() error {
 			reloader, err2 = tlscert.NewReloader(certPath, keyPath)
 			if err2 == nil {
 				extraTLSConf = reloader.Config()
+				fp = reloader.Fingerprint()
+				if !cfg.Onbox {
+					serverFPFunc = reloader.Fingerprint
+				}
 			}
 		} else {
 			extraTLSConf, fp, err2 = tlscert.Ensure(certPath, keyPath)
@@ -537,11 +553,61 @@ func run() error {
 			origen = "usuario (recarga en caliente al renovar)"
 		} else {
 			log.Printf("[netpulse] TLS autofirmado: %s", certPath)
-			log.Printf("[netpulse] FINGERPRINT SPKI (sha256): %s", fp)
+		}
+		log.Printf("[netpulse] FINGERPRINT SPKI (sha256): %s", fp)
+		// FORK: agents pin this, so pairing must hand it out. It was only
+		// logged, and pairing returned an empty server_fp in this mode.
+		if !cfg.Onbox && !userCerts {
+			serverFP = fp
 		}
 		log.Printf("[netpulse] HTTPS adicional en :%d (cert %s: %s)", cfg.TLSPort, origen, certPath)
 	}
 
+	// FORK: HTTPS with the server's private CA, managed from Settings > HTTPS
+	// (internal/tlsmode). The environment, when it says anything, wins; on-box
+	// and a certificate of the admin's own keep their own HTTPS as above.
+	// Only an explicit NETPULSE_TLS_ENABLED=1 with NETPULSE_TLS_CA=1 locks
+	// the switch: .env.example ships NETPULSE_TLS_ENABLED=0, which is
+	// upstream's default, not a decision to keep HTTPS off. Recovery never
+	// needs HTTPS forced off here - NETPULSE_HTTP_MODE=full restores plain
+	// HTTP, and a CA that cannot be opened leaves plain HTTP as it was.
+	var tlsEnvEnabled *bool
+	if cfg.TLSEnabled && cfg.TLSCA {
+		on := true
+		tlsEnvEnabled = &on
+	}
+	tlsUnavailable := ""
+	switch {
+	case cfg.Onbox:
+		tlsUnavailable = "on-box, the server's own port already serves HTTPS"
+	case cfg.TLSEnabled && !cfg.TLSCA:
+		tlsUnavailable = "HTTPS is set up in the server's environment with its own certificate"
+	}
+	tlsMgr := tlsmode.New(tlsmode.Options{
+		DB:          dbHandle,
+		DataDir:     cfg.DataDir,
+		Port:        cfg.TLSPort,
+		Names:       cfg.TLSNames,
+		PublicURL:   cfg.PublicURL,
+		EnvEnabled:  tlsEnvEnabled,
+		EnvMode:     tlsmode.Mode(cfg.HTTPMode),
+		Unavailable: tlsUnavailable,
+		NewServer: func(addr string, h http.Handler) *http.Server {
+			return newHTTPServer(addr, withSSEWriteTimeout(h, sseWriteTimeout))
+		},
+		Logf: log.Printf,
+	})
+	if serverFPFunc == nil && serverFP == "" && tlsMgr.Available() {
+		serverFPFunc = tlsMgr.Fingerprint
+	}
+	legacyFP := func() string {
+		if serverFPFunc != nil {
+			return serverFPFunc()
+		}
+		return serverFP
+	}
+	arm.SetTrust(func(base string) reinstall.Trust { return tlsmode.AgentTrust(tlsMgr, legacyFP, base) })
+
 	// Speedtest WAN periódico (#511): store + runner + scheduler. Las
 	// alertas de "velocidad por debajo del plan" se emiten por el MISMO
 	// motor del adapter (la lista de eventos es por instancia). Solo en
@@ -629,6 +695,8 @@ func run() error {
 		Rearmer:         arm,
 		AgentHub:        agentHub,
 		ServerFP:        serverFP,
+		ServerFPFunc:    serverFPFunc,
+		TLS:             tlsMgr,
 		Orchestr:        orchMgr,
 		MQTT:            mqttMgr,
 		TokenStore:      tokenStore,
@@ -648,18 +716,33 @@ func run() error {
 	})
 
 	// Envolver el handler con GET /fingerprint (sin auth) si on-box.
-	if cfg.Onbox {
-		fp := serverFP
+	// FORK: and whenever the extra TLS listener is up, which serves TLS too.
+	if cfg.Onbox || extraTLSConf != nil || tlsMgr.Available() {
+		fp := func() string { return serverFP }
+		if serverFPFunc != nil {
+			fp = serverFPFunc
+		}
 		fpMux := http.NewServeMux()
-		fpMux.HandleFunc("GET /fingerprint", func(w http.ResponseWriter, _ *http.Request) {
+		fpMux.HandleFunc("GET /fingerprint", func(w http.ResponseWriter, r *http.Request) {
+			v := fp()
+			if v == "" { // HTTPS is off: there is nothing to pin
+				http.NotFound(w, r)
+				return
+			}
 			w.Header().Set("Content-Type", "application/json")
-			fmt.Fprintf(w, `{"spki_sha256":%q}`, fp)
+			fmt.Fprintf(w, `{"spki_sha256":%q}`, v)
 		})
 		fpMux.Handle("/", handler)
 		handler = fpMux
 	}
 
-	srv := newHTTPServer(fmt.Sprintf(":%d", cfg.Port), withSSEWriteTimeout(handler, sseWriteTimeout))
+	// FORK: the TLS listener, when HTTPS is on, serves the same handler.
+	if err := tlsMgr.Start(handler); err != nil {
+		return fmt.Errorf("HTTPS: %w", err)
+	}
+	defer tlsMgr.Close()
+	// FORK: on the plain port, what the HTTP mode allows (a no-op in full).
+	srv := newHTTPServer(fmt.Sprintf(":%d", cfg.Port), withSSEWriteTimeout(tlsMgr.PlainHandler(handler), sseWriteTimeout))
 
 	// Listener HTTPS adicional (#696): mismo handler y timeouts que el HTTP.
 	var tlsSrv *http.Server
@@ -693,7 +776,14 @@ func run() error {
 		if cfg.Onbox {
 			errCh <- srv.ListenAndServeTLS("", "")
 		} else {
-			errCh <- srv.ListenAndServe()
+			// FORK: through the sniffing listener, so a browser upgraded to
+			// https on this port by an HSTS policy is still served.
+			ln, err := net.Listen("tcp", srv.Addr)
+			if err != nil {
+				errCh <- err
+				return
+			}
+			errCh <- srv.Serve(tlsMgr.SniffListener(ln))
 		}
 	}()
 

+ 2 - 0
server-go/cmd/netpulse/main_test.go

@@ -47,6 +47,8 @@ func TestIsSSEStreamPath(t *testing.T) {
 		"/api/stream":                true,
 		"/api/agents/gw/stream":      true,
 		"/api/agents/gateway/stream": true,
+		"/api/update/stream":         true, // FORK
+		"/api/update/status":         false,
 		"/api/agents/gw/binary":      false,
 		"/api/agents/gw/refresh":     false,
 		"/api/agents/gw/stream/x":    false,

+ 52 - 9
server-go/internal/auth/auth.go

@@ -31,6 +31,14 @@ import (
 const (
 	// SessionCookie es el nombre de la cookie de sesión.
 	SessionCookie = "session"
+	// SecureSessionCookie is the session cookie's name when it is Secure.
+	// FORK: cookies are shared by every port and scheme of a host, so a
+	// Secure "session" set over HTTPS could not be replaced by a login over
+	// plain HTTP, and was not sent there - signing in over plain HTTP looped
+	// while both were in use. Under its own name each keeps its own cookie.
+	// The __Host- prefix makes browsers insist it is Secure, host-only and
+	// for Path=/.
+	SecureSessionCookie = "__Host-session"
 	// SessionTTLMS = 30 días en ms (Max-Age=2592000).
 	SessionTTLMS = 30 * 24 * 60 * 60 * 1000
 	// LockMS = 5 minutos en ms.
@@ -200,6 +208,33 @@ func sessionCookieValue(r *http.Request) string {
 	return m[1]
 }
 
+// FORK: secureCookieRe finds the Secure session cookie (SecureSessionCookie).
+var secureCookieRe = regexp.MustCompile(`(?:^|;\s*)__Host-session=([^;]+)`)
+
+// sessionCookieValues is every session cookie the request carries, the
+// Secure one first. Browsers only send that one over HTTPS.
+func sessionCookieValues(r *http.Request) []string {
+	var out []string
+	if m := secureCookieRe.FindStringSubmatch(r.Header.Get("Cookie")); m != nil {
+		out = append(out, m[1])
+	}
+	if v := sessionCookieValue(r); v != "" {
+		out = append(out, v)
+	}
+	return out
+}
+
+// validSessionID is the first of the request's session cookies that verifies
+// and names a live session, or "".
+func validSessionID(d *db.DB, secret string, r *http.Request) string {
+	for _, v := range sessionCookieValues(r) {
+		if id := VerifySessionCookie(secret, v); id != "" && GetSession(d, id) != nil {
+			return id
+		}
+	}
+	return ""
+}
+
 // IsSecureRequest: URL https, o primer X-Forwarded-Proto == "https" SOLO si
 // TRUST_PROXY (despliegue detrás de proxy con TLS terminado fuera). Sin
 // TRUST_PROXY, un cliente de la LAN no puede forzar la cookie Secure
@@ -233,8 +268,12 @@ func CookieSecureFlag(cfg *config.Config, r *http.Request) bool {
 
 // BuildSessionCookie compone el header Set-Cookie (literal de auth.js:119-129).
 func BuildSessionCookie(cfg *config.Config, r *http.Request, signedID string, maxAgeSec int64) string {
+	name := SessionCookie
+	if CookieSecureFlag(cfg, r) {
+		name = SecureSessionCookie
+	}
 	parts := []string{
-		fmt.Sprintf("%s=%s", SessionCookie, signedID),
+		fmt.Sprintf("%s=%s", name, signedID),
 		"Path=/",
 		"HttpOnly",
 		"SameSite=Lax",
@@ -249,6 +288,10 @@ func BuildSessionCookie(cfg *config.Config, r *http.Request, signedID string, ma
 // ClearSessionCookie borra la cookie (literal, SIN Secure aunque sea HTTPS).
 const ClearSessionCookie = "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"
 
+// ClearSecureSessionCookie deletes the Secure session cookie. FORK: it can
+// only be deleted over HTTPS, and must carry Secure to be accepted.
+const ClearSecureSessionCookie = "__Host-session=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"
+
 // ---------------------------------------------------------------------------
 // Sesiones en SQLite
 // ---------------------------------------------------------------------------
@@ -324,7 +367,7 @@ type SessionUser struct {
 // SessionUserFromRequest: cookie válida + sesión en DB con user_id NO nulo +
 // usuario existente (una sesión legacy sin user_id NO autentica).
 func SessionUserFromRequest(d *db.DB, secret string, r *http.Request) *SessionUser {
-	id := VerifySessionCookie(secret, sessionCookieValue(r))
+	id := validSessionID(d, secret, r)
 	sess := GetSession(d, id)
 	if sess == nil || !sess.UserID.Valid {
 		return nil
@@ -338,11 +381,7 @@ func SessionUserFromRequest(d *db.DB, secret string, r *http.Request) *SessionUs
 
 // SessionIDFromRequest devuelve el id de sesión válida (sin exigir user_id).
 func SessionIDFromRequest(d *db.DB, secret string, r *http.Request) string {
-	id := VerifySessionCookie(secret, sessionCookieValue(r))
-	if GetSession(d, id) == nil {
-		return ""
-	}
-	return id
+	return validSessionID(d, secret, r)
 }
 
 // ---------------------------------------------------------------------------
@@ -463,7 +502,11 @@ func HandleLogin(d *db.DB, secret string, r *http.Request, username, password st
 
 // HandleLogout destruye la sesión de la cookie (si existe y es válida).
 func HandleLogout(d *db.DB, secret string, r *http.Request) {
-	if id := SessionIDFromRequest(d, secret, r); id != "" {
-		DestroySession(d, id)
+	// FORK: every session cookie the request carries - over HTTPS that can
+	// be both the Secure one and a plain one from a sign-in over HTTP.
+	for _, v := range sessionCookieValues(r) {
+		if id := VerifySessionCookie(secret, v); id != "" {
+			DestroySession(d, id)
+		}
 	}
 }

+ 13 - 0
server-go/internal/auth/middleware.go

@@ -66,10 +66,23 @@ func isAgentReportPath(path string) bool {
 			strings.HasSuffix(path, "/firmware-result"))
 }
 
+// IsAgentRequest reports whether r is a route agents and embedders call with
+// their own token - pushes, reports, pairing, config backups - rather than a
+// person with a session or an API token. FORK: while HTTPS is being rolled
+// out these keep working over plain HTTP until each agent has moved, when
+// everything else is already refused there.
+func IsAgentRequest(r *http.Request) bool {
+	p := r.URL.Path
+	return p == "/api/ingest/agent" || p == "/api/agents/pair" || p == "/api/agents/pair/hello" ||
+		p == "/api/agents/executor-token" || isAgentReportPath(p) ||
+		(p == "/api/config-backup" && r.Method == http.MethodPost)
+}
+
 // isAnonymousPath indica si la ruta no requiere sesión (auth propia en el handler).
 func isAnonymousPath(path string) bool {
 	if path == "/api/health" || path == "/api/auth/login" ||
 		path == "/api/ingest/agent" || path == "/api/agents/pair" ||
+		path == "/api/agents/pair/hello" || // FORK: proves the served key; no secret in or out
 		path == "/api/agents/executor-token" ||
 		isAgentReportPath(path) {
 		return true

+ 44 - 0
server-go/internal/config/config.go

@@ -77,6 +77,13 @@ type Config struct {
 	TLSPort    int
 	TLSCert    string // NETPULSE_TLS_CERT: path del cert del usuario (opcional; junto a TLSKey)
 	TLSKey     string // NETPULSE_TLS_KEY: path de la clave del usuario (opcional; junto a TLSCert)
+	// FORK: HTTPS with the server's own private CA (internal/tlsmode).
+	// NETPULSE_TLS_ENABLED=1 with NETPULSE_TLS_CA=1 turns it on and locks
+	// the switch in Settings > HTTPS; NETPULSE_HTTP_MODE locks the mode.
+	// Anything else leaves both to the admin there.
+	TLSCA    bool     // NETPULSE_TLS_CA=1: the extra listener serves a leaf of the private CA
+	TLSNames []string // NETPULSE_TLS_NAMES: extra names/addresses for the certificate
+	HTTPMode string   // NETPULSE_HTTP_MODE: full | migrate | redirect ("" = from the UI)
 	// RTLConsolePass (NETPULSE_RTL_PASS): contraseña web de la consola de
 	// switches RTLPlayground (KP-9000, #639) para el sondeo HTTP de firmware
 	// y uptime. Default "1234" (la que trae el firmware tras flasheo).
@@ -508,6 +515,40 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CERT/NETPULSE_TLS_KEY", "both must be set together"})
 	}
 
+	// FORK: the private CA and what plain HTTP may do (internal/tlsmode).
+	tlsCA := false
+	switch v := strings.TrimSpace(env["NETPULSE_TLS_CA"]); v {
+	case "", "0":
+	case "1":
+		tlsCA = true
+		switch {
+		case !tlsEnabled:
+			errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "needs NETPULSE_TLS_ENABLED=1 (or leave both unset and turn HTTPS on in Settings)"})
+		case tlsCert != "":
+			errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "cannot be used with NETPULSE_TLS_CERT/NETPULSE_TLS_KEY: the certificate comes from one or the other"})
+		}
+	default:
+		errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "Invalid enum value. Expected '0' | '1'"})
+	}
+	var tlsNames []string
+	for _, n := range strings.Split(env["NETPULSE_TLS_NAMES"], ",") {
+		if n = strings.TrimSpace(n); n != "" {
+			tlsNames = append(tlsNames, n)
+		}
+	}
+	httpMode := strings.TrimSpace(env["NETPULSE_HTTP_MODE"])
+	switch httpMode {
+	case "", "full":
+	case "migrate", "redirect":
+		// Only the private-CA HTTPS knows how to restrict plain HTTP; with
+		// HTTPS configured otherwise the setting would be silently ignored.
+		if onbox || (tlsEnabled && !tlsCA) {
+			errs.issues = append(errs.issues, issue{"NETPULSE_HTTP_MODE", "only applies to HTTPS with the private CA (NETPULSE_TLS_CA=1, or HTTPS turned on in Settings)"})
+		}
+	default:
+		errs.issues = append(errs.issues, issue{"NETPULSE_HTTP_MODE", "Invalid enum value. Expected 'full' | 'migrate' | 'redirect'"})
+	}
+
 	if len(errs.issues) > 0 {
 		return nil, &errs
 	}
@@ -585,6 +626,9 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		TLSPort:           tlsPort,
 		TLSCert:           tlsCert,
 		TLSKey:            tlsKey,
+		TLSCA:             tlsCA,
+		TLSNames:          tlsNames,
+		HTTPMode:          httpMode,
 	}, nil
 }
 

+ 37 - 0
server-go/internal/config/config_test.go

@@ -203,3 +203,40 @@ func TestLoadPollIntervalInvalido(t *testing.T) {
 		}
 	}
 }
+
+// FORK: the private CA and plain-HTTP mode settings.
+func TestPrivateCASettings(t *testing.T) {
+	base := func(kv ...string) map[string]string {
+		env := map[string]string{"AUTH_PASS": "segura-y-larga"}
+		for i := 0; i+1 < len(kv); i += 2 {
+			env[kv[i]] = kv[i+1]
+		}
+		return env
+	}
+	cfg, err := Load(base(), t.TempDir())
+	if err != nil || cfg.TLSCA || cfg.HTTPMode != "" {
+		t.Fatalf("defaults: %+v %v", cfg, err)
+	}
+	cfg, err = Load(base("NETPULSE_TLS_ENABLED", "1", "NETPULSE_TLS_CA", "1",
+		"NETPULSE_TLS_NAMES", " monitor-box.example.lan , 192.168.50.2 ,", "NETPULSE_HTTP_MODE", "migrate"), t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !cfg.TLSCA || cfg.HTTPMode != "migrate" ||
+		strings.Join(cfg.TLSNames, "|") != "monitor-box.example.lan|192.168.50.2" {
+		t.Fatalf("parsed %+v", cfg)
+	}
+	for name, env := range map[string]map[string]string{
+		"CA without TLS":          base("NETPULSE_TLS_CA", "1"),
+		"CA with a user cert":     base("NETPULSE_TLS_ENABLED", "1", "NETPULSE_TLS_CA", "1", "NETPULSE_TLS_CERT", "/c", "NETPULSE_TLS_KEY", "/k"),
+		"CA not 0 or 1":           base("NETPULSE_TLS_CA", "yes"),
+		"an unknown mode":         base("NETPULSE_HTTP_MODE", "strict"),
+		"a mode with a user cert": base("NETPULSE_TLS_ENABLED", "1", "NETPULSE_TLS_CERT", "/c", "NETPULSE_TLS_KEY", "/k", "NETPULSE_HTTP_MODE", "redirect"),
+		"a mode with self-signed": base("NETPULSE_TLS_ENABLED", "1", "NETPULSE_HTTP_MODE", "migrate"),
+		"a mode on-box":           base("NETPULSE_ONBOX", "1", "NETPULSE_HTTP_MODE", "migrate"),
+	} {
+		if _, err := Load(env, t.TempDir()); err == nil {
+			t.Errorf("%s: accepted", name)
+		}
+	}
+}

+ 23 - 8
server-go/internal/httpapi/agent.go

@@ -35,6 +35,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 	"github.com/gnacho/netpulse/server-go/internal/uninstall"
 	"github.com/gnacho/netpulse/server-go/internal/vercmp"
 )
@@ -259,6 +260,8 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	s.agents.Ingest(&p)
+	// FORK: which agents still report over plain HTTP (Settings > HTTPS).
+	s.noteAgentTransport(p.Router, auth.IsSecureRequest(r))
 	// Fase 18 (#452): persistir scans pasivos de vecinos si el payload trae
 	// datos wireless. Se guardan incluso si el payload no es "fresco" para no
 	// perder la muestra recién recibida.
@@ -454,15 +457,25 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	if s.cfg != nil && s.cfg.SSHKeyPath != "" {
 		sshKeyArg = " --ssh-key=" + s.cfg.SSHKeyPath
 	}
-	// #851: HTTPS exige pinning SPKI. On-box el server conoce su propio FP;
-	// detrás de un proxy TLS, install-agent.sh lo deriva del certificado.
-	fpArg := ""
-	if scheme == "https" && s.serverFP != "" {
-		fpArg = " --server-fp=" + s.serverFP
+	// FORK: with HTTPS on, the line points the agent at it and pins the
+	// root; the root travels inside the line - copied from the admin's own
+	// session - so the binary download, token included, is verified too.
+	caArg, fpArg := "", ""
+	if tr := tlsmode.AgentTrust(s.tlsMgr, s.fingerprint, server); tr.ServerURL != "" {
+		server = tr.ServerURL
+		pemEsc := strings.ReplaceAll(strings.TrimSpace(string(tr.CAPEM)), "\n", `\n`)
+		caArg = fmt.Sprintf("NPCA=$(mktemp) && printf '%%b' '%s\\n' > \"$NPCA\" && ", pemEsc)
+		fpArg = " --server-fp=" + tr.ServerFP
+	} else if tr.ServerFP != "" {
+		fpArg = " --server-fp=" + tr.ServerFP
+	}
+	curlCA := ""
+	if caArg != "" {
+		curlCA = ` --cacert "$NPCA"`
 	}
 	return fmt.Sprintf(
-		"curl -fsSL -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary=/tmp/netpulse-agent --host=%s --server=%s --slug=%s --token=%s%s%s",
-		token, server, slug, host, server, slug, token, sshKeyArg, fpArg)
+		"%scurl -fsSL%s -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary=/tmp/netpulse-agent --host=%s --server=%s --slug=%s --token=%s%s%s",
+		caArg, curlCA, token, server, slug, host, server, slug, token, fpArg, sshKeyArg)
 }
 
 // agentListItem: lo que ve la UI — NUNCA el token ni su hash.
@@ -820,7 +833,9 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	// y, si el SSH falla, se restaura el hash previo en kv — así el agente no
 	// se queda empujando un token que el servidor ya no acepta (401 eterno).
 	token, err := s.rotateAgentTokenAtomic(slug, func(t string) error {
-		_, runErr := s.pool.Run(host, reinstall.Script(slug, t, serverURL, reinstall.ServerFP(serverURL), reinstall.Digests()), 300*time.Second)
+		// FORK: with HTTPS on, the agent moves to it and pins the root.
+		trust := tlsmode.AgentTrust(s.tlsMgr, s.fingerprint, serverURL)
+		_, runErr := s.pool.Run(host, reinstall.Script(slug, t, serverURL, reinstall.ServerFP(serverURL), reinstall.Digests(), trust), 300*time.Second)
 		return runErr
 	})
 	if err != nil {

+ 4 - 0
server-go/internal/httpapi/auth.go

@@ -48,6 +48,10 @@ func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
 func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
 	auth.HandleLogout(s.db, s.secret, r)
 	w.Header().Set("Set-Cookie", auth.ClearSessionCookie)
+	// FORK: and the Secure one, which can only be deleted over HTTPS.
+	if auth.IsSecureRequest(r) {
+		w.Header().Add("Set-Cookie", auth.ClearSecureSessionCookie)
+	}
 	w.WriteHeader(http.StatusNoContent)
 }
 

+ 10 - 0
server-go/internal/httpapi/discovery.go

@@ -33,6 +33,8 @@ import (
 	"strconv"
 	"sync"
 	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 )
 
 // discoveryProbeV es la única versión de probe aceptada.
@@ -61,6 +63,11 @@ type discoveryResponse struct {
 	URL          string `json:"url"`
 	Autoenroll   bool   `json:"autoenroll"`
 	PairingToken string `json:"pairing_token,omitempty"`
+	// FORK: with HTTPS on, where to reach it and the key to pin. These are
+	// hints: nothing in a UDP reply is authenticated, so a receiver that
+	// pins ServerFP from here is trusting whoever answered first.
+	URLHTTPS string `json:"url_https,omitempty"`
+	ServerFP string `json:"server_fp,omitempty"`
 }
 
 // autoenrollTokenTTL: el token de red rota cuando su ts de generación
@@ -162,6 +169,9 @@ func (s *server) answerDiscovery(pc net.PacketConn, src net.Addr) {
 		URL:        fmt.Sprintf("http://%s:%d", local.IP.String(), port),
 		Autoenroll: s.autoenrollEnabled(),
 	}
+	if tr := tlsmode.AgentTrust(s.tlsMgr, nil, resp.URL); tr.ServerURL != "" {
+		resp.URLHTTPS, resp.ServerFP = tr.ServerURL, tr.ServerFP
+	}
 	if resp.Autoenroll {
 		tok, err := s.getAutoenrollToken()
 		if err != nil {

+ 47 - 0
server-go/internal/httpapi/discovery_test.go

@@ -6,6 +6,7 @@ package httpapi
 import (
 	"encoding/json"
 	"net"
+	"net/http"
 	"net/http/httptest"
 	"strconv"
 	"strings"
@@ -15,6 +16,8 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/tlscert"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 )
 
 // newDiscoveryTestServer: server mínimo con cfg configurable (autoenroll y
@@ -182,3 +185,47 @@ func TestAutoenrollTokenStableAndRotatable(t *testing.T) {
 		t.Fatal("checkAutoenrollToken debe rechazar con el flag apagado")
 	}
 }
+
+// FORK: with HTTPS on, the reply also says where HTTPS is and which key to
+// pin - as hints, since nothing in a UDP reply is authenticated - and never
+// sends a router to a loopback address.
+func TestDiscoveryAnswerCarriesHTTPSHints(t *testing.T) {
+	s := newDiscoveryTestServer(t, false)
+	ln, _ := net.Listen("tcp", "127.0.0.1:0")
+	port := ln.Addr().(*net.TCPAddr).Port
+	ln.Close()
+	m := tlsmode.New(tlsmode.Options{
+		DB: s.db, DataDir: t.TempDir(), Port: port,
+		NewServer: func(addr string, h http.Handler) *http.Server { return &http.Server{Addr: addr, Handler: h} },
+		CAOptions: func(o tlscert.CAOptions) tlscert.CAOptions {
+			o.Addrs = func() ([]net.IP, error) { return []net.IP{net.ParseIP("192.168.50.2")}, nil }
+			o.Hostname = func() (string, error) { return "monitor-box", nil }
+			o.SearchDomains = func() []string { return nil }
+			return o
+		},
+	})
+	if err := m.Start(http.NotFoundHandler()); err != nil {
+		t.Fatal(err)
+	}
+	defer m.Close()
+	s.tlsMgr = m
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	if resp := probeAndWait(t, addr); resp.URLHTTPS != "" || resp.ServerFP != "" {
+		t.Fatalf("HTTPS off, yet hints were sent: %+v", resp)
+	}
+	if err := m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	resp := probeAndWait(t, addr)
+	if resp.URLHTTPS != "https://192.168.50.2:"+strconv.Itoa(port) || resp.ServerFP != m.Fingerprint() {
+		t.Fatalf("hints: %+v", resp)
+	}
+	if resp.URL != "http://127.0.0.1:3457" {
+		t.Fatalf("the plain URL changed: %q", resp.URL)
+	}
+}

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

@@ -888,7 +888,6 @@ func TestSecurityHeaders(t *testing.T) {
 		"X-Frame-Options":           "DENY",
 		"Referrer-Policy":           "strict-origin-when-cross-origin",
 		"Permissions-Policy":        "geolocation=(), microphone=(), camera=()",
-		"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
 		"Content-Security-Policy":   "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'",
 	}
 	for k, v := range want {
@@ -896,6 +895,29 @@ func TestSecurityHeaders(t *testing.T) {
 			t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
 		}
 	}
+	// FORK: HSTS only on secure responses; plain HTTP never carries it.
+	if got := res.Header.Get("Strict-Transport-Security"); got != "" {
+		t.Errorf("plain HTTP response carried HSTS %q", got)
+	}
+}
+
+// FORK: behind a TLS-terminating proxy the server trusts (the test server
+// sets TRUST_PROXY), a request forwarded as https gets HSTS.
+func TestSecurityHeadersHSTSOnSecureRequests(t *testing.T) {
+	srv := makeTestServer(t)
+	req, err := http.NewRequest("GET", srv.URL+"/api/health", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	req.Header.Set("X-Forwarded-Proto", "https")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if got := res.Header.Get("Strict-Transport-Security"); got != "max-age=31536000" {
+		t.Errorf("HSTS on a secure request = %q, want max-age=31536000", got)
+	}
 }
 
 func TestSPAFallback(t *testing.T) {

+ 341 - 0
server-go/internal/httpapi/https_settings.go

@@ -0,0 +1,341 @@
+package httpapi
+
+// FORK: Settings > HTTPS - turning HTTPS on, choosing what plain HTTP may
+// still do, and handing out the private CA's root. See internal/tlsmode.
+//
+//	GET  /api/settings/https          (admin) state, and the agents still on HTTP
+//	POST /api/settings/https          (admin, password) {enabled?, mode?, force?}
+//	POST /api/settings/https/confirm  (admin, over HTTPS) {code}
+//	GET  /netpulse-ca.crt | .pem      (anyone) the root, for devices to install
+
+import (
+	"errors"
+	"net/http"
+	"net/url"
+	"slices"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/security"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
+)
+
+type agentTransport struct {
+	TLS   bool
+	At    time.Time
+	saved time.Time // when it was last written to kv
+}
+
+const (
+	agentTransportPrefix = "agent.transport."
+	// An agent silent for longer than this no longer counts as "still on
+	// HTTP": it is gone, or will show up again when it next reports.
+	agentTransportWindow = 24 * time.Hour
+	// Written to kv when the transport changes, and at most this often
+	// otherwise - not on every push.
+	agentTransportSaveEvery = time.Hour
+)
+
+// noteAgentTransport records how an agent's push arrived. It is kept in kv
+// too: the check before refusing plain HTTP to agents must not forget them
+// because the server restarted.
+func (s *server) noteAgentTransport(slug string, overTLS bool) {
+	now := time.Now()
+	t := agentTransport{TLS: overTLS, At: now}
+	if v, ok := s.agentTransport.Load(slug); ok {
+		prev := v.(agentTransport)
+		t.saved = prev.saved
+		if prev.TLS != overTLS {
+			t.saved = time.Time{}
+		}
+	}
+	if s.db != nil && now.Sub(t.saved) >= agentTransportSaveEvery {
+		v := "http"
+		if overTLS {
+			v = "tls"
+		}
+		if _, err := s.db.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+			agentTransportPrefix+slug, v+" "+strconv.FormatInt(now.Unix(), 10)); err == nil {
+			t.saved = now
+		}
+	}
+	s.agentTransport.Store(slug, t)
+}
+
+// agentOnHTTP is an agent and the last time it reported.
+type agentOnHTTP struct {
+	Slug     string    `json:"slug"`
+	LastSeen time.Time `json:"lastSeen"`
+}
+
+// agentsByTransport lists the agents whose last push came over TLS (tls) or
+// over plain HTTP (!tls): recent ones, that still exist.
+func (s *server) agentsByTransport(tls bool) []agentOnHTTP {
+	last := map[string]agentTransport{}
+	if s.db != nil {
+		rows, err := s.db.Query("SELECT key, value FROM kv WHERE key LIKE ?", agentTransportPrefix+"%")
+		if err == nil {
+			for rows.Next() {
+				var k, v string
+				if rows.Scan(&k, &v) != nil {
+					continue
+				}
+				kind, ts, _ := strings.Cut(v, " ")
+				sec, err := strconv.ParseInt(ts, 10, 64)
+				if err != nil {
+					continue
+				}
+				last[strings.TrimPrefix(k, agentTransportPrefix)] = agentTransport{TLS: kind == "tls", At: time.Unix(sec, 0)}
+			}
+			rows.Close()
+		}
+	}
+	s.agentTransport.Range(func(k, v any) bool {
+		last[k.(string)] = v.(agentTransport)
+		return true
+	})
+	// Never nil: the page reads the list's length, and a JSON null there
+	// took the whole Settings page down.
+	out := []agentOnHTTP{}
+	for slug, t := range last {
+		if t.TLS != tls || time.Since(t.At) > agentTransportWindow || !s.agentExists(slug) {
+			continue
+		}
+		out = append(out, agentOnHTTP{Slug: slug, LastSeen: t.At})
+	}
+	slices.SortFunc(out, func(a, b agentOnHTTP) int { return strings.Compare(a.Slug, b.Slug) })
+	return out
+}
+
+func (s *server) agentsOnHTTP() []agentOnHTTP { return s.agentsByTransport(false) }
+
+// agentExists: a deleted agent's token is gone.
+func (s *server) agentExists(slug string) bool {
+	if s.db == nil {
+		return true
+	}
+	var v string
+	return s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&v) == nil
+}
+
+// hsts decides the Strict-Transport-Security header (see security.Middleware:
+// it is per host, not per port).
+func (s *server) hsts(r *http.Request) string {
+	secure := auth.IsSecureRequest(r)
+	// Once the private CA exists the manager decides - with HTTPS off too,
+	// when the plain port's TLS side answers max-age=0.
+	if s.tlsMgr != nil && s.tlsMgr.Available() && s.tlsMgr.CA() != nil {
+		return s.tlsMgr.HSTS(secure)
+	}
+	switch {
+	case r.TLS != nil && s.cfg != nil && s.cfg.Onbox:
+		// On-box, PORT itself is TLS: no plain port is left to break.
+		return security.HSTS
+	case r.TLS == nil && secure:
+		// Behind a TLS-terminating proxy the server trusts, which serves
+		// every port of the name.
+		return security.HSTS
+	default:
+		// The extra TLS listener while PORT still serves plain HTTP: a
+		// policy from it would make browsers rewrite http://name:PORT to
+		// https://name:PORT, where nothing speaks TLS.
+		return ""
+	}
+}
+
+func (s *server) registerHTTPS(mux *http.ServeMux) {
+	if s.tlsMgr == nil {
+		return
+	}
+	mux.Handle("GET /api/settings/https", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSStatus)))
+	mux.Handle("POST /api/settings/https", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSChange)))
+	mux.Handle("POST /api/settings/https/confirm", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSConfirm)))
+	mux.Handle("POST /api/settings/https/renew", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSRenew)))
+	mux.HandleFunc("GET /netpulse-ca.crt", s.handleCARoot(false))
+	mux.HandleFunc("GET /netpulse-ca.pem", s.handleCARoot(true))
+}
+
+type httpsStatus struct {
+	tlsmode.Status
+	AgentsOnHTTP []agentOnHTTP `json:"agentsOnHttp"`
+}
+
+func (s *server) handleHTTPSStatus(w http.ResponseWriter, _ *http.Request) {
+	writeJSON(w, http.StatusOK, httpsStatus{Status: s.tlsMgr.Status(), AgentsOnHTTP: s.agentsOnHTTP()})
+}
+
+// handleHTTPSChange turns HTTPS on or off and requests a mode. Every change
+// asks for the admin's password again: transport security is not something
+// a stolen session cookie alone should be able to change, in either
+// direction.
+func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
+	me := auth.UserFromContext(r.Context())
+	var body struct {
+		Enabled  *bool   `json:"enabled"`
+		Mode     *string `json:"mode"`
+		Force    bool    `json:"force"`
+		Password string  `json:"password"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "password" }`)
+		return
+	}
+	// Counted as sign-in attempts: a stolen session must not be a way to
+	// guess the password without the sign-in's lockout.
+	if limited, retry := auth.LoginRateLimited(s.db, r); limited {
+		writeJSON(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "retryAfterSec": retry})
+		return
+	}
+	if me == nil || !s.checkOwnPassword(me.ID, body.Password) {
+		auth.RegisterLoginFail(s.db, r)
+		writeError(w, http.StatusUnauthorized, "invalid_credentials", "the password is not correct")
+		return
+	}
+	by := me.Username + " from " + auth.ClientIP(r)
+	if body.Enabled != nil && !*body.Enabled && !body.Force {
+		// Agents already moved to HTTPS pin its key and have no way back to
+		// plain HTTP by themselves: turning it off cuts them off.
+		if moved := s.agentsByTransport(true); len(moved) > 0 && s.tlsMgr.Enabled() {
+			writeJSON(w, http.StatusConflict, map[string]any{
+				"error":   "agents_on_https",
+				"message": "these agents report over HTTPS and would stop reporting",
+				"agents":  moved,
+			})
+			return
+		}
+	}
+	if body.Enabled != nil {
+		if err := s.tlsMgr.SetEnabled(*body.Enabled, by); err != nil {
+			writeHTTPSError(w, err)
+			return
+		}
+	}
+	resp := map[string]any{}
+	if body.Mode != nil {
+		mode, err := tlsmode.ParseMode(*body.Mode)
+		if err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
+			return
+		}
+		if mode == tlsmode.Redirect && !body.Force {
+			if left := s.agentsOnHTTP(); len(left) > 0 {
+				writeJSON(w, http.StatusConflict, map[string]any{
+					"error":   "agents_on_http",
+					"message": "these agents still report over plain HTTP and would stop reporting",
+					"agents":  left,
+				})
+				return
+			}
+		}
+		code, expires, err := s.tlsMgr.RequestMode(mode, by)
+		if err != nil {
+			writeHTTPSError(w, err)
+			return
+		}
+		if code != "" {
+			resp["pending"] = mode
+			resp["expires"] = expires
+			resp["confirmUrl"] = s.confirmURL(r, code)
+		}
+	}
+	resp["status"] = s.tlsMgr.Status()
+	writeJSON(w, http.StatusOK, resp)
+}
+
+// confirmURL is the HTTPS page the change must be confirmed from.
+func (s *server) confirmURL(r *http.Request, code string) string {
+	u := &url.URL{Path: "/settings", RawQuery: url.Values{"tab": {"https"}, "confirm": {code}}.Encode()}
+	req := r.Clone(r.Context())
+	req.URL = u
+	if target, ok := s.tlsMgr.RedirectTarget(req); ok {
+		return target
+	}
+	return u.String()
+}
+
+func (s *server) handleHTTPSConfirm(w http.ResponseWriter, r *http.Request) {
+	me := auth.UserFromContext(r.Context())
+	var body struct {
+		Code string `json:"code"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", `expected { "code": "..." }`)
+		return
+	}
+	by := "unknown"
+	if me != nil {
+		by = me.Username + " from " + auth.ClientIP(r)
+	}
+	if _, err := s.tlsMgr.Confirm(body.Code, auth.IsSecureRequest(r), by); err != nil {
+		writeHTTPSError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"status": s.tlsMgr.Status()})
+}
+
+// handleHTTPSRenew re-checks the certificate against the host's current
+// addresses and names. No password: it changes nothing an admin could not
+// already get by waiting for the periodic check - same root, same pins.
+func (s *server) handleHTTPSRenew(w http.ResponseWriter, r *http.Request) {
+	by := "unknown"
+	if me := auth.UserFromContext(r.Context()); me != nil {
+		by = me.Username + " from " + auth.ClientIP(r)
+	}
+	issued, err := s.tlsMgr.Renew(by)
+	if err != nil {
+		writeHTTPSError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"issued": issued, "status": s.tlsMgr.Status()})
+}
+
+func writeHTTPSError(w http.ResponseWriter, err error) {
+	switch {
+	case errors.Is(err, tlsmode.ErrLocked):
+		writeError(w, http.StatusConflict, "locked", err.Error())
+	case errors.Is(err, tlsmode.ErrNotFull):
+		writeError(w, http.StatusConflict, "not_full", err.Error())
+	case errors.Is(err, tlsmode.ErrConfirm):
+		writeError(w, http.StatusGone, "expired", err.Error())
+	default:
+		writeError(w, http.StatusBadRequest, "https_error", err.Error())
+	}
+}
+
+// checkOwnPassword checks the signed-in user's password, as changing it does.
+func (s *server) checkOwnPassword(userID int64, password string) bool {
+	if password == "" {
+		return false
+	}
+	var hash string
+	if err := s.db.QueryRow("SELECT pass_hash FROM users WHERE id = ?", userID).Scan(&hash); err != nil {
+		return false
+	}
+	return auth.CheckPassword(password, hash)
+}
+
+// handleCARoot serves the root certificate. It is public by nature - devices
+// need it before they can trust HTTPS - and the page that links it tells the
+// admin to compare its fingerprint with the one the server logged.
+func (s *server) handleCARoot(asPEM bool) http.HandlerFunc {
+	return func(w http.ResponseWriter, _ *http.Request) {
+		ca := s.tlsMgr.CA()
+		if ca == nil || !s.tlsMgr.Enabled() {
+			http.NotFound(w, nil)
+			return
+		}
+		if asPEM {
+			w.Header().Set("Content-Type", "application/x-pem-file")
+			w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.pem"`)
+			_, _ = w.Write(ca.RootPEM())
+			return
+		}
+		// DER with this type is what Android and iOS offer to install.
+		w.Header().Set("Content-Type", "application/x-x509-ca-cert")
+		w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.crt"`)
+		_, _ = w.Write(ca.RootDER())
+	}
+}

+ 445 - 0
server-go/internal/httpapi/https_settings_test.go

@@ -0,0 +1,445 @@
+package httpapi_test
+
+// FORK: tests for Settings > HTTPS (https_settings.go). Addresses are from
+// the private and documentation ranges, names invented.
+
+import (
+	"crypto/hmac"
+	"crypto/sha256"
+	"crypto/tls"
+	"crypto/x509"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"os/exec"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+	"github.com/gnacho/netpulse/server-go/internal/tlscert"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
+)
+
+func makeHTTPSTestServer(t *testing.T) (*agentTestServer, *tlsmode.Manager) {
+	t.Helper()
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatal(err)
+	}
+	ln, _ := net.Listen("tcp", "127.0.0.1:0")
+	port := ln.Addr().(*net.TCPAddr).Port
+	ln.Close()
+	mgr := tlsmode.New(tlsmode.Options{
+		DB: d, DataDir: dataDir, Port: port,
+		NewServer: func(addr string, h http.Handler) *http.Server { return &http.Server{Addr: addr, Handler: h} },
+		CAOptions: func(o tlscert.CAOptions) tlscert.CAOptions {
+			o.Addrs = func() ([]net.IP, error) { return []net.IP{net.ParseIP("192.168.50.2")}, nil }
+			o.Hostname = func() (string, error) { return "monitor-box", nil }
+			o.SearchDomains = func() []string { return nil }
+			return o
+		},
+	})
+	reg := adapters.NewAgentRegistry(90 * time.Second)
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Secret: secret,
+		Hub:    sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Agents: reg, Started: time.Now(), TLS: mgr,
+		ServerFPFunc: mgr.Fingerprint,
+	})
+	if err := mgr.Start(handler); err != nil {
+		t.Fatal(err)
+	}
+	srv := httptest.NewServer(mgr.PlainHandler(handler))
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if status != 204 {
+		t.Fatalf("login: %d", status)
+	}
+	t.Cleanup(func() {
+		mgr.Close()
+		srv.Close()
+		d.Close()
+	})
+	return &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}, mgr
+}
+
+// httpsCall makes an admin request; secure marks it as having arrived over
+// HTTPS through a proxy the server trusts.
+func httpsCall(t *testing.T, ts *agentTestServer, method, path, body string, secure bool) (int, map[string]any) {
+	t.Helper()
+	req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	if secure {
+		req.Header.Set("X-Forwarded-Proto", "https")
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer res.Body.Close()
+	var out map[string]any
+	data, _ := io.ReadAll(res.Body)
+	_ = json.Unmarshal(data, &out)
+	return res.StatusCode, out
+}
+
+func TestEveryHTTPSChangeAsksForThePassword(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	for _, pw := range []string{"", "not-the-password"} {
+		if st, _ := httpsCall(t, ts, "POST", "/api/settings/https",
+			fmt.Sprintf(`{"enabled":true,"password":%q}`, pw), true); st != http.StatusUnauthorized {
+			t.Fatalf("password %q: status %d, want 401", pw, st)
+		}
+	}
+	if mgr.Enabled() {
+		t.Fatal("HTTPS was turned on without the password")
+	}
+	st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":true,"password":"test123456"}`, true)
+	if st != http.StatusOK || !mgr.Enabled() {
+		t.Fatalf("enable: %d %v", st, body)
+	}
+	_, status := httpsCall(t, ts, "GET", "/api/settings/https", "", true)
+	if status["rootSha256"] == "" || status["fingerprint"] == "" || status["mode"] != "full" {
+		t.Fatalf("status: %v", status)
+	}
+}
+
+func TestTheRootIsServedToAnyone(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	res, _ := http.Get(ts.URL + "/netpulse-ca.crt")
+	res.Body.Close()
+	if res.StatusCode != http.StatusNotFound {
+		t.Fatalf("with HTTPS off: %d, want 404", res.StatusCode)
+	}
+	if err := mgr.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	res, err := http.Get(ts.URL + "/netpulse-ca.crt") // no session
+	if err != nil {
+		t.Fatal(err)
+	}
+	der, _ := io.ReadAll(res.Body)
+	res.Body.Close()
+	if res.Header.Get("Content-Type") != "application/x-x509-ca-cert" {
+		t.Fatalf("content type %q", res.Header.Get("Content-Type"))
+	}
+	root, err := x509.ParseCertificate(der)
+	if err != nil || !root.IsCA || tlscert.Fingerprint(root) != mgr.Fingerprint() {
+		t.Fatalf("served root is not the CA agents pin: %v", err)
+	}
+}
+
+func TestAStricterModeIsConfirmedOverHTTPSOnly(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_ = mgr.SetEnabled(true, "test")
+	st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"migrate","password":"test123456"}`, false)
+	if st != http.StatusOK || body["pending"] != "migrate" || mgr.Mode() != tlsmode.Full {
+		t.Fatalf("request: %d %v, mode %s", st, body, mgr.Mode())
+	}
+	confirmURL, _ := body["confirmUrl"].(string)
+	if !strings.HasPrefix(confirmURL, "https://") || !strings.Contains(confirmURL, "confirm=") {
+		t.Fatalf("confirmUrl %q", confirmURL)
+	}
+	code := confirmURL[strings.Index(confirmURL, "confirm=")+len("confirm="):]
+	if i := strings.IndexByte(code, '&'); i >= 0 {
+		code = code[:i]
+	}
+	// Over plain HTTP the confirmation is refused - and in fact the request
+	// is already refused as a session call, even before the mode applies.
+	if st, _ := httpsCall(t, ts, "POST", "/api/settings/https/confirm", fmt.Sprintf(`{"code":%q}`, code), false); st == http.StatusOK {
+		t.Fatal("confirmed over plain HTTP")
+	}
+	if st, body := httpsCall(t, ts, "POST", "/api/settings/https/confirm", fmt.Sprintf(`{"code":%q}`, code), true); st != http.StatusOK || mgr.Mode() != tlsmode.Migrate {
+		t.Fatalf("confirm over HTTPS: %d %v, mode %s", st, body, mgr.Mode())
+	}
+	// Now plain HTTP refuses the session call outright.
+	if st, _ := httpsCall(t, ts, "GET", "/api/settings/https", "", false); st != http.StatusForbidden {
+		t.Fatalf("a session call over plain HTTP in migrate: %d, want 403", st)
+	}
+}
+
+// Redirect would cut off agents still on plain HTTP; the page says which, and
+// only an explicit force goes ahead.
+func TestRedirectWaitsForAgentsOnHTTP(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_ = mgr.SetEnabled(true, "test")
+	_, token, _ := createAgentToken(t, ts, "test-router")
+	res := ingest(t, ts, token, "192.0.2.50", validPayloadFor("test-router"))
+	res.Body.Close()
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest: %d", res.StatusCode)
+	}
+	st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"redirect","password":"test123456"}`, true)
+	if st != http.StatusConflict || body["error"] != "agents_on_http" || !strings.Contains(fmt.Sprint(body["agents"]), "test-router") {
+		t.Fatalf("redirect with an agent on HTTP: %d %v", st, body)
+	}
+	st, body = httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"redirect","force":true,"password":"test123456"}`, true)
+	if st != http.StatusOK || body["pending"] != "redirect" {
+		t.Fatalf("forced: %d %v", st, body)
+	}
+}
+
+func validPayloadFor(slug string) string {
+	return fmt.Sprintf(`{"router":%q,"ts":%d,"version":"test","data":{}}`, slug, time.Now().Unix())
+}
+
+// The confirmation arrives over the real HTTPS listener - the one it is
+// meant to prove works - and applies the mode.
+func TestAModeIsConfirmedThroughTheRealHTTPSListener(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	if err := mgr.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	code, _, err := mgr.RequestMode(tlsmode.Migrate, "test")
+	if err != nil {
+		t.Fatal(err)
+	}
+	pool := x509.NewCertPool()
+	pool.AppendCertsFromPEM(mgr.CA().RootPEM())
+	client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{
+		TLSClientConfig: &tls.Config{RootCAs: pool},
+	}}
+	url := fmt.Sprintf("https://127.0.0.1:%d/api/settings/https/confirm", mgr.Status().Port)
+	var res *http.Response
+	for i := 0; i < 50; i++ { // the listener starts in a goroutine
+		req, _ := http.NewRequest("POST", url, strings.NewReader(fmt.Sprintf(`{"code":%q}`, code)))
+		req.Header.Set("Content-Type", "application/json")
+		req.Header.Set("Cookie", "session="+ts.cookie)
+		if res, err = client.Do(req); err == nil {
+			break
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != http.StatusOK || mgr.Mode() != tlsmode.Migrate {
+		t.Fatalf("confirm over the HTTPS listener: %d, mode %s", res.StatusCode, mgr.Mode())
+	}
+}
+
+// Agents already on HTTPS would be cut off by turning it off; the page says
+// which, and only an explicit force goes ahead. Turning it off in a stricter
+// mode is refused outright.
+func TestTurningHTTPSOffWarnsAboutAgentsOnIt(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_ = mgr.SetEnabled(true, "test")
+	_, token, _ := createAgentToken(t, ts, "test-router")
+	req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(validPayloadFor("test-router")))
+	res := ingestSecure(t, req, token)
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest over https: %d", res.StatusCode)
+	}
+	st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"password":"test123456"}`, true)
+	if st != http.StatusConflict || body["error"] != "agents_on_https" {
+		t.Fatalf("turning off with an agent on HTTPS: %d %v", st, body)
+	}
+	code, _, _ := mgr.RequestMode(tlsmode.Migrate, "test")
+	_, _ = mgr.Confirm(code, true, "test")
+	st, body = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"force":true,"password":"test123456"}`, true)
+	if st != http.StatusConflict || body["error"] != "not_full" {
+		t.Fatalf("turning off in migrate: %d %v", st, body)
+	}
+	_, _, _ = mgr.RequestMode(tlsmode.Full, "test")
+	st, _ = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"force":true,"password":"test123456"}`, true)
+	if st != http.StatusOK || mgr.Enabled() {
+		t.Fatalf("forced off from full: %d, enabled %v", st, mgr.Enabled())
+	}
+}
+
+// ingestSecure pushes as an agent would through a trusted TLS proxy.
+func ingestSecure(t *testing.T, req *http.Request, token string) *http.Response {
+	t.Helper()
+	body, _ := io.ReadAll(req.Body)
+	req.Body = io.NopCloser(strings.NewReader(string(body)))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("X-Forwarded-Proto", "https")
+	req.Header.Set("X-Forwarded-For", "192.0.2.51")
+	req.Header.Set("Authorization", "Bearer "+token)
+	mac := hmac.New(sha256.New, []byte(token))
+	mac.Write(body)
+	req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	return res
+}
+
+// In migrate, the admin pairing token is refused over plain HTTP, and
+// accepted over HTTPS.
+func TestMigrateRefusesThePairingTokenOverPlainHTTP(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_ = mgr.SetEnabled(true, "test")
+	code, _, _ := mgr.RequestMode(tlsmode.Migrate, "test")
+	_, _ = mgr.Confirm(code, true, "test")
+	var tok string
+	if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'pairing.token'").Scan(&tok); err != nil {
+		// Created on first use.
+		tok = "11111111-2222-4333-8444-555555555555"
+		if _, err := ts.db.Exec("INSERT INTO kv (key, value) VALUES ('pairing.token', ?)", tok); err != nil {
+			t.Fatal(err)
+		}
+	}
+	pair := func(secure bool) int {
+		req, _ := http.NewRequest("POST", ts.URL+"/api/agents/pair",
+			strings.NewReader(fmt.Sprintf(`{"pairing_token":%q,"slug":"new-router"}`, tok)))
+		req.Header.Set("Content-Type", "application/json")
+		if secure {
+			req.Header.Set("X-Forwarded-Proto", "https")
+		}
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatal(err)
+		}
+		res.Body.Close()
+		return res.StatusCode
+	}
+	if st := pair(false); st != http.StatusForbidden {
+		t.Fatalf("over plain HTTP: %d, want 403", st)
+	}
+	if st := pair(true); st != http.StatusCreated {
+		t.Fatalf("over HTTPS: %d, want 201", st)
+	}
+}
+
+// Wrong passwords here count towards the sign-in lockout.
+func TestThePasswordCheckIsRateLimited(t *testing.T) {
+	ts, _ := makeHTTPSTestServer(t)
+	last := 0
+	for i := 0; i < 6; i++ {
+		last, _ = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":true,"password":"wrong"}`, true)
+	}
+	if last != http.StatusTooManyRequests {
+		t.Fatalf("after six wrong passwords: %d, want 429", last)
+	}
+}
+
+// A sign-in over HTTPS gets its own Secure cookie, so it does not replace -
+// and cannot lock out - a sign-in over plain HTTP on the same host.
+func TestHTTPSAndHTTPSignInsKeepTheirOwnCookies(t *testing.T) {
+	ts, _ := makeHTTPSTestServer(t)
+	_, _, plainSet := loginCookie(t, ts.URL, "admin", "test123456")
+	if !strings.HasPrefix(plainSet, "session=") || strings.Contains(plainSet, "Secure") {
+		t.Fatalf("plain sign-in: %q", plainSet)
+	}
+	_, _, secureSet := loginCookie(t, ts.URL, "admin", "test123456", "X-Forwarded-Proto", "https")
+	if !strings.HasPrefix(secureSet, "__Host-session=") || !strings.Contains(secureSet, "; Secure") {
+		t.Fatalf("secure sign-in: %q", secureSet)
+	}
+	secureVal := strings.SplitN(strings.TrimPrefix(secureSet, "__Host-session="), ";", 2)[0]
+
+	// Both cookies at once, as a browser sends them over HTTPS.
+	req, _ := http.NewRequest("GET", ts.URL+"/api/auth/me", nil)
+	req.Header.Set("Cookie", "session=stale.value; __Host-session="+secureVal)
+	req.Header.Set("X-Forwarded-Proto", "https")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("the Secure session was not accepted: %d", res.StatusCode)
+	}
+
+	// Signing out over HTTPS clears both, and ends the session.
+	req, _ = http.NewRequest("POST", ts.URL+"/api/auth/logout", nil)
+	req.Header.Set("Cookie", "__Host-session="+secureVal)
+	req.Header.Set("X-Forwarded-Proto", "https")
+	res, err = http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	cleared := strings.Join(res.Header.Values("Set-Cookie"), " | ")
+	if !strings.Contains(cleared, "session=; Path=/") || !strings.Contains(cleared, "__Host-session=; Path=/; HttpOnly; Secure") {
+		t.Fatalf("logout cleared: %s", cleared)
+	}
+	req, _ = http.NewRequest("GET", ts.URL+"/api/auth/me", nil)
+	req.Header.Set("Cookie", "__Host-session="+secureVal)
+	req.Header.Set("X-Forwarded-Proto", "https")
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("the session outlived logout: %d", res.StatusCode)
+	}
+}
+
+// The install line carries the root and the pin once HTTPS is on, and the
+// printf that writes the root reproduces it exactly.
+func TestTheInstallLineCarriesTheRoot(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_, _, before := createAgentToken(t, ts, "test-router")
+	if strings.Contains(before, "NPCA") || strings.Contains(before, "--server-fp") {
+		t.Fatalf("with HTTPS off the line changed: %s", before)
+	}
+	if err := mgr.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	_, _, line := createAgentToken(t, ts, "test-router-2")
+	wantServer := fmt.Sprintf("--server=https://192.168.50.2:%d", mgr.Status().Port)
+	for _, want := range []string{`--cacert "$NPCA"`, "NPCA=$(mktemp)", "--server-fp=" + mgr.Fingerprint(), wantServer} {
+		if !strings.Contains(line, want) {
+			t.Fatalf("install line lacks %q:\n%s", want, line)
+		}
+	}
+	dir := t.TempDir()
+	// Up to the download: create the file, write the root, show where.
+	upTo := line[:strings.Index(line, " && curl")]
+	upTo = strings.Replace(upTo, "$(mktemp)", dir+"/ca.pem", 1)
+	if out, err := exec.Command("sh", "-c", upTo).CombinedOutput(); err != nil {
+		t.Fatalf("%v: %s", err, out)
+	}
+	got, _ := os.ReadFile(dir + "/ca.pem")
+	if string(got) != string(mgr.CA().RootPEM()) {
+		t.Fatalf("the line writes:\n%s\nwant:\n%s", got, mgr.CA().RootPEM())
+	}
+}
+
+// With no agent reporting, the list is empty, never null: the page reads its
+// length, and a null took the whole Settings page down.
+func TestTheAgentListIsNeverNull(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	_ = mgr.SetEnabled(true, "test")
+	req, _ := http.NewRequest("GET", ts.URL+"/api/settings/https", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	body, _ := io.ReadAll(res.Body)
+	res.Body.Close()
+	if !strings.Contains(string(body), `"agentsOnHttp":[]`) {
+		t.Fatalf("status: %s", body)
+	}
+}

+ 67 - 0
server-go/internal/httpapi/https_transport_test.go

@@ -0,0 +1,67 @@
+package httpapi
+
+// FORK: tests for the record of how each agent reports (https_settings.go).
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// panelTestServer is the minimum the HTTPS tests read: a database and the
+// agent registry. (From the fork's netgrip_panel_test.go helper, kept here so
+// the HTTPS tests do not drag in the whole NetGrip-panel integration.)
+func panelTestServer(t *testing.T) *server {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	return &server{db: d, agents: adapters.NewAgentRegistry(90 * time.Second)}
+}
+
+func TestAgentsOnHTTPSurviveARestartAndForgetTheDeleted(t *testing.T) {
+	s := panelTestServer(t)
+	for _, slug := range []string{"router-a", "router-b", "router-c"} {
+		if _, err := s.db.Exec("INSERT INTO kv (key, value) VALUES (?, 'h')", agentTokenKey(slug)); err != nil {
+			t.Fatal(err)
+		}
+	}
+	s.noteAgentTransport("router-a", false)
+	s.noteAgentTransport("router-b", true)
+	s.noteAgentTransport("router-c", false)
+	// A later push over the other transport is what counts.
+	s.noteAgentTransport("router-c", true)
+
+	// A restarted server - same database, empty memory - still knows.
+	restarted := &server{db: s.db}
+	got := restarted.agentsOnHTTP()
+	if len(got) != 1 || got[0].Slug != "router-a" {
+		t.Fatalf("after a restart, on HTTP: %+v", got)
+	}
+	if tls := restarted.agentsByTransport(true); len(tls) != 2 {
+		t.Fatalf("after a restart, on HTTPS: %+v", tls)
+	}
+
+	// A deleted agent drops out.
+	if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey("router-a")); err != nil {
+		t.Fatal(err)
+	}
+	if got := restarted.agentsOnHTTP(); len(got) != 0 {
+		t.Fatalf("a deleted agent is still listed: %+v", got)
+	}
+}
+
+func TestASilentAgentDropsOut(t *testing.T) {
+	s := panelTestServer(t)
+	if _, err := s.db.Exec("INSERT INTO kv (key, value) VALUES (?, 'h')", agentTokenKey("router-a")); err != nil {
+		t.Fatal(err)
+	}
+	s.agentTransport.Store("router-a", agentTransport{TLS: false, At: time.Now().Add(-agentTransportWindow - time.Minute)})
+	if got := s.agentsOnHTTP(); len(got) != 0 {
+		t.Fatalf("an agent silent for over a day is listed: %+v", got)
+	}
+}

+ 235 - 0
server-go/internal/httpapi/pair_hello_test.go

@@ -0,0 +1,235 @@
+package httpapi_test
+
+// FORK: end to end tests for proving the server's key at pairing - the real
+// handler on a real TLS listener, and the agent's runtime.ProveServerKey on
+// the other end.
+
+import (
+	"context"
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/tls"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/hex"
+	"fmt"
+	"io"
+	"math/big"
+	"net"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	agentruntime "github.com/gnacho/netpulse/agent/runtime"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+const testPairingToken = "11111111-2222-4333-8444-555555555555"
+
+// ownCert is a certificate of its own for a test server: httptest's servers
+// all share one, which would make a "different key" test vacuous.
+func ownCert(t *testing.T) (tls.Certificate, string) {
+	t.Helper()
+	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	serial, _ := rand.Int(rand.Reader, big.NewInt(1<<62))
+	tmpl := &x509.Certificate{
+		SerialNumber: serial,
+		Subject:      pkix.Name{CommonName: "test"},
+		NotBefore:    time.Now().Add(-time.Hour),
+		NotAfter:     time.Now().Add(time.Hour),
+		KeyUsage:     x509.KeyUsageDigitalSignature,
+		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		IPAddresses:  []net.IP{net.ParseIP("127.0.0.1")},
+	}
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c, _ := x509.ParseCertificate(der)
+	sum := sha256.Sum256(c.RawSubjectPublicKeyInfo)
+	return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: k}, hex.EncodeToString(sum[:])
+}
+
+// pairServer is the real API on a TLS listener with a key of its own, which
+// is also the key it hands to agents. bodies records every request body.
+type pairServer struct {
+	*httptest.Server
+	fp     string
+	mu     sync.Mutex
+	bodies []string
+}
+
+func newPairServer(t *testing.T) *pairServer {
+	t.Helper()
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { d.Close() })
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := d.Exec("INSERT INTO kv (key, value) VALUES ('pairing.token', ?)", testPairingToken); err != nil {
+		t.Fatal(err)
+	}
+	cert, fp := ownCert(t)
+	ps := &pairServer{fp: fp}
+	api := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Secret: secret,
+		Hub:      sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Agents:   adapters.NewAgentRegistry(0),
+		Started:  time.Now(),
+		ServerFP: fp,
+	})
+	ps.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		b, _ := io.ReadAll(r.Body)
+		ps.mu.Lock()
+		ps.bodies = append(ps.bodies, string(b))
+		ps.mu.Unlock()
+		r.Body = io.NopCloser(strings.NewReader(string(b)))
+		api.ServeHTTP(w, r)
+	}))
+	ps.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
+	ps.StartTLS()
+	t.Cleanup(ps.Close)
+	return ps
+}
+
+func TestProveServerKeyLearnsTheServedKey(t *testing.T) {
+	ps := newPairServer(t)
+	fp, err := agentruntime.ProveServerKey(ps.URL, testPairingToken)
+	if err != nil {
+		t.Fatalf("ProveServerKey: %v", err)
+	}
+	if fp != ps.fp {
+		t.Fatalf("learned %s, the server serves %s", fp, ps.fp)
+	}
+	// The pairing token never went to the server on this connection.
+	ps.mu.Lock()
+	defer ps.mu.Unlock()
+	for _, b := range ps.bodies {
+		if strings.Contains(b, testPairingToken) {
+			t.Fatalf("the pairing token was sent: %s", b)
+		}
+	}
+}
+
+func TestProveServerKeyRefusesAServerWithoutTheToken(t *testing.T) {
+	ps := newPairServer(t)
+	if _, err := agentruntime.ProveServerKey(ps.URL, "not-the-token"); err == nil {
+		t.Fatal("a server that does not know the agent's token was accepted")
+	}
+}
+
+// A man in the middle relays the hello to the real server and returns its
+// genuine answer - over a connection that presents the middle's own key,
+// with or without the real server's certificate attached to its chain.
+func TestProveServerKeyRefusesARelayedProof(t *testing.T) {
+	for _, attachReal := range []bool{false, true} {
+		t.Run(fmt.Sprintf("real certificate attached=%v", attachReal), func(t *testing.T) {
+			relayedProof(t, attachReal)
+		})
+	}
+}
+
+func relayedProof(t *testing.T, attachReal bool) {
+	ps := newPairServer(t)
+	relay := &http.Client{Transport: &http.Transport{
+		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // the attacker's own client
+	}}
+	middleCert, _ := ownCert(t)
+	middle := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		req, _ := http.NewRequest(r.Method, ps.URL+r.URL.Path, r.Body)
+		req.Header = r.Header.Clone()
+		res, err := relay.Do(req)
+		if err != nil {
+			http.Error(w, err.Error(), http.StatusBadGateway)
+			return
+		}
+		defer res.Body.Close()
+		w.WriteHeader(res.StatusCode)
+		io.Copy(w, res.Body)
+	}))
+	if attachReal {
+		middleCert.Certificate = append(middleCert.Certificate, ps.TLS.Certificates[0].Certificate[0])
+	}
+	middle.TLS = &tls.Config{Certificates: []tls.Certificate{middleCert}}
+	middle.StartTLS()
+	defer middle.Close()
+
+	_, err := agentruntime.ProveServerKey(middle.URL, testPairingToken)
+	if err == nil || !strings.Contains(err.Error(), "intercepting") {
+		t.Fatalf("a relayed proof was accepted or refused for the wrong reason: %v", err)
+	}
+}
+
+// Over plain HTTP there is no chain to bind the proof to.
+func TestPairHelloIsRefusedOverPlainHTTP(t *testing.T) {
+	ts := makeTestServer(t)
+	res, err := http.Post(ts.URL+"/api/agents/pair/hello", "application/json",
+		strings.NewReader(`{"nonce":"`+strings.Repeat("ab", 32)+`"}`))
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("status = %d, want 400", res.StatusCode)
+	}
+	if _, err := agentruntime.ProveServerKey(ts.URL, testPairingToken); err == nil {
+		t.Fatal("the agent tried to prove a key over plain http")
+	}
+}
+
+// The whole bootstrap: an agent with a pairing token and no pin pairs with an
+// HTTPS server, and leaves an env file that pins the proven key next to its
+// new token.
+func TestAnAgentPairsOverHTTPSWithoutAPin(t *testing.T) {
+	ps := newPairServer(t)
+	env := t.TempDir() + "/netpulse-agent.env"
+	if err := os.WriteFile(env, []byte("NETPULSE_SERVER="+ps.URL+"\nNETPULSE_SLUG=test-agent\n"+
+		"NETPULSE_PAIRING_TOKEN="+testPairingToken+"\n"), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	err := agentruntime.Run(context.Background(), agentruntime.Options{
+		Server: ps.URL, Slug: "test-agent", PairingToken: testPairingToken, EnvFile: env,
+	})
+	if err != nil {
+		t.Fatalf("pairing: %v", err)
+	}
+	got, err := os.ReadFile(env)
+	if err != nil {
+		t.Fatal(err)
+	}
+	s := string(got)
+	if !strings.Contains(s, "NETPULSE_SERVER_FP="+ps.fp+"\n") {
+		t.Fatalf("the proven pin was not written:\n%s", s)
+	}
+	if !strings.Contains(s, "NETPULSE_TOKEN=") || strings.Contains(s, "NETPULSE_PAIRING_TOKEN") {
+		t.Fatalf("the env was not switched to the agent token:\n%s", s)
+	}
+}

+ 68 - 2
server-go/internal/httpapi/pairing.go

@@ -17,11 +17,15 @@ package httpapi
 import (
 	"crypto/rand"
 	"crypto/subtle"
+	"encoding/hex"
 	"fmt"
 	"net/http"
 
+	"github.com/gnacho/netpulse/agent/pairproof"
+
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 )
 
 const pairingTokenKey = "pairing.token"
@@ -65,7 +69,7 @@ func (s *server) handlePairingToken(w http.ResponseWriter, _ *http.Request) {
 		writeError(w, http.StatusInternalServerError, "pairing_error")
 		return
 	}
-	writeJSON(w, http.StatusOK, map[string]string{"token": tok, "server_fp": s.serverFP})
+	writeJSON(w, http.StatusOK, map[string]string{"token": tok, "server_fp": s.fingerprint()})
 }
 
 // handlePairingRotate (POST /api/pairing/rotate): genera un pairing token
@@ -135,6 +139,15 @@ func (s *server) handleAgentPair(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	adminToken := stored != "" && subtle.ConstantTimeCompare([]byte(body.PairingToken), []byte(stored)) == 1
+	// FORK: once plain HTTP is being retired, the admin pairing token - which
+	// can create or rotate any agent - is not taken over it: pair over https,
+	// where the agent proves the server's key first (pair/hello). Refusing
+	// cannot un-send it, but keeps anything from relying on it.
+	if adminToken && s.tlsMgr != nil && s.tlsMgr.Enabled() && s.tlsMgr.Mode() != tlsmode.Full && !auth.IsSecureRequest(r) {
+		writeError(w, http.StatusForbidden, "use_https",
+			"pair over https: this server no longer takes its pairing token over plain HTTP")
+		return
+	}
 	if !adminToken {
 		if !s.checkAutoenrollToken(body.PairingToken) {
 			writeError(w, http.StatusUnauthorized, "invalid_pairing_token")
@@ -166,7 +179,60 @@ func (s *server) handleAgentPair(w http.ResponseWriter, r *http.Request) {
 	writeJSON(w, http.StatusCreated, pairResponse{
 		Slug:     body.Slug,
 		Token:    token,
-		ServerFP: s.serverFP,
+		ServerFP: s.fingerprint(),
+	})
+}
+
+// handleAgentPairHello (POST /api/agents/pair/hello): FORK. Proves to an
+// agent that the key this server serves is the real server's, so an agent
+// given a pairing token but no pin can learn the pin without trusting
+// whoever answers first. The reply is pairproof.MAC(pairing token, the
+// agent's nonce, our fingerprint); the agent checks it against the chain it
+// was shown (runtime.ProveServerKey). The pairing token itself is never sent
+// to us here, and the reply is useless to anyone who does not hold it.
+//
+// Only the admin pairing token proves anything. The autoenroll token is
+// handed out over UDP to whoever asks, so a MAC keyed with it would prove
+// nothing about who answered.
+func (s *server) handleAgentPairHello(w http.ResponseWriter, r *http.Request) {
+	ip := auth.ClientIP(r)
+	if ok, _ := s.ingestLimit.allow(ip); !ok {
+		writeError(w, http.StatusTooManyRequests, "rate_limited")
+		return
+	}
+	if r.TLS == nil {
+		// Also the answer behind a TLS-terminating proxy: the key the agent
+		// sees is the proxy's, which this server cannot vouch for.
+		writeError(w, http.StatusBadRequest, "use_https",
+			"the server's key can only be proven over a direct https connection to it; "+
+				"behind a TLS-terminating proxy, give the agent NETPULSE_SERVER_FP instead")
+		return
+	}
+	fp := s.fingerprint()
+	if fp == "" {
+		writeError(w, http.StatusConflict, "no_fingerprint",
+			"this server has no key for agents to pin")
+		return
+	}
+	var body struct {
+		Nonce string `json:"nonce"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", `expected { "nonce": "<hex>" }`)
+		return
+	}
+	if b, err := hex.DecodeString(body.Nonce); err != nil || len(b) < 16 || len(b) > 64 {
+		writeError(w, http.StatusBadRequest, "invalid_body", "nonce must be 16 to 64 random bytes in hex")
+		return
+	}
+	tok, err := s.getPairingToken()
+	if err != nil || tok == "" {
+		writeError(w, http.StatusInternalServerError, "pairing_error")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]string{
+		"server_fp": fp,
+		"mac":       pairproof.MAC(tok, body.Nonce, fp),
 	})
 }
 

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

@@ -48,6 +48,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
+	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
 	"github.com/gnacho/netpulse/server-go/internal/wifisle"
 )
@@ -91,6 +92,14 @@ type Deps struct {
 	// ServerFP: fingerprint SPKI del servidor (hex). Vacío si no es on-box.
 	// Se devuelve en /api/agents/pair para que el agentepine el TLS.
 	ServerFP string
+	// FORK: TLS is the HTTPS manager (private CA, plain-HTTP mode) behind
+	// Settings > HTTPS. nil: no such settings, and HSTS follows the legacy
+	// rule below.
+	TLS *tlsmode.Manager
+	// FORK: ServerFPFunc, when set, is read on every request and wins over
+	// ServerFP: a user-supplied certificate can change key on renewal, and a
+	// fingerprint captured at start-up would hand agents a stale pin.
+	ServerFPFunc func() string
 	// Orchestr: motor de plan/apply (Fase 10). nil → sin rutas /api/plans.
 	Orchestr *orchestr.Manager
 	// MQTT: publisher de flota MQTT (#838). nil → las rutas de ajustes MQTT
@@ -146,6 +155,11 @@ type server struct {
 
 	// Fingerprint SPKI del servidor (vacío si no es on-box).
 	serverFP string
+	// FORK: see Deps.ServerFPFunc.
+	serverFPFunc func() string
+	// FORK: see Deps.TLS; agentTransport is each agent's last transport.
+	tlsMgr         *tlsmode.Manager
+	agentTransport sync.Map // slug -> agentTransport
 
 	// Anti-martilleo de POST /api/refresh (global, min 5 s entre sondeos).
 	refreshMu   sync.Mutex
@@ -238,6 +252,8 @@ func NewHandler(d Deps) http.Handler {
 		lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
 		agentHub:        d.AgentHub,
 		serverFP:        d.ServerFP,
+		serverFPFunc:    d.ServerFPFunc,
+		tlsMgr:          d.TLS,
 		ingestLimit:     newIPRateLimit(ingestRateLimit, ingestRateWindow),
 		upgrades:        newUpgradeTracker(),
 		tokenStore:      d.TokenStore,
@@ -444,6 +460,8 @@ func NewHandler(d Deps) http.Handler {
 	// --- Fase 9 R3: Pairing / adopción de agentes ---
 	// POST /api/agents/pair: sin sesión (el pairing token ES la auth), rate limited.
 	mux.HandleFunc("POST /api/agents/pair", s.handleAgentPair)
+	// FORK: POST /api/agents/pair/hello: proves the served key, no session.
+	mux.HandleFunc("POST /api/agents/pair/hello", s.handleAgentPairHello)
 	// Gestión del pairing token (admin).
 	mux.Handle("GET /api/pairing/token", auth.RequireAdmin(http.HandlerFunc(s.handlePairingToken)))
 	mux.Handle("POST /api/pairing/rotate", auth.RequireAdmin(http.HandlerFunc(s.handlePairingRotate)))
@@ -537,7 +555,8 @@ func NewHandler(d Deps) http.Handler {
 	if s.tokenStore != nil {
 		tv = s.tokenStore
 	}
-	return requestID(security.Middleware(auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))))
+	s.registerHTTPS(mux)
+	return requestID(security.Middleware(s.hsts, auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))))
 }
 
 // requestID lee o genera un x-request-id para cada petición y lo expone en
@@ -750,3 +769,12 @@ func (s *server) handleConfigBackupDelete(w http.ResponseWriter, r *http.Request
 	}
 	writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
 }
+
+// fingerprint is the SPKI fingerprint agents should pin, or "" when this
+// server serves no TLS.
+func (s *server) fingerprint() string {
+	if s.serverFPFunc != nil {
+		return s.serverFPFunc()
+	}
+	return s.serverFP
+}

+ 45 - 0
server-go/internal/httpapi/server_fp_test.go

@@ -0,0 +1,45 @@
+package httpapi
+
+// FORK: tests for the live server fingerprint (Deps.ServerFPFunc).
+
+import (
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+)
+
+// Pairing hands agents the key the server serves now, not the one it served
+// at start-up: a user-supplied certificate can change key on renewal.
+func TestPairingHandsOutTheLiveFingerprint(t *testing.T) {
+	s := panelTestServer(t)
+	s.serverFP = "stale-static-value"
+	current := "aa11"
+	s.serverFPFunc = func() string { return current }
+
+	read := func() string {
+		rec := httptest.NewRecorder()
+		s.handlePairingToken(rec, httptest.NewRequest(http.MethodGet, "/api/pairing/token", nil))
+		var body map[string]string
+		if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+			t.Fatalf("decode: %v (%s)", err, rec.Body.String())
+		}
+		return body["server_fp"]
+	}
+	if got := read(); got != "aa11" {
+		t.Fatalf("server_fp = %q, want the live value", got)
+	}
+	current = "bb22"
+	if got := read(); got != "bb22" {
+		t.Fatalf("server_fp = %q after a renewal, want the new key", got)
+	}
+}
+
+// Without a live source the static value is used, as before.
+func TestPairingFallsBackToTheStaticFingerprint(t *testing.T) {
+	s := panelTestServer(t)
+	s.serverFP = "cc33"
+	if got := s.fingerprint(); got != "cc33" {
+		t.Fatalf("fingerprint = %q, want the static value", got)
+	}
+}

+ 13 - 1
server-go/internal/rearmer/rearmer.go

@@ -18,6 +18,7 @@ import (
 	"fmt"
 	"log"
 	"sync"
+	"sync/atomic"
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
@@ -176,8 +177,15 @@ type Rearmer struct {
 
 	mu        sync.Mutex
 	lastRearm map[string]time.Time
+
+	// FORK: how a reinstalled agent should reach the server (HTTPS). Set
+	// once at start-up, possibly after the supervisor is already running.
+	trust atomic.Pointer[func(base string) reinstall.Trust]
 }
 
+// SetTrust sets how reinstalled agents reach the server. FORK.
+func (r *Rearmer) SetTrust(f func(base string) reinstall.Trust) { r.trust.Store(&f) }
+
 // New construye un Rearmer. engine puede ser nil (sin alertas; tests).
 // pollWait <= 0 → PollWait.
 func New(db *sql.DB, agents *adapters.AgentRegistry, pool SSHRunner, engine AlertsEngine, pollWait time.Duration) *Rearmer {
@@ -380,7 +388,11 @@ func (r *Rearmer) Reinstall(slug, publicURL string) (Result, error) {
 		}
 	}
 	if err := r.rotateTokenAtomic(slug, func(t string) error {
-		_, err := r.pool.Run(host, reinstall.Script(slug, t, publicURL, reinstall.ServerFP(publicURL), reinstall.Digests()), ReinstallSSHWait)
+		var trust []reinstall.Trust
+		if f := r.trust.Load(); f != nil {
+			trust = append(trust, (*f)(publicURL))
+		}
+		_, err := r.pool.Run(host, reinstall.Script(slug, t, publicURL, reinstall.ServerFP(publicURL), reinstall.Digests(), trust...), ReinstallSSHWait)
 		return err
 	}); err != nil {
 		return Result{}, fmt.Errorf("no se pudo instalar el agente en %s: %w", host, err)

+ 59 - 6
server-go/internal/reinstall/reinstall.go

@@ -5,7 +5,27 @@
 // importa rearmer y ninguno de los dos puede importar al otro.
 package reinstall
 
-import "github.com/gnacho/netpulse/server-go/internal/agentbin"
+import (
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/agentbin"
+)
+
+// Trust is how an agent reaches the server over HTTPS. FORK.
+//
+// The zero value leaves the script behaving as before. With a CA, the script
+// writes the root to the router - over the SSH session it runs in, whose host
+// key the server has verified - and downloads verify the server against it,
+// so the agent token in the request header is not handed to whoever answers.
+// The binary's sha256 was always checked; this protects the token.
+type Trust struct {
+	ServerURL string // replaces the URL given to Script, e.g. https://host:3443
+	ServerFP  string // written as NETPULSE_SERVER_FP: what the agent pins
+	CAPEM     []byte // the root to verify downloads with
+}
+
+// caPath is where the router keeps the root.
+const caPath = "/etc/netpulse-ca.pem"
 
 // Script construye el POSIX sh que se ejecuta en el router: instala el
 // agente completo (binario verificado por sha256, config .env, init procd
@@ -20,7 +40,34 @@ import "github.com/gnacho/netpulse/server-go/internal/agentbin"
 // server lo pudo derivar (ServerFP), va en el .env para que el agente no
 // entre en bucle fatal de "HTTPS requiere NETPULSE_SERVER_FP"; vacío = el
 // comportamiento previo (env sin FP).
-func Script(slug, token, serverURL, serverFP string, digests map[string]string) string {
+//
+// FORK: trust, when given, is how the agent should reach the server now -
+// the HTTPS address with the private CA - and wins over serverURL and
+// serverFP; its root is written to the router to verify downloads with.
+func Script(slug, token, serverURL, serverFP string, digests map[string]string, trust ...Trust) string {
+	var tr Trust
+	if len(trust) > 0 {
+		tr = trust[0]
+	}
+	if tr.ServerURL != "" {
+		serverURL = tr.ServerURL
+	}
+	if tr.ServerFP != "" {
+		serverFP = tr.ServerFP
+	}
+	// Without a root, one left from an earlier install (a CA since replaced)
+	// would make every https download fail against it.
+	caSetup := "\nrm -f " + caPath + "\n"
+	if len(tr.CAPEM) > 0 {
+		caSetup = `
+# FORK: the server's root, to verify downloads with (written over this SSH
+# session, so it is the server's own)
+cat > ` + caPath + ` <<'CAEOF'
+` + strings.TrimSpace(string(tr.CAPEM)) + `
+CAEOF
+chmod 644 ` + caPath + `
+`
+	}
 	return `#!/bin/sh
 set -e
 INIT=/etc/init.d/netpulse-agent
@@ -30,6 +77,10 @@ SERVER="` + serverURL + `"
 SLUG="` + slug + `"
 TOKEN="` + token + `"
 SERVER_FP="` + serverFP + `"
+` + caSetup + `
+# FORK: verify https downloads against the server's root when there is one
+CURL_TLS=""; WGET_TLS=""
+if [ -f ` + caPath + ` ]; then CURL_TLS="--cacert ` + caPath + `"; WGET_TLS="--ca-certificate=` + caPath + `"; fi
 
 # Detectar arquitectura del router y el digest esperado del binario embebido
 ARCH=$(uname -m)
@@ -53,9 +104,9 @@ esac
 
 # Descargar el binario del propio server (auth por token)
 if command -v curl >/dev/null 2>&1; then
-	curl -fsSL --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
+	curl -fsSL $CURL_TLS --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
 else
-	wget -q -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
+	wget -q $WGET_TLS -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
 fi
 
 # Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
@@ -130,10 +181,12 @@ selfheal_binary() {
 	url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
 	logger -t netpulse-agent "self-heal: binario ausente, descargando de $NETPULSE_SERVER"
 	tmp=/tmp/netpulse-agent.$$
+	local ctls="" wtls=""
+	if [ -f /etc/netpulse-ca.pem ]; then ctls="--cacert /etc/netpulse-ca.pem"; wtls="--ca-certificate=/etc/netpulse-ca.pem"; fi
 	if command -v curl >/dev/null 2>&1; then
-		curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+		curl -fsSL $ctls -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
 	else
-		wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+		wget -q $wtls -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
 	fi
 	chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
 	logger -t netpulse-agent "self-heal: binario restaurado"

+ 49 - 0
server-go/internal/reinstall/script_test.go

@@ -3,6 +3,7 @@
 package reinstall_test
 
 import (
+	"os/exec"
 	"strings"
 	"testing"
 
@@ -269,3 +270,51 @@ func TestTokenPushPreservesServerFP(t *testing.T) {
 		}
 	}
 }
+
+// FORK: with a Trust the script moves the agent to the HTTPS address, writes
+// the root to the router, verifies its downloads - including the self-heal's
+// - against it, and pins the server. Without one nothing of that appears.
+func TestScriptWithTrust(t *testing.T) {
+	root := "-----BEGIN CERTIFICATE-----\nMIIBtestroot\n-----END CERTIFICATE-----\n"
+	fp := strings.Repeat("ab", 32)
+	// A pin derived for the old address is replaced by the trust's.
+	s := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", strings.Repeat("99", 32),
+		map[string]string{}, reinstall.Trust{ServerURL: "https://192.0.2.10:3443", ServerFP: fp, CAPEM: []byte(root)})
+	for _, want := range []string{
+		`SERVER="https://192.0.2.10:3443"`,
+		"cat > /etc/netpulse-ca.pem <<'CAEOF'\n" + strings.TrimSpace(root) + "\nCAEOF",
+		`curl -fsSL $CURL_TLS`,
+		`wget -q $WGET_TLS`,
+		`SERVER_FP="` + fp + `"`,
+		`ctls="--cacert /etc/netpulse-ca.pem"`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("script lacks %q", want)
+		}
+	}
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("not valid sh: %v\n%s", err, out)
+	}
+
+	plain := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", "", map[string]string{})
+	if !strings.Contains(plain, "rm -f /etc/netpulse-ca.pem") {
+		t.Error("a script without a root leaves a stale one on the router")
+	}
+	if strings.Contains(s, "rm -f /etc/netpulse-ca.pem") {
+		t.Error("a script with a root removes it")
+	}
+	if strings.Contains(s, strings.Repeat("99", 32)) {
+		t.Error("the pin passed in survived the trust's")
+	}
+	if !strings.Contains(plain, `SERVER_FP=""`) {
+		t.Error("a script without a pin sets one")
+	}
+	for _, notWant := range []string{"CAEOF", "https://"} {
+		if strings.Contains(plain, notWant) {
+			t.Errorf("a script without Trust contains %q", notWant)
+		}
+	}
+	if out, err := exec.Command("sh", "-n", "-c", plain).CombinedOutput(); err != nil {
+		t.Fatalf("not valid sh: %v\n%s", err, out)
+	}
+}

+ 21 - 4
server-go/internal/security/security.go

@@ -10,7 +10,6 @@ var Headers = []struct{ K, V string }{
 	{"X-Frame-Options", "DENY"},
 	{"Referrer-Policy", "strict-origin-when-cross-origin"},
 	{"Permissions-Policy", "geolocation=(), microphone=(), camera=()"},
-	{"Strict-Transport-Security", "max-age=31536000; includeSubDomains"},
 	// style-src lleva 'unsafe-inline' a propósito (#485): Radix (posicionado
 	// popper) y framer-motion (transform/opacity) escriben atributos style
 	// CON VALORES DINÁMICOS (píxeles calculados), imposibles de hashear con
@@ -21,13 +20,31 @@ var Headers = []struct{ K, V string }{
 	{"Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'"},
 }
 
-// Middleware aplica los headers a todas las respuestas (HSTS también por
-// HTTP plano — comportamiento del JS, preservado).
-func Middleware(next http.Handler) http.Handler {
+// HSTS is the Strict-Transport-Security value for a server whose every
+// port speaks TLS.
+//
+// includeSubDomains is left out: nothing lives under the server's own name,
+// and the flag would pin every host below it to HTTPS for a year, which
+// makes turning HTTPS off again much harder to undo.
+const HSTS = "max-age=31536000"
+
+// Middleware applies the headers to every response, and the HSTS value hsts
+// returns for it, if any.
+//
+// HSTS is per host, not per port (RFC 6797 section 8.3): a policy received on
+// one port makes the browser rewrite http://host:ANY to https://host:ANY. So
+// it may only be sent where no port of the host still serves plain HTTP that
+// people need - the caller decides that, not this package.
+func Middleware(hsts func(*http.Request) string, next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		for _, h := range Headers {
 			w.Header().Set(h.K, h.V)
 		}
+		if hsts != nil {
+			if v := hsts(r); v != "" {
+				w.Header().Set("Strict-Transport-Security", v)
+			}
+		}
 		next.ServeHTTP(w, r)
 	})
 }

+ 13 - 0
server-go/internal/sse/agenthub.go

@@ -32,6 +32,10 @@ type agentConn struct {
 	wmu     sync.Mutex
 	done    chan struct{}
 	once    sync.Once
+	// FORK: set under wmu before the stream's handler returns; see
+	// client.finished in hub.go - a Send racing the disconnect otherwise
+	// writes to a dead ResponseWriter and panics the server.
+	finished bool
 }
 
 // NewAgentHub crea el hub de agentes. checkToken valida el Bearer del agente.
@@ -111,6 +115,9 @@ func (h *AgentHub) remove(slug string) {
 func (c *agentConn) write(payload string) error {
 	c.wmu.Lock()
 	defer c.wmu.Unlock()
+	if c.finished {
+		return errFinished
+	}
 	rc := http.NewResponseController(c.w)
 	_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
 	if _, err := fmt.Fprint(c.w, payload); err != nil {
@@ -119,6 +126,7 @@ func (c *agentConn) write(payload string) error {
 	if err := rc.Flush(); err != nil {
 		return err
 	}
+	_ = rc.SetWriteDeadline(time.Now().Add(idleDeadline)) // FORK: see idleDeadline
 	return nil
 }
 
@@ -168,6 +176,11 @@ func (h *AgentHub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	h.conns[slug] = c
 	h.mu.Unlock()
 	defer h.removeConn(c)
+	defer func() { // FORK: runs first, before the handler returns
+		c.wmu.Lock()
+		c.finished = true
+		c.wmu.Unlock()
+	}()
 
 	// Enviar evento "connected" al agente (confirmación)
 	_ = c.write("event: connected\ndata: {}\n\n")

+ 71 - 0
server-go/internal/sse/h2_idle_test.go

@@ -0,0 +1,71 @@
+package sse
+
+// FORK: a stream served over HTTP/2 survives idle time past the write
+// deadline a single write needs.
+
+import (
+	"bufio"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+)
+
+func TestAStreamOverHTTP2OutlivesTheWriteDeadline(t *testing.T) {
+	if testing.Short() {
+		t.Skip("waits past the 10 s write deadline")
+	}
+	h := NewAgentHub(func(string, string) bool { return true })
+	mux := http.NewServeMux()
+	mux.HandleFunc("GET /api/agents/{slug}/stream", h.HandleStream)
+	ts := httptest.NewUnstartedServer(mux)
+	ts.EnableHTTP2 = true
+	ts.StartTLS()
+	defer ts.Close()
+
+	req, _ := http.NewRequest("GET", ts.URL+"/api/agents/test-router/stream", nil)
+	req.Header.Set("Authorization", "Bearer x")
+	res, err := ts.Client().Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer res.Body.Close()
+	if res.ProtoMajor != 2 {
+		t.Fatalf("served over HTTP/%d, the test needs HTTP/2", res.ProtoMajor)
+	}
+	lines := make(chan string, 16)
+	go func() {
+		sc := bufio.NewScanner(res.Body)
+		for sc.Scan() {
+			lines <- sc.Text()
+		}
+		close(lines)
+	}()
+	waitFor := func(want string, within time.Duration) bool {
+		deadline := time.After(within)
+		for {
+			select {
+			case l, ok := <-lines:
+				if !ok {
+					return false
+				}
+				if strings.Contains(l, want) {
+					return true
+				}
+			case <-deadline:
+				return false
+			}
+		}
+	}
+	if !waitFor("event: connected", 3*time.Second) {
+		t.Fatal("no connected event")
+	}
+	time.Sleep(12 * time.Second) // past the 10 s a write's deadline allows
+	if !h.Send("test-router", "ping", map[string]int{"n": 1}) {
+		t.Fatal("the stream was gone after 12 s idle")
+	}
+	if !waitFor("event: ping", 3*time.Second) {
+		t.Fatal("a command sent after 12 s idle never arrived")
+	}
+}

+ 28 - 0
server-go/internal/sse/hub.go

@@ -9,6 +9,7 @@ package sse
 
 import (
 	"encoding/json"
+	"errors"
 	"fmt"
 	"net/http"
 	"sync"
@@ -21,6 +22,13 @@ import (
 // Heartbeat = 30 s (HEARTBEAT_MS de sse.js:16).
 const Heartbeat = 30 * time.Second
 
+// idleDeadline is the write deadline left on a stream between writes. FORK:
+// under HTTP/2 a write deadline that passes resets the stream even when no
+// write is pending, so the 10 s deadline a write needs cannot be left in
+// place: every stream served over HTTPS died 10 s after its last event. Two
+// missed heartbeats and a margin still end a stream nobody reads.
+const idleDeadline = 3 * Heartbeat
+
 type client struct {
 	id        int
 	sessionID string
@@ -29,11 +37,29 @@ type client struct {
 	wmu       sync.Mutex
 	done      chan struct{}
 	once      sync.Once
+	// FORK: finished is set, under wmu, before HandleStream returns. After
+	// that the ResponseWriter is dead - writing to it panics inside
+	// net/http and takes the whole server down - yet a Broadcast that
+	// listed this client just before it left can still reach write.
+	finished bool
+}
+
+// errFinished is returned for a write to a client whose request is over.
+var errFinished = errors.New("sse: client gone")
+
+// finish marks the client's request as over; see client.finished.
+func (c *client) finish() {
+	c.wmu.Lock()
+	c.finished = true
+	c.wmu.Unlock()
 }
 
 func (c *client) write(payload string) error {
 	c.wmu.Lock()
 	defer c.wmu.Unlock()
+	if c.finished {
+		return errFinished
+	}
 	rc := http.NewResponseController(c.w)
 	_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
 	if _, err := fmt.Fprint(c.w, payload); err != nil {
@@ -42,6 +68,7 @@ func (c *client) write(payload string) error {
 	if err := rc.Flush(); err != nil {
 		return err
 	}
+	_ = rc.SetWriteDeadline(time.Now().Add(idleDeadline))
 	return nil
 }
 
@@ -154,6 +181,7 @@ func (h *Hub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	h.clients[c.id] = c
 	h.mu.Unlock()
 	defer h.remove(c)
+	defer c.finish() // FORK: runs first, before the handler returns
 
 	// Primer snapshot inmediato al conectar
 	if h.getOverview != nil {

+ 75 - 0
server-go/internal/sse/hub_finish_test.go

@@ -0,0 +1,75 @@
+package sse
+
+// FORK: a write racing a client's departure must not reach its dead
+// ResponseWriter - net/http panics there and takes the server down.
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"sync/atomic"
+	"testing"
+	"time"
+)
+
+// deadAfterWriter panics on use once its request is over, as net/http's own
+// ResponseWriter does after the handler has returned.
+type deadAfterWriter struct {
+	h    http.Header
+	dead atomic.Bool
+}
+
+func (w *deadAfterWriter) Header() http.Header { return w.h }
+func (w *deadAfterWriter) Write(p []byte) (int, error) {
+	if w.dead.Load() {
+		panic("write after the handler returned")
+	}
+	return len(p), nil
+}
+func (w *deadAfterWriter) WriteHeader(int) {}
+func (w *deadAfterWriter) Flush() {
+	if w.dead.Load() {
+		panic("flush after the handler returned")
+	}
+}
+
+func TestAWriteAfterTheClientLeftIsRefused(t *testing.T) {
+	h := NewHub(nil, 10, nil)
+	w := &deadAfterWriter{h: http.Header{}}
+	ctx, cancel := context.WithCancel(context.Background())
+	req := httptest.NewRequest("GET", "/api/stream", nil).WithContext(ctx)
+	returned := make(chan struct{})
+	go func() { h.HandleStream(w, req); close(returned) }()
+
+	var c *client
+	for i := 0; i < 100 && c == nil; i++ {
+		h.mu.Lock()
+		for _, x := range h.clients {
+			c = x
+		}
+		h.mu.Unlock()
+		time.Sleep(5 * time.Millisecond)
+	}
+	if c == nil {
+		t.Fatal("the stream never registered its client")
+	}
+	cancel()
+	<-returned
+	w.dead.Store(true) // what net/http does once the handler has returned
+
+	// A Broadcast that listed the client before it left gets here.
+	if err := c.write("event: x\ndata: {}\n\n"); err != errFinished {
+		t.Fatalf("write after the client left: %v, want errFinished", err)
+	}
+}
+
+func TestAnAgentCommandAfterTheAgentLeftIsRefused(t *testing.T) {
+	c := &agentConn{w: &deadAfterWriter{h: http.Header{}}, done: make(chan struct{})}
+	c.wmu.Lock()
+	c.finished = true
+	c.wmu.Unlock()
+	c.w.(*deadAfterWriter).dead.Store(true)
+	if err := c.write("event: x\ndata: {}\n\n"); err != errFinished {
+		t.Fatalf("write after the agent left: %v, want errFinished", err)
+	}
+}

+ 711 - 0
server-go/internal/tlscert/ca.go

@@ -0,0 +1,711 @@
+package tlscert
+
+// FORK: a private certificate authority for this server.
+//
+// Browsers only register a service worker - Web Push, installing the PWA -
+// on a certificate they trust outright; an exception accepted for a
+// self-signed certificate is not enough. So the server can run its own root
+// CA, which the admin installs once on their devices, and serve a leaf it
+// signs. Agents pin the root (tlspin accepts a CA pin), so the leaf can be
+// re-issued - on renewal, or when the server's addresses change - without
+// breaking any of them.
+//
+// A root the admin's devices trust is a powerful thing to keep on a server.
+// Three properties bound it:
+//
+//   - The root carries Name Constraints: private address ranges and
+//     local DNS names only. A copy of its key cannot be used to impersonate
+//     any public site to a device that trusts it.
+//   - Its key is only ever used to sign this server's own leaf, stays in a
+//     0700 directory in a 0600 file owned by the service user, and the server
+//     refuses to start if either has been opened up.
+//   - It is created once and never replaced implicitly: a missing half of the
+//     pair is an error, not a reason to mint a new root the devices do not
+//     trust.
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/tls"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/pem"
+	"errors"
+	"fmt"
+	"io/fs"
+	"math/big"
+	"net"
+	"os"
+	"path/filepath"
+	"slices"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"time"
+)
+
+const (
+	caCertFile   = "ca.pem"
+	caKeyFile    = "ca-key.pem"
+	leafCertFile = "leaf.pem"
+	leafKeyFile  = "leaf-key.pem"
+
+	rootValidity = 10 * 365 * 24 * time.Hour
+	rootBackdate = 365 * 24 * time.Hour
+	// Short-lived leaves limit how long a mis-issued one would be accepted;
+	// renewal is automatic and the key does not change, so it costs nothing.
+	leafValidity    = 90 * 24 * time.Hour
+	leafRenewBefore = 30 * 24 * time.Hour
+	// How often Run re-checks the leaf: for expiry, and for a change in the
+	// server's addresses.
+	caCheckEvery = 10 * time.Minute
+)
+
+// Address ranges a leaf may name: private, carrier-grade NAT (which overlay
+// VPNs use), loopback and IPv6 unique-local.
+var permittedIPRanges = []string{
+	"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10",
+	"127.0.0.0/8", "::1/128", "fc00::/7",
+}
+
+// DNS suffixes that are local by definition or by convention. The host's own
+// names and search domains are added when the root is created.
+var permittedLocalSuffixes = []string{"lan", "home.arpa", "internal", "local"}
+
+// CAOptions configures OpenCA. The function fields exist for tests; nil
+// means the real system.
+type CAOptions struct {
+	Dir        string   // where the CA and leaf live; created 0700
+	Names      []string // extra names or addresses for the leaf (NETPULSE_TLS_NAMES)
+	PublicHost string   // host of NETPULSE_PUBLIC_URL, if set
+
+	Addrs         func() ([]net.IP, error)
+	Hostname      func() (string, error)
+	SearchDomains func() []string
+	Now           func() time.Time
+	Logf          func(format string, args ...any)
+}
+
+// CA is the server's private CA and the leaf it serves.
+type CA struct {
+	opts    CAOptions
+	root    *x509.Certificate
+	rootKey *ecdsa.PrivateKey
+	leafKey *ecdsa.PrivateKey
+
+	mu          sync.Mutex // serializes Refresh
+	lastDropped string
+	uncovered   []string // names and addresses the root cannot vouch for
+	cur         atomic.Pointer[tls.Certificate]
+}
+
+// OpenCA loads the CA in opts.Dir, creating it on first use, and makes sure
+// a current leaf is ready to serve.
+func OpenCA(opts CAOptions) (*CA, error) {
+	if opts.Dir == "" {
+		return nil, errors.New("tls: no directory for the CA")
+	}
+	if opts.Addrs == nil {
+		opts.Addrs = interfaceAddrs
+	}
+	if opts.Hostname == nil {
+		opts.Hostname = os.Hostname
+	}
+	if opts.SearchDomains == nil {
+		opts.SearchDomains = resolvSearchDomains
+	}
+	if opts.Now == nil {
+		opts.Now = time.Now
+	}
+	if opts.Logf == nil {
+		opts.Logf = func(string, ...any) {}
+	}
+	if err := ensurePrivateDir(opts.Dir); err != nil {
+		return nil, err
+	}
+	ca := &CA{opts: opts}
+	if err := ca.openRoot(); err != nil {
+		return nil, err
+	}
+	key, err := loadOrCreateKey(filepath.Join(opts.Dir, leafKeyFile))
+	if err != nil {
+		return nil, fmt.Errorf("tls: leaf key: %w", err)
+	}
+	ca.leafKey = key
+	if err := ca.loadLeaf(); err != nil {
+		opts.Logf("[netpulse] TLS: the stored leaf cannot be used (%v); issuing a new one", err)
+	}
+	if _, err := ca.Refresh(); err != nil {
+		return nil, err
+	}
+	return ca, nil
+}
+
+func (ca *CA) openRoot() error {
+	certPath := filepath.Join(ca.opts.Dir, caCertFile)
+	keyPath := filepath.Join(ca.opts.Dir, caKeyFile)
+	haveCert, haveKey := fileExists(certPath), fileExists(keyPath)
+	switch {
+	case haveCert && haveKey:
+		key, err := loadKey(keyPath)
+		if err != nil {
+			return fmt.Errorf("tls: CA key: %w", err)
+		}
+		cert, err := loadCert(certPath)
+		if err != nil {
+			return fmt.Errorf("tls: CA certificate: %w", err)
+		}
+		if !cert.IsCA || !key.PublicKey.Equal(cert.PublicKey) {
+			return fmt.Errorf("tls: %s and %s are not a CA and its key", certPath, keyPath)
+		}
+		ca.root, ca.rootKey = cert, key
+		return nil
+	case haveCert || haveKey:
+		// Never mint a replacement: every device that trusts the old root
+		// would silently stop trusting the server.
+		return fmt.Errorf("tls: only one of %s and %s exists; restore the other from a backup, "+
+			"or remove both to create a new CA (every device will need the new root installed)", certPath, keyPath)
+	}
+	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		return err
+	}
+	tmpl, err := ca.rootTemplate()
+	if err != nil {
+		return err
+	}
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+	if err != nil {
+		return fmt.Errorf("tls: create CA: %w", err)
+	}
+	cert, err := x509.ParseCertificate(der)
+	if err != nil {
+		return err
+	}
+	// Key first: a crash between the two writes leaves a key without a
+	// certificate, which openRoot refuses loudly, rather than a certificate
+	// devices might already trust whose key is lost.
+	if err := writeKey(keyPath, key); err != nil {
+		return fmt.Errorf("tls: write CA key: %w", err)
+	}
+	if err := writeAtomic(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
+		return fmt.Errorf("tls: write CA certificate: %w", err)
+	}
+	ca.root, ca.rootKey = cert, key
+	ca.opts.Logf("[netpulse] TLS: created a private CA; install it on your devices and check its fingerprint: %s", ca.RootSHA256())
+	return nil
+}
+
+func (ca *CA) rootTemplate() (*x509.Certificate, error) {
+	serial, err := randomSerial()
+	if err != nil {
+		return nil, err
+	}
+	var ranges []*net.IPNet
+	for _, r := range permittedIPRanges {
+		_, n, err := net.ParseCIDR(r)
+		if err != nil {
+			return nil, err
+		}
+		ranges = append(ranges, n)
+	}
+	domains := slices.Clone(permittedLocalSuffixes)
+	host, _ := ca.opts.Hostname()
+	domains = append(domains, hostNames(host)...)
+	// Only this host under each search domain, never the whole domain: a
+	// search domain can be a company's or a public one, and permitting it
+	// would let a copy of the CA key vouch for everything in it.
+	if short := firstLabel(host); short != "" {
+		for _, d := range ca.opts.SearchDomains() {
+			domains = append(domains, short+"."+d)
+		}
+	}
+	for _, n := range append(slices.Clone(ca.opts.Names), ca.opts.PublicHost) {
+		if n = normName(n); n != "" && net.ParseIP(n) == nil {
+			// A name is permitted with everything below it - name
+			// constraints cannot say "this name only" - so a public one
+			// widens what the root may vouch for. Allowed, since it was
+			// asked for, but said.
+			if !underLocalSuffix(n) {
+				ca.opts.Logf("[netpulse] TLS: the CA may also vouch for everything under %s, "+
+					"which is not a local name (NETPULSE_TLS_NAMES / NETPULSE_PUBLIC_URL)", n)
+			}
+			domains = append(domains, n)
+		}
+	}
+	slices.Sort(domains)
+	domains = slices.Compact(domains)
+	now := ca.opts.Now()
+	cn := "NetPulse local CA"
+	if short := firstLabel(host); short != "" {
+		cn += " (" + short + ")"
+	}
+	// Backdated well past any clock skew: the root is never replaced, so one
+	// created while the clock ran fast must not stay "not yet valid" for
+	// months.
+	notBefore := now.Add(-rootBackdate)
+	// The name constraints are not marked critical: mbedTLS - OpenWrt's TLS
+	// library, behind its wget and curl - refuses to load a certificate with
+	// a critical extension it does not implement, and it does not implement
+	// this one, so routers could not verify the server at all. Go, OpenSSL,
+	// Chrome and Firefox enforce them either way; the CA/B Baseline
+	// Requirements allowed them non-critical for the same reason.
+	return &x509.Certificate{
+		SerialNumber:                serial,
+		Subject:                     pkix.Name{CommonName: cn, Organization: []string{"NetPulse"}},
+		NotBefore:                   notBefore,
+		NotAfter:                    now.Add(rootValidity),
+		IsCA:                        true,
+		BasicConstraintsValid:       true,
+		MaxPathLen:                  0,
+		MaxPathLenZero:              true,
+		KeyUsage:                    x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+		PermittedDNSDomainsCritical: false,
+		PermittedDNSDomains:         domains,
+		PermittedIPRanges:           ranges,
+	}, nil
+}
+
+func (ca *CA) loadLeaf() error {
+	path := filepath.Join(ca.opts.Dir, leafCertFile)
+	if !fileExists(path) {
+		return nil
+	}
+	leaf, err := loadCert(path)
+	if err != nil {
+		return err
+	}
+	ca.store(leaf)
+	return nil
+}
+
+func (ca *CA) store(leaf *x509.Certificate) {
+	ca.cur.Store(&tls.Certificate{
+		Certificate: [][]byte{leaf.Raw, ca.root.Raw},
+		PrivateKey:  ca.leafKey,
+		Leaf:        leaf,
+	})
+}
+
+// Refresh re-issues the leaf if it is missing, near expiry, not this CA's,
+// not for the leaf key, or names a different set of addresses than the
+// server now has. It reports whether it issued one. On failure the leaf being
+// served is kept.
+func (ca *CA) Refresh() (bool, error) {
+	ca.mu.Lock()
+	defer ca.mu.Unlock()
+	dns, ips := ca.desiredNames()
+	now := ca.opts.Now()
+	if cur := ca.cur.Load(); cur != nil && !ca.needsReissue(cur.Leaf, dns, ips, now) {
+		return false, nil
+	}
+	serial, err := randomSerial()
+	if err != nil {
+		return false, err
+	}
+	tmpl := &x509.Certificate{
+		SerialNumber: serial,
+		Subject:      pkix.Name{CommonName: "NetPulse"},
+		NotBefore:    now.Add(-time.Hour),
+		NotAfter:     now.Add(leafValidity),
+		KeyUsage:     x509.KeyUsageDigitalSignature,
+		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		DNSNames:     dns,
+		IPAddresses:  ips,
+	}
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &ca.leafKey.PublicKey, ca.rootKey)
+	if err != nil {
+		return false, fmt.Errorf("tls: issue leaf: %w", err)
+	}
+	leaf, err := x509.ParseCertificate(der)
+	if err != nil {
+		return false, err
+	}
+	if err := writeAtomic(filepath.Join(ca.opts.Dir, leafCertFile),
+		pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
+		return false, fmt.Errorf("tls: write leaf: %w", err)
+	}
+	ca.store(leaf)
+	ca.opts.Logf("[netpulse] TLS: issued a certificate for %s, valid until %s",
+		strings.Join(sanList(dns, ips), ", "), leaf.NotAfter.Format(time.DateOnly))
+	return true, nil
+}
+
+func (ca *CA) needsReissue(leaf *x509.Certificate, dns []string, ips []net.IP, now time.Time) bool {
+	if leaf == nil || leaf.CheckSignatureFrom(ca.root) != nil {
+		return true
+	}
+	if pub, ok := leaf.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&ca.leafKey.PublicKey) {
+		return true
+	}
+	if now.Add(leafRenewBefore).After(leaf.NotAfter) || now.Before(leaf.NotBefore) {
+		return true
+	}
+	return !slices.Equal(sanList(leaf.DNSNames, leaf.IPAddresses), sanList(dns, ips))
+}
+
+// desiredNames is what the leaf should name now: every address the server
+// can be reached at and every name it goes by, limited to what the root may
+// vouch for.
+func (ca *CA) desiredNames() ([]string, []net.IP) {
+	var names []string
+	ips := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
+	if addrs, err := ca.opts.Addrs(); err == nil {
+		ips = append(ips, addrs...)
+	} else {
+		ca.opts.Logf("[netpulse] TLS: cannot list this host's addresses: %v", err)
+	}
+	host, _ := ca.opts.Hostname()
+	names = append(names, hostNames(host)...)
+	if short := firstLabel(host); short != "" {
+		for _, d := range ca.opts.SearchDomains() {
+			names = append(names, short+"."+d)
+		}
+	}
+	for _, n := range append(slices.Clone(ca.opts.Names), ca.opts.PublicHost) {
+		n = normName(n)
+		if n == "" {
+			continue
+		}
+		if ip := net.ParseIP(n); ip != nil {
+			ips = append(ips, ip)
+		} else {
+			names = append(names, n)
+		}
+	}
+
+	var dns, dropped []string
+	var keep []net.IP
+	for _, n := range names {
+		if ca.permitsName(n) {
+			dns = append(dns, n)
+		} else {
+			dropped = append(dropped, n)
+		}
+	}
+	for _, ip := range ips {
+		if ip.IsLinkLocalUnicast() || ip.IsMulticast() || ip.IsUnspecified() {
+			continue
+		}
+		if ca.permitsIP(ip) {
+			keep = append(keep, ip)
+		} else {
+			dropped = append(dropped, ip.String())
+		}
+	}
+	slices.Sort(dns)
+	dns = slices.Compact(dns)
+	slices.SortFunc(keep, func(a, b net.IP) int { return strings.Compare(a.String(), b.String()) })
+	keep = slices.CompactFunc(keep, func(a, b net.IP) bool { return a.Equal(b) })
+
+	// Said once per change, not on every check.
+	slices.Sort(dropped)
+	dropped = slices.Compact(dropped)
+	ca.uncovered = dropped
+	if d := strings.Join(dropped, ", "); d != ca.lastDropped {
+		ca.lastDropped = d
+		if d != "" {
+			ca.opts.Logf("[netpulse] TLS: the certificate cannot name %s: the CA only vouches for private "+
+				"addresses, and for local names and the names it was created with. A name can be added by "+
+				"creating a new CA with it in NETPULSE_TLS_NAMES (docs/https.md, \"Starting over\"); a "+
+				"public address cannot be covered.", d)
+		}
+	}
+	return dns, keep
+}
+
+func (ca *CA) permitsName(n string) bool {
+	for _, d := range ca.root.PermittedDNSDomains {
+		if n == d || strings.HasSuffix(n, "."+d) {
+			return true
+		}
+	}
+	return false
+}
+
+func (ca *CA) permitsIP(ip net.IP) bool {
+	for _, r := range ca.root.PermittedIPRanges {
+		if r.Contains(ip) {
+			return true
+		}
+	}
+	return false
+}
+
+// Run re-checks the leaf until done is closed.
+func (ca *CA) Run(done <-chan struct{}) {
+	t := time.NewTicker(caCheckEvery)
+	defer t.Stop()
+	for {
+		select {
+		case <-done:
+			return
+		case <-t.C:
+			if _, err := ca.Refresh(); err != nil {
+				ca.opts.Logf("[netpulse] TLS: %v (still serving the previous certificate)", err)
+			}
+		}
+	}
+}
+
+// TLSConfig serves the current leaf with the root attached, so a client that
+// pins the root can verify the chain.
+func (ca *CA) TLSConfig() *tls.Config {
+	return &tls.Config{
+		GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
+			return ca.cur.Load(), nil
+		},
+		MinVersion: tls.VersionTLS12,
+		// TLS 1.2 is limited to forward-secret AEAD suites; the key is ECDSA,
+		// so only ECDSA suites can be used anyway. TLS 1.3 suites are all
+		// sound and not configurable.
+		CipherSuites: []uint16{
+			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+			tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
+			tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
+		},
+		CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256},
+	}
+}
+
+// Fingerprint is the root's SPKI fingerprint: the pin agents use.
+func (ca *CA) Fingerprint() string { return Fingerprint(ca.root) }
+
+// RootSHA256 is the SHA-256 of the root certificate, in the colon-separated
+// form phones and browsers show when installing it - what an admin compares.
+func (ca *CA) RootSHA256() string {
+	sum := sha256.Sum256(ca.root.Raw)
+	parts := make([]string, len(sum))
+	for i, b := range sum {
+		parts[i] = fmt.Sprintf("%02X", b)
+	}
+	return strings.Join(parts, ":")
+}
+
+// RootDER and RootPEM are the root certificate, for devices to install.
+func (ca *CA) RootDER() []byte { return slices.Clone(ca.root.Raw) }
+func (ca *CA) RootPEM() []byte {
+	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.root.Raw})
+}
+
+// Uncovered lists the host's names and addresses the certificate leaves out
+// because the root may not vouch for them, as of the last check.
+func (ca *CA) Uncovered() []string {
+	ca.mu.Lock()
+	defer ca.mu.Unlock()
+	return slices.Clone(ca.uncovered)
+}
+
+// Leaf is the certificate being served now.
+func (ca *CA) Leaf() *x509.Certificate {
+	if cur := ca.cur.Load(); cur != nil {
+		return cur.Leaf
+	}
+	return nil
+}
+
+// --- names and addresses ---
+
+func interfaceAddrs() ([]net.IP, error) {
+	addrs, err := net.InterfaceAddrs()
+	if err != nil {
+		return nil, err
+	}
+	var ips []net.IP
+	for _, a := range addrs {
+		if n, ok := a.(*net.IPNet); ok {
+			ips = append(ips, n.IP)
+		}
+	}
+	return ips, nil
+}
+
+// resolvSearchDomains reads the local DNS domains from /etc/resolv.conf, so
+// the leaf names the host as the network's DNS knows it.
+func resolvSearchDomains() []string {
+	data, err := os.ReadFile("/etc/resolv.conf")
+	if err != nil {
+		return nil
+	}
+	var out []string
+	for _, line := range strings.Split(string(data), "\n") {
+		f := strings.Fields(line)
+		if len(f) < 2 || (f[0] != "search" && f[0] != "domain") {
+			continue
+		}
+		for _, d := range f[1:] {
+			if d = normName(d); d != "" && d != "." {
+				out = append(out, d)
+			}
+		}
+	}
+	return out
+}
+
+// hostNames is the host name as given and its first label, lower-cased.
+func hostNames(host string) []string {
+	host = normName(host)
+	if host == "" {
+		return nil
+	}
+	if short := firstLabel(host); short != host {
+		return []string{host, short}
+	}
+	return []string{host}
+}
+
+// underLocalSuffix reports whether n is one of the local suffixes or below
+// one.
+func underLocalSuffix(n string) bool {
+	for _, d := range permittedLocalSuffixes {
+		if n == d || strings.HasSuffix(n, "."+d) {
+			return true
+		}
+	}
+	return false
+}
+
+func firstLabel(host string) string {
+	host = normName(host)
+	if i := strings.IndexByte(host, '.'); i >= 0 {
+		return host[:i]
+	}
+	return host
+}
+
+func normName(n string) string {
+	return strings.TrimSuffix(strings.ToLower(strings.TrimSpace(n)), ".")
+}
+
+func sanList(dns []string, ips []net.IP) []string {
+	out := slices.Clone(dns)
+	for _, ip := range ips {
+		out = append(out, ip.String())
+	}
+	slices.Sort(out)
+	return out
+}
+
+// --- files ---
+
+// ensurePrivateDir creates dir 0700, or checks that an existing one is not
+// open to other users.
+func ensurePrivateDir(dir string) error {
+	if err := os.MkdirAll(dir, 0o700); err != nil {
+		return fmt.Errorf("tls: %w", err)
+	}
+	fi, err := os.Stat(dir)
+	if err != nil {
+		return fmt.Errorf("tls: %w", err)
+	}
+	if fi.Mode().Perm()&0o077 != 0 {
+		return fmt.Errorf("tls: %s is open to other users (mode %04o); it holds the CA key. Run: chmod 700 %s",
+			dir, fi.Mode().Perm(), dir)
+	}
+	if !ownedByMe(fi) {
+		return fmt.Errorf("tls: %s is not owned by the user the server runs as", dir)
+	}
+	return nil
+}
+
+// checkPrivateFile refuses a key file other users could read or replace.
+func checkPrivateFile(path string, fi fs.FileInfo) error {
+	if fi.Mode().Perm()&0o077 != 0 {
+		return fmt.Errorf("%s is open to other users (mode %04o). Run: chmod 600 %s", path, fi.Mode().Perm(), path)
+	}
+	if !ownedByMe(fi) {
+		return fmt.Errorf("%s is not owned by the user the server runs as", path)
+	}
+	return nil
+}
+
+func loadOrCreateKey(path string) (*ecdsa.PrivateKey, error) {
+	if fileExists(path) {
+		return loadKey(path)
+	}
+	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		return nil, err
+	}
+	return key, writeKey(path, key)
+}
+
+func loadKey(path string) (*ecdsa.PrivateKey, error) {
+	fi, err := os.Stat(path)
+	if err != nil {
+		return nil, err
+	}
+	if err := checkPrivateFile(path, fi); err != nil {
+		return nil, err
+	}
+	data, err := os.ReadFile(path)
+	if err != nil {
+		return nil, err
+	}
+	block, _ := pem.Decode(data)
+	if block == nil || block.Type != "EC PRIVATE KEY" {
+		return nil, fmt.Errorf("%s: not a PEM EC private key", path)
+	}
+	return x509.ParseECPrivateKey(block.Bytes)
+}
+
+func writeKey(path string, key *ecdsa.PrivateKey) error {
+	der, err := x509.MarshalECPrivateKey(key)
+	if err != nil {
+		return err
+	}
+	return writeAtomic(path, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}), 0o600)
+}
+
+func loadCert(path string) (*x509.Certificate, error) {
+	data, err := os.ReadFile(path)
+	if err != nil {
+		return nil, err
+	}
+	block, _ := pem.Decode(data)
+	if block == nil || block.Type != "CERTIFICATE" {
+		return nil, fmt.Errorf("%s: not a PEM certificate", path)
+	}
+	return x509.ParseCertificate(block.Bytes)
+}
+
+// writeAtomic replaces path so that a reader - or a crash - sees either the
+// old content or the new, never half of it.
+func writeAtomic(path string, data []byte, mode os.FileMode) error {
+	dir := filepath.Dir(path)
+	tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
+	if err != nil {
+		return err
+	}
+	name := tmp.Name()
+	defer os.Remove(name) // no-op once renamed
+	if err := tmp.Chmod(mode); err != nil {
+		tmp.Close()
+		return err
+	}
+	if _, err := tmp.Write(data); err != nil {
+		tmp.Close()
+		return err
+	}
+	if err := tmp.Sync(); err != nil {
+		tmp.Close()
+		return err
+	}
+	if err := tmp.Close(); err != nil {
+		return err
+	}
+	if err := os.Rename(name, path); err != nil {
+		return err
+	}
+	if d, err := os.Open(dir); err == nil {
+		_ = d.Sync()
+		d.Close()
+	}
+	return nil
+}
+
+func randomSerial() (*big.Int, error) {
+	return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
+}

+ 343 - 0
server-go/internal/tlscert/ca_test.go

@@ -0,0 +1,343 @@
+package tlscert
+
+// FORK: tests for the private CA. Addresses are from the documentation and
+// private ranges, names invented.
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/tls"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"fmt"
+	"net"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	agentruntime "github.com/gnacho/netpulse/agent/runtime"
+)
+
+// fakeHost is the system as the CA sees it.
+type fakeHost struct {
+	addrs []net.IP
+	now   time.Time
+	logs  []string
+}
+
+func (h *fakeHost) opts(dir string) CAOptions {
+	return CAOptions{
+		Dir:           dir,
+		Addrs:         func() ([]net.IP, error) { return h.addrs, nil },
+		Hostname:      func() (string, error) { return "monitor-box", nil },
+		SearchDomains: func() []string { return []string{"example.lan"} },
+		Now:           func() time.Time { return h.now },
+		Logf:          func(f string, a ...any) { h.logs = append(h.logs, fmt.Sprintf(f, a...)) },
+	}
+}
+
+func newHost() *fakeHost {
+	return &fakeHost{
+		addrs: []net.IP{net.ParseIP("192.168.50.2"), net.ParseIP("fe80::1")},
+		now:   time.Now(),
+	}
+}
+
+func openTestCA(t *testing.T, h *fakeHost, dir string) *CA {
+	t.Helper()
+	ca, err := OpenCA(h.opts(dir))
+	if err != nil {
+		t.Fatalf("OpenCA: %v", err)
+	}
+	return ca
+}
+
+func verifyFor(t *testing.T, ca *CA, leaf *x509.Certificate, name string) error {
+	t.Helper()
+	roots := x509.NewCertPool()
+	roots.AddCert(ca.root)
+	_, err := leaf.Verify(x509.VerifyOptions{
+		DNSName: name, Roots: roots, CurrentTime: time.Now(),
+		KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+	})
+	return err
+}
+
+func TestTheRootIsConstrainedAndPrivate(t *testing.T) {
+	dir := filepath.Join(t.TempDir(), "tls")
+	ca := openTestCA(t, newHost(), dir)
+	r := ca.root
+	if !r.IsCA || !r.MaxPathLenZero || r.MaxPathLen != 0 || r.KeyUsage&x509.KeyUsageCertSign == 0 {
+		t.Fatalf("root is not a path-length-0 CA: isCA=%v pathlen=%d", r.IsCA, r.MaxPathLen)
+	}
+	// Non-critical on purpose: mbedTLS (OpenWrt) refuses a critical one.
+	if r.PermittedDNSDomainsCritical || len(r.PermittedIPRanges) == 0 || len(r.PermittedDNSDomains) == 0 {
+		t.Fatal("root lacks its name constraints, or marks them critical")
+	}
+	for _, want := range []string{"lan", "home.arpa", "monitor-box", "example.lan"} {
+		if !ca.permitsName(want) {
+			t.Errorf("root does not permit %q", want)
+		}
+	}
+	for path, want := range map[string]os.FileMode{
+		dir:                             0o700,
+		filepath.Join(dir, caKeyFile):   0o600,
+		filepath.Join(dir, leafKeyFile): 0o600,
+	} {
+		fi, err := os.Stat(path)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if fi.Mode().Perm() != want {
+			t.Errorf("%s mode %04o, want %04o", filepath.Base(path), fi.Mode().Perm(), want)
+		}
+	}
+}
+
+func TestTheLeafNamesTheHostAndVerifies(t *testing.T) {
+	ca := openTestCA(t, newHost(), tlsDir(t))
+	leaf := ca.Leaf()
+	for _, name := range []string{"192.168.50.2", "127.0.0.1", "monitor-box", "monitor-box.example.lan"} {
+		if err := verifyFor(t, ca, leaf, name); err != nil {
+			t.Errorf("%s: %v", name, err)
+		}
+	}
+	for _, ip := range leaf.IPAddresses {
+		if ip.IsLinkLocalUnicast() {
+			t.Errorf("leaf names link-local %s", ip)
+		}
+	}
+}
+
+// The point of the constraints: even a certificate signed with the CA's own
+// key is refused for a public name or address.
+func TestTheRootCannotVouchForPublicNames(t *testing.T) {
+	ca := openTestCA(t, newHost(), tlsDir(t))
+	for _, tc := range []struct {
+		dns string
+		ip  string
+	}{
+		{dns: "bank.example.com"},
+		{ip: "203.0.113.7"},
+	} {
+		k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+		serial, _ := randomSerial()
+		tmpl := &x509.Certificate{
+			SerialNumber: serial, Subject: pkix.Name{CommonName: "forged"},
+			NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
+			KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		}
+		name := tc.dns
+		if tc.dns != "" {
+			tmpl.DNSNames = []string{tc.dns}
+		} else {
+			tmpl.IPAddresses = []net.IP{net.ParseIP(tc.ip)}
+			name = tc.ip
+		}
+		der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &k.PublicKey, ca.rootKey)
+		if err != nil {
+			t.Fatal(err)
+		}
+		forged, _ := x509.ParseCertificate(der)
+		if err := verifyFor(t, ca, forged, name); err == nil {
+			t.Errorf("a certificate for %s signed by the CA verified", name)
+		}
+	}
+}
+
+// A public address the host has is left out of the leaf, and said so once.
+func TestAddressesOutsideTheConstraintsAreLeftOut(t *testing.T) {
+	h := newHost()
+	h.addrs = append(h.addrs, net.ParseIP("203.0.113.7"))
+	ca := openTestCA(t, h, tlsDir(t))
+	for _, ip := range ca.Leaf().IPAddresses {
+		if ip.Equal(net.ParseIP("203.0.113.7")) {
+			t.Fatal("the leaf names a public address")
+		}
+	}
+	if _, err := ca.Refresh(); err != nil {
+		t.Fatal(err)
+	}
+	n := 0
+	for _, l := range h.logs {
+		if strings.Contains(l, "203.0.113.7") {
+			n++
+		}
+	}
+	if n != 1 {
+		t.Fatalf("the dropped address was logged %d times, want once", n)
+	}
+}
+
+func TestReopeningKeepsTheRootAndTheLeaf(t *testing.T) {
+	h := newHost()
+	dir := tlsDir(t)
+	first := openTestCA(t, h, dir)
+	second := openTestCA(t, h, dir)
+	if first.Fingerprint() != second.Fingerprint() {
+		t.Fatal("reopening created a new root")
+	}
+	if first.Leaf().SerialNumber.Cmp(second.Leaf().SerialNumber) != 0 {
+		t.Fatal("reopening re-issued a leaf that was still good")
+	}
+}
+
+func TestTheLeafFollowsTheHostsAddressesWithTheSameKey(t *testing.T) {
+	h := newHost()
+	ca := openTestCA(t, h, tlsDir(t))
+	before := ca.Leaf()
+	h.addrs = []net.IP{net.ParseIP("10.20.30.40")}
+	issued, err := ca.Refresh()
+	if err != nil || !issued {
+		t.Fatalf("an address change did not re-issue the leaf (issued=%v, err=%v)", issued, err)
+	}
+	after := ca.Leaf()
+	if err := verifyFor(t, ca, after, "10.20.30.40"); err != nil {
+		t.Fatalf("new leaf does not name the new address: %v", err)
+	}
+	if !after.PublicKey.(*ecdsa.PublicKey).Equal(before.PublicKey) {
+		t.Fatal("re-issuing changed the leaf key")
+	}
+	if issued, _ := ca.Refresh(); issued {
+		t.Fatal("an unchanged host re-issued the leaf again")
+	}
+}
+
+func TestTheLeafIsRenewedBeforeItExpires(t *testing.T) {
+	h := newHost()
+	ca := openTestCA(t, h, tlsDir(t))
+	h.now = h.now.Add(leafValidity - leafRenewBefore + time.Hour)
+	if issued, err := ca.Refresh(); err != nil || !issued {
+		t.Fatalf("a leaf inside the renewal window was not renewed (issued=%v, err=%v)", issued, err)
+	}
+	if !ca.Leaf().NotAfter.After(h.now.Add(leafRenewBefore)) {
+		t.Fatal("the renewed leaf is not valid for long enough")
+	}
+}
+
+func TestAFailedWriteKeepsServingThePreviousLeaf(t *testing.T) {
+	if os.Geteuid() == 0 {
+		t.Skip("root ignores directory permissions")
+	}
+	h := newHost()
+	dir := tlsDir(t)
+	ca := openTestCA(t, h, dir)
+	before := ca.Leaf()
+	if err := os.Chmod(dir, 0o500); err != nil {
+		t.Fatal(err)
+	}
+	defer os.Chmod(dir, 0o700)
+	h.addrs = []net.IP{net.ParseIP("10.20.30.40")}
+	if _, err := ca.Refresh(); err == nil {
+		t.Fatal("writing into a read-only directory succeeded")
+	}
+	if ca.Leaf() != before {
+		t.Fatal("a failed re-issue replaced the served leaf")
+	}
+}
+
+func TestOpenKeyFilesAreRefused(t *testing.T) {
+	for _, tc := range []struct {
+		name string
+		mess func(dir string) error
+		want string
+	}{
+		{"a readable CA key", func(dir string) error { return os.Chmod(filepath.Join(dir, caKeyFile), 0o644) }, "chmod 600"},
+		{"a readable directory", func(dir string) error { return os.Chmod(dir, 0o755) }, "chmod 700"},
+		{"a CA certificate without its key", func(dir string) error { return os.Remove(filepath.Join(dir, caKeyFile)) }, "only one of"},
+		{"a CA key without its certificate", func(dir string) error { return os.Remove(filepath.Join(dir, caCertFile)) }, "only one of"},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			h := newHost()
+			dir := filepath.Join(t.TempDir(), "tls")
+			openTestCA(t, h, dir)
+			if err := tc.mess(dir); err != nil {
+				t.Fatal(err)
+			}
+			_, err := OpenCA(h.opts(dir))
+			if err == nil || !strings.Contains(err.Error(), tc.want) {
+				t.Fatalf("OpenCA error %v, want one saying %q", err, tc.want)
+			}
+		})
+	}
+}
+
+// End to end: an agent that pins the root reaches the server over TLS.
+func TestAnAgentPinningTheRootConnects(t *testing.T) {
+	ca := openTestCA(t, newHost(), tlsDir(t))
+	// A listener with exactly the CA's config: httptest would add its own
+	// certificate, which Go serves instead of GetCertificate's to a client
+	// that sends no SNI - as one dialling an address does.
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		fmt.Fprint(w, "ok")
+	})}
+	go srv.Serve(tls.NewListener(ln, ca.TLSConfig()))
+	defer srv.Close()
+	url := "https://" + ln.Addr().String()
+
+	tr, err := agentruntime.ServerTransport(url, ca.Fingerprint())
+	if err != nil {
+		t.Fatal(err)
+	}
+	res, err := (&http.Client{Transport: tr, Timeout: 5 * time.Second}).Get(url)
+	if err != nil {
+		t.Fatalf("an agent pinning the root could not connect: %v", err)
+	}
+	res.Body.Close()
+	if res.TLS == nil || res.TLS.Version < tls.VersionTLS12 {
+		t.Fatal("not a TLS 1.2+ connection")
+	}
+}
+
+func TestRootSHA256IsWhatDevicesShow(t *testing.T) {
+	ca := openTestCA(t, newHost(), tlsDir(t))
+	fp := ca.RootSHA256()
+	if len(fp) != 32*3-1 || strings.Count(fp, ":") != 31 || strings.ToUpper(fp) != fp {
+		t.Fatalf("RootSHA256 = %q, want 32 upper-case hex pairs joined by colons", fp)
+	}
+}
+
+// tlsDir is a directory the CA creates itself, as DATA_DIR/tls is.
+func tlsDir(t *testing.T) string {
+	t.Helper()
+	return filepath.Join(t.TempDir(), "tls")
+}
+
+// A search domain lets the root vouch for this host under it, never for the
+// whole domain, which can be a company's or a public one.
+func TestASearchDomainOnlyCoversThisHost(t *testing.T) {
+	h := newHost()
+	opts := h.opts(tlsDir(t))
+	opts.SearchDomains = func() []string { return []string{"corp.example"} }
+	ca, err := OpenCA(opts)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !ca.permitsName("monitor-box.corp.example") {
+		t.Fatal("the host under its search domain is not covered")
+	}
+	for _, n := range []string{"corp.example", "mail.corp.example"} {
+		if ca.permitsName(n) {
+			t.Errorf("the root may vouch for %s", n)
+		}
+	}
+}
+
+// Created with a clock running fast, the root is still valid once the clock
+// is corrected.
+func TestTheRootToleratesAFastClockAtCreation(t *testing.T) {
+	h := newHost()
+	h.now = time.Now().Add(90 * 24 * time.Hour)
+	ca := openTestCA(t, h, tlsDir(t))
+	if !ca.root.NotBefore.Before(time.Now()) {
+		t.Fatalf("root not valid before %v", ca.root.NotBefore)
+	}
+}

+ 8 - 0
server-go/internal/tlscert/owner_other.go

@@ -0,0 +1,8 @@
+//go:build !unix
+
+package tlscert
+
+import "io/fs"
+
+// ownedByMe cannot be checked here; the mode checks still apply.
+func ownedByMe(fs.FileInfo) bool { return true }

+ 15 - 0
server-go/internal/tlscert/owner_unix.go

@@ -0,0 +1,15 @@
+//go:build unix
+
+package tlscert
+
+import (
+	"io/fs"
+	"os"
+	"syscall"
+)
+
+// ownedByMe reports whether fi belongs to the user this process runs as.
+func ownedByMe(fi fs.FileInfo) bool {
+	st, ok := fi.Sys().(*syscall.Stat_t)
+	return !ok || int(st.Uid) == os.Geteuid()
+}

+ 21 - 0
server-go/internal/tlscert/reloader.go

@@ -2,6 +2,7 @@ package tlscert
 
 import (
 	"crypto/tls"
+	"crypto/x509"
 	"os"
 	"sync"
 	"time"
@@ -65,6 +66,26 @@ func (r *Reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error
 	return r.cert, nil
 }
 
+// Fingerprint is the SPKI fingerprint of the certificate being served now,
+// after picking up a renewal as a handshake would. It is read live because
+// renewals often change the key (certbot issues a new one unless told
+// --reuse-key), and a value captured at start-up would hand agents a pin
+// the server no longer matches. Empty if the served pair cannot be parsed.
+func (r *Reloader) Fingerprint() string {
+	cert, _ := r.GetCertificate(nil)
+	if cert == nil || len(cert.Certificate) == 0 {
+		return ""
+	}
+	leaf := cert.Leaf
+	if leaf == nil {
+		var err error
+		if leaf, err = x509.ParseCertificate(cert.Certificate[0]); err != nil {
+			return ""
+		}
+	}
+	return Fingerprint(leaf)
+}
+
 // reload repuebla la caché desde disco. Debe llamarse con r.mu tomado.
 func (r *Reloader) reload() error {
 	cert, err := tls.LoadX509KeyPair(r.certPath, r.keyPath)

+ 35 - 0
server-go/internal/tlscert/reloader_test.go

@@ -134,3 +134,38 @@ func copyFile(t *testing.T, src, dst string) {
 		t.Fatalf("escribir %s: %v", dst, err)
 	}
 }
+
+// FORK: the fingerprint follows a renewal that changes the key, since agents
+// are handed it at pairing.
+func TestReloaderFingerprintFollowsARenewal(t *testing.T) {
+	dir := t.TempDir()
+	certPath, keyPath := filepath.Join(dir, "c.pem"), filepath.Join(dir, "k.pem")
+	_, first, err := Ensure(certPath, keyPath)
+	if err != nil {
+		t.Fatal(err)
+	}
+	r, err := NewReloader(certPath, keyPath)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if got := r.Fingerprint(); got != first {
+		t.Fatalf("fingerprint = %q, want the served key %q", got, first)
+	}
+
+	other := t.TempDir()
+	_, second, err := Ensure(filepath.Join(other, "c.pem"), filepath.Join(other, "k.pem"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	copyFile(t, filepath.Join(other, "c.pem"), certPath)
+	copyFile(t, filepath.Join(other, "k.pem"), keyPath)
+	future := time.Now().Add(time.Minute)
+	for _, p := range []string{certPath, keyPath} {
+		if err := os.Chtimes(p, future, future); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if got := r.Fingerprint(); got != second || got == first {
+		t.Fatalf("after renewal fingerprint = %q, want the new key %q", got, second)
+	}
+}

+ 658 - 0
server-go/internal/tlsmode/manager.go

@@ -0,0 +1,658 @@
+// Package tlsmode runs HTTPS with the server's private CA and decides what
+// plain HTTP may still do, as settings an admin changes from the web UI
+// without a restart.
+//
+// FORK: see docs/https.md. In short:
+//
+//   - Enabling HTTPS only adds a TLS listener (NETPULSE_TLS_PORT, 3443 by
+//     default) served with a leaf of the private CA. Plain HTTP keeps working
+//     exactly as before (mode "full"), so enabling it cannot lock anyone out.
+//   - Mode "migrate" stops plain HTTP from carrying credentials - logins,
+//     sessions, API tokens - and redirects browsers to HTTPS, while agents
+//     keep reporting over it until each one has moved.
+//   - Mode "redirect" leaves plain HTTP with nothing but redirects, the root
+//     certificate and a loopback health check.
+//
+// A stricter mode only takes effect once confirmed from a page loaded over
+// HTTPS, within a few minutes: the admin has then proved they can reach and
+// log in over HTTPS before plain HTTP stops accepting logins.
+//
+// The environment always wins over the UI (NETPULSE_TLS_ENABLED with
+// NETPULSE_TLS_CA, NETPULSE_HTTP_MODE): a setting fixed there is shown as
+// locked, and is how to recover over SSH if the UI cannot be reached.
+package tlsmode
+
+import (
+	"context"
+	"crypto/rand"
+	"crypto/subtle"
+	"database/sql"
+	"encoding/hex"
+	"errors"
+	"fmt"
+	"net"
+	"net/http"
+	"net/url"
+	"os"
+	"path/filepath"
+	"slices"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"syscall"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/tlscert"
+)
+
+// Mode is what plain HTTP may still do once HTTPS is on.
+type Mode string
+
+const (
+	Full     Mode = "full"
+	Migrate  Mode = "migrate"
+	Redirect Mode = "redirect"
+)
+
+// ParseMode accepts the three modes; anything else is an error.
+func ParseMode(s string) (Mode, error) {
+	switch m := Mode(s); m {
+	case Full, Migrate, Redirect:
+		return m, nil
+	}
+	return "", fmt.Errorf("unknown HTTP mode %q (want full, migrate or redirect)", s)
+}
+
+const (
+	kvEnabled = "settings.https.enabled"
+	kvMode    = "settings.https.mode"
+
+	// ConfirmWindow is how long a staged mode change waits for confirmation
+	// from an HTTPS page before it is dropped.
+	ConfirmWindow = 5 * time.Minute
+)
+
+// KV is the part of the database the manager uses.
+type KV interface {
+	QueryRow(query string, args ...any) *sql.Row
+	Exec(query string, args ...any) (sql.Result, error)
+}
+
+// Options configures New.
+type Options struct {
+	DB        KV
+	DataDir   string
+	Port      int      // the TLS listener's port
+	Names     []string // NETPULSE_TLS_NAMES
+	PublicURL string   // NETPULSE_PUBLIC_URL
+
+	// EnvEnabled is non-nil when the environment decides whether HTTPS with
+	// the private CA is on; EnvMode is non-empty when it fixes the mode.
+	EnvEnabled *bool
+	EnvMode    Mode
+	// Unavailable, when not empty, says why this server's HTTPS is managed
+	// elsewhere (on-box, or a certificate of the admin's own), and the
+	// manager stays off.
+	Unavailable string
+
+	// NewServer builds the TLS listener's server with the same timeouts as
+	// the plain one.
+	NewServer func(addr string, h http.Handler) *http.Server
+
+	Logf func(format string, args ...any)
+	Now  func() time.Time
+	// CAOptions adjusts the CA's options; tests use it to fake the host.
+	CAOptions func(tlscert.CAOptions) tlscert.CAOptions
+}
+
+// Manager is the HTTPS state of the running server.
+type Manager struct {
+	opts Options
+
+	mu       sync.Mutex
+	handler  http.Handler
+	enabled  bool
+	ca       *tlscert.CA
+	srv      *http.Server
+	caStop   chan struct{}
+	lastErr  string
+	pending  *pendingMode
+	mode     atomic.Value // Mode
+	caLoaded atomic.Pointer[tlscert.CA]
+
+	sniff *sniffServer
+}
+
+type pendingMode struct {
+	mode    Mode
+	code    string
+	expires time.Time
+	by      string
+}
+
+// New reads the saved settings. Nothing listens until Start.
+func New(opts Options) *Manager {
+	if opts.Logf == nil {
+		opts.Logf = func(string, ...any) {}
+	}
+	if opts.Now == nil {
+		opts.Now = time.Now
+	}
+	m := &Manager{opts: opts}
+	m.mode.Store(Full)
+	if opts.Unavailable != "" {
+		return m
+	}
+	m.enabled = m.savedEnabled()
+	if opts.EnvEnabled != nil {
+		m.enabled = *opts.EnvEnabled
+	}
+	mode := m.savedMode()
+	if opts.EnvMode != "" {
+		mode = opts.EnvMode
+	}
+	if !m.enabled {
+		mode = Full
+	}
+	m.mode.Store(mode)
+	return m
+}
+
+// Start begins serving HTTPS if it is enabled. h is the API handler, served
+// on the TLS listener exactly as on the plain one. An error is returned only
+// when the environment asked for HTTPS; a UI setting that cannot be applied
+// is reported in the status instead, and plain HTTP keeps working.
+func (m *Manager) Start(h http.Handler) error {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.handler = h
+	m.sniff = newSniffServer(m)
+	if !m.enabled {
+		// A CA from an earlier run is opened even with HTTPS off, so the
+		// plain port can still answer browsers holding an HSTS policy (see
+		// SniffListener). Failing here only loses that.
+		if fileExists(filepath.Join(m.opts.DataDir, "tls", "ca.pem")) {
+			if err := m.openCALocked(); err != nil {
+				m.opts.Logf("[netpulse] TLS: CA not opened: %v", err)
+			}
+		}
+		return nil
+	}
+	if err := m.startLocked(); err != nil {
+		m.enabled = false
+		m.mode.Store(Full)
+		m.lastErr = err.Error()
+		if m.opts.EnvEnabled != nil && *m.opts.EnvEnabled {
+			return err
+		}
+		m.opts.Logf("[netpulse] HTTPS could not start, plain HTTP only: %v", err)
+	}
+	return nil
+}
+
+func (m *Manager) openCALocked() error {
+	if m.ca != nil {
+		return nil
+	}
+	copts := tlscert.CAOptions{
+		Dir:        filepath.Join(m.opts.DataDir, "tls"),
+		Names:      m.opts.Names,
+		PublicHost: urlHost(m.opts.PublicURL),
+		Logf:       m.opts.Logf,
+	}
+	if m.opts.CAOptions != nil {
+		copts = m.opts.CAOptions(copts)
+	}
+	ca, err := tlscert.OpenCA(copts)
+	if err != nil {
+		return err
+	}
+	m.ca = ca
+	m.caLoaded.Store(ca)
+	// Renewal runs for as long as the CA is loaded - with HTTPS off too,
+	// since the plain port's TLS side still serves the leaf.
+	m.caStop = make(chan struct{})
+	go ca.Run(m.caStop)
+	m.opts.Logf("[netpulse] TLS: root certificate SHA-256 %s", ca.RootSHA256())
+	m.opts.Logf("[netpulse] TLS: agents pin %s", ca.Fingerprint())
+	return nil
+}
+
+func (m *Manager) startLocked() error {
+	if err := m.openCALocked(); err != nil {
+		return err
+	}
+	addr := fmt.Sprintf(":%d", m.opts.Port)
+	// Turning HTTPS off and on again quickly can find the previous listener
+	// still closing (stopLocked shuts it down in the background).
+	var ln net.Listener
+	var err error
+	for i := 0; i < 20; i++ {
+		if ln, err = net.Listen("tcp", addr); err == nil || !errors.Is(err, syscall.EADDRINUSE) {
+			break
+		}
+		time.Sleep(100 * time.Millisecond)
+	}
+	if err != nil {
+		return fmt.Errorf("HTTPS listener on %s: %w", addr, err)
+	}
+	srv := m.opts.NewServer(addr, m.handler)
+	srv.TLSConfig = m.ca.TLSConfig()
+	m.srv = srv
+	go func() {
+		if err := srv.ServeTLS(ln, "", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
+			m.opts.Logf("[netpulse] HTTPS listener stopped: %v", err)
+		}
+	}()
+	m.lastErr = ""
+	m.opts.Logf("[netpulse] HTTPS on :%d (private CA)", m.opts.Port)
+	return nil
+}
+
+func (m *Manager) stopLocked() {
+	if srv := m.srv; srv != nil {
+		m.srv = nil
+		// Shutdown closes the listener at once - the port is free to be
+		// opened again - and lets requests in flight finish, including the
+		// one that turned HTTPS off, whose answer would otherwise be lost.
+		go func() {
+			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+			defer cancel()
+			if err := srv.Shutdown(ctx); err != nil {
+				_ = srv.Close()
+			}
+		}()
+	}
+}
+
+// Close stops the TLS listeners and the leaf's renewal.
+func (m *Manager) Close() {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.stopLocked()
+	if m.caStop != nil {
+		close(m.caStop)
+		m.caStop = nil
+	}
+	if m.sniff != nil {
+		m.sniff.close()
+	}
+}
+
+// ErrLocked is returned for a change to a setting the environment fixes.
+var ErrLocked = errors.New("this setting is fixed in the server's environment")
+
+// ErrNotFull is returned for turning HTTPS off in a stricter mode.
+var ErrNotFull = errors.New("choose \"Everything\" first: browsers told to always use HTTPS in a stricter mode " +
+	"need it answering for a while to be told to stop")
+
+// SetEnabled turns HTTPS on or off, live. Turning it off also returns plain
+// HTTP to full service: without HTTPS there is nowhere to redirect to.
+func (m *Manager) SetEnabled(on bool, by string) error {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.opts.Unavailable != "" || m.opts.EnvEnabled != nil {
+		return ErrLocked
+	}
+	if on == m.enabled {
+		return nil
+	}
+	if on {
+		if err := m.startLocked(); err != nil {
+			m.lastErr = err.Error()
+			return err
+		}
+	} else {
+		if m.opts.EnvMode != "" && m.opts.EnvMode != Full {
+			return fmt.Errorf("%w: NETPULSE_HTTP_MODE=%s needs HTTPS", ErrLocked, m.opts.EnvMode)
+		}
+		// Only from full: browsers that got an HSTS policy in a stricter
+		// mode need a while of full, where HTTPS answers with max-age=0,
+		// to be told to drop it.
+		if m.Mode() != Full {
+			return ErrNotFull
+		}
+		m.stopLocked()
+		m.pending = nil
+	}
+	m.enabled = on
+	m.saveEnabled(on)
+	m.opts.Logf("[netpulse] HTTPS turned %s by %s", onOff(on), by)
+	return nil
+}
+
+// RequestMode changes what plain HTTP may do. Going back to full takes effect
+// at once; a stricter mode is staged and returns the code to confirm it with
+// from an HTTPS page (Confirm) before ConfirmWindow runs out.
+func (m *Manager) RequestMode(mode Mode, by string) (code string, expires time.Time, err error) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.opts.Unavailable != "" || m.opts.EnvMode != "" {
+		return "", time.Time{}, ErrLocked
+	}
+	if !m.enabled && mode != Full {
+		return "", time.Time{}, errors.New("turn HTTPS on first")
+	}
+	if mode == Full {
+		m.pending = nil
+		m.applyModeLocked(Full, by)
+		return "", time.Time{}, nil
+	}
+	b := make([]byte, 16)
+	if _, err := rand.Read(b); err != nil {
+		return "", time.Time{}, err
+	}
+	p := &pendingMode{mode: mode, code: hex.EncodeToString(b), expires: m.opts.Now().Add(ConfirmWindow), by: by}
+	m.pending = p
+	m.opts.Logf("[netpulse] HTTP mode %s staged by %s; waiting for confirmation over HTTPS", mode, by)
+	return p.code, p.expires, nil
+}
+
+// ErrConfirm is returned for a confirmation that does not apply.
+var ErrConfirm = errors.New("no such change is waiting for confirmation; it may have expired")
+
+// Confirm applies a staged mode change. It must arrive over TLS: the point
+// is proving HTTPS works for the admin before plain HTTP is restricted.
+func (m *Manager) Confirm(code string, overTLS bool, by string) (Mode, error) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if !overTLS {
+		return "", errors.New("confirm from the HTTPS address, not over plain HTTP")
+	}
+	p := m.pending
+	if p == nil || m.opts.Now().After(p.expires) ||
+		subtle.ConstantTimeCompare([]byte(code), []byte(p.code)) != 1 {
+		return "", ErrConfirm
+	}
+	m.pending = nil
+	m.applyModeLocked(p.mode, by)
+	return p.mode, nil
+}
+
+func (m *Manager) applyModeLocked(mode Mode, by string) {
+	old := m.Mode()
+	m.mode.Store(mode)
+	m.saveMode(mode)
+	if old != mode {
+		m.opts.Logf("[netpulse] HTTP mode %s -> %s by %s", old, mode, by)
+	}
+}
+
+// Mode is what plain HTTP may do now.
+func (m *Manager) Mode() Mode { return m.mode.Load().(Mode) }
+
+// Enabled reports whether the private-CA HTTPS listener is on.
+func (m *Manager) Enabled() bool {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.enabled
+}
+
+// Fingerprint is the pin agents should use: the root's SPKI, or "" while
+// HTTPS is off.
+func (m *Manager) Fingerprint() string {
+	if !m.Enabled() {
+		return ""
+	}
+	if ca := m.caLoaded.Load(); ca != nil {
+		return ca.Fingerprint()
+	}
+	return ""
+}
+
+// CA is the private CA once it has been opened, for serving its root.
+func (m *Manager) CA() *tlscert.CA { return m.caLoaded.Load() }
+
+// Status is what the settings page shows.
+type Status struct {
+	Available     bool      `json:"available"`
+	Unavailable   string    `json:"unavailable,omitempty"`
+	Enabled       bool      `json:"enabled"`
+	EnabledLocked bool      `json:"enabledLocked"`
+	Mode          Mode      `json:"mode"`
+	ModeLocked    bool      `json:"modeLocked"`
+	Port          int       `json:"port"`
+	RootSHA256    string    `json:"rootSha256,omitempty"`
+	Fingerprint   string    `json:"fingerprint,omitempty"`
+	Names         []string  `json:"names,omitempty"`
+	Uncovered     []string  `json:"uncovered,omitempty"`
+	ValidUntil    time.Time `json:"validUntil,omitzero"`
+	Pending       Mode      `json:"pending,omitempty"`
+	PendingUntil  time.Time `json:"pendingUntil,omitzero"`
+	Error         string    `json:"error,omitempty"`
+}
+
+// Status reports the current state.
+func (m *Manager) Status() Status {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	st := Status{
+		Available:     m.opts.Unavailable == "",
+		Unavailable:   m.opts.Unavailable,
+		Enabled:       m.enabled,
+		EnabledLocked: m.opts.Unavailable != "" || m.opts.EnvEnabled != nil,
+		Mode:          m.Mode(),
+		ModeLocked:    m.opts.Unavailable != "" || m.opts.EnvMode != "",
+		Port:          m.opts.Port,
+		Error:         m.lastErr,
+	}
+	if p := m.pending; p != nil && m.opts.Now().Before(p.expires) {
+		st.Pending, st.PendingUntil = p.mode, p.expires
+	}
+	if m.ca != nil && m.enabled {
+		st.RootSHA256 = m.ca.RootSHA256()
+		st.Fingerprint = m.ca.Fingerprint()
+		st.Uncovered = m.ca.Uncovered()
+		if leaf := m.ca.Leaf(); leaf != nil {
+			st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
+			st.ValidUntil = leaf.NotAfter
+		}
+	}
+	return st
+}
+
+// Renew re-reads the host's addresses and names now, instead of at the next
+// periodic check, and issues a new certificate if they changed. It reports
+// whether it issued one. The root, and so every pin, stays the same.
+func (m *Manager) Renew(by string) (bool, error) {
+	m.mu.Lock()
+	ca, on := m.ca, m.enabled
+	m.mu.Unlock()
+	if ca == nil || !on {
+		return false, errors.New("turn HTTPS on first")
+	}
+	issued, err := ca.Refresh()
+	if err == nil {
+		m.opts.Logf("[netpulse] TLS: certificate checked by %s (new one issued: %v)", by, issued)
+	}
+	return issued, err
+}
+
+// HSTS is the Strict-Transport-Security value for a response, "" for none.
+//
+// While plain HTTP still serves everything (full), HTTPS responses send
+// max-age=0: that clears any HSTS a browser kept from a stricter mode, so
+// going back to full really does make plain HTTP usable again. During
+// migrate the policy is short, so undoing it is cheap; only redirect, which
+// is meant to stay, gets a year. includeSubDomains is never sent.
+func (m *Manager) HSTS(secure bool) string {
+	if !secure || m.CA() == nil {
+		return ""
+	}
+	if !m.Enabled() {
+		return "max-age=0" // served through the plain port's TLS side
+	}
+	switch m.Mode() {
+	case Migrate:
+		return "max-age=86400"
+	case Redirect:
+		return "max-age=31536000"
+	default:
+		return "max-age=0"
+	}
+}
+
+// RedirectTarget is where a plain HTTP request is sent: the same path and
+// query, on the HTTPS port, at a host this server's certificate names. The
+// request's Host header is only used when the certificate names it, so a
+// forged Host cannot turn this into a redirect elsewhere.
+func (m *Manager) RedirectTarget(r *http.Request) (string, bool) {
+	ca := m.caLoaded.Load()
+	if ca == nil {
+		return "", false
+	}
+	leaf := ca.Leaf()
+	if leaf == nil {
+		return "", false
+	}
+	named := func(h string) bool { return h != "" && leafNames(leaf.DNSNames, leaf.IPAddresses, h) }
+	// In order: the name the browser used; the address the request arrived
+	// on; the public URL's host; any address the certificate names.
+	host := strings.ToLower(hostOnly(r.Host))
+	if !named(host) {
+		host = ""
+		if a, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
+			if h := hostOnly(a.String()); named(h) {
+				host = h
+			}
+		}
+		if h := urlHost(m.opts.PublicURL); host == "" && named(h) {
+			host = h
+		}
+		if host == "" {
+			host = firstReachable(leaf.IPAddresses)
+		}
+	}
+	if host == "" {
+		return "", false
+	}
+	u := url.URL{
+		Scheme:   "https",
+		Host:     net.JoinHostPort(host, fmt.Sprint(m.opts.Port)),
+		Path:     r.URL.Path,
+		RawQuery: r.URL.RawQuery,
+	}
+	return u.String(), true
+}
+
+// --- persistence ---
+
+func (m *Manager) savedEnabled() bool {
+	return m.kvGet(kvEnabled) == "1"
+}
+
+func (m *Manager) savedMode() Mode {
+	if mode, err := ParseMode(m.kvGet(kvMode)); err == nil {
+		return mode
+	}
+	return Full
+}
+
+func (m *Manager) saveEnabled(on bool) {
+	v := "0"
+	if on {
+		v = "1"
+	}
+	m.kvSet(kvEnabled, v)
+}
+
+func (m *Manager) saveMode(mode Mode) {
+	if m.opts.EnvMode == "" {
+		m.kvSet(kvMode, string(mode))
+	}
+}
+
+func (m *Manager) kvGet(key string) string {
+	if m.opts.DB == nil {
+		return ""
+	}
+	var v string
+	_ = m.opts.DB.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v)
+	return v
+}
+
+func (m *Manager) kvSet(key, value string) {
+	if m.opts.DB == nil {
+		return
+	}
+	if _, err := m.opts.DB.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		key, value); err != nil {
+		m.opts.Logf("[netpulse] HTTPS: could not save %s: %v", key, err)
+	}
+}
+
+// --- helpers ---
+
+func onOff(b bool) string {
+	if b {
+		return "on"
+	}
+	return "off"
+}
+
+func urlHost(raw string) string {
+	if raw == "" {
+		return ""
+	}
+	u, err := url.Parse(raw)
+	if err != nil {
+		return ""
+	}
+	return u.Hostname()
+}
+
+func hostOnly(hostport string) string {
+	if h, _, err := net.SplitHostPort(hostport); err == nil {
+		return h
+	}
+	return hostport
+}
+
+func leafNames(dns []string, ips []net.IP, host string) bool {
+	if ip := net.ParseIP(host); ip != nil {
+		return slices.ContainsFunc(ips, ip.Equal)
+	}
+	for _, d := range dns {
+		if d == host {
+			return true
+		}
+	}
+	return false
+}
+
+// firstReachable picks an address other devices can use: IPv4, not
+// loopback, and outside 172.16/12 when possible - where container bridges
+// usually live, which nothing else on the network can reach.
+func firstReachable(ips []net.IP) string {
+	_, bridges, _ := net.ParseCIDR("172.16.0.0/12")
+	fallback := ""
+	for _, ip := range ips {
+		if ip.IsLoopback() || ip.To4() == nil {
+			continue
+		}
+		if !bridges.Contains(ip) {
+			return ip.String()
+		}
+		if fallback == "" {
+			fallback = ip.String()
+		}
+	}
+	return fallback
+}
+
+func ipStrings(ips []net.IP) []string {
+	out := make([]string, 0, len(ips))
+	for _, ip := range ips {
+		out = append(out, ip.String())
+	}
+	return out
+}
+
+// Available reports whether this server's HTTPS is managed here at all.
+func (m *Manager) Available() bool { return m.opts.Unavailable == "" }
+
+func fileExists(path string) bool {
+	_, err := os.Stat(path)
+	return err == nil
+}

+ 622 - 0
server-go/internal/tlsmode/manager_test.go

@@ -0,0 +1,622 @@
+package tlsmode
+
+// FORK: tests for the HTTPS manager. Addresses are from the documentation
+// and private ranges, names invented.
+
+import (
+	"context"
+	"crypto/tls"
+	"crypto/x509"
+	"errors"
+	"fmt"
+	"io"
+	"net"
+	"net/http"
+	"net/http/httptest"
+	"path/filepath"
+	"slices"
+	"strings"
+	"sync/atomic"
+	"syscall"
+	"testing"
+	"time"
+
+	agentruntime "github.com/gnacho/netpulse/agent/runtime"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/tlscert"
+)
+
+type rig struct {
+	t    *testing.T
+	m    *Manager
+	db   *db.DB
+	dir  string
+	now  time.Time
+	port int
+}
+
+func freePort(t *testing.T) int {
+	t.Helper()
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer ln.Close()
+	return ln.Addr().(*net.TCPAddr).Port
+}
+
+func newRig(t *testing.T, tweak func(*Options)) *rig {
+	t.Helper()
+	dir := t.TempDir()
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { d.Close() })
+	r := &rig{t: t, db: d, dir: dir, now: time.Now(), port: freePort(t)}
+	opts := Options{
+		DB: d, DataDir: dir, Port: r.port,
+		NewServer: func(addr string, h http.Handler) *http.Server {
+			return &http.Server{Addr: addr, Handler: h, ReadHeaderTimeout: 5 * time.Second}
+		},
+		Now: func() time.Time { return r.now },
+		CAOptions: func(o tlscert.CAOptions) tlscert.CAOptions {
+			o.Addrs = func() ([]net.IP, error) { return []net.IP{net.ParseIP("192.168.50.2")}, nil }
+			o.Hostname = func() (string, error) { return "monitor-box", nil }
+			o.SearchDomains = func() []string { return []string{"example.lan"} }
+			return o
+		},
+	}
+	if tweak != nil {
+		tweak(&opts)
+	}
+	r.m = New(opts)
+	// As the real API does, the handler sets the HSTS policy the mode calls
+	// for; the plain port's TLS side serves this same handler.
+	if err := r.m.Start(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+		if v := r.m.HSTS(req.TLS != nil); v != "" {
+			w.Header().Set("Strict-Transport-Security", v)
+		}
+		fmt.Fprintf(w, "tls=%v", req.TLS != nil)
+	})); err != nil {
+		t.Fatalf("Start: %v", err)
+	}
+	t.Cleanup(r.m.Close)
+	return r
+}
+
+// get fetches path from the TLS listener, pinning the root as an agent would.
+func (r *rig) getTLS(path string) (string, error) {
+	tr, err := agentruntime.ServerTransport(fmt.Sprintf("https://127.0.0.1:%d", r.port), r.m.Fingerprint())
+	if err != nil {
+		return "", err
+	}
+	var res *http.Response
+	for i := 0; i < 50; i++ { // the listener starts in a goroutine
+		res, err = (&http.Client{Transport: tr, Timeout: 2 * time.Second}).Get(fmt.Sprintf("https://127.0.0.1:%d%s", r.port, path))
+		if err == nil {
+			break
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	if err != nil {
+		return "", err
+	}
+	defer res.Body.Close()
+	b, _ := io.ReadAll(res.Body)
+	return string(b), nil
+}
+
+func TestEnablingStartsHTTPSAndDisablingStopsIt(t *testing.T) {
+	r := newRig(t, nil)
+	if r.m.Fingerprint() != "" {
+		t.Fatal("a server with HTTPS off hands out a pin")
+	}
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatalf("enable: %v", err)
+	}
+	body, err := r.getTLS("/")
+	if err != nil || body != "tls=true" {
+		t.Fatalf("an agent pinning the root could not reach HTTPS: %q %v", body, err)
+	}
+	if r.m.Mode() != Full {
+		t.Fatal("enabling HTTPS changed what plain HTTP may do")
+	}
+	if err := r.m.SetEnabled(false, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	closed := false
+	for i := 0; i < 50 && !closed; i++ { // closed from a goroutine, see stopLocked
+		c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", r.port), time.Second)
+		if err != nil {
+			closed = true
+			break
+		}
+		c.Close()
+		time.Sleep(20 * time.Millisecond)
+	}
+	if !closed {
+		t.Fatal("the HTTPS listener is still open after turning HTTPS off")
+	}
+	// And it can be turned on again at once, on the same port.
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatalf("re-enable: %v", err)
+	}
+}
+
+func TestSettingsSurviveARestart(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	code, _, err := r.m.RequestMode(Migrate, "admin")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := r.m.Confirm(code, true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	r.m.Close()
+	again := New(r.m.opts)
+	if !again.Enabled() || again.Mode() != Migrate {
+		t.Fatalf("after a restart enabled=%v mode=%s, want on and migrate", again.Enabled(), again.Mode())
+	}
+}
+
+func TestTheEnvironmentWins(t *testing.T) {
+	off := false
+	r := newRig(t, func(o *Options) { o.EnvEnabled = &off; o.EnvMode = Full })
+	if err := r.m.SetEnabled(true, "admin"); !errors.Is(err, ErrLocked) {
+		t.Fatalf("enabling a setting fixed in the environment: %v, want ErrLocked", err)
+	}
+	if _, _, err := r.m.RequestMode(Migrate, "admin"); !errors.Is(err, ErrLocked) {
+		t.Fatalf("changing a mode fixed in the environment: %v, want ErrLocked", err)
+	}
+	st := r.m.Status()
+	if !st.EnabledLocked || !st.ModeLocked {
+		t.Fatal("status does not show the settings as locked")
+	}
+}
+
+func TestAStricterModeWaitsForConfirmationOverHTTPS(t *testing.T) {
+	r := newRig(t, nil)
+	if _, _, err := r.m.RequestMode(Migrate, "admin"); err == nil {
+		t.Fatal("a stricter mode was accepted with HTTPS off")
+	}
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	code, expires, err := r.m.RequestMode(Redirect, "admin")
+	if err != nil || code == "" {
+		t.Fatalf("RequestMode: %q %v", code, err)
+	}
+	if r.m.Mode() != Full {
+		t.Fatal("the mode changed before it was confirmed")
+	}
+	if !expires.Equal(r.now.Add(ConfirmWindow)) {
+		t.Fatalf("expires %v, want %v", expires, r.now.Add(ConfirmWindow))
+	}
+	if _, err := r.m.Confirm(code, false, "admin"); err == nil {
+		t.Fatal("confirmed over plain HTTP")
+	}
+	wrong := "0" + code[1:]
+	if code[0] == '0' {
+		wrong = "1" + code[1:]
+	}
+	if _, err := r.m.Confirm(wrong, true, "admin"); !errors.Is(err, ErrConfirm) {
+		t.Fatalf("a wrong code: %v, want ErrConfirm", err)
+	}
+	if mode, err := r.m.Confirm(code, true, "admin"); err != nil || mode != Redirect || r.m.Mode() != Redirect {
+		t.Fatalf("confirm: %s %v, mode now %s", mode, err, r.m.Mode())
+	}
+	if _, err := r.m.Confirm(code, true, "admin"); !errors.Is(err, ErrConfirm) {
+		t.Fatal("a code was accepted twice")
+	}
+}
+
+func TestAnUnconfirmedChangeLapses(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	code, _, _ := r.m.RequestMode(Migrate, "admin")
+	r.now = r.now.Add(ConfirmWindow + time.Second)
+	if _, err := r.m.Confirm(code, true, "admin"); !errors.Is(err, ErrConfirm) {
+		t.Fatalf("a lapsed change was applied: %v", err)
+	}
+	if r.m.Mode() != Full || r.m.Status().Pending != "" {
+		t.Fatal("a lapsed change left something behind")
+	}
+}
+
+// Going back to full is always immediate: it is the way out.
+func TestFullTakesEffectAtOnce(t *testing.T) {
+	r := newRig(t, nil)
+	_ = r.m.SetEnabled(true, "admin")
+	code, _, _ := r.m.RequestMode(Redirect, "admin")
+	_, _ = r.m.Confirm(code, true, "admin")
+	if err := r.m.SetEnabled(false, "admin"); !errors.Is(err, ErrNotFull) {
+		t.Fatalf("turning HTTPS off in redirect: %v, want ErrNotFull", err)
+	}
+	if _, _, err := r.m.RequestMode(Full, "admin"); err != nil || r.m.Mode() != Full {
+		t.Fatalf("back to full: %v, mode %s", err, r.m.Mode())
+	}
+	if err := r.m.SetEnabled(false, "admin"); err != nil || r.m.Mode() != Full {
+		t.Fatalf("turning HTTPS off from full: %v", err)
+	}
+}
+
+func setMode(t *testing.T, r *rig, mode Mode) {
+	t.Helper()
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	if mode == Full {
+		return
+	}
+	code, _, err := r.m.RequestMode(mode, "admin")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := r.m.Confirm(code, true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestWhatPlainHTTPMayDo(t *testing.T) {
+	type want struct {
+		status   int
+		location string // prefix, for redirects
+	}
+	cases := []struct {
+		method, path, remote string
+		full, migrate, redir want
+	}{
+		{"POST", "/api/auth/login", "192.168.50.9:5000", want{200, ""}, want{403, ""}, want{426, ""}},
+		{"GET", "/api/overview", "192.168.50.9:5000", want{200, ""}, want{403, ""}, want{426, ""}},
+		{"POST", "/api/ingest/agent", "192.168.50.9:5000", want{200, ""}, want{200, ""}, want{426, ""}},
+		{"GET", "/api/agents/gw/stream", "192.168.50.9:5000", want{200, ""}, want{200, ""}, want{426, ""}},
+		{"POST", "/api/config-backup", "192.168.50.9:5000", want{200, ""}, want{200, ""}, want{426, ""}},
+		{"GET", "/devices?q=x", "192.168.50.9:5000", want{200, ""}, want{308, "https://192.168.50.2:"}, want{308, "https://192.168.50.2:"}},
+		{"POST", "/devices", "192.168.50.9:5000", want{200, ""}, want{403, ""}, want{426, ""}},
+		{"GET", "/netpulse-ca.crt", "192.168.50.9:5000", want{200, ""}, want{200, ""}, want{200, ""}},
+		{"GET", "/api/health", "192.168.50.9:5000", want{200, ""}, want{200, ""}, want{426, ""}},
+		{"GET", "/api/health", "127.0.0.1:5000", want{200, ""}, want{200, ""}, want{200, ""}},
+	}
+	for _, mode := range []Mode{Full, Migrate, Redirect} {
+		t.Run(string(mode), func(t *testing.T) {
+			r := newRig(t, nil)
+			setMode(t, r, mode)
+			h := r.m.PlainHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
+			for _, c := range cases {
+				w := map[Mode]want{Full: c.full, Migrate: c.migrate, Redirect: c.redir}[mode]
+				req := httptest.NewRequest(c.method, "http://192.168.50.2:3000"+c.path, nil)
+				req.RemoteAddr = c.remote
+				rec := httptest.NewRecorder()
+				h.ServeHTTP(rec, req)
+				if rec.Code != w.status {
+					t.Errorf("%s %s from %s: %d, want %d", c.method, c.path, c.remote, rec.Code, w.status)
+				}
+				if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, w.location) {
+					t.Errorf("%s %s: Location %q, want %q...", c.method, c.path, loc, w.location)
+				}
+			}
+		})
+	}
+}
+
+// The redirect never takes a host from the request unless the certificate
+// names it: a forged Host header cannot send the browser elsewhere.
+func TestTheRedirectOnlyGoesToNamesTheCertificateCarries(t *testing.T) {
+	r := newRig(t, nil)
+	setMode(t, r, Migrate)
+	for host, want := range map[string]string{
+		"monitor-box.example.lan:3000": "https://monitor-box.example.lan:",
+		"192.168.50.2:3000":            "https://192.168.50.2:",
+		"attacker.example.com:3000":    "https://192.168.50.2:",
+		"198.51.100.1:3000":            "https://192.168.50.2:",
+	} {
+		req := httptest.NewRequest("GET", "/settings?tab=https", nil)
+		req.Host = host
+		got, ok := r.m.RedirectTarget(req)
+		if !ok || !strings.HasPrefix(got, want) || !strings.HasSuffix(got, "/settings?tab=https") {
+			t.Errorf("Host %s: redirected to %q, want %s...", host, got, want)
+		}
+	}
+}
+
+func TestHSTSFollowsTheMode(t *testing.T) {
+	r := newRig(t, nil)
+	if got := r.m.HSTS(true); got != "" {
+		t.Fatalf("HTTPS never on: HSTS %q", got)
+	}
+	setMode(t, r, Full)
+	if got := r.m.HSTS(true); got != "max-age=0" {
+		t.Fatalf("full: %q, want max-age=0 (clears an earlier policy)", got)
+	}
+	if got := r.m.HSTS(false); got != "" {
+		t.Fatalf("plain response: %q", got)
+	}
+	code, _, _ := r.m.RequestMode(Migrate, "admin")
+	_, _ = r.m.Confirm(code, true, "admin")
+	if got := r.m.HSTS(true); got != "max-age=86400" {
+		t.Fatalf("migrate: %q", got)
+	}
+	code, _, _ = r.m.RequestMode(Redirect, "admin")
+	_, _ = r.m.Confirm(code, true, "admin")
+	if got := r.m.HSTS(true); got != "max-age=31536000" {
+		t.Fatalf("redirect: %q", got)
+	}
+}
+
+// One port, both protocols. Before HTTPS was ever on the plain port is plain
+// only, as before. Once the CA exists it also answers TLS - in every mode,
+// and with HTTPS turned off again - so a browser holding an HSTS policy for
+// the name can still get in, and there be told max-age=0.
+func TestThePlainPortAlsoSpeaksTLSOnceTheCAExists(t *testing.T) {
+	for _, tc := range []struct {
+		name     string
+		setup    func(t *testing.T, r *rig)
+		wantTLS  bool
+		wantHSTS string
+	}{
+		{"never enabled", func(*testing.T, *rig) {}, false, ""},
+		{"full", func(t *testing.T, r *rig) { setMode(t, r, Full) }, true, "max-age=0"},
+		{"migrate", func(t *testing.T, r *rig) { setMode(t, r, Migrate) }, true, "max-age=86400"},
+		{"turned off again", func(t *testing.T, r *rig) {
+			setMode(t, r, Full)
+			if err := r.m.SetEnabled(false, "test"); err != nil {
+				t.Fatal(err)
+			}
+		}, true, "max-age=0"},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			r := newRig(t, nil)
+			tc.setup(t, r)
+			ln, err := net.Listen("tcp", "127.0.0.1:0")
+			if err != nil {
+				t.Fatal(err)
+			}
+			srv := &http.Server{Handler: r.m.PlainHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+				if v := r.m.HSTS(req.TLS != nil); v != "" {
+					w.Header().Set("Strict-Transport-Security", v)
+				}
+				fmt.Fprintf(w, "tls=%v", req.TLS != nil)
+			}))}
+			go srv.Serve(r.m.SniffListener(ln))
+			defer srv.Close()
+			addr := ln.Addr().String()
+
+			res, err := http.Get("http://" + addr + "/api/health")
+			if err != nil {
+				t.Fatal(err)
+			}
+			b, _ := io.ReadAll(res.Body)
+			res.Body.Close()
+			if string(b) != "tls=false" {
+				t.Fatalf("plain client got %q", b)
+			}
+
+			var pool *x509.CertPool
+			if ca := r.m.CA(); ca != nil {
+				pool = x509.NewCertPool()
+				pool.AppendCertsFromPEM(ca.RootPEM())
+			}
+			c := &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{
+				TLSClientConfig: &tls.Config{RootCAs: pool},
+			}}
+			res, err = c.Get("https://" + addr + "/api/health")
+			if !tc.wantTLS {
+				if err == nil {
+					res.Body.Close()
+					t.Fatal("the plain port answered TLS before HTTPS was ever on")
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("TLS on the plain port: %v", err)
+			}
+			b, _ = io.ReadAll(res.Body)
+			res.Body.Close()
+			if string(b) != "tls=true" {
+				t.Fatalf("TLS client got %q", b)
+			}
+			if got := res.Header.Get("Strict-Transport-Security"); got != tc.wantHSTS {
+				t.Fatalf("HSTS %q, want %q", got, tc.wantHSTS)
+			}
+		})
+	}
+}
+
+// A client that connects and sends nothing does not hold up the next one.
+func TestASilentClientDoesNotBlockTheNext(t *testing.T) {
+	r := newRig(t, nil)
+	setMode(t, r, Migrate)
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	srv := &http.Server{Handler: r.m.PlainHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		fmt.Fprint(w, "ok")
+	}))}
+	go srv.Serve(r.m.SniffListener(ln))
+	defer srv.Close()
+	silent, err := net.Dial("tcp", ln.Addr().String())
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer silent.Close()
+	c := &http.Client{Timeout: 2 * time.Second}
+	res, err := c.Get("http://" + ln.Addr().String() + "/api/health")
+	if err != nil {
+		t.Fatalf("a silent connection blocked the next client: %v", err)
+	}
+	res.Body.Close()
+}
+
+func TestTheCALivesInItsOwnDirectory(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatal(err)
+	}
+	st := r.m.Status()
+	if st.RootSHA256 == "" || st.Fingerprint == "" || len(st.Names) == 0 {
+		t.Fatalf("status lacks the root: %+v", st)
+	}
+	if _, err := tlscert.OpenCA(tlscert.CAOptions{Dir: filepath.Join(r.dir, "tls")}); err != nil {
+		t.Fatalf("the CA is not in DATA_DIR/tls: %v", err)
+	}
+}
+
+// flakyListener fails its first Accept the way a process out of file
+// descriptors does.
+type flakyListener struct {
+	net.Listener
+	failed atomic.Bool
+}
+
+func (l *flakyListener) Accept() (net.Conn, error) {
+	if !l.failed.Swap(true) {
+		return nil, &net.OpError{Op: "accept", Net: "tcp", Err: syscall.EMFILE}
+	}
+	return l.Listener.Accept()
+}
+
+// One temporary accept error must not stop the plain port for good.
+func TestThePlainPortSurvivesATemporaryAcceptError(t *testing.T) {
+	r := newRig(t, nil)
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })}
+	go srv.Serve(r.m.SniffListener(&flakyListener{Listener: ln}))
+	defer srv.Close()
+	c := &http.Client{Timeout: 3 * time.Second}
+	res, err := c.Get("http://" + ln.Addr().String() + "/")
+	if err != nil {
+		t.Fatalf("after a temporary accept error the port stopped serving: %v", err)
+	}
+	res.Body.Close()
+}
+
+func TestRedirectHostsTheClientCanReach(t *testing.T) {
+	r := newRig(t, nil)
+	setMode(t, r, Migrate)
+	// Host names are case-insensitive.
+	req := httptest.NewRequest("GET", "/", nil)
+	req.Host = "MONITOR-BOX.Example.LAN:3000"
+	if got, _ := r.m.RedirectTarget(req); !strings.HasPrefix(got, "https://monitor-box.example.lan:") {
+		t.Errorf("mixed-case host: %q", got)
+	}
+	// A name the certificate lacks: the address the request arrived on.
+	req = httptest.NewRequest("GET", "/", nil)
+	req.Host = "localhost:3000"
+	req = req.WithContext(context.WithValue(req.Context(), http.LocalAddrContextKey,
+		&net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 3000}))
+	if got, _ := r.m.RedirectTarget(req); !strings.HasPrefix(got, "https://127.0.0.1:") {
+		t.Errorf("localhost: %q", got)
+	}
+}
+
+func TestFirstReachableAvoidsLoopbackAndBridges(t *testing.T) {
+	ips := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("172.17.0.1"), net.ParseIP("192.168.50.2")}
+	if got := firstReachable(ips); got != "192.168.50.2" {
+		t.Fatalf("got %s", got)
+	}
+	if got := firstReachable(ips[:2]); got != "172.17.0.1" {
+		t.Fatalf("with only a bridge, it is still better than nothing: got %s", got)
+	}
+}
+
+func TestAgentTrust(t *testing.T) {
+	r := newRig(t, nil)
+	legacy := func() string { return "legacy-pin" }
+	if tr := AgentTrust(r.m, legacy, "http://192.168.50.2:3000"); tr.ServerURL != "" || tr.ServerFP != "" || tr.CAPEM != nil {
+		t.Fatalf("HTTPS off, plain base: %+v", tr)
+	}
+	if tr := AgentTrust(r.m, legacy, "https://192.168.50.2:3443"); tr.ServerFP != "legacy-pin" || tr.ServerURL != "" {
+		t.Fatalf("HTTPS off, https base keeps its legacy pin: %+v", tr)
+	}
+	if tr := AgentTrust(nil, legacy, "http://192.168.50.2:3000"); tr.ServerURL != "" {
+		t.Fatalf("no manager: %+v", tr)
+	}
+	_ = r.m.SetEnabled(true, "test")
+	want := fmt.Sprintf("https://192.168.50.2:%d", r.port)
+	for _, base := range []string{
+		"http://192.168.50.2:3000",
+		"http://monitor-box.example.lan:3000", // a name the leaf carries...
+		"http://127.0.0.1:3000",               // ...and loopback, which it must not hand out
+		"http://198.51.100.1:3000",            // an address it does not name
+	} {
+		tr := AgentTrust(r.m, legacy, base)
+		if base == "http://monitor-box.example.lan:3000" {
+			if tr.ServerURL != fmt.Sprintf("https://monitor-box.example.lan:%d", r.port) {
+				t.Errorf("%s -> %s", base, tr.ServerURL)
+			}
+		} else if tr.ServerURL != want {
+			t.Errorf("%s -> %s, want %s", base, tr.ServerURL, want)
+		}
+		if tr.ServerFP != r.m.Fingerprint() || len(tr.CAPEM) == 0 {
+			t.Errorf("%s: pin or root missing: %+v", base, tr)
+		}
+	}
+}
+
+// In the stricter modes a plain-HTTP answer to a person deletes the plain
+// session cookie; an agent's is left alone.
+func TestStricterModesDropThePlainSessionCookie(t *testing.T) {
+	r := newRig(t, nil)
+	setMode(t, r, Migrate)
+	h := r.m.PlainHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+	for path, want := range map[string]bool{"/devices": true, "/api/overview": true, "/api/ingest/agent": false} {
+		method := "GET"
+		if path == "/api/ingest/agent" {
+			method = "POST"
+		}
+		rec := httptest.NewRecorder()
+		h.ServeHTTP(rec, httptest.NewRequest(method, "http://192.168.50.2:3000"+path, nil))
+		got := strings.Contains(strings.Join(rec.Header().Values("Set-Cookie"), ";"), "session=; Path=/")
+		if got != want {
+			t.Errorf("%s: cookie deleted = %v, want %v", path, got, want)
+		}
+	}
+}
+
+// Renew picks up a changed address at once, keeps the root, and says which
+// addresses the root cannot vouch for.
+func TestRenewFollowsAChangedAddress(t *testing.T) {
+	addrs := []net.IP{net.ParseIP("192.168.50.2")}
+	r := newRig(t, func(o *Options) {
+		inner := o.CAOptions
+		o.CAOptions = func(c tlscert.CAOptions) tlscert.CAOptions {
+			c = inner(c)
+			c.Addrs = func() ([]net.IP, error) { return addrs, nil }
+			return c
+		}
+	})
+	if _, err := r.m.Renew("test"); err == nil {
+		t.Fatal("renewed with HTTPS off")
+	}
+	_ = r.m.SetEnabled(true, "test")
+	pin := r.m.Fingerprint()
+
+	addrs = []net.IP{net.ParseIP("10.20.30.40"), net.ParseIP("203.0.113.7")}
+	issued, err := r.m.Renew("test")
+	if err != nil || !issued {
+		t.Fatalf("Renew after an address change: issued=%v err=%v", issued, err)
+	}
+	st := r.m.Status()
+	if !slices.Contains(st.Names, "10.20.30.40") || slices.Contains(st.Names, "192.168.50.2") {
+		t.Fatalf("names after renew: %v", st.Names)
+	}
+	if !slices.Equal(st.Uncovered, []string{"203.0.113.7"}) {
+		t.Fatalf("uncovered: %v", st.Uncovered)
+	}
+	if r.m.Fingerprint() != pin {
+		t.Fatal("renewing changed the root agents pin")
+	}
+	if issued, _ := r.m.Renew("test"); issued {
+		t.Fatal("renewing with nothing changed issued a certificate")
+	}
+}

+ 276 - 0
server-go/internal/tlsmode/plain.go

@@ -0,0 +1,276 @@
+package tlsmode
+
+import (
+	"bufio"
+	"crypto/tls"
+	"errors"
+	"net"
+	"net/http"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// PlainHandler wraps the handler served on the plain HTTP port with what the
+// current mode allows there. Requests that arrived over TLS - on that port,
+// through the sniffing listener - are not restricted.
+func (m *Manager) PlainHandler(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		// Secure is a TLS connection, or one a trusted TLS-terminating proxy
+		// forwarded as https - the same rule the session cookie follows. A
+		// client that fakes the proxy's header only sends its own
+		// credentials in clear.
+		if auth.IsSecureRequest(r) || !m.Enabled() {
+			next.ServeHTTP(w, r)
+			return
+		}
+		switch m.Mode() {
+		case Migrate:
+			if auth.IsAgentRequest(r) || isPublicPath(r.URL.Path) {
+				next.ServeHTTP(w, r)
+				return
+			}
+			dropPlainSession(w)
+			if m.redirectBrowser(w, r) {
+				return
+			}
+			// Refused, not redirected: a redirect cannot protect a password
+			// or token that has already been sent in clear.
+			auth.WriteError(w, http.StatusForbidden, "use_https",
+				"this server only accepts sign-ins and API calls over HTTPS")
+		case Redirect:
+			if isPublicPath(r.URL.Path) && r.URL.Path != "/api/health" && r.URL.Path != "/health" ||
+				isHealthPath(r.URL.Path) && fromLoopback(r) {
+				next.ServeHTTP(w, r)
+				return
+			}
+			dropPlainSession(w)
+			if m.redirectBrowser(w, r) {
+				return
+			}
+			w.Header().Set("Upgrade", "TLS/1.2, HTTP/1.1")
+			w.Header().Set("Connection", "Upgrade")
+			auth.WriteError(w, http.StatusUpgradeRequired, "use_https",
+				"this server only answers over HTTPS")
+		default:
+			next.ServeHTTP(w, r)
+		}
+	})
+}
+
+// dropPlainSession deletes the session cookie of a sign-in made over plain
+// HTTP. A browser sends it with every http:// request - an old bookmark,
+// access by address, which HSTS never covers - in clear, until it expires;
+// once plain HTTP is no longer for people, it is only a liability.
+func dropPlainSession(w http.ResponseWriter) {
+	w.Header().Add("Set-Cookie", auth.ClearSessionCookie)
+}
+
+// redirectBrowser sends a page load to the HTTPS address. API calls are not
+// redirected: a client that would follow one has usually sent its
+// credentials already.
+func (m *Manager) redirectBrowser(w http.ResponseWriter, r *http.Request) bool {
+	if (r.Method != http.MethodGet && r.Method != http.MethodHead) || strings.HasPrefix(r.URL.Path, "/api/") {
+		return false
+	}
+	target, ok := m.RedirectTarget(r)
+	if !ok {
+		return false
+	}
+	http.Redirect(w, r, target, http.StatusPermanentRedirect)
+	return true
+}
+
+// isPublicPath is what carries no credential and is safe over plain HTTP: the
+// health checks, and the root certificate and fingerprint a device needs
+// before it can trust HTTPS at all.
+func isPublicPath(p string) bool {
+	return isHealthPath(p) || p == "/fingerprint" || p == "/netpulse-ca.crt" || p == "/netpulse-ca.pem"
+}
+
+func isHealthPath(p string) bool { return p == "/api/health" || p == "/health" }
+
+// fromLoopback looks at the connection, never at forwarded headers.
+func fromLoopback(r *http.Request) bool {
+	host, _, err := net.SplitHostPort(r.RemoteAddr)
+	if err != nil {
+		return false
+	}
+	ip := net.ParseIP(host)
+	return ip != nil && ip.IsLoopback()
+}
+
+// --- one port, both protocols ---
+
+// peekTimeout bounds how long a new connection may take to send its first
+// byte before it is dropped, so a client that sends nothing cannot hold a
+// goroutine forever.
+const peekTimeout = 10 * time.Second
+
+// SniffListener wraps the plain port's listener. Once the CA exists, a
+// connection that opens with a TLS handshake is served as HTTPS on the same
+// port: a browser holding an HSTS policy for the server's name upgrades
+// http://name:PORT to https://name:PORT, which would otherwise fail against
+// a plain listener and never see the redirect. Before HTTPS was ever turned
+// on, connections are passed through untouched, as before.
+func (m *Manager) SniffListener(ln net.Listener) net.Listener {
+	l := &sniffListener{
+		Listener: ln,
+		m:        m,
+		plain:    make(chan net.Conn),
+		errc:     make(chan error, 1),
+		done:     make(chan struct{}),
+	}
+	go l.acceptLoop()
+	return l
+}
+
+type sniffListener struct {
+	net.Listener
+	m     *Manager
+	plain chan net.Conn
+	errc  chan error
+	done  chan struct{}
+	once  sync.Once
+}
+
+func (l *sniffListener) Accept() (net.Conn, error) {
+	select {
+	case c := <-l.plain:
+		return c, nil
+	case err := <-l.errc:
+		return nil, err
+	case <-l.done:
+		return nil, net.ErrClosed
+	}
+}
+
+func (l *sniffListener) Close() error {
+	l.once.Do(func() { close(l.done) })
+	return l.Listener.Close()
+}
+
+func (l *sniffListener) acceptLoop() {
+	var delay time.Duration
+	for {
+		c, err := l.Listener.Accept()
+		if err != nil {
+			// Only a closed listener ends the loop. Anything else - running
+			// out of file descriptors under a burst of connections, say - is
+			// waited out: handing it to http.Server would make it stop
+			// serving for good while the process, and the port, stay up.
+			if errors.Is(err, net.ErrClosed) {
+				select {
+				case l.errc <- err:
+				case <-l.done:
+				}
+				return
+			}
+			if delay == 0 {
+				delay = 5 * time.Millisecond
+			} else if delay *= 2; delay > time.Second {
+				delay = time.Second
+			}
+			select {
+			case <-time.After(delay):
+			case <-l.done:
+				return
+			}
+			continue
+		}
+		delay = 0
+		go l.route(c)
+	}
+}
+
+func (l *sniffListener) route(c net.Conn) {
+	// Once the CA exists the port answers TLS in every mode, and with HTTPS
+	// off: a browser that got an HSTS policy for the name while a stricter
+	// mode was on keeps rewriting http://name:PORT to https://name:PORT for
+	// as long as the policy lasts. Served here, it gets max-age=0 and the
+	// page; refused, the name would be unreachable from it until then.
+	if l.m.CA() == nil {
+		l.deliver(c)
+		return
+	}
+	_ = c.SetReadDeadline(time.Now().Add(peekTimeout))
+	br := bufio.NewReader(c)
+	first, err := br.Peek(1)
+	_ = c.SetReadDeadline(time.Time{})
+	if err != nil {
+		c.Close()
+		return
+	}
+	pc := &peekedConn{Conn: c, r: br}
+	if first[0] == 0x16 { // a TLS handshake record
+		l.m.sniff.serve(pc)
+		return
+	}
+	l.deliver(pc)
+}
+
+func (l *sniffListener) deliver(c net.Conn) {
+	select {
+	case l.plain <- c:
+	case <-l.done:
+		c.Close()
+	}
+}
+
+// peekedConn gives back the byte read to tell the protocols apart.
+type peekedConn struct {
+	net.Conn
+	r *bufio.Reader
+}
+
+func (c *peekedConn) Read(p []byte) (int, error) { return c.r.Read(p) }
+
+// sniffServer serves the TLS connections found on the plain port.
+type sniffServer struct {
+	m     *Manager
+	conns chan net.Conn
+	done  chan struct{}
+	once  sync.Once
+}
+
+func newSniffServer(m *Manager) *sniffServer {
+	s := &sniffServer{m: m, conns: make(chan net.Conn), done: make(chan struct{})}
+	srv := m.opts.NewServer("", m.handler)
+	go func() { _ = srv.Serve(chanListener{s}) }()
+	go func() {
+		<-s.done
+		_ = srv.Close()
+	}()
+	return s
+}
+
+func (s *sniffServer) serve(c net.Conn) {
+	ca := s.m.CA()
+	if ca == nil {
+		c.Close()
+		return
+	}
+	select {
+	case s.conns <- tls.Server(c, ca.TLSConfig()):
+	case <-s.done:
+		c.Close()
+	}
+}
+
+func (s *sniffServer) close() { s.once.Do(func() { close(s.done) }) }
+
+// chanListener hands the sniffing server its connections.
+type chanListener struct{ s *sniffServer }
+
+func (l chanListener) Accept() (net.Conn, error) {
+	select {
+	case c := <-l.s.conns:
+		return c, nil
+	case <-l.s.done:
+		return nil, net.ErrClosed
+	}
+}
+func (chanListener) Close() error   { return nil }
+func (chanListener) Addr() net.Addr { return &net.TCPAddr{} }

+ 62 - 0
server-go/internal/tlsmode/trust.go

@@ -0,0 +1,62 @@
+package tlsmode
+
+import (
+	"net"
+	"strconv"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// HTTPSURL is base moved to this server's HTTPS port - same host if the
+// certificate names it, else one it does - or "" while HTTPS is off. base is
+// whatever address routers were given (NETPULSE_PUBLIC_URL, or the one the
+// admin browsed to).
+func (m *Manager) HTTPSURL(base string) string {
+	if !m.Enabled() {
+		return ""
+	}
+	ca := m.CA()
+	if ca == nil || ca.Leaf() == nil {
+		return ""
+	}
+	leaf := ca.Leaf()
+	host := urlHost(base)
+	if host == "" {
+		host = hostOnly(base)
+	}
+	// A loopback address names the server only to itself; the router, or
+	// any other device given this URL, would dial its own loopback.
+	if !leafNames(leaf.DNSNames, leaf.IPAddresses, host) || isLoopbackHost(host) {
+		host = firstReachable(leaf.IPAddresses)
+	}
+	if host == "" {
+		return ""
+	}
+	return "https://" + net.JoinHostPort(host, strconv.Itoa(m.opts.Port))
+}
+
+// AgentTrust is how an agent (re)installed with base as its server should
+// reach this server. With HTTPS on, it moves to the HTTPS address, pins the
+// root and verifies its downloads against it. Otherwise an https base keeps
+// working with legacyFP (the pin of a self-signed or user certificate), and
+// a plain one is left as it is.
+func AgentTrust(m *Manager, legacyFP func() string, base string) reinstall.Trust {
+	if m != nil {
+		if url := m.HTTPSURL(base); url != "" {
+			ca := m.CA()
+			return reinstall.Trust{ServerURL: url, ServerFP: ca.Fingerprint(), CAPEM: ca.RootPEM()}
+		}
+	}
+	if strings.HasPrefix(base, "https://") && legacyFP != nil {
+		return reinstall.Trust{ServerFP: legacyFP()}
+	}
+	return reinstall.Trust{}
+}
+
+func isLoopbackHost(host string) bool {
+	if ip := net.ParseIP(host); ip != nil {
+		return ip.IsLoopback()
+	}
+	return host == "localhost"
+}