From 49dd4ee7739116b04ea5f929a646b850ad37200f Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 20 Nov 2026 09:25:51 -0600 Subject: [PATCH 01/15] List my claimed repeaters on My account (#2430) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #2415, see #2414. ## Situation A user can claim repeaters, but no page lists the ones they claimed. Claims show on each node page ("Maintained by"), in the admin user detail and in the "Download my data" export. A maintainer of several repeaters has to remember them and open each node page to see whether one went quiet. ## Change **`GET /api/account/repeaters`** (browser session; device tokens answer 403) returns the caller's claims. For each one: - `pubkey` and `name`. - `known`: false once the node left the analyzer database. The claim stays. - `role` and `claimedAt`. - `lastHeard`: the newer of the last advert and the last transmission certainly from the node, the same sources as the node page's Last Heard. - `lastRelayed`: when its hop prefix last relayed. Only used to mark a silent repeater as uncertain, since the prefix can be shared. - `status`: the saved repeater status, or null. - `comaintainers`: the other active claimers' display names. The list is sorted by name, with unnamed repeaters after, by pubkey. It's built on the existing `RepeaterClaimsByUser`, `NotifyNodes` and `LastHeardMap`. **My account, My repeaters**, a new section after Companions: - Silent repeaters come first. Health uses `getNodeStatus`, so the threshold matches the node pages and map (`infraSilentMs`): - green "heard 2h ago"; - yellow "last heard …, its prefix still relays"; - red "silent, last heard 184d ago" or "never heard"; - grey "no longer in the database". - Each row links to the node page and shows the saved status ("no details yet" without one), the claim date and "also maintained by …". - *Unclaim* asks for confirmation, then uses the existing `DELETE /api/repeaters/{pubkey}/claim`. - The empty state says how to claim. - `#/account?section=repeaters` deep-links to the section, like `section=notifications`. Editing stays on the node page, so there's only one editor. The admin user detail and the export are unchanged. Docs: `openapi.go` and the Repeater info section of `docs/user-guide/accounts.md`. ## Notes - A mobile client will want the same list. #2429 proposes device-token scopes for repeater claims. If it lands, letting a `repeater:claim` token read this route is a one-line addition to the bearer route table, and I'd rather do that there than here. - The two PRs touch nearby lines in `openapi.go`, `repeater_handlers.go` (route registration) and `public/account.js`. Whichever merges second needs a small rebase. ## Tests - `cmd/server/my_repeaters_test.go`: - empty list; - ordering (named first, case-insensitive); - unheard, heard and departed nodes; - saved status; - co-maintainers, excluding the caller and disabled users; - another user's view; - unclaim removes the row; - anonymous gets 401 and a device token 403; - no analyzer DB. - `tests/unit/test-user-management-ui.js`: health sort and chips, escaping, the short-pubkey fallback, status and co-maintainer lines, Unclaim on every row, and the empty state. - `tests/e2e/test-user-management-e2e.js`: - the claimed repeater appears with its status and node link; - axe on the section; - Unclaim: dismissing the confirm keeps the claim, accepting empties the list. Run locally: - `make test`: all 16 modules OK. - `sh test-all.sh` and `node tests/e2e/test-lint-network-calls.js`: pass, run in `node:24-bookworm`. - `npx eslint public/*.js`: 0 errors, the same 87 warnings as master. - `test-user-management-e2e.js` against local e2etest servers with the CI config: 46/46. - Manually in Chrome, light and dark: heard, silent and co-maintained rows, and the deep link. Not run: the full Playwright shard matrix from CI. --------- Co-authored-by: Adam <196335+anieto@users.noreply.github.com> --- cmd/server/my_repeaters.go | 145 +++++++++++++++++++ cmd/server/my_repeaters_test.go | 192 ++++++++++++++++++++++++++ cmd/server/openapi.go | 1 + cmd/server/repeater_handlers.go | 1 + cmd/server/repeater_lookup.go | 38 +++++ docs/user-guide/accounts.md | 6 + internal/users/repeaters.go | 39 ++++++ public/account.js | 87 +++++++++++- tests/e2e/test-user-management-e2e.js | 37 +++++ tests/unit/test-user-management-ui.js | 92 ++++++++++++ 10 files changed, 634 insertions(+), 4 deletions(-) create mode 100644 cmd/server/my_repeaters.go create mode 100644 cmd/server/my_repeaters_test.go diff --git a/cmd/server/my_repeaters.go b/cmd/server/my_repeaters.go new file mode 100644 index 000000000..a16209219 --- /dev/null +++ b/cmd/server/my_repeaters.go @@ -0,0 +1,145 @@ +package main + +import ( + "log" + "net/http" + "sort" + "strings" + "time" + + "github.com/meshcore-analyzer/users" +) + +// myRepeaterJSON is one repeater the caller claimed, for My account, My +// repeaters: enough to spot one that went quiet without opening each node. +type myRepeaterJSON struct { + Pubkey string `json:"pubkey"` + Name string `json:"name"` // "" when unnamed or in neither nodes nor inactive_nodes + Known bool `json:"known"` // false when the node is in neither nodes nor inactive_nodes + // Inactive: retention moved the node to inactive_nodes (silent longer + // than retention.nodeDays); name, role and lastHeard come from there. + Inactive bool `json:"inactive"` + Role string `json:"role"` // as stored, lowercase; "" when not known + // ClaimedAt is the caller's own claim. + ClaimedAt string `json:"claimedAt"` + // LastHeard is the newer of the node's last advert and the last + // transmission certainly from it (the node page's Last Heard); null when + // neither is known. + LastHeard *string `json:"lastHeard"` + // LastRelayed is the last time its hop prefix was seen relaying. The + // prefix can be shared with other repeaters, so it only marks a silent + // repeater as uncertain, never as heard. + LastRelayed *string `json:"lastRelayed"` + // Status is the saved repeater status (active, maintenance, + // decommissioned); null when none is saved. + Status *string `json:"status"` + // Comaintainers are the other active claimers, by display name. + Comaintainers []string `json:"comaintainers"` +} + +type myRepeatersJSON struct { + Repeaters []myRepeaterJSON `json:"repeaters"` +} + +// handleMyRepeaters lists the repeaters the caller claimed, by name (then +// pubkey). A node retention moved to inactive_nodes is read from there and +// marked inactive; a claim of a node in neither table is kept as known: false. +func (s *Server) handleMyRepeaters(w http.ResponseWriter, _ *http.Request, u *users.User, _ *users.Session) { + claims, err := s.auth.st.RepeaterClaimsByUser(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + out := myRepeatersJSON{Repeaters: make([]myRepeaterJSON, 0, len(claims))} + if len(claims) == 0 { + writeJSON(w, out) + return + } + pks := make([]string, len(claims)) + for i, c := range claims { + pks[i] = c.Pubkey + } + nodes := map[string]notifyNode{} + inactive := map[string]notifyNode{} + if s.db != nil { + if nodes, err = s.db.NotifyNodes(pks, false); err != nil { + log.Printf("[users] my repeaters %d: nodes: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + var missing []string + for _, pk := range pks { + if _, ok := nodes[pk]; !ok { + missing = append(missing, pk) + } + } + if len(missing) > 0 { + if inactive, err = s.db.InactiveNodeBasics(missing); err != nil { + log.Printf("[users] my repeaters %d: inactive nodes: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + } + } + infos, err := s.auth.st.RepeaterInfoOfUserRepeaters(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: info: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + claimers, err := s.auth.st.RepeaterClaimsOfUserRepeaters(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: claims: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + heard := map[string]time.Time{} + var relay map[string]RepeaterRelayInfo + if s.store != nil { + heard, _ = s.store.LastHeardMap(pks) + relay = s.store.GetRepeaterRelayInfoMap(s.cfg.GetHealthThresholds().RelayActiveHours) + } + for _, c := range claims { + nd, known := nodes[c.Pubkey] + gone := false + if !known { + nd, gone = inactive[c.Pubkey] + known = gone + } + r := myRepeaterJSON{Pubkey: c.Pubkey, Name: nd.Name, Known: known, Inactive: gone, Role: strings.ToLower(nd.Role), + ClaimedAt: rfc3339(c.ClaimedAt), Comaintainers: []string{}} + last, _ := parseRelayTS(nd.LastSeen) + if t, ok := heard[c.Pubkey]; ok && t.After(last) { + last = t + } + if !last.IsZero() { + ts := last.UTC().Format(time.RFC3339) + r.LastHeard = &ts + } + if info, ok := lookupRelayInfo(relay, c.Pubkey); ok { + r.LastRelayed = stringPtrOrNil(info.LastRelayed) + } + if info, ok := infos[c.Pubkey]; ok { + r.Status = stringPtrOrNil(info.Status) + } + for _, o := range claimers[c.Pubkey] { + if o.UserID != u.ID { + r.Comaintainers = append(r.Comaintainers, o.DisplayName) + } + } + out.Repeaters = append(out.Repeaters, r) + } + sort.SliceStable(out.Repeaters, func(i, j int) bool { + a, b := out.Repeaters[i], out.Repeaters[j] + if an, bn := strings.ToLower(a.Name), strings.ToLower(b.Name); an != bn { + // Named repeaters first, then the unnamed by pubkey. + if an == "" || bn == "" { + return bn == "" + } + return an < bn + } + return a.Pubkey < b.Pubkey + }) + writeJSON(w, out) +} diff --git a/cmd/server/my_repeaters_test.go b/cmd/server/my_repeaters_test.go new file mode 100644 index 000000000..1fe2d3a23 --- /dev/null +++ b/cmd/server/my_repeaters_test.go @@ -0,0 +1,192 @@ +package main + +import ( + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/users" +) + +const rpkGone = "dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44" + +func TestMyRepeatersEmpty(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + w := f.do("GET", "/api/account/repeaters", nil, as(alice)) + expectStatus(t, w, http.StatusOK) + if strings.TrimSpace(w.Body.String()) != `{"repeaters":[]}` { + t.Fatalf("body = %s", w.Body.String()) + } +} + +func TestMyRepeatersList(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + carol := f.registerAndActivate(t, "carol@example.org", "Carol", pw) + const rpkNamed = "ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55" + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET name = 'Zulu Hill', last_seen = '2026-11-01T10:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + if _, err := f.srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role, last_seen) VALUES (?, 'alpha peak', 'repeater', NULL)`, rpkNamed); err != nil { + t.Fatal(err) + } + // Alice claims three: two known (one co-maintained, one with details), + // and one that has left the analyzer database since. + for _, pk := range []string{rpkA, rpkNamed, rpkGone} { + if _, err := f.st.ClaimRepeater(alice.me.ID, pk); err != nil { + t.Fatal(err) + } + } + for _, uid := range []int64{bob.me.ID, carol.me.ID} { + if _, err := f.st.ClaimRepeater(uid, rpkA); err != nil { + t.Fatal(err) + } + } + if err := f.st.SetStatus(carol.me.ID, users.StatusDisabled); err != nil { + t.Fatal(err) + } + if _, err := f.st.SaveRepeaterInfo(alice.me.ID, rpkA, users.RepeaterEdit{Status: users.RepeaterStatusMaintenance}); err != nil { + t.Fatal(err) + } + + w := f.do("GET", "/api/account/repeaters", nil, as(alice)) + expectStatus(t, w, http.StatusOK) + got := decode[myRepeatersJSON](t, w).Repeaters + var order []string + for _, r := range got { + order = append(order, r.Pubkey) + } + // Named first, by name ignoring case; then unnamed by pubkey. + if want := []string{rpkNamed, rpkA, rpkGone}; !slices.Equal(order, want) { + t.Fatalf("order = %v, want %v", order, want) + } + named, zulu, gone := got[0], got[1], got[2] + if !named.Known || named.Name != "alpha peak" || named.LastHeard != nil || named.Status != nil || len(named.Comaintainers) != 0 { + t.Errorf("unheard repeater = %+v", named) + } + if !zulu.Known || zulu.Role != "repeater" || zulu.LastHeard == nil || *zulu.LastHeard != "2026-11-01T10:00:00Z" { + t.Errorf("heard repeater = %+v", zulu) + } + if zulu.Status == nil || *zulu.Status != "maintenance" { + t.Errorf("status = %v", zulu.Status) + } + // Bob is listed; Alice herself and the disabled Carol are not. + if !slices.Equal(zulu.Comaintainers, []string{"Bob"}) { + t.Errorf("comaintainers = %v", zulu.Comaintainers) + } + if gone.Known || gone.Inactive || gone.Name != "" || gone.ClaimedAt == "" { + t.Errorf("departed repeater = %+v", gone) + } + if strings.Contains(w.Body.String(), "@") { + t.Errorf("body leaks an email: %s", w.Body.String()) + } + + // Bob sees only his own claim, with Alice as the other maintainer. + b := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(bob))).Repeaters + if len(b) != 1 || b[0].Pubkey != rpkA || !slices.Equal(b[0].Comaintainers, []string{"Alice"}) { + t.Fatalf("Bob's list = %+v", b) + } + // Unclaiming through the existing route takes it off the list. + expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, as(bob)), http.StatusOK) + if b := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(bob))).Repeaters; len(b) != 0 { + t.Fatalf("after unclaim = %+v", b) + } +} + +func TestMyRepeatersNeedsBrowserSession(t *testing.T) { + f := repeaterFixture(t) + f.registerAndActivate(t, "alice@example.org", "Alice", pw) + expectStatus(t, f.do("GET", "/api/account/repeaters", nil), http.StatusUnauthorized) + tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token + expectStatus(t, f.do("GET", "/api/account/repeaters", nil, bearer(tok)), http.StatusForbidden) +} + +// Without the analyzer database (auth-only fixture) the claims still list, +// as not known. +func TestMyRepeatersWithoutAnalyzerDB(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 1 || got[0].Known || got[0].LastHeard != nil { + t.Fatalf("list = %+v", got) + } +} + +// A repeater silent past retention.nodeDays sits in inactive_nodes, not +// nodes: it still lists by name with its last advert, marked inactive. +func TestMyRepeatersInactiveNode(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + const rpkOld = "ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66" + for _, q := range []string{ + `CREATE TABLE IF NOT EXISTS inactive_nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, last_seen TEXT)`, + `INSERT INTO inactive_nodes (public_key, name, role, last_seen) VALUES ('` + rpkOld + `', 'Old Tower', 'Repeater', '2026-10-01T08:00:00Z')`, + } { + if _, err := f.srv.db.conn.Exec(q); err != nil { + t.Fatal(err) + } + } + // The claim route already accepts it (RepeaterKnown reads inactive_nodes). + expectStatus(t, f.do("POST", repPath(rpkOld, "claim"), nil, as(alice)), http.StatusOK) + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkGone); err != nil { + t.Fatal(err) + } + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 2 { + t.Fatalf("list = %+v", got) + } + old, gone := got[0], got[1] + if old.Pubkey != rpkOld || !old.Known || !old.Inactive || old.Name != "Old Tower" || old.Role != "repeater" || + old.LastHeard == nil || *old.LastHeard != "2026-10-01T08:00:00Z" { + t.Errorf("inactive repeater = %+v", old) + } + if gone.Pubkey != rpkGone || gone.Known || gone.Inactive { + t.Errorf("unknown repeater = %+v", gone) + } +} + +// The production path: a packet store whose certain-heard entry is newer +// than the node's last advert, and a relay entry for its prefix. +func TestMyRepeatersUsesPacketStore(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET name = 'Zulu Hill', last_seen = '2026-11-01T10:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + ps := NewPacketStore(nil, nil) + heard := time.Date(2026, 11, 3, 12, 30, 0, 0, time.UTC) + ps.certainHeard = map[string]string{rpkA: heard.Format(time.RFC3339)} + ps.repeaterRelayCache = map[string]RepeaterRelayInfo{rpkA: {LastRelayed: "2026-11-05T09:15:00Z", RelayActive: true, WindowHours: 24}} + f.srv.store = ps + + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 1 { + t.Fatalf("list = %+v", got) + } + r := got[0] + if r.LastHeard == nil || *r.LastHeard != "2026-11-03T12:30:00Z" { + t.Errorf("lastHeard = %v, want the certain-heard time over the older advert", r.LastHeard) + } + if r.LastRelayed == nil || *r.LastRelayed != "2026-11-05T09:15:00Z" { + t.Errorf("lastRelayed = %v", r.LastRelayed) + } + + // An advert newer than the certain-heard entry wins. + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET last_seen = '2026-11-04T00:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + got = decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if got[0].LastHeard == nil || *got[0].LastHeard != "2026-11-04T00:00:00Z" { + t.Errorf("lastHeard = %v, want the newer advert", got[0].LastHeard) + } +} diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 241b73d90..63803d600 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -87,6 +87,7 @@ func routeDescriptions() map[string]routeMeta { "DELETE /api/account/settings": {Summary: "Delete own synced settings", Description: "Removes the stored document; the next PUT (baseRevision 0) starts a new one in a new generation.", Tag: "users", Session: true}, "POST /api/account/companions/challenge": {Summary: "Start linking a companion", Description: "Body {pubkey} (64 hex). 200 {challenge, expiresAt, host}: host is what to sign (the host of userManagement.publicBaseUrl); challenge is 32 random bytes as hex, single use, valid 5 minutes, bound to the caller and the pubkey. 400 malformed pubkey; 429 above 60 challenge + link requests per hour per user and per IP. Accepts a device token (Authorization: Bearer).", Tag: "users", Session: true}, "POST /api/account/companions": {Summary: "Link a companion", Description: "Body {pubkey, challenge, signature, name}. signature is the companion's Ed25519 signature (64 bytes, hex) over the UTF-8 string \"corescope-link:\" + host of userManagement.publicBaseUrl + \":\" + challenge. The challenge is consumed in every case. 200 {pubkey, name, linkedAt}. The synced settings (meshcore-my-nodes) are not touched: a companion is not a node to monitor. A companion linked to another account moves to the caller (the newest proof wins); both get a companion.transfer audit row and the previous owner a mail (a security notice, sent whatever the node notification settings are). 400 malformed pubkey or signature, or a signature that does not verify; 410 challenge missing, expired, used, or bound to another user or pubkey; 429 rate limited. Accepts a device token.", Tag: "users", Session: true}, + "GET /api/account/repeaters": {Summary: "List own claimed repeaters", Description: "{repeaters: [{pubkey, name, known, inactive, role, claimedAt, lastHeard, lastRelayed, status, comaintainers}]} for My account, My repeaters: named repeaters first by name, then the unnamed by pubkey. inactive is true when retention moved the node to inactive_nodes (silent longer than retention.nodeDays); its name, role and last advert are read from there. known is false only when the node is in neither nodes nor inactive_nodes (the claim stays). lastHeard is the newer of the last advert and the last transmission certainly from the node, or null; lastRelayed is the last time its hop prefix was seen relaying (it may be shared with other repeaters), or null. status is the saved repeater status or null. comaintainers are the other active claimers' display names. Browser session only; device tokens answer 403.", Tag: "users", Session: true}, "GET /api/account/companions": {Summary: "List own linked companions", Description: "[{pubkey, name, linkedAt, lastSeenAt}], newest link first. lastSeenAt is the newest client reception of that companion (rx_at as stored) or null. Accepts a device token.", Tag: "users", Session: true}, "DELETE /api/account/companions/{pubkey}": {Summary: "Unlink an own companion", Description: "204. Stored coverage stays. 400 malformed pubkey, 404 not linked to the caller. Accepts a device token.", Tag: "users", Session: true}, "GET /api/account/observer-login": {Summary: "Own observer MQTT login", Description: "{login: null} or {login: {username, createdAt, revoked}, observers: [{pubkey, name, lastSeenAt}]}. observers are the pubkeys bound to the caller (the first time an observer publishes with the login); name and lastSeenAt come from the analyzer observers (empty name and null lastSeenAt when unknown). Never contains the password, its hash or its ciphertext. Routes exist only when userManagement.observerLogins is enabled. Not available to device tokens.", Tag: "users", Session: true}, diff --git a/cmd/server/repeater_handlers.go b/cmd/server/repeater_handlers.go index ad7f68896..5e9327151 100644 --- a/cmd/server/repeater_handlers.go +++ b/cmd/server/repeater_handlers.go @@ -55,6 +55,7 @@ func (s *Server) registerRepeaterRoutes(r *mux.Router) { r.HandleFunc("/api/repeaters/{pubkey}/info", s.withUser(s.handleRepeaterInfoPut)).Methods("PUT") r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterClaim)).Methods("POST") r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterUnclaim)).Methods("DELETE") + r.HandleFunc("/api/account/repeaters", s.withUser(s.handleMyRepeaters)).Methods("GET") r.HandleFunc("/api/admin/repeaters/{pubkey}/claims/{userId}", s.withAdmin(s.handleAdminRepeaterUnclaim)).Methods("DELETE") } diff --git a/cmd/server/repeater_lookup.go b/cmd/server/repeater_lookup.go index fb850dff2..569ca7dac 100644 --- a/cmd/server/repeater_lookup.go +++ b/cmd/server/repeater_lookup.go @@ -3,6 +3,7 @@ package main import ( "database/sql" "errors" + "strings" ) // RepeaterKnown reports whether pubkey (lowercase) is a known node, and @@ -31,3 +32,40 @@ func (db *DB) RepeaterKnown(pubkey string) (found bool, isRepeater bool, err err } return false, false, nil } + +// InactiveNodeBasics reads name, role and last_seen of the given pubkeys +// from inactive_nodes (nodes retention moved there), keyed by lowercase +// pubkey. Empty when the table does not exist. Read-only. +func (db *DB) InactiveNodeBasics(pubkeys []string) (map[string]notifyNode, error) { + out := make(map[string]notifyNode, len(pubkeys)) + if !db.inactiveNodesPresent() { + return out, nil + } + for i := 0; i < len(pubkeys); i += notifyNodeChunk { + chunk := pubkeys[i:min(i+notifyNodeChunk, len(pubkeys))] + args := make([]any, len(chunk)) + for j, pk := range chunk { + args[j] = pk + } + rows, err := db.conn.Query(`SELECT public_key, COALESCE(name, ''), COALESCE(role, ''), COALESCE(last_seen, '') + FROM inactive_nodes WHERE public_key IN (`+sqlPlaceholders(len(chunk))+`)`, args...) + if err != nil { + return nil, err + } + for rows.Next() { + var n notifyNode + if err := rows.Scan(&n.Pubkey, &n.Name, &n.Role, &n.LastSeen); err != nil { + rows.Close() + return nil, err + } + n.Pubkey = strings.ToLower(n.Pubkey) + out[n.Pubkey] = n + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + } + return out, nil +} diff --git a/docs/user-guide/accounts.md b/docs/user-guide/accounts.md index fe0460bfd..f1137316b 100644 --- a/docs/user-guide/accounts.md +++ b/docs/user-guide/accounts.md @@ -343,6 +343,12 @@ enabled. but hidden and do not count, so a repeater whose only claimer is disabled is open again. - **Audit log:** edits are recorded as `repeater.edit` (with the old and new value of each changed field), claims as `repeater.claim` and `repeater.unclaim`. +- **My repeaters:** *My account, My repeaters* lists the repeaters you claimed, silent ones + first: when each was last heard (by the same rule as the node pages), its saved status, who + else maintains it, and an *Unclaim* button. A repeater silent longer than + `retention.nodeDays`, which the analyzer moves to its inactive nodes, stays listed by name as + silent with its last advert. A repeater the analyzer has no record of at all is listed as no + longer in the database until you unclaim it. Deep link: `#/account?section=repeaters`. - **Removing a claim:** *Admin, Users*, open the user, *Remove* next to the claim. Admins use this when a claimer left or claimed a repeater that is not theirs. diff --git a/internal/users/repeaters.go b/internal/users/repeaters.go index a7e1aee5b..60596f9bd 100644 --- a/internal/users/repeaters.go +++ b/internal/users/repeaters.go @@ -297,6 +297,45 @@ func (s *Store) RepeaterClaimsByUser(userID int64) ([]RepeaterClaim, error) { return scanRepeaterClaims(rows) } +// RepeaterClaimsOfUserRepeaters returns the active claimers of every +// repeater the user claimed, by pubkey, in one query (My repeaters). +func (s *Store) RepeaterClaimsOfUserRepeaters(userID int64) (map[string][]RepeaterClaim, error) { + rows, err := s.db.Query(repeaterClaimsSelect+` WHERE u.status = 'active' + AND c.pubkey IN (SELECT pubkey FROM repeater_claims WHERE user_id = ?) + ORDER BY c.pubkey, c.claimed_at, c.user_id`, userID) + if err != nil { + return nil, err + } + list, err := scanRepeaterClaims(rows) + if err != nil { + return nil, err + } + out := make(map[string][]RepeaterClaim) + for _, c := range list { + out[c.Pubkey] = append(out[c.Pubkey], c) + } + return out, nil +} + +// RepeaterInfoOfUserRepeaters returns the saved info of every repeater the +// user claimed that has some, by pubkey, in one query (My repeaters). +func (s *Store) RepeaterInfoOfUserRepeaters(userID int64) (map[string]RepeaterInfo, error) { + rows, err := s.db.Query(repeaterInfoSelect+` WHERE i.pubkey IN (SELECT pubkey FROM repeater_claims WHERE user_id = ?)`, userID) + if err != nil { + return nil, err + } + defer rows.Close() + out := make(map[string]RepeaterInfo) + for rows.Next() { + ri, err := scanRepeaterInfo(rows) + if err != nil { + return nil, err + } + out[ri.Pubkey] = *ri + } + return out, rows.Err() +} + // CanEditRepeater: admin always; a non-active user never; with no active // claimers any active user; otherwise only the active claimers. func (s *Store) CanEditRepeater(u *User, pubkey string) (bool, error) { diff --git a/public/account.js b/public/account.js index e8ed60634..98d57d06f 100644 --- a/public/account.js +++ b/public/account.js @@ -113,6 +113,7 @@ submitBtn('Change address') + msgBox('emailMsg') + '' + '

Devices

' + msgBox('sessMsg') + '

Companions

' + msgBox('compMsg') + + '

My repeaters

' + msgBox('myRepMsg') + (observerLoginsOn() ? '

Observer MQTT login

' + msgBox('obsLoginMsg') : '') + (window.CSProposals && window.CSProposals.enabled() ? '

My proposals

' + msgBox('propMsg') : '') + (window.CSNotify && window.CSNotify.enabled() ? '

Notifications

' + msgBox('notifyMsg') : '') + @@ -164,6 +165,59 @@ return html; } + // How a claimed repeater sounds on the mesh, with the rule the node pages + // use (getNodeStatus from roles.js: silent past the repeater threshold is + // stale; a silent one whose prefix still relays is uncertain). fns carries + // getNodeStatus and timeAgo so tests can pass the real ones in. + function repeaterHealth(r, fns) { + if (!r.known) return { state: 'gone', rank: 0, text: 'no longer in the database' }; + if (!r.lastHeard) return { state: 'stale', rank: 1, text: 'never heard' }; + var node = { role: r.role || 'repeater', last_heard: r.lastHeard, last_relayed: r.lastRelayed || null }; + var state = fns.getNodeStatus(node); + var when = fns.timeAgo(r.lastHeard); + if (state === 'active') return { state: state, rank: 3, text: 'heard ' + when }; + if (state === 'uncertain') return { state: state, rank: 2, text: 'last heard ' + when + ', its prefix still relays' }; + // inactive: retention dropped it from the node list, which is also why + // its row has no node page to link to. + return { state: 'stale', rank: 1, text: 'silent, last heard ' + when + (r.inactive ? ' · no longer in the node list' : '') }; + } + + var HEALTH_CHIP = { active: 'um-status-active', uncertain: 'um-status-pending', stale: 'um-status-disabled', gone: 'um-chip-unsubscribed' }; + + // The repeaters this account claimed, silent ones first, each with its + // saved status, the other maintainers and an Unclaim button. A repeater + // retention moved to inactive_nodes (inactive) is listed as silent from + // its last advert there. Inactive and unknown rows show the name as plain + // text: /api/nodes/{pubkey} reads only nodes, so the node page would say + // Node not found. + function myRepeatersHtml(list, fns) { + fns = fns || { getNodeStatus: window.getNodeStatus, timeAgo: window.timeAgo }; + if (!list || !list.length) { + return '
  • You have not claimed a repeater. ' + + 'Open a repeater\'s node page and choose Claim under Repeater info; it then shows up here.
  • '; + } + var rows = list.map(function (r, i) { return { r: r, h: repeaterHealth(r, fns), i: i }; }); + rows.sort(function (a, b) { return a.h.rank - b.h.rank || a.i - b.i; }); + var html = ''; + rows.forEach(function (x) { + var r = x.r, h = x.h; + var name = r.name || shortKey(r.pubkey); + var others = r.comaintainers || []; + var linked = r.known && !r.inactive; + html += '
  • ' + + (linked ? '' + escapeHtml(name) + ' ' + : ' ') + + '' + escapeHtml(shortKey(r.pubkey)) + ' ' + + '' + escapeHtml(h.text) + '' + + '
    ' + escapeHtml(r.status ? 'status ' + r.status : 'no details yet') + + ' · claimed ' + escapeHtml(fmtDate(r.claimedAt)) + + (others.length ? ' · also maintained by ' + escapeHtml(others.join(', ')) : '') + '
    ' + + '
  • '; + }); + return html; + } + function observerLoginsOn() { return !!(window.MC_USER_MGMT && window.MC_USER_MGMT.observerLogins); } // The observer MQTT login section. No API returns the password, so none is @@ -446,16 +500,41 @@ }).catch(function () { CSAuth.say('compMsg', 'Network error, try again.', false); }); } document.getElementById('compList').addEventListener('click', function (e) { - var pk = e.target && e.target.getAttribute && e.target.getAttribute('data-unlink'); - if (!pk) return; + var btn = e.target; + var pk = btn && btn.getAttribute && btn.getAttribute('data-unlink'); + if (!pk || btn.disabled) return; if (!window.confirm('Unlink this companion? Its coverage no longer counts as yours. ' + 'Link it again by logging in from CoreDrive RX.')) return; + btn.disabled = true; // a second click while the DELETE runs would 404 over the success message return CSAuth.request('DELETE', '/api/account/companions/' + encodeURIComponent(pk)).then(function (r) { CSAuth.say('compMsg', r.ok ? 'Companion unlinked.' : CSAuth.errText(r), r.ok); loadCompanions(); - }).catch(function () { CSAuth.say('compMsg', 'Network error, try again.', false); }); + }).catch(function () { CSAuth.say('compMsg', 'Network error, try again.', false); }) + .then(function () { btn.disabled = false; }); }); loadCompanions(); + + function loadMyRepeaters() { + return CSAuth.request('GET', '/api/account/repeaters').then(function (r) { + var list = document.getElementById('myRepList'); + if (!list) return; + if (!r.ok) { CSAuth.say('myRepMsg', CSAuth.errText(r), false); return; } + list.innerHTML = myRepeatersHtml(r.data && r.data.repeaters); + }).catch(function () { CSAuth.say('myRepMsg', 'Network error, try again.', false); }); + } + document.getElementById('myRepList').addEventListener('click', function (e) { + var btn = e.target; + var pk = btn && btn.getAttribute && btn.getAttribute('data-unclaim'); + if (!pk || btn.disabled) return; + if (!window.confirm('Unclaim this repeater? Your name is no longer shown as its maintainer.')) return; + btn.disabled = true; // a second click while the DELETE runs would 404 over the success message + return CSAuth.request('DELETE', '/api/repeaters/' + encodeURIComponent(pk) + '/claim').then(function (r) { + CSAuth.say('myRepMsg', r.ok ? 'Repeater unclaimed.' : CSAuth.errText(r), r.ok); + loadMyRepeaters(); + }).catch(function () { CSAuth.say('myRepMsg', 'Network error, try again.', false); }) + .then(function () { btn.disabled = false; }); + }); + loadMyRepeaters().then(function () { scrollToSection('repeaters'); }); } }; @@ -488,5 +567,5 @@ } registerPage('account', { init: init, destroy: destroy }); - window.CSAccount = { _test: { profileHtml: profileHtml, sessionsHtml: sessionsHtml, companionsHtml: companionsHtml, observerLoginHtml: observerLoginHtml, renewLinkHtml: renewLinkHtml, views: views, checkMailHtml: checkMailHtml } }; + window.CSAccount = { _test: { profileHtml: profileHtml, sessionsHtml: sessionsHtml, companionsHtml: companionsHtml, myRepeatersHtml: myRepeatersHtml, observerLoginHtml: observerLoginHtml, renewLinkHtml: renewLinkHtml, views: views, checkMailHtml: checkMailHtml } }; })(); diff --git a/tests/e2e/test-user-management-e2e.js b/tests/e2e/test-user-management-e2e.js index 0cd47ef1e..ad2b911bc 100644 --- a/tests/e2e/test-user-management-e2e.js +++ b/tests/e2e/test-user-management-e2e.js @@ -695,6 +695,17 @@ async function until(fn, label) { assert((await userA.textContent(riSel + ' [data-ri-unclaim]')).trim() === 'Unclaim', 'button text'); }); + await step('repeater info: My account, My repeaters lists the claim with its status; axe on the section', async () => { + await userA.goto(BASE + '/#/account?section=repeaters'); + const row = '#myRepList li[data-pubkey="' + rpk + '"]'; + await userA.waitForSelector(row); + const t = (await userA.innerText(row)).replace(/\s+/g, ' '); + assert(t.indexOf('status maintenance') !== -1, 'status missing: ' + t); + assert((await userA.getAttribute(row + ' a', 'href')) === '#/nodes/' + rpk, 'no node link'); + assert((await userA.locator(row + ' [data-unclaim]').count()) === 1, 'no Unclaim button'); + await axeClean(userA, '#myRepList'); + }); + await step('repeater info: user B sees Claim but no Edit, and a direct PUT is 403', async () => { await registerAndActivate(userB, 'ri-b@e2e.test', 'Repeater B'); await openRepeater(userB); @@ -705,6 +716,32 @@ async function until(fn, label) { assert(status === 403, 'PUT by non-maintainer returned ' + status); }); + await step('repeater info: Unclaim on My repeaters asks first, then empties the list', async () => { + await userA.goto(BASE + '/#/account?section=repeaters'); + const btn = '#myRepList [data-unclaim="' + rpk + '"]'; + await userA.waitForSelector(btn); + // Record claim DELETEs instead of waiting a fixed time: the dismissed + // confirm must send none, and the claim must still be listed. + const deletes = []; + const onReq = (req) => { if (req.method() === 'DELETE' && req.url().indexOf('/api/repeaters/' + rpk + '/claim') !== -1) deletes.push(req.url()); }; + userA.on('request', onReq); + userA.once('dialog', (d) => d.dismiss()); + await userA.click(btn); + const listed = await userA.evaluate(() => window.CSAuth.request('GET', '/api/account/repeaters') + .then((r) => (r.data && r.data.repeaters || []).map((x) => x.pubkey))); + userA.off('request', onReq); + assert(deletes.length === 0, 'dismissing the confirm sent ' + deletes.join(', ')); + assert(listed.indexOf(rpk) !== -1, 'dismissing the confirm still unclaimed'); + assert((await userA.locator(btn).count()) === 1, 'Unclaim button gone after dismissing'); + userA.once('dialog', (d) => d.accept()); + await userA.click(btn); + await userA.waitForSelector('#myRepEmpty'); + assert((await userA.textContent('#myRepMsg')).indexOf('Repeater unclaimed.') !== -1, 'no confirmation message'); + // Claim again for the steps below. + const status = await userA.evaluate((pk) => window.CSAuth.request('POST', '/api/repeaters/' + pk + '/claim').then((r) => r.status), rpk); + assert(status === 200, 're-claim returned ' + status); + }); + await step('repeater info: the section deep link scrolls the section into view', async () => { const small = await (await userB.context().browser().newContext({ viewport: { width: 1280, height: 400 } })).newPage(); small.setDefaultTimeout(8000); diff --git a/tests/unit/test-user-management-ui.js b/tests/unit/test-user-management-ui.js index 80e33c6b1..7ef09c4e9 100644 --- a/tests/unit/test-user-management-ui.js +++ b/tests/unit/test-user-management-ui.js @@ -426,6 +426,98 @@ test('device tokens render as CoreDrive RX with a marker and keep their logout b assert(h.indexOf('data-sess="2"') !== -1 && h.indexOf('data-sess="3"') !== -1, 'device rows lost their logout button'); }); +// getNodeStatus as the browser runs it: the real roles.js (default 72 h +// repeater threshold), in a sandbox with the DOM bits it touches at load. +function realGetNodeStatus() { + // window is the global object, as in a browser: roles.js sets + // window.HEALTH_THRESHOLDS and reads it bare. + const ctx = { addEventListener() {}, dispatchEvent() {}, console, Date, Math, JSON, Object, String, Number, Array, RegExp, isNaN, parseInt, parseFloat, + document: { readyState: 'complete', createElement: () => ({ style: {} }), head: { appendChild() {} }, + getElementById: () => null, addEventListener() {}, querySelectorAll: () => [], querySelector: () => null, + documentElement: { style: { setProperty() {} }, dataset: {} } }, + setTimeout() {}, clearTimeout() {}, setInterval() {}, clearInterval() {}, + fetch: () => new Promise(() => {}), localStorage: { getItem: () => null, setItem() {}, removeItem() {} }, + location: { hash: '' }, navigator: {} }; + ctx.window = ctx; + vm.createContext(ctx); + loadApiBase(ctx); + vm.runInContext(fs.readFileSync(path.join(ROOT, 'public/roles.js'), 'utf8'), ctx); + assert.strictEqual(typeof ctx.getNodeStatus, 'function', 'roles.js did not define getNodeStatus'); + return ctx.getNodeStatus; +} + +test('my repeaters: silent ones first, escaped, with status, co-maintainers and Unclaim', () => { + const env = loadAccount('#/account', () => ({})); + const fns = { getNodeStatus: realGetNodeStatus(), timeAgo: () => 'AGO' }; + const recent = new Date(Date.now() - 3600 * 1000).toISOString(); + const old = new Date(Date.now() - 10 * 86400 * 1000).toISOString(); + const relayedNow = new Date(Date.now() - 600 * 1000).toISOString(); + const pkOk = 'aa'.repeat(32), pkOld = 'bb'.repeat(32), pkGone = 'cc'.repeat(32), pkNever = 'dd'.repeat(32); + const pkUnc = 'ee'.repeat(32), pkInact = 'ff'.repeat(32); + const h = env.t.myRepeatersHtml([ + { pubkey: pkOk, name: 'Hill ', known: true, role: 'repeater', claimedAt: '2026-11-01T00:00:00Z', lastHeard: recent, status: 'active', comaintainers: ['Bob', 'Eve'] }, + { pubkey: pkUnc, name: 'Mesa', known: true, role: 'repeater', claimedAt: '2026-11-01T00:00:00Z', lastHeard: old, lastRelayed: relayedNow, status: null, comaintainers: [] }, + { pubkey: pkOld, name: 'Tower', known: true, role: 'repeater', claimedAt: '2026-11-01T00:00:00Z', lastHeard: old, status: null, comaintainers: [] }, + { pubkey: pkNever, name: '', known: true, role: 'repeater', claimedAt: '2026-11-01T00:00:00Z', lastHeard: null, status: null, comaintainers: [] }, + { pubkey: pkInact, name: 'Old Tower', known: true, inactive: true, role: 'repeater', claimedAt: '2026-09-01T00:00:00Z', lastHeard: '2026-05-01T00:00:00Z', status: null, comaintainers: [] }, + { pubkey: pkGone, name: '', known: false, role: '', claimedAt: '2026-11-01T00:00:00Z', lastHeard: null, status: null, comaintainers: [] }], fns); + assert(h.indexOf('') === -1 && h.indexOf('') === -1, 'raw tag: ' + h); + const order = (h.match(/data-pubkey="([0-9a-f]+)"/g) || []).map(x => x.slice(13, 15)); + assert.deepStrictEqual(order, ['cc', 'bb', 'dd', 'ff', 'ee', 'aa'], 'gone, then silent (input order), then uncertain, then heard: ' + order); + assert(h.indexOf('data-pubkey="' + pkUnc + '" data-health="uncertain"') !== -1 && + /last heard AGO, its prefix still relays<\/span>/.test(h), 'uncertain row: ' + h); + assert(h.indexOf('data-pubkey="' + pkInact + '" data-health="stale"') !== -1 && + h.indexOf('') !== -1 && + h.indexOf('silent, last heard AGO · no longer in the node list') !== -1, 'inactive row: plain name, marked as dropped: ' + h); + // The node page reads only nodes: inactive and unknown rows are not links. + for (const pk of [pkInact, pkGone]) { + assert(h.indexOf('href="#/nodes/' + pk + '"') === -1, 'row links to a missing node page: ' + pk); + } + assert(h.indexOf('href="#/nodes/' + pkOld + '"') !== -1, 'known row lost its link'); + assert.strictEqual((h.match(/no longer in the node list/g) || []).length, 1, 'only the inactive row carries the note'); + assert(h.indexOf('data-health="gone"') !== -1 && h.indexOf('no longer in the database') !== -1, 'departed row: ' + h); + assert(h.indexOf('data-pubkey="' + pkOld + '" data-health="stale"') !== -1 && h.indexOf('silent, last heard') !== -1, 'stale row: ' + h); + assert(h.indexOf('never heard') !== -1, 'never-heard row: ' + h); + assert(h.indexOf('data-pubkey="' + pkOk + '" data-health="active"') !== -1 && h.indexOf('um-status-active') !== -1, 'heard row: ' + h); + assert(h.indexOf('href="#/nodes/' + pkOk + '"') !== -1 && h.indexOf('Hill <b>') !== -1, 'node link: ' + h); + assert(h.indexOf('>' + pkNever.slice(0, 12) + '…') !== -1, 'unnamed row does not fall back to the short pubkey: ' + h); + assert(h.indexOf('status active') !== -1 && (h.match(/no details yet/g) || []).length === 5, 'status lines: ' + h); + assert(h.indexOf('also maintained by Bob, <i>Eve</i>') !== -1, 'co-maintainers: ' + h); + assert.strictEqual((h.match(/data-unclaim=/g) || []).length, 6, 'every row has Unclaim'); +}); + +test('my repeaters: Unclaim is disabled while its DELETE runs, so a double click sends one', async () => { + const pk = 'ab'.repeat(32); + let release; + const env = loadAccount('#/account', () => ({ ok: true, status: 200, data: { repeaters: [] } }), { confirm: () => true }); + env.setRequest((method, p) => { + if (method === 'DELETE') return new Promise((r) => { release = () => r({ ok: true, status: 200, data: {} }); }); + if (p === '/api/account/repeaters') return Promise.resolve({ ok: true, status: 200, data: { repeaters: [] } }); + return Promise.resolve({ ok: true, status: 200, data: [] }); + }); + env.user.current = { id: 1, email: 'a@b.c', displayName: 'Ann', role: 'user' }; + env.t.views.profile({ set innerHTML(v) {} }); + await new Promise((r) => setTimeout(r, 5)); + const btn = { getAttribute: (a) => (a === 'data-unclaim' ? pk : null) }; + const first = env.els.myRepList.handlers.click({ target: btn }); + assert.strictEqual(btn.disabled, true, 'button not disabled while the DELETE runs'); + env.els.myRepList.handlers.click({ target: btn }); + release(); + await first; + await new Promise((r) => setTimeout(r, 5)); + assert.strictEqual(env.calls.filter((c) => c.method === 'DELETE').length, 1, 'second click sent another DELETE'); + assert.strictEqual(env.els.myRepMsg.textContent, 'Repeater unclaimed.'); + assert.strictEqual(btn.disabled, false, 'button stays disabled after the DELETE'); +}); + +test('my repeaters empty state explains how to claim', () => { + const env = loadAccount('#/account', () => ({})); + for (const list of [[], null, undefined]) { + const h = env.t.myRepeatersHtml(list); + assert(h.indexOf('id="myRepEmpty"') !== -1 && h.indexOf('Claim') !== -1 && h.indexOf('data-unclaim') === -1, h); + } +}); + test('companions list escapes fields, shortens the pubkey and says never without a reception', () => { const env = loadAccount('#/account', () => ({})); const pk = 'ab'.repeat(32); From 9a57b2fca610d815df80d212f4e1cf70851fc357 Mon Sep 17 00:00:00 2001 From: Zach Date: Sat, 21 Nov 2026 15:26:05 -0600 Subject: [PATCH 02/15] test(server): set the local zone in a child process, not via time.Local (#2438) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `TestNodeAnalyticsWindowIgnoresLocalZone` set the zone by assigning the global `time.Local`. Every `time.Now()` reads that variable, so if a timer left over from an earlier test fires during this test, the race detector reports a data race. It counts as a failure of this test, whichever test left the timer. It showed up as an intermittent failure of the server race detector (shard 3/4) on a PR run (#2436). Three local runs of the same shard passed. The code under test is fine; only the test was racy. ## Change The test now re-runs itself in a child process with `TZ=Etc/GMT-2` (UTC+2) and writes nothing global: - **Embedded zone data:** `time/tzdata` is embedded in the test binary, so the zone resolves without the host's zoneinfo. - **Zone check:** the child first checks that its local offset really is +02:00. - **Test name:** the child's `-test.run` pattern is built from `t.Name()`. - **Vacuous pass guarded:** the parent requires `--- PASS: ` in the child's output, so a rename can't make it pass without running. - **Windows:** the test is skipped there before the re-exec. Go on Windows takes the local zone from the OS and ignores `TZ`, so the child cannot be put in UTC+2. - **Bounded child:** the child runs under a 60 s context, so a hung child fails with its output. This follows the existing re-exec pattern in `distance_background_fill_test.go`. `TestMain` is just `os.Exit(m.Run())`, so the child runs only this test. It works under the sharded `-test.run` in the race job, and in coverage builds. ## Testing - `go test -race -run TestNodeAnalyticsWindowIgnoresLocalZone`: pass. gofmt and vet are clean. - **Still guards the original bug:** with `time.Now().UTC()` changed back to `time.Now()` in `GetNodeAnalytics`, it fails as before. The 7d window holds 166 of 168 packets, and `From` is `...+02:00`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- cmd/server/node_analytics_coverage_test.go | 37 ++++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/cmd/server/node_analytics_coverage_test.go b/cmd/server/node_analytics_coverage_test.go index f0baf5c4c..9fecc1e18 100644 --- a/cmd/server/node_analytics_coverage_test.go +++ b/cmd/server/node_analytics_coverage_test.go @@ -1,9 +1,16 @@ package main import ( + "context" "fmt" + "os" + "os/exec" + "regexp" + "runtime" + "strings" "testing" "time" + _ "time/tzdata" // TZ=Etc/GMT-2 in the child, without the host's zoneinfo ) const coverageNodePK = "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" @@ -130,10 +137,34 @@ func TestNodeAnalyticsCoverageEmptyStore(t *testing.T) { // TestNodeAnalyticsWindowIgnoresLocalZone: the window bound is compared as a // string with UTC FirstSeen values, so it must be formatted in UTC. With a // +02:00 local zone the old code dropped the oldest two hours of a 7d range. +// +// The zone is set by running this test again in a child process with +// TZ=Etc/GMT-2 (UTC+2): assigning time.Local here would race with any timer +// still running in the test binary (time.Now reads it), which the race +// detector reports as a failure of whichever test is running. func TestNodeAnalyticsWindowIgnoresLocalZone(t *testing.T) { - saved := time.Local - time.Local = time.FixedZone("UTC+2", 2*3600) - t.Cleanup(func() { time.Local = saved }) + if os.Getenv("CS_TEST_LOCAL_ZONE_CHILD") != "1" { + if runtime.GOOS == "windows" { + t.Skip("Go takes the local zone from the OS on Windows and ignores TZ") + } + // A hung child fails here with its output, not at the parent's timeout. + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.v") + cmd.Env = append(os.Environ(), "CS_TEST_LOCAL_ZONE_CHILD=1", "TZ=Etc/GMT-2") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("child run with TZ=Etc/GMT-2 failed: %v\n%s", err, out) + } + // A pattern that matched nothing would also exit 0. + if !strings.Contains(string(out), "--- PASS: "+t.Name()) { + t.Fatalf("child run did not run %s:\n%s", t.Name(), out) + } + return + } + if _, off := time.Now().Zone(); off != 2*3600 { + t.Fatalf("child local zone offset %d s, want 7200 (TZ=Etc/GMT-2)", off) + } ps := setupCoverageStore(t, 10*24) a, err := ps.GetNodeAnalytics(coverageNodePK, 7) From 01d2bbbbfdf7d22d1d48596b0bb21e3b8db3a335 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 21 Nov 2026 15:26:28 -0600 Subject: [PATCH 03/15] fix(account): keep Unclaim and Unlink disabled until the list reloads (#2440) Follow-up to #2430, covering the two points from @efiten's re-review. - **Unclaim and Unlink stay disabled until the list reloads.** Both click handlers now return the list reload from the DELETE's `.then` (`public/account.js`), so the button is re-enabled only after the redrawn list has replaced it. Before, a click between the DELETE's answer and the list GET's answer sent a second DELETE. - **The dropped-from-node-list note shows in every state.** `repeaterHealth` adds "no longer in the node list" whenever `r.inactive` is set, so an inactive repeater that was heard recently or whose prefix still relays is marked too, not only a silent one. Tests (`tests/unit/test-user-management-ui.js`, 103/103): - For both Unclaim and Unlink, the button stays disabled while the list GET after the DELETE is pending, and a click in that window sends no second DELETE. - An inactive repeater carries the note when active, uncertain, stale and never heard, and none of those rows links to a node page. `tests/e2e/test-lint-network-calls.js` 47/47. Co-authored-by: Adam <196335+anieto@users.noreply.github.com> --- public/account.js | 15 +++++--- tests/unit/test-user-management-ui.js | 53 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/public/account.js b/public/account.js index 98d57d06f..6749471e0 100644 --- a/public/account.js +++ b/public/account.js @@ -169,7 +169,14 @@ // use (getNodeStatus from roles.js: silent past the repeater threshold is // stale; a silent one whose prefix still relays is uncertain). fns carries // getNodeStatus and timeAgo so tests can pass the real ones in. + // An inactive repeater (retention dropped it from the node list, which is + // also why its row has no node page to link to) says so in every state. function repeaterHealth(r, fns) { + var h = repeaterHealthBase(r, fns); + if (r.inactive && r.known) h.text += ' · no longer in the node list'; + return h; + } + function repeaterHealthBase(r, fns) { if (!r.known) return { state: 'gone', rank: 0, text: 'no longer in the database' }; if (!r.lastHeard) return { state: 'stale', rank: 1, text: 'never heard' }; var node = { role: r.role || 'repeater', last_heard: r.lastHeard, last_relayed: r.lastRelayed || null }; @@ -177,9 +184,7 @@ var when = fns.timeAgo(r.lastHeard); if (state === 'active') return { state: state, rank: 3, text: 'heard ' + when }; if (state === 'uncertain') return { state: state, rank: 2, text: 'last heard ' + when + ', its prefix still relays' }; - // inactive: retention dropped it from the node list, which is also why - // its row has no node page to link to. - return { state: 'stale', rank: 1, text: 'silent, last heard ' + when + (r.inactive ? ' · no longer in the node list' : '') }; + return { state: 'stale', rank: 1, text: 'silent, last heard ' + when }; } var HEALTH_CHIP = { active: 'um-status-active', uncertain: 'um-status-pending', stale: 'um-status-disabled', gone: 'um-chip-unsubscribed' }; @@ -508,7 +513,7 @@ btn.disabled = true; // a second click while the DELETE runs would 404 over the success message return CSAuth.request('DELETE', '/api/account/companions/' + encodeURIComponent(pk)).then(function (r) { CSAuth.say('compMsg', r.ok ? 'Companion unlinked.' : CSAuth.errText(r), r.ok); - loadCompanions(); + return loadCompanions(); // the button stays disabled until the list is redrawn }).catch(function () { CSAuth.say('compMsg', 'Network error, try again.', false); }) .then(function () { btn.disabled = false; }); }); @@ -530,7 +535,7 @@ btn.disabled = true; // a second click while the DELETE runs would 404 over the success message return CSAuth.request('DELETE', '/api/repeaters/' + encodeURIComponent(pk) + '/claim').then(function (r) { CSAuth.say('myRepMsg', r.ok ? 'Repeater unclaimed.' : CSAuth.errText(r), r.ok); - loadMyRepeaters(); + return loadMyRepeaters(); // the button stays disabled until the list is redrawn }).catch(function () { CSAuth.say('myRepMsg', 'Network error, try again.', false); }) .then(function () { btn.disabled = false; }); }); diff --git a/tests/unit/test-user-management-ui.js b/tests/unit/test-user-management-ui.js index 7ef09c4e9..258646f8f 100644 --- a/tests/unit/test-user-management-ui.js +++ b/tests/unit/test-user-management-ui.js @@ -510,6 +510,59 @@ test('my repeaters: Unclaim is disabled while its DELETE runs, so a double click assert.strictEqual(btn.disabled, false, 'button stays disabled after the DELETE'); }); +// Unclaim and Unlink keep their button disabled until the list GET after the +// DELETE has answered: the old button is still on screen until then. +for (const c of [ + { name: 'Unclaim', list: 'myRepList', msg: 'myRepMsg', attr: 'data-unclaim', get: '/api/account/repeaters', + empty: { repeaters: [] }, done: 'Repeater unclaimed.' }, + { name: 'Unlink', list: 'compList', msg: 'compMsg', attr: 'data-unlink', get: '/api/account/companions', + empty: [], done: 'Companion unlinked.' }]) { + test(c.name + ' stays disabled until the reloaded list is in', async () => { + const pk = 'ab'.repeat(32); + let releaseList = null; + let deleted = false; + const env = loadAccount('#/account', () => ({ ok: true, status: 200, data: c.empty }), { confirm: () => true }); + env.setRequest((method, p) => { + if (method === 'DELETE') { deleted = true; return Promise.resolve({ ok: true, status: 200, data: {} }); } + if (p === c.get && deleted) return new Promise((r) => { releaseList = () => r({ ok: true, status: 200, data: c.empty }); }); + if (p === c.get) return Promise.resolve({ ok: true, status: 200, data: c.empty }); + return Promise.resolve({ ok: true, status: 200, data: [] }); + }); + env.user.current = { id: 1, email: 'a@b.c', displayName: 'Ann', role: 'user' }; + env.t.views.profile({ set innerHTML(v) {} }); + await new Promise((r) => setTimeout(r, 5)); + const btn = { getAttribute: (a) => (a === c.attr ? pk : null) }; + const first = env.els[c.list].handlers.click({ target: btn }); + await new Promise((r) => setTimeout(r, 5)); + assert(releaseList, 'list not reloaded after the DELETE'); + assert.strictEqual(env.els[c.msg].textContent, c.done); + assert.strictEqual(btn.disabled, true, 'button enabled again while the list GET runs'); + env.els[c.list].handlers.click({ target: btn }); + assert.strictEqual(env.calls.filter((x) => x.method === 'DELETE').length, 1, 'a click before the reload sent another DELETE'); + releaseList(); + await first; + assert.strictEqual(btn.disabled, false, 'button stays disabled after the reload'); + }); +} + +test('an inactive repeater carries the dropped note in every health state', () => { + const env = loadAccount('#/account', () => ({})); + const fns = { getNodeStatus: realGetNodeStatus(), timeAgo: () => 'AGO' }; + const recent = new Date(Date.now() - 3600 * 1000).toISOString(); + const old = new Date(Date.now() - 10 * 86400 * 1000).toISOString(); + const base = { known: true, inactive: true, role: 'repeater', name: 'X', claimedAt: '2026-11-01T00:00:00Z', status: null, comaintainers: [] }; + const h = env.t.myRepeatersHtml([ + Object.assign({ pubkey: '11'.repeat(32), lastHeard: recent }, base), + Object.assign({ pubkey: '22'.repeat(32), lastHeard: old, lastRelayed: recent }, base), + Object.assign({ pubkey: '33'.repeat(32), lastHeard: old }, base), + Object.assign({ pubkey: '44'.repeat(32), lastHeard: null }, base)], fns); + for (const [pk, state] of [['11', 'active'], ['22', 'uncertain'], ['33', 'stale'], ['44', 'stale']]) { + assert(h.indexOf('data-pubkey="' + pk.repeat(32) + '" data-health="' + state + '"') !== -1, pk + ' not ' + state + ': ' + h); + } + assert.strictEqual((h.match(/no longer in the node list/g) || []).length, 4, 'note missing on a state: ' + h); + assert.strictEqual((h.match(/href="#\/nodes\//g) || []).length, 0, 'inactive row links to a node page'); +}); + test('my repeaters empty state explains how to claim', () => { const env = loadAccount('#/account', () => ({})); for (const list of [[], null, undefined]) { From 1a6322a7078f74c61b089b9f2529ee5a71a55eb8 Mon Sep 17 00:00:00 2001 From: Zach Date: Sat, 21 Nov 2026 15:26:46 -0600 Subject: [PATCH 04/15] feat(map): more tile providers (topo, satellite, gray, vector), hillshade overlay and custom tile servers (#2434) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #2428. Adds free and open map providers (topographic, satellite, gray and vector basemaps), a hillshade overlay, and support for operators' own tile servers. Everything is additive and opt-in: Carto stays the default, every new provider group is off until the operator turns it on, and no existing config key or provider was removed. An upgrade with an untouched config changes nothing in the picker. > **Dependency:** #2426 has merged. The branch is rebased onto current `master` (`6c78a1d2`) with no conflicts. ## What's new - **Provider registry** (`public/map-tile-providers.js`). New groups are **opt-in**: each is off until `map.tiles.providers..enabled` is `true` (the boolean), so licences and volunteer servers are the operator's call: - **EOX**: Sentinel-2 satellite (2025 and 2016), Terrain Light, and a place-labels overlay. EOX 2025 imagery is CC BY-NC-SA 4.0 (non-commercial); a commercial deployment should leave `eox` off or license it. - **OSM France**: Humanitarian, CyclOSM, OSM Gray and OSM Gray Dark (volunteer-run, fair use). - **OpenFreeMap** and **VersaTiles** vector styles: Liberty, Bright, Positron, Dark, Fiord, Colorful, Muted and the Gray variants. - **Hillshade** (below) is opt-in the same way. **OpenTopoMap**, the OSM community server, Stamen and USGS keep their existing opt-in. - **Custom tile servers**: `map.tiles.custom` adds raster (XYZ), vector (MapLibre style URL) and raster-overlay entries as `custom-`. They can be used in `darkDefault` / `lightDefault`. Invalid entries are skipped with a console warning. - **Hillshade overlay** (`public/map-hillshade.js`): shaded in the browser from Terrarium elevation tiles. `map.tiles.providers.hillshade.url` can point at a mirror. - **Vector basemaps** (`public/map-vector.js`) use a vendored MapLibre GL 5.24.0 (CSP build) and `@maplibre/maplibre-gl-leaflet` 0.1.4. - They are lazy-loaded only when a vector map is picked (about 380 KB gzipped). - The load times out after 15 s. - Without WebGL the map falls back to the theme's default raster map. - **One picker on Map, Live and Repeater Planner**: Auto, Street, Topographic, Satellite, plus an Overlays group. - **A map picked there is saved** (`localStorage` `mc-tile-pinned`, untrusted: honoured only while registered). Every picker reopens on it after a reload or on another page, until the visitor picks **Auto**. - The other maps (home mini-map, node detail, node reach, analytics) follow the visitor's choice through the shared builder: the saved pick when it suits the current theme (satellite always does), otherwise the theme's map. - Those small maps never load MapLibre, so a vector choice shows the theme's default raster map there. - **Security contract**: the `CONTRACT` block at the top of `map-tile-providers.js` (S1 to S7) covers one shared tile-URL validator (`https?://` or a same-origin path, no credentials in the authority, whitelisted placeholders), attribution HTML-escaped once, picker labels set with `textContent`, explicit MapLibre options, pinned vendored versions, CORS-safe hillshade decoding, and treating stored picks as untrusted input. `map.tiles` is served publicly in `/api/config/client`, so keys put there are public (the docs warn about this). ## Fixes included The race stress suite written for this PR found teardown races when leaving map pages mid-load: - a lazy MapLibre load finishing after navigation; - a hillshade tile decoding after `remove()`; - a provider-change event arriving during teardown. It also found a pre-existing document-listener leak in `AreaFilter` / `RegionFilter`. All of these are fixed in `e6709e74`, with regression tests in `tests/e2e/test-map-teardown-races.js`. The first CI run then caught a bug in that fix (`7f8d792c`). `MC_safeRemoveMap` called `map.off()` before `map.remove()`, so the map's `unload` event reached no one. Leaflet relies on that event to detach controls and clean up the zoom-animation proxy and BoxZoom, and `test-issue-1206` watches it to confirm node maps are disposed. `off()` now runs after `remove()`, and a new regression test checks that `unload` fires, controls detach and no listener is left. A later stress run (a new seed) found a real two-tab bug, fixed in `0506fc1d`. When another tab's overlay pick is already in localStorage but its `storage` event hasn't arrived, a layer-picker click here triggered a sync that added that overlay while Leaflet was still applying the click. Leaflet doesn't redraw the list for changes it sees mid-click, so the overlay's checkbox stayed unticked, and the next click on any overlay removed it and wrote the removal back to every tab. The overlay set now defers a sync until the click has finished. New E2E check `4b` in `test-map-providers-e2e.js` plants another tab's pick and clicks twice: one write per click, the planted overlay stays ticked. It fails on the previous code. ## Docs - `docs/deployment.md`, "Map Tile Providers" section, rewritten. It covers every provider and its licence, turning groups on and off, custom servers, vector maps, hillshade, self-hosting, and what is public. - User guide: - `map.md` gets a "Map style and overlays" section; - `live.md` notes the picker; - `configuration.md` gets a "Map tiles" section; - the FAQ gets a new entry on satellite, terrain and gray maps. - `CHANGELOG.md`: an Unreleased entry. ## Test data Two datasets were used, so every number below says which one it came from. **1. Large synthetic dataset** (perf A/B and screenshots). It is generated, contains no real mesh data, and is not checked in. - **Generator:** `synthgen` 1.0.0, seed 1, "full" scale. Built from upstream `be16173e` and retimed so its 18-day window (2026-10-31 to 2026-11-18) ends at the time of the run. - **Database:** SQLite, 3.94 GB (586 MB as zstd), 11.6 M rows in all. | Table | Rows | |---|---| | Nodes | 18,102 (12,606 companions, 3,652 repeaters, 953 rooms, 891 sensors) | | Nodes with a location | 13,452, spread worldwide (latitude −37° to 60°, longitude −123° to 175°) | | Observers | 1,175, in 42 regions on six continents | | Transmissions | 759,133 | | Observations | 10,569,668 | | Neighbour edges | 42,806 | | Advert route evidence | 212,142 | During the perf runs, the server's packet store was pinned to the newest 48 h with a 1.5 GB memory cap. Each server held about 65 k transmissions and 0.9 M observations in memory (baseline 65,647 / 906,467; candidate 64,862 / 896,248), plus all 18,102 nodes (about 17,650 active) and 1,175 observers. The tracked store was about 450 MB. **2. The repo's CI fixture** (`test-fixtures/e2e-fixture.db`, 704 KB). All E2E suites and the race stress gates ran against it, freshened the way CI does: 204 nodes, 31 observers, 500 transmissions, 502 observations. A second copy with the Repeater Planner enabled was used for the planner-on stress runs. **Perf environment:** - Headless Chromium 158 via Playwright 1.58.2, at 1280×800 with device scale factor 1. - 9 measured runs per scenario plus 1 warm-up, on each of `master` and this branch. - Host: Linux, AMD Ryzen 7 3700X (16 threads), 63 GB RAM. - **Tiles were stubbed.** The harness answers every tile, elevation and style request locally with the same stub on both sides (`--mode stub`), so perf timings involve no network. Only the screenshot gallery uses real tiles. ## Screenshots These were taken from the synthetic dataset with real tiles in a real browser (headless Chromium, 1280×800). Click a thumbnail for the full size. The images are hosted on a separate assets branch, so they are not in this diff. #### Street | | | | |---|---|---| | Street: Carto (default) (light)
    Carto (default) (light) | Street: Carto (default) (dark)
    Carto (default) (dark) | Street: OSM France Humanitarian (light)
    OSM France Humanitarian (light) | #### Gray | | | | |---|---|---| | Gray: OSM France (light)
    OSM France (light) | Gray: OSM France (dark)
    OSM France (dark) | Gray: VersaTiles (light)
    VersaTiles (light) | | Gray: VersaTiles (dark)
    VersaTiles (dark) | Gray: OpenFreeMap Positron (light)
    OpenFreeMap Positron (light) | Gray: OpenFreeMap Dark (dark)
    OpenFreeMap Dark (dark) | #### Topographic | | | | |---|---|---| | Topo: CyclOSM (light)
    CyclOSM (light) | Topo: EOX Terrain Light (light)
    EOX Terrain Light (light) | Topo: OpenTopoMap (opt-in) (light)
    OpenTopoMap (opt-in) (light) | #### Satellite | | | | |---|---|---| | Satellite: Sentinel-2 2025 (light)
    Sentinel-2 2025 (light) | Satellite: Sentinel-2 2025 with labels
(light)
    Sentinel-2 2025 with labels (light) | Satellite: Sentinel-2 2025 (dark)
    Sentinel-2 2025 (dark) | | Satellite: Sentinel-2 2025 with labels
(dark)
    Sentinel-2 2025 with labels (dark) | Satellite: Sentinel-2 2016 (light)
    Sentinel-2 2016 (light) | Satellite: Sentinel-2 2016 with labels
(light)
    Sentinel-2 2016 with labels (light) | #### Vector (MapLibre) | | | | |---|---|---| | Vector: OpenFreeMap Liberty
(light)
    OpenFreeMap Liberty (light) | Vector: OpenFreeMap Dark (dark)
    OpenFreeMap Dark (dark) | Vector: VersaTiles Colorful (light)
    VersaTiles Colorful (light) | | Vector: VersaTiles Colorful Dark
(dark)
    VersaTiles Colorful Dark (dark) | | | #### Hillshade overlay | | | | |---|---|---| | Overlay: hillshade over Sentinel-2
(light)
    hillshade over Sentinel-2 (light) | Overlay: hillshade over Carto
(light)
    hillshade over Carto (light) | Overlay: hillshade over Sentinel-2
(dark)
    hillshade over Sentinel-2 (dark) | | Overlay: hillshade over Carto (dark)
    hillshade over Carto (dark) | | | #### Repeater Planner | | | |---|---| | Planner: Sentinel-2 + hillshade
(light)
    Sentinel-2 + hillshade (light) | Planner: Sentinel-2 + hillshade
(dark)
    Sentinel-2 + hillshade (dark) | #### Layer picker | | | |---|---| | Layer picker open (light)
    Layer picker open (light) | Layer picker open (dark)
    Layer picker open (dark) | #### Custom tile server | | | |---|---| | Custom raster provider on the map
    Custom raster provider on the map | Custom raster provider in the picker
    Custom raster provider in the picker | ## Testing The full suite ran twice, each time on a fresh clone: | | Pass 1 | Pass 2 | |---|---|---| | Commit (before rebase) | `8a56e841` | `9355169b` | | `test-all.sh` (unit) | pass | pass | | `npm run lint` | 0 errors (87 warnings, all pre-existing) | 0 errors (87 warnings, all pre-existing) | | Go `cmd/server` / `cmd/ingestor` | ok / ok | ok / ok | | E2E, map-related files (CI fixture) | 44/44 | 44/44 + planner-on run | | `test-e2e-playwright.js` | 149 passed, 3 skipped | 149 passed, 3 skipped | | Race stress gate (seeds) | 101, 202: all pass | 303, 404: all pass | | Stress with planner enabled | pass | pass (seed 505) | | Gallery | 32/32 | 32/32 | The rebased equivalents of the pass 1 and pass 2 commits are `fde2552c` and `e4d5c447`. **After the first CI run.** The two passes covered only the map-related E2E files, and CI exposed two problems: 1. `test-issue-1206` failed 7 checks. This was the `unload` bug described under "Fixes included". 2. The JS unit gate runs without `node_modules`, so the two new jsdom suites crashed `test-all.sh`. Locally, jsdom was reachable from a parent checkout, which hid this. The second problem is fixed in `57720bf3`, following the `domIntegration` convention in `scripts/non-unit-tests.json`. `test-map-teardown-races.js` moved to `tests/e2e/`, and the three jsdom zoom-limit tests split out into `tests/e2e/test-map-vector-leaflet-zoom.js`, so 30 + 3 = 33 tests are kept. Both run from E2E shard 2 and take a few seconds. The heavy suites (race stress, perf, gallery) stay local-only and are not run in GitHub Actions. These checks ran on the fixed, rebased tree (`57720bf3`): | Check | Result | |---|---| | `test-all.sh` from a copy with no `node_modules` (as CI runs it) | pass | | `test-test-inventory.js` | 399 suites classified | | `npm run lint` | 0 errors | | Go `cmd/server` / `cmd/ingestor` | ok / ok | | `test-issue-1206-resize-observer-leak-e2e.js` | 13/13 (7 were failing) | | `test-e2e-playwright.js` | 149 passed, 3 skipped | | `test-map-providers-e2e.js` / harness E2E | 17/17, 16/16 | | `test-map-teardown-races.js` / `test-map-vector-leaflet-zoom.js` | 19/19, 3/3 | | Race stress (3 iterations) | all scenarios pass | The commits since pass 2 are `76c67184` (docs only), `7f8d792c` and `57720bf3`. **GitHub Actions on `0506fc1d` (rebased onto `master`, with the two-tab fix): every check passed** (13 passed, 4 skipped as usual for a PR). That covers Go build and test, all three E2E shards, the server race detector and both image builds. The moved suites ran in shard 2 (`test-map-teardown-races.js` 19/19, `test-map-vector-leaflet-zoom.js` 3/3), and the unit gate ran `test-map-vector.js` (30/30). **Race stress suite** (`tests/e2e/test-map-race-stress-e2e.js`). Each gate run does 20 iterations of scenarios a to e and 50 cycles of f. The scenarios cover: - rapid provider switching; - theme flips during a vector load; - navigating away mid-load (including a 15 s MapLibre timeout); - repeated map-page navigation with heap checks; - overlay toggles; - cross-page picker persistence. Results for each run: - Listener counts stay flat: at most 3 `mc-tile-provider-changed` listeners and 5 `storage` listeners. - At most one live WebGL context at a time. - Heap growth in the second half of scenario d was 0.25 to 0.45 MB across the four gate runs. - Upstream `master` grows about 0.39 MB per map navigation loop in the same scenario; this branch levels off. ## Maintainer review (addressed) 1. **Licence default.** All five new groups (`eox`, `osmfr`, `openfreemap`, `versatiles`, `hillshade`) are opt-in: off unless `enabled: true` (`"true"`, `1` or `{}` don't count). With an untouched config the picker lists the same 6 base maps as before. Docs, `config.example.json` (now `enabled: false` for each) and the changelog say so, and each group's terms are listed before you turn it on. 2. **Saved pick.** The on-map picker now saves the pick (option 1 of your two), as the docs promised. Behaviour, and what an other-theme pick does: - Every picker opens on the pinned map, on any page and after a reload, until **Auto** is picked. A pin is shown whatever the theme, as an explicit pick already was. - Maps without a picker show it when it fits the current theme (`type` is the theme or `any`), otherwise the theme's map. So a light pin isn't drawn on a dark node map; satellite always is. - A stored pin whose group is turned off reads as Auto, and comes back if the group is turned on again; only picking Auto clears it. - On a map with a picker, Auto always means the theme's map: the pin is only the explicit layer, never loaded into the hidden Auto layer. A choice in the customizer, and Reset All, clear the pin. A failed write (quota full) never brings back an older stored pin. - E2E `7a` to `7c` in `test-map-providers-e2e.js`: pick, reload, the radio and tiles are the pick, the node detail map draws it, and a light pin in dark is kept but not drawn. Auto clears the key; junk in it gives Auto; an untouched config lists none of the new groups. 7a and 7b fail with the save line removed. Unit tests are in `test-map-tile-pin.js` (21). 3. **CI.** `test-map-providers-e2e.js` (24 checks, including `4b`, the two-tab regression check) and `test-map-providers-harness-e2e.js` (16) now run in E2E shard 3 against the fixture server: every tile host is stubbed. Non-blocking: - `getTileUrl()` now returns the raster fallback for a vector pick (`MC_rasterTileUrl`). There's a test in `test-tile-resolver.js` that fails on the old code. - The `map-vector.js` header and the binding's vendor README list the Leaflet and binding internals to recheck on an upgrade. - `docs/deployment.md` says SRI makes a JS-rewriting proxy drop vector maps to raster, so serve `public/vendor/` unmodified. - `scripts/map-perf/README.md` says where `SEED_DB` and `SHIFT_SH` come from. - The maps with `attributionControl: false` are left as they are. That predates this PR, and with every new group opt-in, an upgrade adds no uncredited imagery. Follow-up for all of them: #2441. - The OpenFreeMap credit line is `OpenFreeMap © OpenMapTiles Data from OpenStreetMap` (`2424f3c3`), the line OpenFreeMap gives for clients that don't add it automatically. Verified after these changes: - `test-all.sh` and lint pass, with 0 errors. - Both provider E2E suites pass: 24/24 and 16/16. - Race stress, seed 979: scenarios a, b, d and e pass. c (15/15) and f (37/37) pass after updating their model of the pick: they expected Auto after a return, which was the old unsaved behaviour. - The stress suite now enables the five groups itself, so it keeps exercising them. ## Performance A/B test: `master` against this branch on the large synthetic dataset, with 9 runs per scenario and stubbed tiles (see Test data; `scripts/map-perf/`). The full HTML report is not attached; ask if you want it. - **No budget failures** in either pass. The `raster-no-maplibre` budget holds: no raster scenario loads MapLibre. - **DOMContentLoaded is unchanged on every page**, even with the two new scripts (`map-hillshade.js` and `map-vector.js`, about 635 lines in all; MapLibre itself loads only on demand). - **Switching providers 50 times (raster only), median ms per switch:** - dark: 146 → 108.5; - light: 208 → 208.5. - Heap growth during the run: 0.3 to 0.4% on both sides. - **Flagged and checked:** - Live and Analytics `loadEventMs` are flagged in some runs. This metric has two modes on **both** branches: `load` fires either before Leaflet adds its first tile ``s (about 150 ms) or after they finish (about 400 ms). A direct probe of `master` alone gave 428, 404 and 124 ms. On these scenarios, map creation, first tile, all tiles, first marker and wall time are within a few ms on both sides. - Carto and Positron `allTilesSinceMapMs` are 4 to 6 ms slower, just above `master`'s p95. Tiles are stubbed locally, so this is not network noise. The cause is not isolated. Both providers now go through the shared layer builder, and on the same scenarios first tile, all tiles and wall time are within 10 ms of `master` (Carto Voyager +2 to +3 ms; Positron Dark +6 to +9 ms). - The Analytics map shows one long task of about 50 ms against a `master` median of 0, but `master`'s p95 is 52 to 84 ms. This is disclosed in case it shows up for you. - Other desktop apps were running during the perf runs, so expect some noise. ## Commits 1. `c6bf12ed` feat(map): tile provider registry with custom servers, gray, topo and satellite maps, and overlays 2. `9237230b` feat(map): client-side hillshade overlay 3. `781e41b4` feat(map): vector basemaps via vendored MapLibre GL 5.24.0 4. `dae36d2e` refactor(map): every map surface uses the shared basemap builder 5. `3d4afcdc` fix(map): teardown races and listener leaks when leaving map pages 6. `b798b2fe` test(server): pin map.tiles passthrough in /api/config/client 7. `171b1bc4` test(map): E2E, race stress suite, perf harness and screenshot gallery 8. `61f73875` docs(map): providers, custom tile servers, overlays and self-hosting 9. `135a9b12` test(map): gallery shows opt-in OpenTopoMap and retries slow tile servers 10. `3833572b` test(map): harness waits for vector basemaps; stress suite fixes from test pass 1 11. `3e543cad` test(map-perf): redact tile-URL credentials; compare switch50 like with like 12. `d5006111` docs(map): user guide for map styles, overlays and map.tiles 13. `90ee1d5d` fix(map): MC_safeRemoveMap lets unload listeners run before dropping them 14. `5fc57b5c` test(map): run the jsdom map suites in the E2E job, not the unit gate 15. `bd36b634` fix(map): another tab's overlay pick that lands mid-click is no longer removed 16. `38df65d2` fix(map): new tile groups are opt-in; a map picked in the picker is saved 17. `eafbcac9` ci(e2e): run the map provider E2E suites in shard 3 18. `65b223ec` fix(map): getTileUrl() never returns a vector style url; review notes 19. `f3402c5d` test(map): race stress enables the opt-in groups and expects the saved pick 20. `e92b8631` fix(map): Auto on a picker map ignores the saved pick; customizer clears it 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/deploy.yml | 7 + .gitignore | 1 + CHANGELOG.md | 13 + cmd/server/config_map_tiles_test.go | 157 ++ config.example.json | 25 +- docs/deployment.md | 171 +- docs/user-guide/configuration.md | 21 + docs/user-guide/faq.md | 4 + docs/user-guide/live.md | 2 + docs/user-guide/map.md | 23 + public/analytics.js | 13 +- public/area-filter.js | 23 +- public/customize-v2.js | 58 +- public/home.js | 12 +- public/index.html | 2 + public/live.js | 83 +- public/map-hillshade.js | 215 +++ public/map-tile-providers.js | 1397 +++++++++++++++-- public/map-vector.js | 424 +++++ public/map.js | 107 +- public/node-reach-map.js | 2 +- public/nodes.js | 38 +- public/planner.js | 53 +- public/region-filter.js | 23 +- public/roles.js | 40 +- public/style.css | 14 + public/vendor/maplibre-gl-5.24.0/LICENSE.txt | 116 ++ public/vendor/maplibre-gl-5.24.0/README.md | 23 + .../maplibre-gl-csp-worker.js | 6 + .../maplibre-gl-5.24.0/maplibre-gl-csp.js | 6 + .../vendor/maplibre-gl-5.24.0/maplibre-gl.css | 1 + .../vendor/maplibre-gl-leaflet-0.1.4/LICENSE | 15 + .../maplibre-gl-leaflet-0.1.4/README.md | 19 + .../leaflet-maplibre-gl.js | 234 +++ scripts/map-perf/README.md | 184 +++ scripts/map-perf/budgets.js | 98 ++ scripts/map-perf/gallery.js | 312 ++++ scripts/map-perf/report.js | 294 ++++ scripts/map-perf/run.js | 540 +++++++ scripts/map-perf/scenarios.js | 130 ++ scripts/map-perf/serve-dataset.sh | 194 +++ scripts/non-unit-tests.json | 9 +- test-all.sh | 8 + tests/e2e/lib/map-harness.js | 831 ++++++++++ tests/e2e/test-map-providers-e2e.js | 450 ++++++ tests/e2e/test-map-providers-harness-e2e.js | 137 ++ tests/e2e/test-map-race-stress-e2e.js | 1373 ++++++++++++++++ tests/e2e/test-map-teardown-races.js | 542 +++++++ tests/e2e/test-map-vector-leaflet-zoom.js | 153 ++ tests/emoji-allowlist.txt | 1 + tests/unit/test-issue-1420-tile-providers.js | 11 +- .../unit/test-issue-1470-node-tile-helper.js | 93 ++ .../test-issue-1496-reset-all-complete.js | 21 + .../unit/test-issue-1862-map-region-filter.js | 2 + tests/unit/test-map-custom-providers.js | 697 ++++++++ tests/unit/test-map-harness-png.js | 260 +++ tests/unit/test-map-hillshade.js | 421 +++++ tests/unit/test-map-layer-builder.js | 690 ++++++++ tests/unit/test-map-overlays-vector.js | 899 +++++++++++ tests/unit/test-map-tile-pin.js | 316 ++++ tests/unit/test-map-vector.js | 717 +++++++++ tests/unit/test-planner.js | 3 +- tests/unit/test-secondary-map-tile-builder.js | 221 +++ tests/unit/test-tile-resolver.js | 62 +- tests/unit/test-vendored-libs.js | 25 +- 65 files changed, 12718 insertions(+), 324 deletions(-) create mode 100644 cmd/server/config_map_tiles_test.go create mode 100644 public/map-hillshade.js create mode 100644 public/map-vector.js create mode 100644 public/vendor/maplibre-gl-5.24.0/LICENSE.txt create mode 100644 public/vendor/maplibre-gl-5.24.0/README.md create mode 100644 public/vendor/maplibre-gl-5.24.0/maplibre-gl-csp-worker.js create mode 100644 public/vendor/maplibre-gl-5.24.0/maplibre-gl-csp.js create mode 100644 public/vendor/maplibre-gl-5.24.0/maplibre-gl.css create mode 100644 public/vendor/maplibre-gl-leaflet-0.1.4/LICENSE create mode 100644 public/vendor/maplibre-gl-leaflet-0.1.4/README.md create mode 100644 public/vendor/maplibre-gl-leaflet-0.1.4/leaflet-maplibre-gl.js create mode 100644 scripts/map-perf/README.md create mode 100644 scripts/map-perf/budgets.js create mode 100644 scripts/map-perf/gallery.js create mode 100644 scripts/map-perf/report.js create mode 100644 scripts/map-perf/run.js create mode 100644 scripts/map-perf/scenarios.js create mode 100755 scripts/map-perf/serve-dataset.sh create mode 100644 tests/e2e/lib/map-harness.js create mode 100644 tests/e2e/test-map-providers-e2e.js create mode 100644 tests/e2e/test-map-providers-harness-e2e.js create mode 100644 tests/e2e/test-map-race-stress-e2e.js create mode 100644 tests/e2e/test-map-teardown-races.js create mode 100644 tests/e2e/test-map-vector-leaflet-zoom.js create mode 100644 tests/unit/test-map-custom-providers.js create mode 100644 tests/unit/test-map-harness-png.js create mode 100644 tests/unit/test-map-hillshade.js create mode 100644 tests/unit/test-map-layer-builder.js create mode 100644 tests/unit/test-map-overlays-vector.js create mode 100644 tests/unit/test-map-tile-pin.js create mode 100644 tests/unit/test-map-vector.js create mode 100644 tests/unit/test-secondary-map-tile-builder.js diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1f8c5d2cf..d5993ae6d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -809,6 +809,13 @@ jobs: # The lint rule that keeps network calls on CSApi (needs eslint). suite 1 test-lint-network-calls.js suite 3 test-table-sort.js + # jsdom suites for the map teardown races and vector zoom limits (#2428). + suite 2 test-map-teardown-races.js + suite 2 test-map-vector-leaflet-zoom.js + # The #2428 tile providers and the harness that serves their tiles: every + # tile host is stubbed in the browser, so the fixture server is enough. + suite 3 test-map-providers-e2e.js BASE_URL=$B + suite 3 test-map-providers-harness-e2e.js BASE_URL=$B suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B suite 1 test-nodes-export-e2e.js BASE_URL=$B diff --git a/.gitignore b/.gitignore index 5d3b6bfc0..785b4babf 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,4 @@ docs/superpowers/ # Environment-specific deploy scripts — live only on the deploy host, not tracked deploy-live.sh deploy-staging.sh +test-results/map-perf/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 244fca3b1..9b5eab76c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## [Unreleased] +### Added +- **More map providers** (#2428) - new groups, each off until the operator sets `map.tiles.providers..enabled: true` (an upgrade changes nothing in the picker): EOX (Sentinel-2 satellite 2025 and 2016, Terrain Light, place-label overlays), OSM France (Humanitarian, CyclOSM, OSM Gray, OSM Gray Dark), and the vector styles OpenFreeMap (Liberty, Bright, Positron, Dark, Fiord) and VersaTiles (Colorful, Muted, Gray, Colorful Dark, Gray Dark). Check each group's terms before turning it on: EOX 2025 imagery is non-commercial (CC BY-NC-SA 4.0), OSM France is volunteer-run fair use. +- **Your own tile servers** - `map.tiles.custom` adds raster (XYZ), vector (MapLibre style) and raster overlay entries as `custom-`, usable in `darkDefault` / `lightDefault`. Invalid entries are skipped with a console warning. +- **Overlays** - a hillshade overlay shaded in the browser from Terrarium elevation tiles (`map.tiles.providers.hillshade.url` can point at a mirror) and EOX place labels, ticked from a new Overlays group in the picker (each with its group turned on). +- **The picked map is saved** - a map pinned in the picker survives a reload and applies on every page (the small maps without a picker use it when it suits the current theme); **Auto** clears it. +- **MapLibre GL vendored** in `public/vendor/` and lazy-loaded (about 380 KB gzipped) only when a vector map is picked; without WebGL the map falls back to the default raster map. + +### Changed +- **Every map page follows the provider choice**, including the home page mini-map, with one shared picker (Auto, Street, Topographic, Satellite, Overlays). +- `docs/deployment.md` Map Tile Providers rewritten to match the real config keys. + +Closes #2428. + ## [3.18.0] - 2026-11-17 See [docs/release-notes/v3.18.0.md](docs/release-notes/v3.18.0.md) for the full notes. 11 commits since v3.17.0: 5 fix, 3 feat, 1 test, 1 refactor, 1 docs. diff --git a/cmd/server/config_map_tiles_test.go b/cmd/server/config_map_tiles_test.go new file mode 100644 index 000000000..168084ce5 --- /dev/null +++ b/cmd/server/config_map_tiles_test.go @@ -0,0 +1,157 @@ +package main + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "testing" +) + +// The server must hand map.tiles to the browser untouched: the browser +// validates it, so a server-side refactor that drops or rewrites a field would +// silently break operators' self-hosted tile servers. + +const mapTilesFullJSON = `{ + "darkDefault": "custom-ours-vec", + "lightDefault": "custom-ours", + "providers": { + "carto": {"enabled": true, "key": "k", "domain": "corp"}, + "eox": {"enabled": false}, + "osmfr": {"enabled": true}, + "openfreemap": {"enabled": false}, + "hillshade": {"enabled": true, "url": "https://mirror.example.org/terrarium/{z}/{x}/{y}.png"} + }, + "custom": [ + {"id": "ours", "label": "Our tile server", "type": "light", "category": "street", + "format": "raster", "url": "https://{s}.tiles.example.org/{z}/{x}/{y}.png", + "attribution": "(c) OpenStreetMap contributors", "maxZoom": 19, "maxNativeZoom": 18, + "subdomains": "abc", "overlay": false}, + {"id": "ours-vec", "label": "Our vector style", "type": "dark", "category": "topo", + "format": "vector", "url": "/styles/dark.json", + "attribution": "(c) Example", "maxZoom": 22, "maxNativeZoom": 14, + "subdomains": "", "overlay": true}, + {"id": "x", "label": "", "type": "bogus", "category": "??", + "format": "raster", "url": "javascript:alert(1)", + "attribution": "a", + "maxZoom": -5, "maxNativeZoom": 1e9, "subdomains": "}{", "overlay": "yes", "extra": {"n": null}} + ] +}` + +// clientConfigFor loads a config the way the server does (LoadConfig, which +// runs migrateDeprecatedConfig) and fetches /api/config/client. +func clientConfigFor(t *testing.T, configJSON string) map[string]interface{} { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := LoadConfig(dir) + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + srv, router := setupTestServer(t) + srv.cfg = cfg + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil)) + if w.Code != 200 { + t.Fatalf("status %d: %s", w.Code, w.Body.String()) + } + var out map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + return out +} + +func mustDecodeObject(t *testing.T, s string) map[string]interface{} { + t.Helper() + var m map[string]interface{} + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("fixture: %v", err) + } + return m +} + +func tilesOf(t *testing.T, resp map[string]interface{}) map[string]interface{} { + t.Helper() + m, ok := resp["map"].(map[string]interface{}) + if !ok { + t.Fatalf("response map is %T, want object", resp["map"]) + } + tiles, ok := m["tiles"].(map[string]interface{}) + if !ok { + t.Fatalf("response map.tiles is %T, want object", m["tiles"]) + } + return tiles +} + +func TestClientConfigMapTilesPassThrough(t *testing.T) { + cases := []struct { + name string + tiles string + }{ + {"full new shape with hostile entry", mapTilesFullJSON}, + {"empty custom list", `{"custom": []}`}, + {"providers only", `{"providers": {"eox": {"enabled": false}, "hillshade": {"enabled": false}}}`}, + {"unknown future keys", `{"futureKey": {"a": [1, 2, 3]}, "custom": [{"id": "z", "newField": true}]}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + want := mustDecodeObject(t, tc.tiles) + resp := clientConfigFor(t, `{"map": {"center": [1, 2], "zoom": 7, "tiles": `+tc.tiles+`}}`) + got := tilesOf(t, resp) + if !reflect.DeepEqual(got, want) { + g, _ := json.MarshalIndent(got, "", " ") + w, _ := json.MarshalIndent(want, "", " ") + t.Fatalf("map.tiles changed.\n got: %s\nwant: %s", g, w) + } + m := resp["map"].(map[string]interface{}) + if m["zoom"] != float64(7) { + t.Errorf("map.zoom = %v, want 7", m["zoom"]) + } + }) + } +} + +func TestClientConfigLegacyTilesMigrateWithoutClobberingCustom(t *testing.T) { + custom := `[{"id": "ours", "label": "Ours", "format": "raster", "url": "https://t.example.org/{z}/{x}/{y}.png"}]` + cfgJSON := `{ + "mapDarkTileProvider": "legacy-dark", + "tiles": {"lightDefault": "legacy-light", "custom": [{"id": "legacy"}], "legacyOnly": "x"}, + "map": {"tiles": {"lightDefault": "new-light", "custom": ` + custom + `}} + }` + tiles := tilesOf(t, clientConfigFor(t, cfgJSON)) + + wantCustom := mustDecodeObject(t, `{"c": `+custom+`}`)["c"] + if !reflect.DeepEqual(tiles["custom"], wantCustom) { + t.Errorf("map.tiles.custom clobbered by legacy tiles: %v", tiles["custom"]) + } + if tiles["lightDefault"] != "new-light" { + t.Errorf("explicit map.tiles.lightDefault overridden: %v", tiles["lightDefault"]) + } + if tiles["darkDefault"] != "legacy-dark" { + t.Errorf("mapDarkTileProvider not migrated to darkDefault: %v", tiles["darkDefault"]) + } + if tiles["legacyOnly"] != "x" { + t.Errorf("legacy tiles key not migrated: %v", tiles["legacyOnly"]) + } +} + +func TestClientConfigLegacyTilesOnlyMigrate(t *testing.T) { + tiles := tilesOf(t, clientConfigFor(t, `{"mapDarkTileProvider": "legacy-dark", "tiles": {"lightDefault": "legacy-light"}}`)) + if tiles["darkDefault"] != "legacy-dark" || tiles["lightDefault"] != "legacy-light" { + t.Errorf("legacy keys not migrated into map.tiles: %v", tiles) + } +} + +// Documents today's behaviour: with no map block the server still answers with +// a map object whose tiles is an empty object (migrateDeprecatedConfig). +func TestClientConfigAbsentMapStillUsable(t *testing.T) { + resp := clientConfigFor(t, `{}`) + tiles := tilesOf(t, resp) + if len(tiles) != 0 { + t.Errorf("absent map: tiles = %v, want empty object", tiles) + } +} diff --git a/config.example.json b/config.example.json index 9497c40c3..bda47a260 100644 --- a/config.example.json +++ b/config.example.json @@ -118,8 +118,31 @@ "_comment_usgs": "USGS topographical tile provider. Limited to zoom level 16.", "usgs": { "enabled": false + }, + "_comment_eox": "EOX Sentinel-2 cloudless satellite (latest year and 2016), EOX Terrain Light, and the EOX place-labels overlay. No key. Off unless enabled is true. The 2016 imagery is CC BY 4.0; later years are CC BY-NC-SA 4.0 (non-commercial only) - a commercial deployment must leave it off or license them from EOX.", + "eox": { + "enabled": false + }, + "_comment_osmfr": "OpenStreetMap France community servers: Humanitarian (HOT), CyclOSM (topographic, with hillshading and contours), and OSM Gray / OSM Gray Dark (the OSM France style shown in grayscale). No key, donation-funded fair use. Off unless enabled is true.", + "osmfr": { + "enabled": false + }, + "_comment_openfreemap": "OpenFreeMap vector styles (Liberty, Bright, Positron, Dark, Fiord). No key, no limits. Loads the vendored MapLibre GL only when one of these is picked. Off unless enabled is true.", + "openfreemap": { + "enabled": false + }, + "_comment_versatiles": "VersaTiles vector styles (Gray, Gray Dark, Muted, Colorful, Colorful Dark). No key. Loads the vendored MapLibre GL only when one of these is picked. Off unless enabled is true.", + "versatiles": { + "enabled": false + }, + "_comment_hillshade": "Hillshade overlay, shaded in the browser from Terrarium elevation tiles. url defaults to AWS Open Data (the same bucket as terrain.tileUrl); point it at a mirror to self-host. Off unless enabled is true.", + "hillshade": { + "enabled": false, + "url": "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png" } - } + }, + "_comment_custom": "Your own tile servers. Each entry appears in the map picker as 'custom-' and can be named in darkDefault/lightDefault. format 'raster' takes an XYZ url ({z}/{x}/{y}, optional {s} with subdomains); format 'vector' takes a MapLibre style JSON url. type is 'light', 'dark' or 'any'; category is 'street', 'topo' or 'satellite'. overlay true adds a raster overlay instead of a base map. url must be https://, http:// or a same-site path starting with '/'. At most 20 entries. Every value under map.tiles is sent to anonymous visitors: never put credentials in a URL, and restrict any provider key by domain in that provider's dashboard. A path starting with '/' resolves against the page's origin (on a static/CDN UI deployment, that is the UI host, not the API server). Example: {\"id\": \"ours\", \"label\": \"Our tile server\", \"type\": \"light\", \"category\": \"street\", \"format\": \"raster\", \"url\": \"https://tiles.example.org/{z}/{x}/{y}.png\", \"attribution\": \"(c) OpenStreetMap contributors\", \"maxZoom\": 19}", + "custom": [] } }, "home": { diff --git a/docs/deployment.md b/docs/deployment.md index a2fb5071d..8bb9421df 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -362,7 +362,176 @@ See `config.example.json` in the repository for all available options including: ### Map Tile Providers -Map tile providers are enabled and configured via the `config.json` file. You can provide your custom API credentials (e.g. `osm_url`, `stamen_api_key`, `mapbox_api_key`) to activate external tile services. Once configured on the server, users can select their preferred tile provider from the Customizer UI on the client, and their choice will be persisted automatically. +Map tiles are configured under `map.tiles` in `config.json`. Several providers are built in; you switch whole provider groups on or off, set the key for Carto, and can add your own tile servers. Everything under `map.tiles` is sent to every visitor (see [Public config and privacy](#public-config-and-privacy)). + +#### How the picker works for visitors + +The Map, Live and Repeater Planner pages show the layer picker. Every other map (node detail, node reach, RX coverage, the Analytics route map and the home mini-map) has no picker but follows the same choice; because those maps never load MapLibre, a vector choice shows the theme's default raster map there. **Auto** is the default: it picks the light or dark map to match the current theme, using `lightDefault` / `darkDefault`. A visitor can instead pin a specific map. Pinned maps are listed in **Street**, **Topographic** and **Satellite** groups (gray styles follow the plain ones inside each group), and a separate **Overlays** group has checkboxes for layers drawn on top of the map (place labels, hillshade). A pin is saved per browser in `localStorage` (`mc-tile-pinned`) and survives a reload: every picker opens on it until the visitor picks **Auto** again, and the maps without a picker show it whenever it suits the current theme (satellite always does), otherwise the theme's map. Ticked overlays are saved the same way. Nothing is stored on the server. + +#### Built-in providers + +The group is the key under `map.tiles.providers`. "Default" is the state when the group is absent from your config. + +| Group | Maps (ids) | Category | Theme | Key | Default | Terms | +|---|---|---|---|---|---|---| +| `carto` | `carto-light`, `carto-dark`, `carto-voyager`, `carto-voyager-dark`, `positron-dark` | street | light / dark | Yes, free (see [below](#carto-now-requires-an-api-key)) | On | Free key, 5M tiles/month | +| `osm` | `osm-standard`, `osm-dark` | street | light / dark | Optional (`provider` + `token`: `thunderforest`, `maptiler` or `mapbox`) | Off | Without a token this is the OSM community server: fair use only | +| `opentopomap` | `opentopomap` | topographic | light | No | Off | Fair use, zoom up to 17 | +| `stamen` | `stamen-toner-lite`, `stamen-toner-dark` | street | light / dark | Yes (`token`, Stadia Maps); not offered without one | Off | Stadia Maps terms | +| `usgs` | `usgs-topo`, `usgs-imagery` | topographic, satellite | light | No | Off | US coverage, zoom up to 16 | +| `esri` | `esri-darkgray-labels` | street | dark | No | Always on | Esri terms | +| `eox` | `eox-s2-2025`, `eox-s2-2016` (Sentinel-2 satellite), `eox-terrain-light`; overlays `eox-labels`, `eox-labels-dark` | satellite, topographic | any (satellite), light (terrain) | No | Off | 2016 imagery CC BY 4.0; 2025 imagery CC BY-NC-SA 4.0 (non-commercial) | +| `osmfr` | `osmfr-hot` (Humanitarian), `osmfr-cyclosm` (CyclOSM), `osmfr-gray` (OSM Gray), `osmfr-gray-dark` (OSM Gray Dark) | street, topographic | light / dark | No | Off | OSM France community servers, donation-funded fair use | +| `openfreemap` | `openfreemap-liberty`, `-bright`, `-positron` (light); `openfreemap-dark`, `-fiord` (dark) | street (vector) | light / dark | No | Off | Free, no limits | +| `versatiles` | `versatiles-colorful`, `-muted`, `-gray` (light); `versatiles-colorful-dark`, `-gray-dark` (dark) | street (vector) | light / dark | No | Off | Free | +| `hillshade` | overlay `hillshade` | overlay | any | No | Off | Elevation tiles from AWS Open Data by default | + +**EOX licensing.** The 2016 Sentinel-2 imagery is CC BY 4.0. The later years (including 2025) are CC BY-NC-SA 4.0, which excludes commercial use. The group is off by default; a commercial deployment should leave it off or license the imagery from EOX. The EOX group also carries Terrain Light and the place-label overlays, so leaving it off leaves those out too. + +**Be a good neighbour.** OSM France, OpenTopoMap and the OSM community server are volunteer-run. Keep your instance's traffic modest, or self-host (see [Self-hosting](#self-hosting-tiles)). + +#### Turning groups on and off + +Set `enabled` on a group: + +```json +"map": { + "tiles": { + "providers": { + "osm": { "enabled": true }, + "openfreemap": { "enabled": true }, + "hillshade": { "enabled": true } + } + } +} +``` + +- `eox`, `osmfr`, `openfreemap`, `versatiles`, `hillshade`, `osm`, `opentopomap`, `stamen` and `usgs` are off until you set `"enabled": true` (the boolean; a string does not count). `stamen` additionally needs a `token`. Upgrading therefore changes nothing in the picker until you turn a group on: check the group's terms in the table above first. +- `carto` is on unless `"enabled": false`; `esri` is always available. +- Disabling a group removes its maps from the picker. If a visitor had saved one, or `darkDefault` / `lightDefault` names one, it falls back to the default. + +`darkDefault` and `lightDefault` pick which map **Auto** uses in the dark and light theme. They take any registered map id from the table above or a custom entry as `custom-`. Defaults are `carto-dark` and `carto-light`; an unknown or disabled id is ignored. + +#### Your own tile servers: `map.tiles.custom` + +`map.tiles.custom` is a list of up to 20 entries. Each appears in the picker as `custom-`. Custom entries are always enabled when valid. + +| Field | Required | Values | Default | +|---|---|---|---| +| `id` | Yes | 1-32 characters of `a-z`, `0-9`, `-`, starting with a letter or digit. Unique across all custom entries | | +| `url` | Yes | See URL rules below. Raster: an XYZ template containing `{z}`, `{x}` and `{y}` (or `{-y}`). Vector: a MapLibre style JSON URL | | +| `label` | No | Text, at most 64 characters | the `id` | +| `type` | No | `light`, `dark` or `any`. `any` is listed under both themes and is never color-inverted (use for satellite) | `light` | +| `category` | No | `street`, `topo` or `satellite` | `street` | +| `format` | No | `raster` or `vector` | `raster` | +| `attribution` | No | Plain text, at most 200 characters (HTML is escaped, not rendered) | empty | +| `maxZoom` | No | Number, clamped to 0-24 | 19 | +| `maxNativeZoom` | No | Number, clamped to 0-24. Highest zoom the server really has; the browser stretches tiles above it up to `maxZoom` | unset | +| `subdomains` | No | 1-8 characters of `a-z`, `0-9`, used for `{s}` | `abc` | +| `overlay` | No | `true` adds a raster layer drawn over the base map (checkbox under **Overlays**) instead of a base map. Must be `format: "raster"` | `false` | + +**URL rules.** `url` is at most 2048 characters and must be one of: + +- `https://host/...` or `http://host/...` (an `http://` tile URL is blocked by browsers on an `https` page, and vector maps refuse it outright); +- a same-site path starting with a single `/`, for example `/tiles/{z}/{x}/{y}.png`. + +Rejected: any other scheme (`javascript:`, `data:`, `file:`, `ftp:`), protocol-relative `//host/...`, `/\host`, credentials in the URL (`user:pass@host`), backslashes, whitespace or control characters, and any `{...}` other than `{z}` `{x}` `{y}` `{s}` `{r}` `{-y}`. + +**What happens to a bad entry.** An invalid entry is skipped; the rest still load. For each skipped entry the browser console shows one warning such as `[tiles] custom tile "ours" skipped: url must be an https://, http:// or '/' URL ...` that names the entry's `id` and the reason (it never prints the URL, which may carry a key). If the `id` itself is invalid the warning names the list position instead, for example `map.tiles.custom[2] skipped: id must be ...`. Entries beyond the 20th are ignored with a warning, a duplicate `id` is skipped, and a vector entry with `overlay: true` is skipped. Open the browser console on the map page to check your config. + +**Example 1: self-hosted raster XYZ server** + +```json +"custom": [ + { + "id": "ours", + "label": "Our tile server", + "type": "light", + "category": "street", + "format": "raster", + "url": "https://tiles.example.org/{z}/{x}/{y}.png", + "attribution": "(c) OpenStreetMap contributors", + "maxZoom": 19 + } +] +``` + +**Example 2: self-hosted vector style** + +The `url` is a MapLibre style JSON. It can come from a self-hosted OpenFreeMap, or from tileserver-gl, Martin or Protomaps serving a `style.json`. The tile and glyph URLs inside the style must also be `https://` (or `http://` only if the page itself is `http://`). + +```json +"custom": [ + { + "id": "ours-vector", + "label": "Our vector map", + "type": "light", + "category": "street", + "format": "vector", + "url": "https://maps.example.org/styles/liberty", + "attribution": "OpenMapTiles, OpenStreetMap contributors" + }, + { + "id": "ours-vector-dark", + "label": "Our vector map (dark)", + "type": "dark", + "format": "vector", + "url": "https://maps.example.org/styles/dark", + "attribution": "OpenMapTiles, OpenStreetMap contributors" + } +] +``` + +**Example 3: a raster overlay (contour lines)** + +Use transparent PNG tiles. The overlay is off until a visitor ticks it under **Overlays**. + +```json +"custom": [ + { + "id": "contours", + "label": "Contour lines", + "overlay": true, + "format": "raster", + "url": "https://tiles.example.org/contours/{z}/{x}/{y}.png", + "attribution": "Contours (c) Example Org", + "maxZoom": 19, + "maxNativeZoom": 16 + } +] +``` + +To make a custom map the default, name it in `darkDefault` / `lightDefault`, for example `"lightDefault": "custom-ours"`. + +#### Vector maps + +OpenFreeMap, VersaTiles and custom `vector` entries are drawn with MapLibre GL, which is vendored in `public/vendor/` (no third-party script host). It is about 380 KB gzipped and is downloaded only the first time a vector map is shown; visitors who stay on raster maps never fetch it. The scripts are loaded with Subresource Integrity, so a proxy or CDN that rewrites JavaScript (minifying, injecting) makes them fail the check: vector maps then fall back to the raster map with only a console warning. Serve `public/vendor/` unmodified. If WebGL is unavailable, the library fails to load within 15 seconds, or the GL context is lost, the map falls back to the shipped default raster map for the current theme (Carto Positron or Carto Dark). + +#### Hillshade overlay + +The `hillshade` overlay shades terrain in the visitor's browser from Terrarium-encoded elevation tiles (`elevation m = R*256 + G + B/256 - 32768`, 256x256 or 512x512 PNG). By default it reads AWS Open Data, the same bucket the repeater planner uses for `terrain.tileUrl`. To read from your own mirror, set a template URL (same URL rules as `custom`, and it must contain `{z}`, `{x}`, `{y}`; otherwise the default is used and a console warning is logged): + +```json +"hillshade": { "enabled": true, "url": "https://tiles.example.org/terrarium/{z}/{x}/{y}.png" } +``` + +The tile host must allow cross-origin image reads (`Access-Control-Allow-Origin`); without it the browser cannot read pixels and the overlay stays blank. It is off for visitors until they tick it. + +#### Self-hosting tiles + +Self-hosting removes the third-party dependency and keeps visitors' requests on your infrastructure. Follow the upstream documentation rather than any steps here: + +- **OpenFreeMap**: run your own copy of the planet tiles and styles; see (self-hosting guide). Point a `vector` custom entry at your `styles/` URL. +- **Protomaps (PMTiles)**: a single-file tile archive served from static storage or a small server; see . Use its style JSON as a `vector` custom entry. +- **Any XYZ raster server** (tileserver-gl, Martin, a static tile tree on object storage): use a `raster` custom entry. +- **Elevation for hillshade**: mirror the Terrarium tiles (`s3://elevation-tiles-prod/terrarium`, public, no credentials needed) and set `hillshade.url`. The bucket is large; mirror only your region's zoom levels (hillshade uses up to zoom 15). +- **Elevation for the planner**: mirror the SRTM `skadi` tree (`s3://elevation-tiles-prod/skadi`) and set `terrain.tileUrl` to its `https` base URL (no query string). That setting is server-side and separate from `map.tiles`; see [docs/api-spec.md](api-spec.md). + +#### Public config and privacy + +- **Everything under `map.tiles` is public.** The server sends it to every visitor, including anonymous ones. Never put credentials in a URL, and restrict any provider key by domain in that provider's dashboard. This applies to the Carto key, the `osm` and `stamen` tokens, and custom URLs alike. +- **Visitors' browsers fetch tiles directly** from the chosen host, not through CoreScope. That host sees the visitor's IP address and the map area being viewed. Browsers send only your site's origin as the Referer, not the full page path. If this matters for your users, pick a provider you trust or self-host. +- **A `/path` URL resolves against the page's origin.** On a static/CDN UI deployment (see [Static host or CDN](#static-host-or-cdn)) that is the UI host, not the API server. #### CARTO now requires an API key diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index b84df8eb7..698539904 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -134,6 +134,27 @@ See [Channels](channels.md) for details. Initial map center and zoom level. +## Map tiles + +Which maps visitors can pick (street, gray, topographic, satellite, vector), the light and dark defaults, the Carto key, the hillshade overlay and your own tile servers are all set under `map.tiles`: + +```json +"map": { + "tiles": { + "darkDefault": "carto-dark", + "lightDefault": "carto-light", + "providers": { + "carto": { "key": "YOUR_CARTO_KEY" }, + "opentopomap": { "enabled": true }, + "openfreemap": { "enabled": true } + }, + "custom": [] + } +} +``` + +Everything under `map.tiles` is sent to every visitor's browser, so only put keys there that are meant to be public (domain-restricted). Of the built-in groups only `carto` and `esri` are on unless you say otherwise; every other group (including the newer `eox`, `osmfr`, `openfreemap`, `versatiles` and `hillshade`) needs `"enabled": true`. The full list of maps, their licences and examples for custom and self-hosted tile servers are in [Map Tile Providers](../deployment.md#map-tile-providers). + ## Regions ```json diff --git a/docs/user-guide/faq.md b/docs/user-guide/faq.md index 34d84efa9..bf21b8608 100644 --- a/docs/user-guide/faq.md +++ b/docs/user-guide/faq.md @@ -53,6 +53,10 @@ CoreScope uses URL hashes for deep linking. Copy the URL from your browser — i - `#/analytics?tab=collisions` — the hash issues tab - `#/nodes/pubkey123` — a specific node's detail page +## 11. Can I see satellite imagery, terrain or a gray map? + +Yes. Use the layers button on the [Map](map.md#map-style-and-overlays) page (also on Live and the Repeater Planner) to pick a street, gray, topographic or satellite map, and tick **Hillshade** to add shaded relief on top. The choice is saved in your browser. Operators control which maps are offered: see [Map Tile Providers](../deployment.md#map-tile-providers). + ### Where is the API documentation? CoreScope auto-generates an OpenAPI 3.0 specification from its route definitions: diff --git a/docs/user-guide/live.md b/docs/user-guide/live.md index d22b5b4e6..ac90206ba 100644 --- a/docs/user-guide/live.md +++ b/docs/user-guide/live.md @@ -18,6 +18,8 @@ The feed scrolls automatically. New packets appear at the top. ## Map animations +The map style can be changed with the layers button in the top-right corner, the same picker as on the [Map](map.md#map-style-and-overlays) page. + When a packet arrives, the Live map animates the signal path: - A pulse appears at the sender's location diff --git a/docs/user-guide/map.md b/docs/user-guide/map.md index f880deb26..7bbba8ff0 100644 --- a/docs/user-guide/map.md +++ b/docs/user-guide/map.md @@ -4,6 +4,27 @@ The Map page shows all nodes on an interactive map, color-coded by role. [Screenshot: map with colored markers and controls panel] +## Map style and overlays + +The layers button on the map (top-left) chooses what the map underneath the nodes looks like. The same picker is on the [Live](live.md) page (top-right) and the Repeater Planner. + +- **Auto** (the default) follows the site theme: a light map in light mode, a dark map in dark mode. +- Or pick a specific map. They are grouped by kind: + - **Street**: road maps, including gray and dark styles that keep the node markers easy to read. + - **Topographic**: terrain and contour maps. + - **Satellite**: aerial imagery. Satellite maps look the same in light and dark mode. +- **Overlays** are checkboxes drawn on top of whichever map you chose: + - **Hillshade**: shaded relief, so hills and valleys stand out. Useful with any map when you are judging radio line of sight. + - **Place labels**: town and road names, mainly for satellite imagery, which has none. + +Your choice is saved in your browser: the picker opens on it after a reload and on the Live and Repeater Planner pages too. The small maps on node pages, Analytics and Home show it whenever it suits the current theme (a satellite map always does; a light map is not used in dark mode), and otherwise the theme's map. It is not shared with other visitors and not stored on the server. Pick **Auto** to go back to following the theme. + +Which maps the picker lists is up to the site's operator: the newer providers are offered only once the operator turns them on. + +Some maps in the Street group are vector maps, drawn by your browser rather than downloaded as pictures. They stay sharp at every zoom level. If your browser can't draw them (no WebGL), or they fail to load within 15 seconds, the page shows the regular map for the current theme instead. The small maps on node pages, Analytics and Home always use a regular map: there, a vector choice shows the theme's default map. + +Which maps appear in the list is up to the site operator, who can turn groups of maps on and off and add their own tile server. See [Map Tile Providers](../deployment.md#map-tile-providers). + ## Marker shapes and colors Each node role has a distinct shape and color: @@ -69,3 +90,5 @@ Click any marker to see: - Use the role checkboxes to isolate repeaters and understand coverage - The neighbor filter is great for seeing which nodes can directly hear each other - Node colors are [customizable](customization.md) in the theme settings +- Turn on the **Hillshade** overlay to see which nodes have high ground between them +- A gray street map makes colored markers stand out on a busy mesh diff --git a/public/analytics.js b/public/analytics.js index 97eba0930..cbb99aa75 100644 --- a/public/analytics.js +++ b/public/analytics.js @@ -21,6 +21,7 @@ if (abs < 86400) return (v / 3600).toFixed(1) + 'h'; return (v / 86400).toFixed(1) + 'd'; } + var _subpathMap = null; // subpath detail minimap; removed on re-render and page destroy (WebGL/Leaflet leak) // #1085 — auto-refresh timer for the Roles tab. Started when the Roles // tab is rendered, cleared on tab switch and destroy. var _rolesRefreshTimer = null; @@ -2465,13 +2466,21 @@ // Render minimap if (hasMap && typeof L !== 'undefined') { + if (_subpathMap) { try { _subpathMap.remove(); } catch (_e) {} _subpathMap = null; } const map = L.map('subpathMap', { zoomControl: false, attributionControl: false }); + _subpathMap = map; // Shared resolver for attribution/maxZoom parity with the other maps // (OpenTopoMap caps at 17, USGS at 16 — a hardcoded 18 404s above those). const _tileR = (typeof window.MC_resolveTile === 'function') ? window.MC_resolveTile(typeof window.MC_isDarkTheme === 'function' ? window.MC_isDarkTheme() : false) : null; - L.tileLayer((_tileR && _tileR.url) || getTileUrl(), { maxZoom: (_tileR && _tileR.maxZoom) || 18 }).addTo(map); + (_tileR && typeof window.MC_buildTileLayer === 'function' + ? window.MC_buildTileLayer(_tileR, { raster: true }) + : L.tileLayer((_tileR && _tileR.url) || getTileUrl(), { maxZoom: (_tileR && _tileR.maxZoom) || 18 })).addTo(map); + try { // dark-inverted providers need their CSS filter on this map too + const _pane = _tileR && _tileR.invertFilter && map.getPane('tilePane'); + if (_pane) _pane.style.filter = _tileR.invertFilter; + } catch (_e) {} const latlngs = []; nodesWithLoc.forEach((n, i) => { @@ -3217,7 +3226,7 @@ } } -function destroy() { _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRetry(); _analyticsData = {}; _loadError = null; if (_regionChangeHandler) { RegionFilter.offChange(_regionChangeHandler); _regionChangeHandler = null; } if (_areaChangeHandler) { AreaFilter.offChange(_areaChangeHandler); _areaChangeHandler = null; } _channelData = null; if (_ngState && _ngState.animId) { cancelAnimationFrame(_ngState.animId); } _ngState = null; if (_themeRefreshHandler) { window.removeEventListener('theme-refresh', _themeRefreshHandler); _themeRefreshHandler = null; } } +function destroy() { if (_subpathMap) { window.MC_safeRemoveMap(_subpathMap); _subpathMap = null; } _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRetry(); _analyticsData = {}; _loadError = null; if (_regionChangeHandler) { RegionFilter.offChange(_regionChangeHandler); _regionChangeHandler = null; } if (_areaChangeHandler) { AreaFilter.offChange(_areaChangeHandler); _areaChangeHandler = null; } _channelData = null; if (_ngState && _ngState.animId) { cancelAnimationFrame(_ngState.animId); } _ngState = null; if (_themeRefreshHandler) { window.removeEventListener('theme-refresh', _themeRefreshHandler); _themeRefreshHandler = null; } } // Expose for testing if (typeof window !== 'undefined') { diff --git a/public/area-filter.js b/public/area-filter.js index e91bb0b5d..fda008d7a 100644 --- a/public/area-filter.js +++ b/public/area-filter.js @@ -53,7 +53,16 @@ return 'Area: ' + (area ? area.label : _selected) + ' ▾'; } + // Drops the outside-click listener a render() put on document. It closes + // over the container, so a page that leaves it behind pins that page's + // whole detached DOM for the life of the tab. + function release(container) { + if (container && container._areaCleanup) { container._areaCleanup(); container._areaCleanup = null; } + } + function render(container) { + if (_container && _container !== container) release(_container); + _container = container; if (_areas.length === 0) { container.innerHTML = ''; container.style.display = 'none'; @@ -61,7 +70,7 @@ } container.style.display = ''; - if (container._areaCleanup) { container._areaCleanup(); container._areaCleanup = null; } + release(container); var html = '
    '; html += '