From 517391da50031a952d5df8d25511b91c9105e5c2 Mon Sep 17 00:00:00 2001 From: dborup Date: Thu, 3 Dec 2026 04:35:18 +0100 Subject: [PATCH 1/5] feat(nodes): recommended scopes for where the node stands, info only (#1035 M2) GET /api/nodes/{pubkey}/scope-check sets a repeater's or room's own scopes next to what meshguide.dk recommends for its advertised position, through M1's engine (internal/scopeguide Recommend + Compare, unchanged): one typed node-row read by primary key, one DAGI point lookup on the in-memory index, a named response struct. 404 for unknown, hidden or blacklisted nodes and while dagi.enabled is off. The full node page shows it as "Recommended scopes here (meshguide.dk)" (public/node-scope-check.js, textContent only): the recommended chips, the node's default scope ("cannot be decoded" for an unnamed one) and the observer-reported list in neutral wording, a meshguide.dk link, nothing for companions or nodes without a position. ?section=node-scope-check deep links to it. The page renders twice on a cold load, so the module reuses the last answer for a minute: one request per node view. Relates to #1035 Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 1 + cmd/server/go.mod | 6 + cmd/server/node_scope_check.go | 176 ++++++++ cmd/server/node_scope_check_test.go | 385 ++++++++++++++++++ cmd/server/openapi.go | 1 + cmd/server/routes.go | 3 + public/index.html | 1 + public/node-scope-check.js | 197 +++++++++ public/nodes.js | 12 +- public/style.css | 23 ++ scripts/e2e-shards.json | 3 +- test-1035-node-scope-check.js | 295 ++++++++++++++ test-all.sh | 1 + test-fixtures/seed-1035-scope-check-nodes.sql | 30 ++ test-issue-1035-m2-node-scope-check-e2e.js | 225 ++++++++++ tests/e2e-1055-live.js | 6 +- 16 files changed, 1361 insertions(+), 4 deletions(-) create mode 100644 cmd/server/node_scope_check.go create mode 100644 cmd/server/node_scope_check_test.go create mode 100644 public/node-scope-check.js create mode 100644 test-1035-node-scope-check.js create mode 100644 test-fixtures/seed-1035-scope-check-nodes.sql create mode 100644 test-issue-1035-m2-node-scope-check-e2e.js diff --git a/Dockerfile b/Dockerfile index 2b755e678..3d77775e5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -40,6 +40,7 @@ COPY internal/copdem/ ../../internal/copdem/ COPY internal/heritage/ ../../internal/heritage/ COPY internal/buildings/ ../../internal/buildings/ COPY internal/skraafoto/ ../../internal/skraafoto/ +COPY internal/scopeguide/ ../../internal/scopeguide/ RUN go mod download COPY cmd/server/ ./ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ diff --git a/cmd/server/go.mod b/cmd/server/go.mod index 2e151dee3..e72b4bc82 100644 --- a/cmd/server/go.mod +++ b/cmd/server/go.mod @@ -131,3 +131,9 @@ replace github.com/meshcore-analyzer/skraafoto => ../../internal/skraafoto require github.com/meshcore-analyzer/configkey v0.0.0 replace github.com/meshcore-analyzer/configkey => ../../internal/configkey + +// internal/scopeguide (#1035): meshguide.dk's scope rules (vendored) and +// the neutral verdict, served by GET /api/nodes/{pubkey}/scope-check (M2). +require github.com/meshcore-analyzer/scopeguide v0.0.0 + +replace github.com/meshcore-analyzer/scopeguide => ../../internal/scopeguide diff --git a/cmd/server/node_scope_check.go b/cmd/server/node_scope_check.go new file mode 100644 index 000000000..471b9438e --- /dev/null +++ b/cmd/server/node_scope_check.go @@ -0,0 +1,176 @@ +package main + +import ( + "database/sql" + "net/http" + "strings" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/scopeguide" +) + +// #1035 M2: GET /api/nodes/{pubkey}/scope-check — the scopes meshguide.dk +// recommends for where a repeater or room stands, next to what the node +// has: its observed default scope (nodes.default_scope) and, when an +// observer reported it, its configured allow-list (nodes.configured_scope). +// +// The recommendation and the comparison are M1's engine +// (internal/scopeguide, Recommend + Compare), unchanged. Everything is +// information, never a warning (owner decision 5 on #1035). +// +// Cost per request: one node row by primary key, one DAGI point lookup on +// the in-memory index and M1's Recommend + Compare on the embedded table +// (TestScopeCheckComputeBudget). Nothing scales with nodes or packets, so +// there is no cache. Read-only (#1283). Gated by dagi.enabled, like every +// DAGI feature; public, like the node page itself. + +// meshguideScopesURL is meshguide.dk's region-scope recommendation page; it +// has no per-location deep link. Config later (#1035 M4). +const meshguideScopesURL = "https://meshguide.dk/#/defaults/region-scopes" + +// NotApplicablePosition: a repeater or room without a usable advertised +// position (estimated positions are never used). +const NotApplicablePosition = "position" + +// NodeScopeCheckSource names where the rules come from. +type NodeScopeCheckSource struct { + Name string `json:"name"` + URL string `json:"url"` + Repo string `json:"repo"` + Commit string `json:"commit"` +} + +// NodeScopeCheckResponse is the endpoint's answer: M1's Verdict plus the +// times of the node-side evidence. +type NodeScopeCheckResponse struct { + Pubkey string `json:"pubkey"` + scopeguide.Verdict + // DefaultConfirmedAt is set when the firmware itself reported the + // default scope (nodes.default_scope_confirmed_at). + DefaultConfirmedAt string `json:"defaultConfirmedAt,omitempty"` + // ListReportedAt is when an observer last reported the allow-list. + ListReportedAt string `json:"listReportedAt,omitempty"` + Source NodeScopeCheckSource `json:"source"` +} + +// nodeScopeRow is the part of a node row the check reads, cast at the +// boundary from GetNodeByPubkey's map. +type nodeScopeRow struct { + Role string + Lat, Lon float64 + HasPosition bool + // DefaultKnown: nodes.default_scope is not NULL. "" then means a scoped + // advert whose scope this instance cannot name. + DefaultKnown bool + DefaultScope string + DefaultConfirmedAt string + // ListKnown: nodes.configured_scope is not NULL (an observer report). + ListKnown bool + List string + ListAt string +} + +// nodeScopeRow reads one node's row by primary key, typed at the +// boundary. The scope columns are optional (#899, #1865): a DB without them +// reads as "not known". ok is false when there is no such node. +func (db *DB) nodeScopeRow(pubkey string) (row nodeScopeRow, name string, ok bool, err error) { + cols := "name, role, lat, lon" + var nm, role, def, list, listAt, defAt sql.NullString + var lat, lon sql.NullFloat64 + args := []interface{}{&nm, &role, &lat, &lon} + if db.hasDefaultScope() { + cols += ", default_scope" + args = append(args, &def) + } + if db.hasConfiguredScope() { + cols += ", configured_scope, configured_scope_at" + args = append(args, &list, &listAt) + } + if db.hasDefaultScopeConfirmedAt() { + cols += ", default_scope_confirmed_at" + args = append(args, &defAt) + } + err = db.conn.QueryRow("SELECT "+cols+" FROM nodes WHERE public_key = ?", pubkey).Scan(args...) + if err == sql.ErrNoRows { + return row, "", false, nil + } + if err != nil { + return row, "", false, err + } + row.Role = role.String + if lat.Valid && lon.Valid && isValidNodePosition(lat.Float64, lon.Float64) { + row.Lat, row.Lon, row.HasPosition = lat.Float64, lon.Float64, true + } + row.DefaultScope, row.DefaultKnown = def.String, def.Valid + row.DefaultConfirmedAt = defAt.String + row.List, row.ListKnown = list.String, list.Valid + row.ListAt = listAt.String + return row, nm.String, true, nil +} + +// buildNodeScopeCheck is the pure part of the endpoint. +func buildNodeScopeCheck(g *scopeguide.Guide, idx *dagiIndex, pubkey string, row nodeScopeRow) NodeScopeCheckResponse { + var rec scopeguide.Recommendation + if row.HasPosition { + if p := idx.Lookup(row.Lat, row.Lon).Postnummer; p != nil { + rec = g.Recommend(row.Lat, row.Lon, p.Code) + } + } + v := g.Compare(rec, scopeguide.Node{ + Role: row.Role, + DefaultScope: row.DefaultScope, + DefaultUndecoded: row.DefaultKnown && strings.TrimSpace(row.DefaultScope) == "", + Configured: row.List, + ConfiguredReported: row.ListKnown, + }) + if v.NotApplicable == scopeguide.NotApplicableOutside && !row.HasPosition { + v.NotApplicable = NotApplicablePosition + } + up := g.Upstream() + out := NodeScopeCheckResponse{ + Pubkey: pubkey, + Verdict: v, + Source: NodeScopeCheckSource{Name: "meshguide.dk", URL: meshguideScopesURL, Repo: up.Repo, Commit: up.Commit}, + } + if v.Applicable { + if v.Default.Status != scopeguide.DefaultNone { + out.DefaultConfirmedAt = row.DefaultConfirmedAt + } + if v.List.Reported { + out.ListReportedAt = row.ListAt + } + } + return out +} + +func (s *Server) handleNodeScopeCheck(w http.ResponseWriter, r *http.Request) { + idx := s.dagiIndex() + if idx == nil { + writeError(w, http.StatusNotFound, "Not found") + return + } + pubkey := strings.ToLower(mux.Vars(r)["pubkey"]) + if !isHexPubkey(pubkey) { + writeError(w, http.StatusBadRequest, "invalid pubkey: expected 64 hex chars") + return + } + if s.cfg.IsBlacklisted(pubkey) { + writeError(w, http.StatusNotFound, "Not found") + return + } + g, err := scopeguide.Load() + if err != nil { + writeError(w, http.StatusServiceUnavailable, "scope guide unavailable") + return + } + row, name, found, err := s.db.nodeScopeRow(pubkey) + if err != nil { + writeError(w, http.StatusInternalServerError, "query failed") + return + } + if !found || s.cfg.IsNameHidden(name) { + writeError(w, http.StatusNotFound, "Not found") + return + } + writeJSON(w, buildNodeScopeCheck(g, idx, pubkey, row)) +} diff --git a/cmd/server/node_scope_check_test.go b/cmd/server/node_scope_check_test.go new file mode 100644 index 000000000..864d63376 --- /dev/null +++ b/cmd/server/node_scope_check_test.go @@ -0,0 +1,385 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "regexp" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/scopeguide" +) + +// #1035 M2: GET /api/nodes/{pubkey}/scope-check sets a repeater's or room's +// own scopes next to what meshguide.dk recommends for where it stands. The +// verdict is M1's engine (internal/scopeguide); these tests pin the wiring: +// which position, which postnummer, which node columns, and when there is +// no recommendation at all. + +const ( + scOdensePK = "5c00000000000000000000000000000000000000000000000000000000000001" // Fyn + scRoskildePK = "5c00000000000000000000000000000000000000000000000000000000000002" // Sjælland + scAarhusPK = "5c00000000000000000000000000000000000000000000000000000000000003" // Jylland + scKbhKPK = "5c00000000000000000000000000000000000000000000000000000000000004" // København K (street postcode group) + scRonnePK = "5c00000000000000000000000000000000000000000000000000000000000005" // Bornholm + scNoPosPK = "5c00000000000000000000000000000000000000000000000000000000000006" // repeater without a position + scCompanionPK = "5c00000000000000000000000000000000000000000000000000000000000007" // companion in Odense + scMalmoPK = "5c00000000000000000000000000000000000000000000000000000000000008" // repeater in Sweden + scHiddenPK = "5c00000000000000000000000000000000000000000000000000000000000009" // hidden by name prefix + scRoomPK = "5c0000000000000000000000000000000000000000000000000000000000000a" // room in Aarhus + scBlacklistPK = "5c0000000000000000000000000000000000000000000000000000000000000b" + scUnknownPK = "5c0000000000000000000000000000000000000000000000000000000000000c" // no row + scConfirmedPK = "5c0000000000000000000000000000000000000000000000000000000000000d" // firmware-confirmed default + scPreScopeDBPK = "5c0000000000000000000000000000000000000000000000000000000000000e" + scZeroPosPK = "5c0000000000000000000000000000000000000000000000000000000000000f" // 0,0 = no position +) + +type scSeed struct { + pk, name, role string + lat, lon interface{} + def interface{} // nodes.default_scope: nil = NULL + conf, confAt interface{} // nodes.configured_scope / _at + defAt interface{} // nodes.default_scope_confirmed_at +} + +var scSeeds = []scSeed{ + {scOdensePK, "SC Odense", "repeater", 55.3959, 10.3883, "dk", "*,#dk,#dk-fyn,#dk-kb", "2026-12-01T10:00:00Z", nil}, + {scRoskildePK, "SC Roskilde", "repeater", 55.6415, 12.0803, "dk-sjl", nil, nil, nil}, + {scAarhusPK, "SC Aarhus", "repeater", 56.1572, 10.2107, "", "#dk,#dk-aarhus", "2026-12-02T08:00:00Z", nil}, + {scKbhKPK, "SC Kbh K", "repeater", 55.6805, 12.5860, nil, nil, nil, nil}, + {scRonnePK, "SC Ronne", "repeater", 55.1009, 14.7067, "dk-bhm", "", "2026-12-02T09:00:00Z", nil}, + {scNoPosPK, "SC NoPos", "repeater", nil, nil, "dk", nil, nil, nil}, + {scCompanionPK, "SC Companion", "companion", 55.3959, 10.3883, "dk", nil, nil, nil}, + {scMalmoPK, "SC Malmo", "repeater", 55.6050, 13.0038, "se", nil, nil, nil}, + {scHiddenPK, "ZZhidden SC", "repeater", 56.1572, 10.2107, "dk", nil, nil, nil}, + {scRoomPK, "SC Room", "room", 56.1572, 10.2107, "europe", nil, nil, nil}, + {scBlacklistPK, "SC Blacklisted", "repeater", 56.1572, 10.2107, "dk", nil, nil, nil}, + {scZeroPosPK, "SC ZeroPos", "repeater", 0.0, 0.0, "dk", nil, nil, nil}, + {scConfirmedPK, "SC Confirmed", "repeater", 56.1572, 10.2107, "dk", nil, nil, "2026-12-02T12:00:00Z"}, +} + +func setupScopeCheckServer(t *testing.T, mutate func(*Config)) (*Server, http.Handler) { + t.Helper() + srv, _ := setupTestServer(t) + for _, col := range []string{"default_scope", "configured_scope", "configured_scope_at", "default_scope_confirmed_at"} { + if _, err := srv.db.conn.Exec(`ALTER TABLE nodes ADD COLUMN ` + col + ` TEXT`); err != nil { + t.Fatalf("alter nodes add %s: %v", col, err) + } + } + srv.db.detectSchema() + for _, s := range scSeeds { + if _, err := srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, + default_scope, configured_scope, configured_scope_at, default_scope_confirmed_at) + VALUES (?, ?, ?, ?, ?, '2026-12-02T12:00:00Z', '2026-11-01T00:00:00Z', ?, ?, ?, ?)`, + s.pk, s.name, s.role, s.lat, s.lon, s.def, s.conf, s.confAt, s.defAt); err != nil { + t.Fatalf("seed %s: %v", s.name, err) + } + } + srv.cfg.SetHiddenNamePrefixes([]string{"ZZhidden"}) + srv.cfg.SetNodeBlacklist([]string{scBlacklistPK}) + if mutate != nil { + mutate(srv.cfg) + } + router := mux.NewRouter() + srv.RegisterRoutes(router) + return srv, router +} + +func getScopeCheck(t *testing.T, h http.Handler, pk string) (*httptest.ResponseRecorder, NodeScopeCheckResponse) { + t.Helper() + req := httptest.NewRequest("GET", "/api/nodes/"+pk+"/scope-check", nil) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + var out NodeScopeCheckResponse + if rr.Code == http.StatusOK { + if err := json.Unmarshal(rr.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v\n%s", err, rr.Body.String()) + } + } + return rr, out +} + +func scNames(s []scopeguide.Scope, kind scopeguide.Kind) []string { + var out []string + for _, x := range s { + if kind == "" || x.Kind == kind { + out = append(out, x.Name) + } + } + return out +} + +func scHas(list []string, name string) bool { + for _, s := range list { + if s == name { + return true + } + } + return false +} + +func mustOK(t *testing.T, rr *httptest.ResponseRecorder) { + t.Helper() + if rr.Code != http.StatusOK { + t.Fatalf("status %d, want 200: %s", rr.Code, rr.Body.String()) + } +} + +func TestScopeCheckFyn(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scOdensePK) + mustOK(t, rr) + if !v.Applicable || v.NotApplicable != "" { + t.Fatalf("Odense repeater must be applicable: %+v", v) + } + rec := v.Recommendation + if rec.Postnummer != "5000" || rec.PostnummerName != "Odense C" || !rec.PostalData || rec.Default != "dk" { + t.Fatalf("Odense recommendation: %+v", rec) + } + regions := scNames(rec.Scopes, scopeguide.KindRegion) + postal := scNames(rec.Scopes, scopeguide.KindPostal) + if !scHas(regions, "dk-fyn-odense") || !scHas(regions, "dk-fyn") { + t.Errorf("Fyn region scopes missing: %v", regions) + } + if !scHas(postal, "dk5000") || !scHas(postal, "dk5") { + t.Errorf("Fyn postal scopes missing: %v", postal) + } + if !scHas(scNames(rec.Scopes, scopeguide.KindFixed), "dk") { + t.Errorf("dk missing: %v", rec.Scopes) + } + if v.Default.Status != scopeguide.DefaultRecommended || v.Default.Scope != "dk" { + t.Errorf("default: %+v", v.Default) + } + l := v.List + if !l.Reported || !l.Wildcard || !scHas(l.Listed, "dk") || !scHas(l.Listed, "dk-fyn") || !scHas(l.NotMeshguide, "dk-kb") { + t.Errorf("list: %+v", l) + } + if v.ListReportedAt != "2026-12-01T10:00:00Z" { + t.Errorf("listReportedAt %q", v.ListReportedAt) + } + if v.Source.URL != meshguideScopesURL || v.Source.Commit == "" || v.Source.Repo == "" { + t.Errorf("source: %+v", v.Source) + } + if v.Pubkey != scOdensePK { + t.Errorf("pubkey %q", v.Pubkey) + } +} + +func TestScopeCheckSjaelland(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scRoskildePK) + mustOK(t, rr) + rec := v.Recommendation + if !v.Applicable || rec.Postnummer != "4000" || !rec.PostalData { + t.Fatalf("Roskilde: %+v", v) + } + if !scHas(scNames(rec.Scopes, scopeguide.KindRegion), "dk-sjl") || !scHas(scNames(rec.Scopes, scopeguide.KindPostal), "dk4000") { + t.Errorf("Sjælland scopes: %v", rec.Scopes) + } + if v.Default.Status != scopeguide.DefaultInList || v.Default.Scope != "dk-sjl" { + t.Errorf("default: %+v", v.Default) + } + if v.List.Reported || v.ListReportedAt != "" { + t.Errorf("no report: list must be unreported: %+v %q", v.List, v.ListReportedAt) + } +} + +func TestScopeCheckAarhusNoPostalAndUndecodedDefault(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scAarhusPK) + mustOK(t, rr) + rec := v.Recommendation + if !v.Applicable || rec.Postnummer != "8000" || rec.PostalData { + t.Fatalf("Aarhus: %+v", v) + } + if p := scNames(rec.Scopes, scopeguide.KindPostal); len(p) != 0 { + t.Errorf("Jylland must get no postal scopes (owner decision 4): %v", p) + } + if !scHas(scNames(rec.Scopes, scopeguide.KindRegion), "dk-aarhus") { + t.Errorf("Aarhus regions: %v", rec.Scopes) + } + // default_scope "" = a scoped advert this instance could not name. + if v.Default.Status != scopeguide.DefaultUndecoded { + t.Errorf("default_scope '' must be undecoded: %+v", v.Default) + } +} + +func TestScopeCheckCopenhagenKGroup(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scKbhKPK) + mustOK(t, rr) + rec := v.Recommendation + if !v.Applicable || rec.Postnummer != "1050" || rec.PostnummerName != "København K" || rec.PostalData { + t.Fatalf("København K group: %+v", rec) + } + if !scHas(scNames(rec.Scopes, scopeguide.KindRegion), "dk-kbh") { + t.Errorf("Copenhagen regions: %v", rec.Scopes) + } + if v.Default.Status != scopeguide.DefaultNone { + t.Errorf("NULL default_scope must be none: %+v", v.Default) + } +} + +func TestScopeCheckBornholm(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scRonnePK) + mustOK(t, rr) + rec := v.Recommendation + if !v.Applicable || rec.PostalData || !scHas(scNames(rec.Scopes, scopeguide.KindRegion), "dk-bhm") { + t.Fatalf("Bornholm: %+v", rec) + } + if !strings.HasPrefix(rec.Postnummer, "37") { + t.Errorf("Rønne postnummer %q", rec.Postnummer) + } + // An empty reported list is a report, not "no report". + if !v.List.Reported || len(v.List.Listed) != 0 || len(v.List.NotListed) != len(rec.Scopes) { + t.Errorf("empty list: %+v", v.List) + } +} + +func TestScopeCheckNotApplicable(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + for _, c := range []struct { + pk, want string + }{ + {scNoPosPK, NotApplicablePosition}, + {scZeroPosPK, NotApplicablePosition}, + {scCompanionPK, scopeguide.NotApplicableRole}, + {scMalmoPK, scopeguide.NotApplicableOutside}, + } { + rr, v := getScopeCheck(t, h, c.pk) + mustOK(t, rr) + if v.Applicable || v.NotApplicable != c.want { + t.Errorf("%s: applicable=%v notApplicable=%q, want %q", c.pk[len(c.pk)-2:], v.Applicable, v.NotApplicable, c.want) + } + if len(v.Recommendation.Scopes) != 0 || v.List.Reported || v.Default.Status != "" { + t.Errorf("%s: a node without a recommendation must carry nothing: %+v", c.pk[len(c.pk)-2:], v) + } + } +} + +func TestScopeCheckRoomAndConfirmedDefault(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scRoomPK) + mustOK(t, rr) + if !v.Applicable || v.Default.Status != scopeguide.DefaultInList { + t.Fatalf("room: %+v", v) + } + if v.DefaultConfirmedAt != "" { + t.Errorf("unconfirmed default carries a time: %q", v.DefaultConfirmedAt) + } + rr, v = getScopeCheck(t, h, scConfirmedPK) + mustOK(t, rr) + if v.DefaultConfirmedAt != "2026-12-02T12:00:00Z" { + t.Errorf("confirmed default time %q", v.DefaultConfirmedAt) + } +} + +func TestScopeCheckRejectsAndHides(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + for _, c := range []struct { + pk string + code int + }{ + {"nothex", http.StatusBadRequest}, + {scOdensePK[:20], http.StatusBadRequest}, + {scUnknownPK, http.StatusNotFound}, + {scHiddenPK, http.StatusNotFound}, + {scBlacklistPK, http.StatusNotFound}, + {strings.ToUpper(scBlacklistPK), http.StatusNotFound}, + } { + rr, _ := getScopeCheck(t, h, c.pk) + if rr.Code != c.code { + t.Errorf("%s: status %d, want %d", c.pk, rr.Code, c.code) + } + } + // Upper-case keys are the same node. + rr, v := getScopeCheck(t, h, strings.ToUpper(scOdensePK)) + mustOK(t, rr) + if v.Pubkey != scOdensePK { + t.Errorf("pubkey %q", v.Pubkey) + } +} + +func TestScopeCheckGatedByDagi(t *testing.T) { + off := false + _, h := setupScopeCheckServer(t, func(c *Config) { c.Dagi = &DagiConfig{Enabled: &off} }) + rr, _ := getScopeCheck(t, h, scOdensePK) + if rr.Code != http.StatusNotFound { + t.Fatalf("dagi.enabled=false: status %d, want 404", rr.Code) + } +} + +// A DB from before #899/#1865 has none of the scope columns: still a +// recommendation, the node's side simply unknown. +func TestScopeCheckPreScopeSchema(t *testing.T) { + srv, _ := setupTestServer(t) + if _, err := srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen) + VALUES (?, 'SC Old', 'repeater', 55.3959, 10.3883, '2026-12-02T12:00:00Z', '2026-11-01T00:00:00Z')`, scPreScopeDBPK); err != nil { + t.Fatal(err) + } + router := mux.NewRouter() + srv.RegisterRoutes(router) + rr, v := getScopeCheck(t, router, scPreScopeDBPK) + mustOK(t, rr) + if !v.Applicable || v.Default.Status != scopeguide.DefaultNone || v.List.Reported { + t.Fatalf("pre-scope schema: %+v", v) + } +} + +// The response is a named struct end to end: no new map[string]interface{} +// in the handler file (AGENTS.md, #1383). +func TestScopeCheckNoInterfaceMaps(t *testing.T) { + src, err := os.ReadFile("node_scope_check.go") + if err != nil { + t.Fatal(err) + } + if regexp.MustCompile(`map\[string\]interface\{\}|map\[string\]any`).Match(src) { + t.Fatal("node_scope_check.go must not use map[string]interface{}") + } +} + +// The work per request is one node row, one DAGI point lookup and M1's +// Recommend+Compare: well under a millisecond, nothing proportional to the +// number of nodes or packets. +func TestScopeCheckComputeBudget(t *testing.T) { + if raceBuild { + t.Skip("timing is not meaningful under -race") + } + g, err := scopeguide.Load() + if err != nil { + t.Fatal(err) + } + idx := dagiIndexOrNil() + if idx == nil { + t.Fatal("no DAGI index") + } + row := nodeScopeRow{Role: "repeater", Lat: 55.6761, Lon: 12.5683, HasPosition: true, + DefaultKnown: true, DefaultScope: "dk", ListKnown: true, List: "*,#dk,#dk-kbh,#dk-sjl,#dk-kb"} + buildNodeScopeCheck(g, idx, scKbhKPK, row) // warm + const n = 5000 + start := time.Now() + for i := 0; i < n; i++ { + buildNodeScopeCheck(g, idx, scKbhKPK, row) + } + per := time.Since(start) / n + t.Logf("buildNodeScopeCheck: %v per call (%d calls)", per, n) + if per > time.Millisecond { + t.Fatalf("buildNodeScopeCheck %v per call, budget 1ms", per) + } +} + +func BenchmarkNodeScopeCheck(b *testing.B) { + g, _ := scopeguide.Load() + idx := dagiIndexOrNil() + row := nodeScopeRow{Role: "repeater", Lat: 55.3959, Lon: 10.3883, HasPosition: true, + DefaultKnown: true, DefaultScope: "dk", ListKnown: true, List: "*,#dk,#dk-fyn,#dk-kb"} + b.ReportAllocs() + for i := 0; i < b.N; i++ { + buildNodeScopeCheck(g, idx, scOdensePK, row) + } +} diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index b1736d885..a6d922533 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -309,6 +309,7 @@ func routeDescriptions() map[string]routeMeta { QueryParams: []paramMeta{ {Name: "days", Description: "Time window in days, 1-365.", Type: "integer"}, }}, + "GET /api/nodes/{pubkey}/scope-check": {Summary: "Recommended scopes for where a node stands", Description: "#1035 M2. For a repeater or room with an advertised position in Denmark: the region scopes meshguide.dk recommends there (postal scopes only on Fyn and Sjælland, where meshguide has postnumre) and dk, next to the node's observed default scope (nodes.default_scope; an empty value is a scope this instance cannot decode) and, when an observer reported it, its configured allow-list. Information only, never a verdict on the node. applicable is false with notApplicable role (companion, sensor), position (no advertised position) or outside (not in a DAGI postnummer). Rules from the vendored meshguide.dk commit named in source. 404 for an unknown, hidden or blacklisted node and while dagi.enabled is off.", Tag: "nodes"}, "GET /api/nodes/{pubkey}/declared-regions": {Summary: "Declared-region reports for a node", Description: "Issue #126. The regions this repeater told mobile collectors it lets flood, one report per answer, newest reported_at first, at most 100 (truncated=true when older reports exist). Each report: collector (an opaque number valid only within this response; collector keys and positions are never served), regions ([] = the repeater answered and floods nothing, with empty=true), truncated (the app's hint), reported_at (collector clock), ingested_at (ingest clock), repeater_clock (the repeater's RTC seconds as reported, or null), has_position. Reports are the collectors' claims, not authoritative. 404 unless clientRegions.enabled; 400 for a key that is not 64 hex; 404 for a blacklisted or hidden node. See docs/client-regions.md.", Tag: "nodes"}, "GET /api/reach-rank": {Summary: "Reach leaderboard", Description: "Nodes ranked by all-time neighbour count: distinct neighbours over valid neighbor_edges rows (both endpoints 64-hex pubkeys, not equal; within the ingestor's edge retention) — a historical count, not a measure of radio quality, range or traffic. Only nodes with a Reach page (node row, or named observer row) that are not blacklisted or hidden are ranked. Rank is competition ranking (1, 1, 3) with ties listed in pubkey order; a search or page never renumbers. Served from a shared snapshot (60s TTL, refreshed in the background) that also backs the Rank on /api/nodes/{pubkey}/reach; snapshot_at is when it was read.", Tag: "nodes", QueryParams: []paramMeta{ diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 3c2d6c947..45a826ba1 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -499,6 +499,9 @@ func (s *Server) RegisterRoutes(r *mux.Router) { // Declared-region reports (#126): always registered, 404 while the opt-in // clientRegions flag is off. See declared_regions.go. r.HandleFunc("/api/nodes/{pubkey}/declared-regions", s.handleNodeDeclaredRegions).Methods("GET") + // #1035 M2: meshguide.dk's recommended scopes for where the node stands, + // next to its own. 404 while dagi.enabled is off. See node_scope_check.go. + r.HandleFunc("/api/nodes/{pubkey}/scope-check", s.handleNodeScopeCheck).Methods("GET") r.HandleFunc("/api/nodes/resolve", s.handleResolvePrefix).Methods("GET") r.HandleFunc("/api/rx-coverage", s.handleRxCoverage).Methods("GET") r.HandleFunc("/api/rx-leaderboard", s.handleRxLeaderboard).Methods("GET") diff --git a/public/index.html b/public/index.html index bdc074d9a..ba81887f3 100644 --- a/public/index.html +++ b/public/index.html @@ -306,6 +306,7 @@ + diff --git a/public/node-scope-check.js b/public/node-scope-check.js new file mode 100644 index 000000000..38f886229 --- /dev/null +++ b/public/node-scope-check.js @@ -0,0 +1,197 @@ +/* node-scope-check.js — #1035 M2: "Recommended scopes here (meshguide.dk)" + * on the full node page of a repeater or room with an advertised position. + * + * Shows the scopes meshguide.dk recommends for where the node stands next + * to what the node has (its observed default scope and, when an observer + * reported it, its configured allow-list). Information only: the wording + * never calls the node wrong (owner decision 5 on #1035). + * + * Data: GET /api/nodes/{pubkey}/scope-check (cmd/server/node_scope_check.go, + * M1's engine), one request per node view. Every value from the API or the + * node is written with textContent (XSS gate). + */ +(function (root) { + 'use strict'; + + var SECTION_ID = 'node-scope-check'; + + // applies: repeaters and rooms with an advertised position (never an + // estimated one), the same rule as the server's. + function applies(n) { + if (!n || (n.role !== 'repeater' && n.role !== 'room')) return false; + var lat = Number(n.lat), lon = Number(n.lon); + if (n.lat == null || n.lon == null || !isFinite(lat) || !isFinite(lon)) return false; + return !(lat === 0 && lon === 0); + } + + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = String(text); + return e; + } + + function chips(names, cls) { + var box = el('span', 'scope-check-chips'); + (names || []).forEach(function (name) { + box.appendChild(el('span', 'badge-scope' + (cls ? ' ' + cls : ''), String(name))); + }); + return box; + } + + var DEFAULT_TEXT = { + recommended: 'the recommended default scope', + in_list: 'in the recommended list for this position', + other_meshguide: 'a meshguide.dk scope recommended for other positions', + not_meshguide: 'not among meshguide.dk’s scopes', + undecoded: 'the scope name cannot be decoded on this instance', + none: 'no scoped flood advert seen' + }; + + function defaultText(status) { + return Object.prototype.hasOwnProperty.call(DEFAULT_TEXT, status) ? DEFAULT_TEXT[status] : DEFAULT_TEXT.none; + } + + function shortDate(s) { + if (!s) return ''; + var d = new Date(s); + return isNaN(d.getTime()) ? String(s) : d.toISOString().slice(0, 10); + } + + function row(dl, label, value, testid) { + var dt = el('dt', null, label); + var dd = el('dd'); + if (testid) dd.setAttribute('data-testid', testid); + if (typeof value === 'string') dd.textContent = value; else dd.appendChild(value); + dl.appendChild(dt); + dl.appendChild(dd); + return dd; + } + + function defaultValue(d, confirmedAt) { + var box = el('span'); + var status = d && d.status; + if (status === 'undecoded') box.appendChild(el('span', 'badge-scope badge-scope-unknown', 'cannot be decoded')); + else if (d && d.scope) box.appendChild(el('span', 'badge-scope', d.scope)); + box.appendChild(el('span', 'scope-check-note', ' ' + defaultText(status))); + if (confirmedAt) box.appendChild(el('span', 'scope-check-note', ' (reported by the node, ' + shortDate(confirmedAt) + ')')); + return box; + } + + function scopeNames(list) { + return (list || []).map(function (s) { return s && s.name; }).filter(Boolean); + } + + function listValue(l, reportedAt) { + var box = el('div', 'scope-check-list'); + box.appendChild(el('div', 'scope-check-note', 'From an observer report' + (reportedAt ? ', ' + shortDate(reportedAt) : '') + '.')); + var listed = l.listed || [], notListed = scopeNames(l.notListed); + var other = l.otherMeshguide || [], unknown = l.notMeshguide || []; + if (!listed.length && !other.length && !unknown.length) { + box.appendChild(el('div', null, l.wildcard ? 'Only * (unscoped floods).' : 'The reported list is empty.')); + } + var parts = [ + ['Recommended, in the list', listed, '', 'scope-check-listed'], + ['Recommended, not in the list', notListed, 'scope-check-chip-muted', 'scope-check-not-listed'], + ['In the list, recommended elsewhere', other, '', 'scope-check-other'], + ['In the list, not a meshguide.dk scope', unknown, '', 'scope-check-unknown'] + ]; + parts.forEach(function (p) { + if (!p[1].length) return; + var line = el('div', 'scope-check-line'); + line.setAttribute('data-testid', p[3]); + line.appendChild(el('span', 'scope-check-label', p[0] + ': ')); + line.appendChild(chips(p[1], p[2])); + box.appendChild(line); + }); + if (l.wildcard && (listed.length || other.length || unknown.length)) { + box.appendChild(el('div', 'scope-check-note', 'The list also has * (unscoped floods).')); + } + return box; + } + + /** render builds the section's content from a scope-check answer; null + * when there is nothing to show (not applicable). credit is an optional + * DAGI credit element. */ + function render(data, credit) { + if (!data || !data.applicable || !data.recommendation) return null; + var rec = data.recommendation; + var frag = el('div', 'scope-check'); + var h = el('h4', null, 'Recommended scopes here '); + h.appendChild(el('span', 'scope-check-note', '(meshguide.dk)')); + frag.appendChild(h); + + var place = [rec.postnummer, rec.postnummerName].filter(Boolean).join(' '); + frag.appendChild(el('p', 'scope-check-lead', 'For the position this node advertises' + (place ? ' (' + place + ')' : '') + ', meshguide.dk recommends:')); + var recLine = chips(scopeNames(rec.scopes)); + recLine.setAttribute('data-testid', 'scope-check-recommended'); + frag.appendChild(recLine); + var defLine = el('p', 'scope-check-note', 'Recommended default scope: ' + (rec.default || 'dk') + '.'); + frag.appendChild(defLine); + if (!rec.postalData) { + frag.appendChild(el('p', 'scope-check-note', 'meshguide.dk has postal scopes only for Fyn and Sjælland, so none are listed here.')); + } + + frag.appendChild(el('h5', null, 'This node has')); + var dl = el('dl', 'scope-check-have'); + row(dl, 'Default scope', defaultValue(data.default, data.defaultConfirmedAt), 'scope-check-default'); + var l = data.list || {}; + row(dl, 'Configured scopes', l.reported ? listValue(l, data.listReportedAt) : 'Not reported by an observer.', 'scope-check-configured'); + frag.appendChild(dl); + + var foot = el('p', 'scope-check-note scope-check-foot'); + foot.appendChild(document.createTextNode('Information only. If the advertised position is wrong, so is this recommendation. ')); + var src = data.source || {}; + var a = el('a', null, 'Open meshguide.dk ↗'); + a.href = /^https:\/\//.test(src.url || '') ? src.url : 'https://meshguide.dk/'; + a.setAttribute('target', '_blank'); + a.setAttribute('rel', 'noopener noreferrer'); + foot.appendChild(a); + if (src.commit) foot.appendChild(document.createTextNode(' Rules at commit ' + String(src.commit).slice(0, 7) + '.')); + frag.appendChild(foot); + if (credit) frag.appendChild(credit); + return frag; + } + + // The node page renders twice on a cold load (nodes.js), so the last + // answer (or the request in flight) is reused for REUSE_MS: one request + // per node view. One entry only; a failed request is not kept. + var REUSE_MS = 60000; + var last = null; + function load(pk) { + var now = Date.now(); + if (last && last.pk === pk && now - last.at < REUSE_MS) return last.promise; + var entry = { pk: pk, at: now, promise: null }; + entry.promise = fetch('/api/nodes/' + encodeURIComponent(pk) + '/scope-check', { credentials: 'same-origin' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .catch(function (e) { if (last === entry) last = null; throw e; }); + last = entry; + return entry.promise; + } + + /** mount fills el (the hidden #node-scope-check card) for node n. It + * stays hidden for anything not applicable or on any error. opts.scroll + * scrolls to it once filled (the ?section= deep link). Returns a promise. */ + function mount(box, n, opts) { + opts = opts || {}; + if (!box || !applies(n) || typeof fetch !== 'function') return Promise.resolve(false); + var pk = n.public_key; + box.setAttribute('data-pubkey', pk); + return load(pk) + .then(function (data) { + // A re-render for another node replaced or re-keyed the card. + if (box.getAttribute('data-pubkey') !== pk || box.isConnected === false) return false; + var credit = root.DagiFilter && typeof root.DagiFilter.creditElement === 'function' ? root.DagiFilter.creditElement() : null; + var content = render(data, credit); + if (!content) return false; + box.textContent = ''; + box.appendChild(content); + box.hidden = false; + if (opts.scroll && typeof box.scrollIntoView === 'function') box.scrollIntoView({ behavior: 'smooth', block: 'start' }); + return true; + }) + .catch(function () { return false; }); + } + + root.NodeScopeCheck = { SECTION_ID: SECTION_ID, applies: applies, render: render, mount: mount, defaultText: defaultText }; +})(typeof window !== 'undefined' ? window : this); diff --git a/public/nodes.js b/public/nodes.js index b7c7ef404..2af234039 100644 --- a/public/nodes.js +++ b/public/nodes.js @@ -1200,7 +1200,8 @@ - ${(n.role === 'repeater' || n.role === 'room') ? '' : ''}`; + ${(n.role === 'repeater' || n.role === 'room') ? '' : ''} + ${window.NodeScopeCheck && NodeScopeCheck.applies(n) ? '' : ''}`; // Map -- shows the real fix (solid pin), the neighbor estimate // (dashed pin), or both at once (connected by a dashed line, fit to @@ -1258,6 +1259,15 @@ else destroyAntennaClaimView(); // #1018 M2a: "N verified owners", once an owner opted in. if (window.AccountLinks) window.AccountLinks.mountNodeOwners(document.getElementById('node-owners'), n); + // #1035 M2: meshguide.dk's recommended scopes for where the node stands + // (info only). Filled after one request; scrolls itself into view for + // ?section=node-scope-check, since it is still hidden at the generic + // deep-link scroll below. + if (window.NodeScopeCheck) { + window.NodeScopeCheck.mount(document.getElementById('node-scope-check'), n, { + scroll: new URLSearchParams(location.hash.split('?')[1] || '').get('section') === 'node-scope-check', + }); + } bindNodeAdverts(document.getElementById('node-packets')); diff --git a/public/style.css b/public/style.css index b895ff544..f7e6609e3 100644 --- a/public/style.css +++ b/public/style.css @@ -8042,3 +8042,26 @@ body.embed .warmup-pills { display: none !important; } .st-an-stations .st-an-group { white-space: normal; } } /* end #1017 M7 */ + +/* #1035 M2 "Recommended scopes here (meshguide.dk)" (node-scope-check.js). + Information only, so nothing here uses a status colour. */ +.scope-check { font-size: 13px; color: var(--text); overflow-wrap: anywhere; } +.scope-check h4 .scope-check-note { text-transform: none; letter-spacing: 0; } +.scope-check h5 { margin: 12px 0 6px; font-size: 13px; color: var(--text); } +.scope-check-lead { margin: 0 0 6px; } +.scope-check-chips { display: inline-flex; flex-wrap: wrap; gap: 4px; vertical-align: middle; max-width: 100%; } +.scope-check-chips .badge-scope { font-size: 11px; } +.scope-check .badge-scope.scope-check-chip-muted { background: transparent; color: var(--text-muted); box-shadow: inset 0 0 0 1px var(--border); } +.scope-check-note { color: var(--text-muted); font-size: 12px; } +p.scope-check-note { margin: 6px 0 0; } +.scope-check-have { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 12px; margin: 0; } +.scope-check-have dt { color: var(--text-muted); } +.scope-check-have dd { margin: 0; min-width: 0; } +.scope-check-line { margin-top: 4px; } +.scope-check-label { color: var(--text-muted); } +.scope-check-foot a { color: var(--link-color, var(--accent)); } +@media (max-width: 480px) { + .scope-check-have { grid-template-columns: minmax(0, 1fr); gap: 2px; } + .scope-check-have dd { margin-bottom: 8px; } +} +/* end #1035 M2 */ diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index e094ba52f..7dfcf85f4 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -368,6 +368,7 @@ {"file":"test-issue-1055-m2-live-dagi-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":30,"measurementNote":"New suite; #1055 M2 the DAGI filter on Live and the Area filter on the Live feed, on its own Go server (ports from 13900, a migrated copy of the fixture seeded with test-fixtures/seed-1055-live-dagi-nodes.sql: two nodes in Aarhus kommune, one in Copenhagen, one in Odense; one test area AARHUS): a cold #/live?kommune=0751 link selects Aarhus, filters the map nodes, draws the outline without moving the map and makes one member request; injected live packets: member ADVERTs shown, a non-member ADVERT and a non-advert dropped, no request per packet; the desktop popover is not covered by the feed; a perf bound on 30,000 Live-shaped messages; Area AARHUS filters the feed with its notice and outline, Area AND DAGI passes nobody and the Area outline keeps the slot; leaving Live leaves no listener; a pick and a clear keep follow= and kiosk=1, a saved choice is written into a kiosk link; at 375x560 with touch from a cold start on Home, real taps open the controls, the bottom sheet (not covered), pick Aarhus (the controls close over the fitted map) and clear it. About 30s locally; no CI duration measured yet. Assigned to shard 3, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-1055-m3-area-rule-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":30,"measurementNote":"New suite; #1055 M3 the area rule on Live (From the area / Touches the area), on its own Go server through the #1055 harness (tests/e2e-1055-live.js, ports from 13900, the M2 seed): a cold #/live?kommune=0751 shows the selector with From checked and the From notice; a click to Touches on the open feed needs no reload and no node request, writes areaRule=touches, names the rule, brings back a dropped member-hop packet and shows hop, observer and sender packets while one touching nothing is dropped; Area AARHUS under Touches; a perf bound on 30,000 Live-shaped messages with 64-hop paths; the hash round-trip with a DAGI clear and pick and follow=; kiosk defaults to Touches and keeps areaRule=from; no listener leak (CDP); Packets keeps the sender rule; at 375x560 with touch from a cold start on Home, real taps switch the rule. About 30s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-1076-recommended-adverts-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":40,"measurementNote":"New suite; #1076 M1 recommended advert settings check on the My Mesh card and the health panel for the #245 seed repeaters (seed-245-advert-intervals.sql), with nodes.recommendedAdverts added to the real /api/config/client response: meshguide.dk values give zero-hop on and flood shorter deviations with the CLI fix and the source link on both cards at 1280x900 and 375x560 (touch), and in the health panel after a real tap on Full health; floodIntervalHours 24 gives no deviation observed; minObservations 20 gives not enough data; the fixture's own config (off) has no nodes block and shows no check on the card or in the health panel. About 40s locally; no CI duration measured yet. Assigned to shard 1, the lightest by meanSeconds.","secondsByExecution":[]}, - {"file":"test-issue-1017-m7-analytics-stations-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":12,"measurementNote":"New suite; #1017 M7 the Analytics Hardware and Power cut tabs: the real GET /api/analytics/stations behind a tab=hardware deep link (one request, the observer total equal to the API and to /api/observers, the empty claims note), then the server shape of the mixed fixture routed by Playwright: 1440x900 dark role rows, bar segments on the --hw-* variables (a live override repaints), the device table and markup kept as text; tab=power restored from the URL, taps writing tab=, another tab dropping it, one request for both tabs; a slow answer after leaving the tab is dropped; 375x560 light and dark from a cold start on Home with real taps (More, Analytics, Hardware, Power cut), every box inside the screen and no sideways scroll. 6 cases, about 12s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds.","secondsByExecution":[]} + {"file":"test-issue-1017-m7-analytics-stations-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":12,"measurementNote":"New suite; #1017 M7 the Analytics Hardware and Power cut tabs: the real GET /api/analytics/stations behind a tab=hardware deep link (one request, the observer total equal to the API and to /api/observers, the empty claims note), then the server shape of the mixed fixture routed by Playwright: 1440x900 dark role rows, bar segments on the --hw-* variables (a live override repaints), the device table and markup kept as text; tab=power restored from the URL, taps writing tab=, another tab dropping it, one request for both tabs; a slow answer after leaving the tab is dropped; 375x560 light and dark from a cold start on Home with real taps (More, Analytics, Hardware, Power cut), every box inside the screen and no sideways scroll. 6 cases, about 12s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, + {"file":"test-issue-1035-m2-node-scope-check-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":25,"measurementNote":"New suite; #1035 M2 the \"Recommended scopes here (meshguide.dk)\" card on the full node page, on its own Go server through the #1055 harness (tests/e2e-1055-live.js, ports from 13900) seeded with test-fixtures/seed-1035-scope-check-nodes.sql: an Odense repeater at 1280x900 light and dark (one /scope-check request per view, the recommended chips with region and postal scopes, its default and the observer list in neutral words, the https meshguide.dk link, colours from the theme variables), an Aarhus repeater with an undecodable default and no postal scopes, no card for a companion, a repeater without a position or one in Malmö, the ?section=node-scope-check deep link scrolling to the card, and 375x560 touch light and dark inside the screen with no sideways scroll. 10 cases, about 25s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds.","secondsByExecution":[]} ] } diff --git a/test-1035-node-scope-check.js b/test-1035-node-scope-check.js new file mode 100644 index 000000000..c90c0ef2e --- /dev/null +++ b/test-1035-node-scope-check.js @@ -0,0 +1,295 @@ +/** + * Unit tests for public/node-scope-check.js (#1035 M2), the "Recommended + * scopes here (meshguide.dk)" section of the full node page. + * + * The real file runs in a vm sandbox (tests/fake-dom.js); fetch is a fake + * whose answers are in GET /api/nodes/{pubkey}/scope-check's shape + * (cmd/server/node_scope_check.go, curled from a local server). + */ +'use strict'; +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const { El, makeDoc, loadPublic, flush } = require('./tests/fake-dom'); + +let passed = 0, failed = 0; +const queue = []; +function test(name, fn) { queue.push([name, fn]); } + +const PK = 'ab'.repeat(32); + +function answer(over) { + return Object.assign({ + pubkey: PK, applicable: true, + recommendation: { + covered: true, postnummer: '5000', postnummerName: 'Odense C', postalData: true, default: 'dk', + scopes: [{ name: 'eu', kind: 'fixed' }, { name: 'europe', kind: 'fixed' }, { name: 'dk', kind: 'fixed' }, + { name: 'dk-fyn-odense', kind: 'region' }, { name: 'dk-fyn', kind: 'region' }, { name: 'dk5', kind: 'postal' }, { name: 'dk5000', kind: 'postal' }], + }, + default: { scope: 'dk', status: 'recommended' }, + list: { reported: true, wildcard: true, listed: ['dk', 'dk-fyn'], + notListed: [{ name: 'eu', kind: 'fixed' }, { name: 'europe', kind: 'fixed' }, { name: 'dk-fyn-odense', kind: 'region' }, { name: 'dk5', kind: 'postal' }, { name: 'dk5000', kind: 'postal' }], + notMeshguide: ['dk-kb'] }, + listReportedAt: '2026-12-01T10:00:00Z', + source: { name: 'meshguide.dk', url: 'https://meshguide.dk/#/defaults/region-scopes', repo: 'github.com/twinoak/meshguide.dk', commit: '9a5d7f5fd210d863067f87581e75eaf562327d71' }, + }, over || {}); +} + +function world(opts) { + opts = opts || {}; + const doc = makeDoc(); + doc.createTextNode = (t) => { const e = new El('#text'); e._text = String(t); return e; }; + const calls = []; + const fetch = (url) => { + calls.push(url); + if (opts.reject || (opts.rejectIf && opts.rejectIf())) return Promise.reject(new Error('network')); + const body = opts.body === undefined ? answer() : opts.body; + return Promise.resolve({ ok: opts.status ? opts.status < 400 : true, status: opts.status || 200, json: () => Promise.resolve(body) }); + }; + const extra = { document: doc, fetch }; + if (opts.Date) extra.Date = opts.Date; + const w = loadPublic('node-scope-check.js', extra); + if (opts.dagi) w.DagiFilter = opts.dagi; + return { w, doc, calls, M: w.NodeScopeCheck }; +} + +const repeater = (over) => Object.assign({ public_key: PK, role: 'repeater', lat: 55.3959, lon: 10.3883 }, over || {}); +const texts = (root, tag) => root.all().filter((e) => e.tagName === tag).map((e) => e.textContent); +const byTestId = (root, id) => root.all().find((e) => e.getAttribute('data-testid') === id); +const chipNames = (root) => root.all().filter((e) => e.classList.contains('badge-scope')).map((e) => e.textContent); + +test('applies only to repeaters and rooms with an advertised position', () => { + const { M } = world(); + assert.strictEqual(M.applies(repeater()), true); + assert.strictEqual(M.applies(repeater({ role: 'room' })), true); + assert.strictEqual(M.applies(repeater({ role: 'companion' })), false); + assert.strictEqual(M.applies(repeater({ role: 'sensor' })), false); + assert.strictEqual(M.applies(repeater({ lat: null, lon: null })), false); + assert.strictEqual(M.applies(repeater({ lat: 0, lon: 0 })), false); + assert.strictEqual(M.applies(repeater({ lat: 'x', lon: 10 })), false); + assert.strictEqual(M.applies(repeater({ lat: 0, lon: 10.5 })), true, 'only 0,0 is the no-position sentinel'); + assert.strictEqual(M.applies(null), false); +}); + +test('render: lead, recommended chips, default, place and source link', () => { + const { M } = world(); + const out = M.render(answer()); + assert.ok(out); + assert.ok(texts(out, 'H4')[0].startsWith('Recommended scopes here')); + assert.ok(/\(meshguide\.dk\)/.test(texts(out, 'H4')[0])); + assert.ok(texts(out, 'P').some((t) => t === 'For the position this node advertises (5000 Odense C), meshguide.dk recommends:')); + assert.deepStrictEqual(chipNames(byTestId(out, 'scope-check-recommended')), ['eu', 'europe', 'dk', 'dk-fyn-odense', 'dk-fyn', 'dk5', 'dk5000']); + assert.ok(texts(out, 'P').includes('Recommended default scope: dk.')); + assert.ok(!texts(out, 'P').some((t) => /postal scopes only/.test(t)), 'Fyn has postal scopes: no note'); + const a = out.all().find((e) => e.tagName === 'A'); + assert.strictEqual(a.href, 'https://meshguide.dk/#/defaults/region-scopes'); + assert.strictEqual(a.getAttribute('target'), '_blank'); + assert.ok(/noopener/.test(a.getAttribute('rel'))); + assert.ok(/Rules at commit 9a5d7f5\./.test(out.textContent)); + assert.ok(/Information only\. If the advertised position is wrong, so is this recommendation\./.test(out.textContent)); +}); + +test('render: what the node has, in neutral words', () => { + const { M } = world(); + const out = M.render(answer()); + const def = byTestId(out, 'scope-check-default'); + assert.strictEqual(def.textContent, 'dk the recommended default scope'); + assert.deepStrictEqual(chipNames(byTestId(out, 'scope-check-listed')), ['dk', 'dk-fyn']); + const notListed = byTestId(out, 'scope-check-not-listed'); + assert.deepStrictEqual(chipNames(notListed), ['eu', 'europe', 'dk-fyn-odense', 'dk5', 'dk5000']); + assert.ok(notListed.all().filter((e) => e.classList.contains('badge-scope')).every((e) => e.classList.contains('scope-check-chip-muted'))); + assert.deepStrictEqual(chipNames(byTestId(out, 'scope-check-unknown')), ['dk-kb']); + assert.strictEqual(byTestId(out, 'scope-check-other'), undefined); + const conf = byTestId(out, 'scope-check-configured'); + assert.ok(/From an observer report, 2026-12-01\./.test(conf.textContent)); + assert.ok(/The list also has \* \(unscoped floods\)\./.test(conf.textContent)); + // The only "wrong" is the position disclaimer; nothing judges the node. + const judged = out.textContent.replace('If the advertised position is wrong, so is this recommendation.', ''); + assert.ok(!/wrong|misconfigur|error|invalid|should|must|missing|lacks/i.test(judged), 'never calls the node wrong: ' + judged); +}); + +test('render: every default status has its own neutral text', () => { + const { M } = world(); + const want = { + recommended: 'the recommended default scope', + in_list: 'in the recommended list for this position', + other_meshguide: 'a meshguide.dk scope recommended for other positions', + not_meshguide: 'not among meshguide.dk’s scopes', + undecoded: 'the scope name cannot be decoded on this instance', + none: 'no scoped flood advert seen', + }; + for (const [status, text] of Object.entries(want)) { + const scope = status === 'none' || status === 'undecoded' ? undefined : 'dk-x'; + const def = byTestId(M.render(answer({ default: { scope, status } })), 'scope-check-default'); + assert.ok(def.textContent.endsWith(text), status + ': ' + def.textContent); + } + assert.strictEqual(M.defaultText('bogus'), want.none); + assert.strictEqual(M.defaultText('constructor'), want.none, 'no prototype keys'); +}); + +test('render: an undecodable default scope reads "cannot be decoded"', () => { + const { M } = world(); + const def = byTestId(M.render(answer({ default: { status: 'undecoded' } })), 'scope-check-default'); + assert.deepStrictEqual(chipNames(def), ['cannot be decoded']); + assert.ok(def.all().find((e) => e.classList.contains('badge-scope')).classList.contains('badge-scope-unknown')); +}); + +test('render: firmware-confirmed default carries its date', () => { + const { M } = world(); + const def = byTestId(M.render(answer({ defaultConfirmedAt: '2026-12-02T12:00:00Z' })), 'scope-check-default'); + assert.ok(/\(reported by the node, 2026-12-02\)/.test(def.textContent)); +}); + +test('render: no observer report, empty list, only *', () => { + const { M } = world(); + let conf = byTestId(M.render(answer({ list: { reported: false } })), 'scope-check-configured'); + assert.strictEqual(conf.textContent, 'Not reported by an observer.'); + conf = byTestId(M.render(answer({ list: { reported: true, notListed: [{ name: 'dk', kind: 'fixed' }] }, listReportedAt: '' })), 'scope-check-configured'); + assert.ok(/^From an observer report\.The reported list is empty\./.test(conf.textContent), conf.textContent); + conf = byTestId(M.render(answer({ list: { reported: true, wildcard: true, notListed: [{ name: 'dk', kind: 'fixed' }] } })), 'scope-check-configured'); + assert.ok(/Only \* \(unscoped floods\)\./.test(conf.textContent)); + assert.ok(!/The list also has/.test(conf.textContent)); + conf = byTestId(M.render(answer({ list: { reported: true, otherMeshguide: ['dk-mj'] } })), 'scope-check-configured'); + assert.deepStrictEqual(chipNames(byTestId(conf, 'scope-check-other')), ['dk-mj']); +}); + +test('render: outside Fyn and Sjælland says why there are no postal scopes', () => { + const { M } = world(); + const out = M.render(answer({ recommendation: { covered: true, postnummer: '8000', postnummerName: 'Aarhus C', postalData: false, default: 'dk', + scopes: [{ name: 'dk', kind: 'fixed' }, { name: 'dk-aarhus', kind: 'region' }] } })); + assert.ok(texts(out, 'P').includes('meshguide.dk has postal scopes only for Fyn and Sjælland, so none are listed here.')); + assert.ok(texts(out, 'P').includes('For the position this node advertises (8000 Aarhus C), meshguide.dk recommends:')); +}); + +test('render: nothing when not applicable', () => { + const { M } = world(); + assert.strictEqual(M.render(answer({ applicable: false, notApplicable: 'role' })), null); + assert.strictEqual(M.render(answer({ recommendation: null })), null); + assert.strictEqual(M.render(null), null); +}); + +test('render: values are text, never markup (XSS)', () => { + const { M } = world(); + const evil = ''; + const out = M.render(answer({ + recommendation: { covered: true, postnummer: evil, postnummerName: evil, postalData: true, default: evil, scopes: [{ name: evil, kind: 'region' }] }, + default: { scope: evil, status: 'not_meshguide' }, + list: { reported: true, notMeshguide: [evil], otherMeshguide: [evil] }, + source: { url: 'javascript:alert(1)', commit: evil }, + })); + assert.ok(out.textContent.includes(evil), 'shown as text'); + assert.ok(out.all().every((e) => e.innerHTML === undefined), 'no innerHTML anywhere'); + assert.strictEqual(out.all().find((e) => e.tagName === 'A').href, 'https://meshguide.dk/', 'only an https link'); + const src = fs.readFileSync(path.join(__dirname, 'public/node-scope-check.js'), 'utf8'); + assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(src), 'no HTML sinks in the module'); + assert.ok(!/#[0-9a-fA-F]{3,8}\b|rgba?\(/.test(src.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '')), 'no colours in the module'); +}); + +test('mount: one request, fills and shows the card, DAGI credit appended', async () => { + const credit = new El('div'); credit.className = 'dagi-credit'; + const { M, doc, calls } = world({ dagi: { creditElement: () => credit } }); + const box = doc.createElement('div'); box.hidden = true; + const ok = await M.mount(box, repeater()); + assert.strictEqual(ok, true); + assert.deepStrictEqual(calls, ['/api/nodes/' + PK + '/scope-check']); + assert.strictEqual(box.hidden, false); + assert.ok(box.find('scope-check').length === 1); + assert.ok(box.contains(credit)); + assert.strictEqual(box.scrolls, undefined, 'no scroll without the deep link'); +}); + +test('mount: ?section=node-scope-check scrolls once filled', async () => { + const { M, doc } = world(); + const box = doc.createElement('div'); box.hidden = true; + await M.mount(box, repeater(), { scroll: true }); + assert.strictEqual(box.scrolls.length, 1); +}); + +test('mount: companions and unpositioned nodes make no request', async () => { + const { M, doc, calls } = world(); + const box = doc.createElement('div'); box.hidden = true; + assert.strictEqual(await M.mount(box, repeater({ role: 'companion' })), false); + assert.strictEqual(await M.mount(box, repeater({ lat: null })), false); + assert.strictEqual(await M.mount(null, repeater()), false); + assert.deepStrictEqual(calls, []); + assert.strictEqual(box.hidden, true); +}); + +test('mount: stays hidden on 404, not applicable or a network error', async () => { + for (const opts of [{ status: 404, body: null }, { body: answer({ applicable: false, notApplicable: 'outside' }) }, { reject: true }]) { + const { M, doc } = world(opts); + const box = doc.createElement('div'); box.hidden = true; + assert.strictEqual(await M.mount(box, repeater()), false); + assert.strictEqual(box.hidden, true); + assert.strictEqual(box.children.length, 0); + } +}); + +test('mount: a re-render of the same node reuses the answer; another node asks again', async () => { + const { M, doc, calls } = world(); + const a = doc.createElement('div'), b = doc.createElement('div'), c = doc.createElement('div'); + await Promise.all([M.mount(a, repeater()), M.mount(b, repeater())]); + assert.strictEqual(calls.length, 1, 'in-flight request reused'); + assert.strictEqual(a.hidden, false); assert.strictEqual(b.hidden, false); + await M.mount(c, repeater({ public_key: 'cd'.repeat(32) })); + assert.strictEqual(calls.length, 2); + await M.mount(doc.createElement('div'), repeater()); + assert.strictEqual(calls.length, 3, 'one entry only'); +}); + +test('mount: the reuse expires after a minute', async () => { + let now = 1e12; + const { M, doc, calls } = world({ Date: class extends Date { static now() { return now; } } }); + await M.mount(doc.createElement('div'), repeater()); + now += 59000; + await M.mount(doc.createElement('div'), repeater()); + assert.strictEqual(calls.length, 1); + now += 2000; + await M.mount(doc.createElement('div'), repeater()); + assert.strictEqual(calls.length, 2); +}); + +test('mount: a failed request is not reused', async () => { + let fail = true; + const { M, doc, calls } = world({ rejectIf: () => fail }); + assert.strictEqual(await M.mount(doc.createElement('div'), repeater()), false); + fail = false; + const box = doc.createElement('div'); box.hidden = true; + assert.strictEqual(await M.mount(box, repeater()), true); + assert.strictEqual(calls.length, 2); +}); + +test('mount: a late answer for another node is dropped', async () => { + const { M, doc } = world(); + const box = doc.createElement('div'); box.hidden = true; + const p = M.mount(box, repeater()); + box.setAttribute('data-pubkey', 'cd'.repeat(32)); + assert.strictEqual(await p, false); + assert.strictEqual(box.hidden, true); +}); + +test('wiring: nodes.js mounts the card and index.html loads the module before it', () => { + const nodes = fs.readFileSync(path.join(__dirname, 'public/nodes.js'), 'utf8'); + assert.ok(/NodeScopeCheck\.applies\(n\) \? '