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/config.go b/cmd/server/config.go index c94616c84..57a754759 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -166,6 +166,10 @@ type Config struct { // embedded. Read from the canonical key dagi.enabled only. Dagi *DagiConfig `json:"dagi,omitempty"` + // ScopeCheck configures the #1035 scope check; publicList switches the + // Scope Audit Location list (GET /api/scope-check) to API-key only. + ScopeCheck *ScopeCheckConfig `json:"scopeCheck,omitempty"` + // ChannelProposals configures publicly suggested hashtag channels // (internal/channelregistry). Submissions open only when enabled AND a // strong apiKey is set; the same block is read by the ingestor. @@ -1277,6 +1281,10 @@ func (c *Config) applyCanonicalKeys(keys *configkey.Doc) error { // On by default: only a canonical boolean switches DAGI off (#740). c.Dagi.Enabled = keys.Bool("dagi", "enabled") } + if c.ScopeCheck != nil { + // Public by default: only a canonical boolean restricts it (#1035). + c.ScopeCheck.PublicList = keys.Bool("scopeCheck", "publicList") + } c.applyTimestampKeys(keys) c.Kiosk = readKioskConfig(keys, c.logf) c.RecommendedAdverts = readRecommendedAdverts(keys, c.logf) 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..b5334c360 --- /dev/null +++ b/cmd/server/node_scope_check.go @@ -0,0 +1,210 @@ +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"` +} + +// NodeScopeCheck is one node's check: M1's Verdict plus the times of the +// node-side evidence. The node endpoint answers one (with its source), the +// Scope Audit list (#1035 M3, GET /api/scope-check) one per row: the same +// helper (nodeScopeVerdict) builds both. +type NodeScopeCheck 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"` +} + +// NodeScopeCheckResponse is the node endpoint's answer. +type NodeScopeCheckResponse struct { + NodeScopeCheck + 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 +} + +// nodeScopeScan is the scan target of the node columns the check reads. +type nodeScopeScan struct { + name, role, def, list, listAt, defAt sql.NullString + lat, lon sql.NullFloat64 +} + +// nodeScopeSelect returns the column list (after public_key) and the scan +// destinations for sc. The scope columns are optional (#899, #1865): a DB +// without them reads as "not known". Shared by the node read and the list's +// bulk read, so both type a row the same way. +func (db *DB) nodeScopeSelect(sc *nodeScopeScan) (string, []interface{}) { + cols := "name, role, lat, lon" + args := []interface{}{&sc.name, &sc.role, &sc.lat, &sc.lon} + if db.hasDefaultScope() { + cols += ", default_scope" + args = append(args, &sc.def) + } + if db.hasConfiguredScope() { + cols += ", configured_scope, configured_scope_at" + args = append(args, &sc.list, &sc.listAt) + } + if db.hasDefaultScopeConfirmedAt() { + cols += ", default_scope_confirmed_at" + args = append(args, &sc.defAt) + } + return cols, args +} + +// row types a scanned row at the boundary. +func (sc *nodeScopeScan) row() nodeScopeRow { + var row nodeScopeRow + row.Role = sc.role.String + if sc.lat.Valid && sc.lon.Valid && isValidNodePosition(sc.lat.Float64, sc.lon.Float64) { + row.Lat, row.Lon, row.HasPosition = sc.lat.Float64, sc.lon.Float64, true + } + row.DefaultScope, row.DefaultKnown = sc.def.String, sc.def.Valid + row.DefaultConfirmedAt = sc.defAt.String + row.List, row.ListKnown = sc.list.String, sc.list.Valid + row.ListAt = sc.listAt.String + return row +} + +// nodeScopeRow reads one node's row by primary key, typed at the +// boundary. ok is false when there is no such node. +func (db *DB) nodeScopeRow(pubkey string) (row nodeScopeRow, name string, ok bool, err error) { + var sc nodeScopeScan + cols, args := db.nodeScopeSelect(&sc) + 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 + } + return sc.row(), sc.name.String, true, nil +} + +// nodeScopeVerdict is the pure check of one node row: the DAGI postnummer +// of its advertised position, M1's Recommend + Compare, and the evidence +// times. Both endpoints use it. +func nodeScopeVerdict(g *scopeguide.Guide, idx *dagiIndex, pubkey string, row nodeScopeRow) NodeScopeCheck { + 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 + } + out := NodeScopeCheck{Pubkey: pubkey, Verdict: v} + if v.Applicable { + if v.Default.Status != scopeguide.DefaultNone { + out.DefaultConfirmedAt = row.DefaultConfirmedAt + } + if v.List.Reported { + out.ListReportedAt = row.ListAt + } + } + return out +} + +// nodeScopeCheckSource names the vendored meshguide commit. +func nodeScopeCheckSource(g *scopeguide.Guide) NodeScopeCheckSource { + up := g.Upstream() + return NodeScopeCheckSource{Name: "meshguide.dk", URL: meshguideScopesURL, Repo: up.Repo, Commit: up.Commit} +} + +// buildNodeScopeCheck is the pure part of the node endpoint. +func buildNodeScopeCheck(g *scopeguide.Guide, idx *dagiIndex, pubkey string, row nodeScopeRow) NodeScopeCheckResponse { + return NodeScopeCheckResponse{NodeScopeCheck: nodeScopeVerdict(g, idx, pubkey, row), Source: nodeScopeCheckSource(g)} +} + +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..d1ccfa9fe 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{ @@ -358,6 +359,7 @@ func routeDescriptions() map[string]routeMeta { {Status: "503", Description: "No analytics snapshot published yet (warming up); Retry-After gives the seconds to wait."}, }}, "GET /api/scope-audit": {Summary: "Declared versus observed forwarding scopes", Description: "Observer-confirmed scope declarations compared with collision-safe flood path evidence. Missing observations are not proof of a configuration error. Unknown scopes, ambiguous hops, absent observations, and declarations older than seven days make evidence incomplete. Observer scope lists may be truncated without a completeness flag. Cached 30 seconds for each of three supported windows; identity visibility is applied live.", Tag: "analytics", QueryParams: []paramMeta{{Name: "window", Description: "Observation window: 1h, 24h (default), or 7d", Type: "string"}}}, + "GET /api/scope-check": {Summary: "Recommended scopes for where each repeater and room stands", Description: "#1035 M3, the Scope Audit Location view. Every repeater and room with an advertised position in Denmark (a DAGI postnummer), each row the same check GET /api/nodes/{pubkey}/scope-check answers (pubkey, applicable, recommendation, default, list, defaultConfirmedAt, listReportedAt) plus name and role: the scopes meshguide.dk recommends there next to the node's observed default scope and, when an observer reported it, its configured list. Information only, never a verdict on a node. Rows are sorted by postnummer, name and key; filtering and sorting are left to the client. summary counts the rows by neutral category (default recommended / in the list / recommended elsewhere / not a meshguide.dk scope / cannot be decoded / none; lists reported, without dk, with names that are not meshguide.dk scopes) and the repeaters and rooms not listed (outside: a position outside Denmark; unpositioned: none). Companions and sensors are never listed. Rules from the vendored meshguide.dk commit named in source. One read-only build is cached 30 seconds (singleflight); identity visibility is applied live. Public unless scopeCheck.publicList is false, then 403 without the API key (X-API-Key). 404 while dagi.enabled is off.", Tag: "analytics"}, "GET /api/scope-audit/transport": {Summary: "Observed scope transport by repeater", Description: "#414: every repeater or room seen forwarding flood traffic (TRANSPORT_FLOOD/FLOOD observations) in the window, including repeaters never asked for a declaration (declaration null, not the same as an empty declaration). With scope, each row reports carrier (distinct transmissions seen carrying it) and nonCarrier (forwarded without it) and an evidence label: carrier, not-seen-carrying, ambiguous (a hop prefix shared with another repeater carried the scope), incomplete (unknown scopes or frames without headers), low-evidence (fewer than minForwarded transmissions) or no-scope-traffic (nobody in the population was seen carrying it). Evidence is observation only, never a configuration verdict: quiet traffic and observer coverage explain absence. Uses the same collision-safe attribution and per-transmission deduplication as /api/scope-audit; repeaters seen only through ambiguous prefixes are not listed. region restricts the whole population (counts, rows and details) to observations heard by observers in those IATA regions. One read-only scan per window and region is cached 30 seconds (bounded, singleflight) and serves every scope; identity visibility is applied live. coverage.complete is false when the oldest stored observation is newer than the window start.", Tag: "analytics", QueryParams: []paramMeta{ {Name: "window", Description: "Observation window: 1h, 24h (default), or 7d", Type: "string"}, {Name: "scope", Description: "Region scope name, exact case, optional leading #; omitted lists forwarders without carrier evidence", Type: "string"}, diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 58acc0295..15b00df46 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -106,6 +106,8 @@ type Server struct { // Cached /api/scope-audit response — per-window, recomputed at most once every 30s scopeAudit scopeAuditCache[ScopeAuditResponse] + // #1035 M3: the cached Location list (one key), see scope_check_list.go. + scopeCheckList scopeAuditCache[scopeCheckListBuild] // Cached /api/scope-audit/transport scans — per window and observer region, bounded scopeTransport scopeAuditCache[scopeTransportScan] @@ -414,6 +416,9 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.HandleFunc("/api/scope-stats", s.handleScopeStats).Methods("GET") r.HandleFunc("/api/scope-audit", s.handleScopeAudit).Methods("GET") r.HandleFunc("/api/scope-audit/transport", s.handleScopeTransport).Methods("GET") + // #1035 M3: every positioned repeater and room next to meshguide.dk's + // recommendation (Scope Audit "Location"). See scope_check_list.go. + r.HandleFunc("/api/scope-check", s.handleScopeCheckList).Methods("GET") r.HandleFunc("/api/analytics/hop-depth", s.handleHopDepthAnalytics).Methods("GET") r.HandleFunc("/api/analytics/observer-comparison", s.handleObserverComparison).Methods("GET") r.HandleFunc("/api/analytics/wardriving", s.handleWardrivingStats).Methods("GET") @@ -499,6 +504,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/cmd/server/scope_check_list.go b/cmd/server/scope_check_list.go new file mode 100644 index 000000000..4d383b1f7 --- /dev/null +++ b/cmd/server/scope_check_list.go @@ -0,0 +1,262 @@ +package main + +import ( + "context" + "net/http" + "sort" + "time" + + "github.com/meshcore-analyzer/scopeguide" +) + +// #1035 M3: GET /api/scope-check — every repeater and room with an +// advertised position in Denmark, each row the NodeScopeCheck the node page +// answers for it (nodeScopeVerdict, M2): what meshguide.dk recommends where +// the node stands next to what the node has. It feeds the "Location" view +// of Scope Audit (public/scope-audit.js). Information only, never a +// warning (owner decision 5); the summary counts neutral categories. +// +// Cost: one bulk read of the node scope columns, then per repeater or room +// with a position one DAGI point lookup and M1's Recommend + Compare: +// O(positioned repeaters and rooms) (TestScopeCheckListBuildBudget, +// BenchmarkScopeCheckList). The result is cached like Scope Audit (30 s +// TTL, singleflight, one key), so a request never rebuilds while it is +// fresh; filtering and sorting happen in the browser. Identity visibility +// is applied to every serve, cache hits included. Read-only (#1283). +// +// Public by default like Scope Audit; scopeCheck.publicList=false keeps the +// list to requests with the API key (owner decision 6). The node page is +// not affected. Gated by dagi.enabled, like every DAGI feature. + +const scopeCheckListKey = "all" + +// ScopeCheckListRow is one node of the list. +type ScopeCheckListRow struct { + Name string `json:"name"` + Role string `json:"role"` + NodeScopeCheck +} + +// ScopeCheckListSummary counts the listed rows by neutral category, and the +// repeaters and rooms that are not listed because they have no position or +// stand outside Denmark. +type ScopeCheckListSummary struct { + Total int `json:"total"` + DefaultRecommended int `json:"defaultRecommended"` + DefaultInList int `json:"defaultInList"` + DefaultOtherMeshguide int `json:"defaultOtherMeshguide"` + DefaultNotMeshguide int `json:"defaultNotMeshguide"` + DefaultUndecoded int `json:"defaultUndecoded"` + DefaultNone int `json:"defaultNone"` + ListReported int `json:"listReported"` + // ListWithoutDk: a reported list that does not have the recommended + // default (dk). + ListWithoutDk int `json:"listWithoutDk"` + ListNotMeshguide int `json:"listNotMeshguide"` + Outside int `json:"outside"` + Unpositioned int `json:"unpositioned"` +} + +// ScopeCheckListResponse is the endpoint's answer. +type ScopeCheckListResponse struct { + GeneratedAt string `json:"generatedAt"` + Summary ScopeCheckListSummary `json:"summary"` + Rows []ScopeCheckListRow `json:"rows"` + Source NodeScopeCheckSource `json:"source"` +} + +// nodeScopeListRow is one repeater or room read for the list. +type nodeScopeListRow struct { + pubkey, name string + row nodeScopeRow +} + +// scopeCheckListBuild is the cached result: the listed rows and the keys +// of the not-listed ones per reason, so visibility can be applied to the +// counts as well as to the rows. +type scopeCheckListBuild struct { + resp ScopeCheckListResponse + outside []scopeCheckIdentity + unpositioned []scopeCheckIdentity +} + +type scopeCheckIdentity struct{ pubkey, name string } + +// ScopeCheckConfig is the scopeCheck config block (#1035). +type ScopeCheckConfig struct { + // PublicList: the Location list is public (missing: true). false + // serves it only with the API key. Read from the canonical key + // scopeCheck.publicList only. + PublicList *bool `json:"publicList,omitempty"` +} + +// ScopeCheckPublicList reports whether the Location list is public. +func (c *Config) ScopeCheckPublicList() bool { + return c == nil || c.ScopeCheck == nil || c.ScopeCheck.PublicList == nil || *c.ScopeCheck.PublicList +} + +// nodeScopeListRows reads every repeater and room with one query. +func (db *DB) nodeScopeListRows(ctx context.Context) ([]nodeScopeListRow, error) { + var sc nodeScopeScan + cols, args := db.nodeScopeSelect(&sc) + var pk string + dest := append([]interface{}{&pk}, args...) + rows, err := db.conn.QueryContext(ctx, "SELECT public_key, "+cols+" FROM nodes WHERE lower(role) IN ('repeater','room')") + if err != nil { + return nil, err + } + defer rows.Close() + var out []nodeScopeListRow + for rows.Next() { + sc = nodeScopeScan{} + if err := rows.Scan(dest...); err != nil { + return nil, err + } + out = append(out, nodeScopeListRow{pubkey: pk, name: sc.name.String, row: sc.row()}) + } + return out, rows.Err() +} + +// buildScopeCheckList is the pure part: one verdict per row, sorted by +// postnummer, name and key. +func buildScopeCheckList(g *scopeguide.Guide, idx *dagiIndex, rows []nodeScopeListRow, now time.Time) *scopeCheckListBuild { + b := &scopeCheckListBuild{resp: ScopeCheckListResponse{ + GeneratedAt: now.UTC().Format(time.RFC3339), + Rows: make([]ScopeCheckListRow, 0, len(rows)), + Source: nodeScopeCheckSource(g), + }} + for _, r := range rows { + v := nodeScopeVerdict(g, idx, r.pubkey, r.row) + switch { + case v.Applicable: + b.resp.Rows = append(b.resp.Rows, ScopeCheckListRow{Name: r.name, Role: r.row.Role, NodeScopeCheck: v}) + case v.NotApplicable == scopeguide.NotApplicableOutside: + b.outside = append(b.outside, scopeCheckIdentity{r.pubkey, r.name}) + case v.NotApplicable == NotApplicablePosition: + b.unpositioned = append(b.unpositioned, scopeCheckIdentity{r.pubkey, r.name}) + } + } + sort.Slice(b.resp.Rows, func(i, j int) bool { + a, c := &b.resp.Rows[i], &b.resp.Rows[j] + if a.Recommendation.Postnummer != c.Recommendation.Postnummer { + return a.Recommendation.Postnummer < c.Recommendation.Postnummer + } + if a.Name != c.Name { + return a.Name < c.Name + } + return a.Pubkey < c.Pubkey + }) + return b +} + +// summarizeScopeCheckList counts rows by category. +func summarizeScopeCheckList(rows []ScopeCheckListRow, outside, unpositioned int) ScopeCheckListSummary { + s := ScopeCheckListSummary{Total: len(rows), Outside: outside, Unpositioned: unpositioned} + for i := range rows { + r := &rows[i] + switch r.Default.Status { + case scopeguide.DefaultRecommended: + s.DefaultRecommended++ + case scopeguide.DefaultInList: + s.DefaultInList++ + case scopeguide.DefaultOtherMeshguide: + s.DefaultOtherMeshguide++ + case scopeguide.DefaultNotMeshguide: + s.DefaultNotMeshguide++ + case scopeguide.DefaultUndecoded: + s.DefaultUndecoded++ + default: + s.DefaultNone++ + } + if !r.List.Reported { + continue + } + s.ListReported++ + for _, n := range r.List.NotListed { + if n.Name == r.Recommendation.Default { + s.ListWithoutDk++ + break + } + } + if len(r.List.NotMeshguide) > 0 { + s.ListNotMeshguide++ + } + } + return s +} + +// scopeCheckListAllowed applies scopeCheck.publicList: a restricted list +// needs a strong API key, exactly as requireAPIKey checks it. +func (s *Server) scopeCheckListAllowed(r *http.Request) bool { + if s.cfg.ScopeCheckPublicList() { + return true + } + key := r.Header.Get("X-API-Key") + return s.cfg.APIKey != "" && constantTimeEqual(key, s.cfg.APIKey) && !IsWeakAPIKey(key) +} + +func (s *Server) handleScopeCheckList(w http.ResponseWriter, r *http.Request) { + idx := s.dagiIndex() + if idx == nil { + writeError(w, http.StatusNotFound, "Not found") + return + } + if !s.scopeCheckListAllowed(r) { + writeError(w, http.StatusForbidden, "the operator keeps this list private (scopeCheck.publicList)") + return + } + g, err := scopeguide.Load() + if err != nil { + writeError(w, http.StatusServiceUnavailable, "scope guide unavailable") + return + } + built, err := s.scopeCheckList.load(scopeCheckListKey, func() (*scopeCheckListBuild, error) { + // Shared by every coalesced waiter: keep only the absolute deadline. + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), scopeAuditQueryTimeout) + defer cancel() + rows, err := s.db.nodeScopeListRows(ctx) + if err != nil { + return nil, err + } + return buildScopeCheckList(g, idx, rows, time.Now()), nil + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "query failed") + return + } + keys := make([]string, 0, len(built.resp.Rows)+len(built.outside)+len(built.unpositioned)) + for _, row := range built.resp.Rows { + keys = append(keys, row.Pubkey) + } + for _, list := range [][]scopeCheckIdentity{built.outside, built.unpositioned} { + for _, id := range list { + keys = append(keys, id.pubkey) + } + } + names, err := s.hiddenIdentityNames(r.Context(), keys) + if err != nil { + writeError(w, http.StatusInternalServerError, "query failed") + return + } + visible := func(pubkey, name string) bool { + return !identityHidden(s.cfg, pubkey, append([]string{name}, names[pubkey]...)...) + } + countVisible := func(list []scopeCheckIdentity) int { + n := 0 + for _, id := range list { + if visible(id.pubkey, id.name) { + n++ + } + } + return n + } + out := built.resp + out.Rows = make([]ScopeCheckListRow, 0, len(built.resp.Rows)) + for _, row := range built.resp.Rows { + if visible(row.Pubkey, row.Name) { + out.Rows = append(out.Rows, row) + } + } + out.Summary = summarizeScopeCheckList(out.Rows, countVisible(built.outside), countVisible(built.unpositioned)) + writeJSON(w, &out) +} diff --git a/cmd/server/scope_check_list_test.go b/cmd/server/scope_check_list_test.go new file mode 100644 index 000000000..cdddc57d7 --- /dev/null +++ b/cmd/server/scope_check_list_test.go @@ -0,0 +1,407 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/scopeguide" +) + +// #1035 M3: GET /api/scope-check lists every repeater and room with an +// advertised position in Denmark, each row the same NodeScopeCheck the node +// page (M2, GET /api/nodes/{pubkey}/scope-check) answers for that node. It +// feeds the "Location" view of Scope Audit. Information only. +// +// The seeds are M2's (scSeeds) plus the shapes the M0 report found on the +// live network: a postal-looking default no meshguide scope has (#dk2100 in +// Frederiksberg), a Danish region scope recommended for another part of the +// country (#dk-sjl in Aarhus), a list without dk and with a name that is not +// a meshguide scope (europa), and a local default that is in the list +// (#dk-fyn in Odense). + +const ( + slFrbPK = "5d00000000000000000000000000000000000000000000000000000000000001" // Frederiksberg, default dk2100 + slAarhusSjlPK = "5d00000000000000000000000000000000000000000000000000000000000002" // Aarhus, default dk-sjl + slNoDkListPK = "5d00000000000000000000000000000000000000000000000000000000000003" // Aarhus, list without dk + slOdenseFynPK = "5d00000000000000000000000000000000000000000000000000000000000004" // Odense, default dk-fyn + slHiddenOutPK = "5d00000000000000000000000000000000000000000000000000000000000005" + slHiddenNoPosPK = "5d00000000000000000000000000000000000000000000000000000000000006" +) + +var slSeeds = []scSeed{ + {slFrbPK, "SL Frederiksberg", "repeater", 55.6786, 12.5320, "dk2100", nil, nil, nil}, + {slAarhusSjlPK, "SL Aarhus sjl", "repeater", 56.1500, 10.2000, "dk-sjl", nil, nil, nil}, + {slNoDkListPK, "SL Aarhus list", "room", 56.1600, 10.2050, "dk", "#dk-aarhus,#dk-mj,#europa", "2026-12-02T10:00:00Z", nil}, + {slOdenseFynPK, "SL Odense fyn", "repeater", 55.3900, 10.3800, "dk-fyn", nil, nil, nil}, + // Hidden by name, outside Denmark and without a position: in no count. + {slHiddenOutPK, "ZZhidden Malmo", "repeater", 55.6050, 13.0038, "se", nil, nil, nil}, + {slHiddenNoPosPK, "ZZhidden NoPos", "room", nil, nil, "dk", nil, nil, nil}, +} + +func setupScopeListServer(t *testing.T, mutate func(*Config)) (*Server, http.Handler) { + t.Helper() + srv, h := setupScopeCheckServer(t, mutate) + for _, s := range slSeeds { + 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) + } + } + return srv, h +} + +func getScopeList(t *testing.T, h http.Handler, header map[string]string) (*httptest.ResponseRecorder, ScopeCheckListResponse) { + t.Helper() + req := httptest.NewRequest("GET", "/api/scope-check", nil) + for k, v := range header { + req.Header.Set(k, v) + } + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + var out ScopeCheckListResponse + 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 +} + +// slBaseCounts is the summary of the base test server alone. +func slBaseCounts(t *testing.T) ScopeCheckListSummary { + t.Helper() + srv, _ := setupTestServer(t) + router := mux.NewRouter() + srv.RegisterRoutes(router) + rr, resp := getScopeList(t, router, nil) + mustOK(t, rr) + if resp.Summary.Total != 0 { + t.Fatalf("the base test server lists %d nodes in Denmark; the counts below assume none", resp.Summary.Total) + } + return resp.Summary +} + +func slRow(t *testing.T, resp ScopeCheckListResponse, pk string) ScopeCheckListRow { + t.Helper() + for _, r := range resp.Rows { + if r.Pubkey == pk { + return r + } + } + t.Fatalf("no row for %s", pk) + return ScopeCheckListRow{} +} + +// Which nodes are listed: applicable repeaters and rooms only; companions, +// positionless nodes, nodes outside Denmark, hidden and blacklisted nodes +// are not, and the first three are counted. +func TestScopeCheckListPopulation(t *testing.T) { + _, h := setupScopeListServer(t, nil) + rr, resp := getScopeList(t, h, nil) + mustOK(t, rr) + want := map[string]bool{scOdensePK: true, scRoskildePK: true, scAarhusPK: true, scKbhKPK: true, scRonnePK: true, + scRoomPK: true, scConfirmedPK: true, slFrbPK: true, slAarhusSjlPK: true, slNoDkListPK: true, slOdenseFynPK: true} + got := map[string]bool{} + for _, r := range resp.Rows { + got[r.Pubkey] = true + if !r.Applicable || r.Recommendation.Postnummer == "" { + t.Errorf("row %s (%s) is not an applicable verdict: %+v", r.Name, r.Pubkey, r.Verdict) + } + } + for pk := range want { + if !got[pk] { + t.Errorf("missing row %s", pk) + } + } + for pk := range got { + if !want[pk] { + t.Errorf("unexpected row %s", pk) + } + } + if resp.Summary.Total != len(want) { + t.Errorf("summary.total %d, want %d", resp.Summary.Total, len(want)) + } + // Malmö; NoPos and 0,0, on top of the base test server's own repeaters + // (none of them in Denmark). The companion, hidden and blacklisted + // nodes are in no count. + base := slBaseCounts(t) + if resp.Summary.Outside != base.Outside+1 || resp.Summary.Unpositioned != base.Unpositioned+2 { + t.Errorf("outside %d unpositioned %d, want %d and %d", resp.Summary.Outside, resp.Summary.Unpositioned, base.Outside+1, base.Unpositioned+2) + } + if resp.Source.Name != "meshguide.dk" || resp.Source.Commit == "" || resp.Source.URL == "" { + t.Errorf("source: %+v", resp.Source) + } + if resp.GeneratedAt == "" { + t.Error("generatedAt empty") + } +} + +// Every row is exactly what the node page's endpoint answers for that node: +// one helper, no second verdict. +func TestScopeCheckListRowsEqualNodeEndpoint(t *testing.T) { + _, h := setupScopeListServer(t, nil) + rr, resp := getScopeList(t, h, nil) + mustOK(t, rr) + for _, r := range resp.Rows { + rr1, single := getScopeCheck(t, h, r.Pubkey) + mustOK(t, rr1) + a, _ := json.Marshal(r.NodeScopeCheck) + b, _ := json.Marshal(single.NodeScopeCheck) + if string(a) != string(b) { + t.Errorf("%s: list row\n%s\nnode endpoint\n%s", r.Name, a, b) + } + } +} + +// The M0 findings, as the list reports them (in neutral categories). +func TestScopeCheckListM0Findings(t *testing.T) { + _, h := setupScopeListServer(t, nil) + _, resp := getScopeList(t, h, nil) + + frb := slRow(t, resp, slFrbPK) + if frb.Recommendation.Postnummer != "2000" || frb.Default.Scope != "dk2100" || frb.Default.Status != scopeguide.DefaultNotMeshguide { + t.Errorf("Frederiksberg dk2100: %+v / %+v", frb.Recommendation.Postnummer, frb.Default) + } + sjl := slRow(t, resp, slAarhusSjlPK) + if sjl.Default.Status != scopeguide.DefaultOtherMeshguide { + t.Errorf("dk-sjl in Aarhus: %+v", sjl.Default) + } + noDk := slRow(t, resp, slNoDkListPK) + if !noDk.List.Reported || !scHas(scNames(noDk.List.NotListed, ""), "dk") || !scHas(noDk.List.NotMeshguide, "europa") { + t.Errorf("list without dk: %+v", noDk.List) + } + if noDk.ListReportedAt != "2026-12-02T10:00:00Z" || noDk.Role != "room" || noDk.Name != "SL Aarhus list" { + t.Errorf("row identity/time: %+v", noDk) + } + fyn := slRow(t, resp, slOdenseFynPK) + if fyn.Default.Status != scopeguide.DefaultInList { + t.Errorf("dk-fyn in Odense: %+v", fyn.Default) + } + und := slRow(t, resp, scAarhusPK) + if und.Default.Status != scopeguide.DefaultUndecoded { + t.Errorf("undecodable default: %+v", und.Default) + } + + s := resp.Summary + base := slBaseCounts(t) + // Recommended dk: Odense, NoDkList(room, default dk), Confirmed. + // In list: Roskilde (dk-sjl), Odense fyn, Ronne (dk-bhm), Room (europe). + // Other meshguide: Aarhus sjl. Not meshguide: Frederiksberg. + // Undecoded: Aarhus. None: Kbh K. + want := ScopeCheckListSummary{Total: 11, Outside: base.Outside + 1, Unpositioned: base.Unpositioned + 2, + DefaultRecommended: 3, DefaultInList: 4, DefaultOtherMeshguide: 1, DefaultNotMeshguide: 1, + DefaultUndecoded: 1, DefaultNone: 1, + // Reported: Odense (has dk), Aarhus (has dk), Ronne (empty), NoDkList. + ListReported: 4, ListWithoutDk: 2, ListNotMeshguide: 2} + if s != want { + t.Errorf("summary\n got %+v\nwant %+v", s, want) + } +} + +// Rows come sorted by postnummer, then name, then key: stable for the pager. +func TestScopeCheckListOrder(t *testing.T) { + _, h := setupScopeListServer(t, nil) + _, resp := getScopeList(t, h, nil) + for i := 1; i < len(resp.Rows); i++ { + a, b := resp.Rows[i-1], resp.Rows[i] + ka := a.Recommendation.Postnummer + "\x00" + a.Name + "\x00" + a.Pubkey + kb := b.Recommendation.Postnummer + "\x00" + b.Name + "\x00" + b.Pubkey + if ka > kb { + t.Fatalf("rows out of order at %d: %q before %q", i, ka, kb) + } + } +} + +// One build serves repeated requests (TTL + singleflight); hidden identities +// are filtered per request, also on a cache hit. +func TestScopeCheckListCachedAndHiddenOnHit(t *testing.T) { + srv, h := setupScopeListServer(t, nil) + builds := 0 + srv.scopeCheckList.buildHook = func() { builds++ } + _, first := getScopeList(t, h, nil) + srv.cfg.SetHiddenNamePrefixes([]string{"ZZhidden", "SL Frederiksberg"}) + _, second := getScopeList(t, h, nil) + if builds != 1 { + t.Fatalf("builds = %d, want 1", builds) + } + for _, r := range second.Rows { + if r.Pubkey == slFrbPK { + t.Fatal("a node hidden after the build is still served from the cache") + } + } + if second.Summary.Total != first.Summary.Total-1 || second.Summary.DefaultNotMeshguide != 0 { + t.Fatalf("summary not recomputed for the visible rows: %+v", second.Summary) + } +} + +// scopeCheck.publicList: missing means public; false needs the API key. +func TestScopeCheckListPublicSwitch(t *testing.T) { + off := false + const key = "a-strong-test-key-1035-m3-0123456789abcdef" + _, h := setupScopeListServer(t, func(c *Config) { + c.ScopeCheck = &ScopeCheckConfig{PublicList: &off} + c.APIKey = key + }) + if rr, _ := getScopeList(t, h, nil); rr.Code != http.StatusForbidden { + t.Fatalf("publicList=false without key: %d, want 403", rr.Code) + } + if rr, _ := getScopeList(t, h, map[string]string{"X-API-Key": "wrong"}); rr.Code != http.StatusForbidden { + t.Fatalf("publicList=false with a wrong key: %d, want 403", rr.Code) + } + if rr, _ := getScopeList(t, h, map[string]string{"X-API-Key": key}); rr.Code != http.StatusOK { + t.Fatalf("publicList=false with the key: %d, want 200", rr.Code) + } + // Restricting the list never touches the node page. + if rr, _ := getScopeCheck(t, h, scOdensePK); rr.Code != http.StatusOK { + t.Fatalf("node endpoint with publicList=false: %d, want 200", rr.Code) + } + on := true + _, hOn := setupScopeListServer(t, func(c *Config) { c.ScopeCheck = &ScopeCheckConfig{PublicList: &on} }) + if rr, _ := getScopeList(t, hOn, nil); rr.Code != http.StatusOK { + t.Fatalf("publicList=true: %d", rr.Code) + } + _, hDefault := setupScopeListServer(t, nil) + if rr, _ := getScopeList(t, hDefault, nil); rr.Code != http.StatusOK { + t.Fatalf("publicList missing: %d", rr.Code) + } + // Restricted with no API key configured at all: closed, never open. + _, hNoKey := setupScopeListServer(t, func(c *Config) { c.ScopeCheck = &ScopeCheckConfig{PublicList: &off}; c.APIKey = "" }) + if rr, _ := getScopeList(t, hNoKey, nil); rr.Code != http.StatusForbidden { + t.Fatalf("publicList=false and no apiKey: %d, want 403", rr.Code) + } +} + +// The switch is read from its canonical key only, like every gate (#884). +func TestScopeCheckPublicListConfigKey(t *testing.T) { + cases := []struct { + json string + want bool + }{ + {`{}`, true}, + {`{"scopeCheck":{}}`, true}, + {`{"scopeCheck":{"publicList":true}}`, true}, + {`{"scopeCheck":{"publicList":false}}`, false}, + {`{"scopeCheck":{"PublicList":false}}`, true}, + } + for _, c := range cases { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(c.json), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := LoadConfig(dir) + if err != nil { + t.Fatalf("%s: %v", c.json, err) + } + if got := cfg.ScopeCheckPublicList(); got != c.want { + t.Errorf("%s: ScopeCheckPublicList() = %v, want %v", c.json, got, c.want) + } + } +} + +func TestScopeCheckListGatedByDagi(t *testing.T) { + off := false + _, h := setupScopeListServer(t, func(c *Config) { c.Dagi = &DagiConfig{Enabled: &off} }) + if rr, _ := getScopeList(t, h, nil); rr.Code != http.StatusNotFound { + t.Fatalf("dagi.enabled=false: %d, want 404", rr.Code) + } +} + +// A DB without the scope columns still lists positioned repeaters, each +// with its side unknown. +func TestScopeCheckListPreScopeSchema(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, resp := getScopeList(t, router, nil) + mustOK(t, rr) + r := slRow(t, resp, scPreScopeDBPK) + if r.Default.Status != scopeguide.DefaultNone || r.List.Reported { + t.Fatalf("pre-scope row: %+v", r) + } +} + +func TestScopeCheckListNoInterfaceMaps(t *testing.T) { + src, err := os.ReadFile("scope_check_list.go") + if err != nil { + t.Fatal(err) + } + if regexp.MustCompile(`map\[string\]interface\{\}|map\[string\]any`).Match(src) { + t.Fatal("scope_check_list.go must not use map[string]interface{}") + } +} + +// slBenchRows makes n positioned repeaters spread over Denmark with the +// shapes the live network has (most dk, some local, some with a list). +func slBenchRows(n int) []nodeScopeListRow { + defs := []string{"dk", "dk", "dk", "dk-mj", "", "dk2100", "dk-sjl"} + // Land points: Odense, Roskilde, Aarhus, København, Aalborg, Esbjerg, + // Rønne, Vejle, Hillerød, Næstved; each row a small offset from one. + towns := [][2]float64{{55.3959, 10.3883}, {55.6415, 12.0803}, {56.1572, 10.2107}, {55.6761, 12.5683}, {57.0488, 9.9217}, + {55.4765, 8.4594}, {55.1009, 14.7067}, {55.7093, 9.5357}, {55.9281, 12.3005}, {55.2299, 11.7609}} + out := make([]nodeScopeListRow, n) + for i := range out { + town := towns[i%len(towns)] + lat := town[0] + float64(i%7-3)*0.003 + lon := town[1] + float64(i%11-5)*0.003 + out[i] = nodeScopeListRow{ + pubkey: fmt.Sprintf("%064x", i), name: fmt.Sprintf("bench %d", i), + row: nodeScopeRow{Role: "repeater", Lat: lat, Lon: lon, HasPosition: true, + DefaultKnown: true, DefaultScope: defs[i%len(defs)]}, + } + if i%5 == 0 { + out[i].row.ListKnown, out[i].row.List = true, "*,#dk,#dk-mj,#dk-kb,#dk5000" + } + } + return out +} + +// The build is O(positioned repeaters and rooms): one DAGI point lookup and +// M1's Recommend + Compare per row. 5,000 rows (about 6x the live network's +// positioned repeaters and rooms) must build well inside the 30 s cache. +func TestScopeCheckListBuildBudget(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() + rows := slBenchRows(5000) + buildScopeCheckList(g, idx, rows, time.Now()) // warm + start := time.Now() + resp := &buildScopeCheckList(g, idx, rows, time.Now()).resp + took := time.Since(start) + t.Logf("buildScopeCheckList: %v for %d rows (%d applicable)", took, len(rows), len(resp.Rows)) + if len(resp.Rows) < 4000 { + t.Fatalf("only %d of 5000 bench rows applicable; the bench points left Denmark", len(resp.Rows)) + } + if took > 100*time.Millisecond { + t.Fatalf("buildScopeCheckList took %v for 5000 rows, budget 100ms", took) + } +} + +func BenchmarkScopeCheckList(b *testing.B) { + g, _ := scopeguide.Load() + idx := dagiIndexOrNil() + rows := slBenchRows(5000) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + buildScopeCheckList(g, idx, rows, time.Now()) + } +} diff --git a/config.example.json b/config.example.json index b667694c7..f12d88ca3 100644 --- a/config.example.json +++ b/config.example.json @@ -659,6 +659,10 @@ "enabled": true, "_comment": "#740: the DAGI filters ?kommune=, ?landsdel=, ?dkregion= and ?postnr= (Klimadatastyrelsen's administrative boundaries, embedded in the server) on /api/nodes, /api/packets and every endpoint that takes area, plus GET /api/config/dagi and /api/config/dagi/polygons. Omit this section or enabled to keep the default (true); only the exact key dagi.enabled is read. false turns the filters and both endpoints off and skips the in-memory index (about 7 MB). Requires a server restart." }, + "scopeCheck": { + "publicList": true, + "_comment": "#1035: the Scope Audit Location list (GET /api/scope-check, Analytics > Scopes > Scope Audit > Location): every repeater and room with a position in Denmark next to the scopes meshguide.dk recommends there. Information only. Omit this section or publicList to keep it public (true); only the exact key scopeCheck.publicList is read. false serves the list only with the API key (X-API-Key); the node page's own check stays public. Requires dagi.enabled. Requires a server restart." + }, "observersCache": { "ttlSeconds": 30, "_comment": "TTL for the default-shape /api/observers response cache (#1481 P0-3). Default 30s. Lower = fresher data, more SQL pressure on the 1.9M-row observations table. TTL-boundary refills are collapsed via singleflight so concurrent requests cause exactly one SQL fill. Issue #1483." diff --git a/public/analytics.js b/public/analytics.js index 9132bfa51..bba0e033e 100644 --- a/public/analytics.js +++ b/public/analytics.js @@ -526,7 +526,7 @@ 'rf-health': ['range', 'observer', 'from', 'to'], collisions: ['section'], hashsizes: [HASHSTATS_MB_FILTER.param, HASHSTATS_MB_SORT.param, HASHSTATS_MB_DIR.param], - scopes: [SCOPES_SUBTAB.param, SCOPES_WINDOW.param, 'saq', 'sap', 'sav', 'scope'], + scopes: [SCOPES_SUBTAB.param, SCOPES_WINDOW.param, 'saq', 'sap', 'sav', 'scope', 'slf', 'sls'], wardriving: [WARDRIVING_WINDOW.param], 'repeater-metrics': [BUSIEST_SORT.param, BUSIEST_OBSERVERS.param, BUSIEST_LIMIT.param], // #896 — the open distribution bucket (#896 M1 block below). @@ -5596,9 +5596,9 @@ function destroy() { if (window.AnalyticsDagiAreas) AnalyticsDagiAreas.leave(); }, // #414 — the transport view counts only observers in the global region selection. region: function() { return window.RegionFilter && RegionFilter.getRegionParam ? RegionFilter.getRegionParam() : ''; }, - onState: function(query, page, view, scope) { + onState: function(query, page, view, scope, loc) { var region = view === 'transport' && window.RegionFilter && RegionFilter.getRegionParam ? RegionFilter.getRegionParam() : ''; - history.replaceState(history.state, '', window.ScopeAudit.hashWithState(location.hash, query, page, view, scope, region)); + history.replaceState(history.state, '', window.ScopeAudit.hashWithState(location.hash, query, page, view, scope, region, loc)); } }) : null; _scopeAuditView = auditView; 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..68d8549a2 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 && window.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/scope-audit.js b/public/scope-audit.js index fa2f66c00..135d8ff39 100644 --- a/public/scope-audit.js +++ b/public/scope-audit.js @@ -1,17 +1,66 @@ /* Scope Audit: one bulk request, local search, and a bounded keyed row diff. - * Two views share the controls: declarations (#378) and observed transport - * (#414). Their evidence is kept apart; the transport view never turns - * absence into a configuration verdict. */ + * Three views share the controls: declarations (#378), observed transport + * (#414) and location (#1035 M3: what meshguide.dk recommends where each + * repeater and room stands, next to what it has; information only). Their + * evidence is kept apart; no view turns absence into a configuration verdict. */ (function(root) { 'use strict'; var PAGE_SIZE = 50; function windowValue(value) { return ['1h', '24h', '7d'].indexOf(value) >= 0 ? value : '24h'; } // Firmware matches region names exactly (strcmp); only a leading # is optional. function normalizeScope(value) { return String(value || '').trim().replace(/^#/, '').trim(); } + // #1035 M3 Location view: filters (slf=) and sorts (sls=). Every filter is + // a neutral category of GET /api/scope-check, never a finding. + var LOCATION_FILTERS = [ + { key: '', label: 'All' }, + { key: 'default-elsewhere', label: 'Default scope not in the list for here' }, + { key: 'default-undecoded', label: 'Default scope cannot be decoded' }, + { key: 'default-none', label: 'No scoped flood advert' }, + { key: 'list-reported', label: 'Configured list reported' }, + { key: 'list-without-dk', label: 'Configured list without dk' }, + { key: 'list-not-meshguide', label: 'List has names meshguide.dk does not have' } + ]; + var LOCATION_SORTS = [{ key: '', label: 'Postnummer' }, { key: 'name', label: 'Name' }]; + function pick(list, value) { return list.some(function(o) { return o.key === value; }) ? value : ''; } + function viewValue(value) { return value === 'transport' || value === 'location' ? value : 'declared'; } function stateFromHash(hash) { var p = new URLSearchParams(String(hash || '').split('?')[1] || ''); return { window: windowValue(p.get('swin')), query: p.get('saq') || '', page: Math.max(0, Math.floor(Number(p.get('sap')) || 0)), - view: p.get('sav') === 'transport' ? 'transport' : 'declared', scope: normalizeScope(p.get('scope')) }; + view: viewValue(p.get('sav')), scope: normalizeScope(p.get('scope')), + filter: pick(LOCATION_FILTERS, p.get('slf') || ''), sort: pick(LOCATION_SORTS, p.get('sls') || '') }; + } + function scopeNames(list) { return (list || []).map(function(s) { return s && s.name; }).filter(Boolean).map(String); } + function locationDefault(row) { return (row && row.default && row.default.status) || 'none'; } + function listWithoutDefault(row) { + var l = row && row.list, rec = row && row.recommendation; + return !!(l && l.reported) && scopeNames(l.notListed).indexOf(String((rec && rec.default) || 'dk')) >= 0; + } + var LOCATION_TESTS = { + 'default-elsewhere': function(r) { var d = locationDefault(r); return d === 'other_meshguide' || d === 'not_meshguide'; }, + 'default-undecoded': function(r) { return locationDefault(r) === 'undecoded'; }, + 'default-none': function(r) { return locationDefault(r) === 'none'; }, + 'list-reported': function(r) { return !!(r.list && r.list.reported); }, + 'list-without-dk': listWithoutDefault, + 'list-not-meshguide': function(r) { return !!(r.list && r.list.reported && (r.list.notMeshguide || []).length); } + }; + // Filter, search and sort the Location rows; the server's order is by + // postnummer, name and key, so the default sort keeps it. + function locationRows(rows, state) { + var test = LOCATION_TESTS[state.filter], q = String(state.query || '').trim().toLowerCase(); + var out = rows.filter(function(r) { + if (test && !test(r)) return false; + if (!q) return true; + var rec = r.recommendation || {}, d = r.default || {}, l = r.list || {}; + return [r.name, r.pubkey, rec.postnummer, rec.postnummerName, d.scope].concat(l.listed || [], l.otherMeshguide || [], l.notMeshguide || []) + .join(' ').toLowerCase().indexOf(q) >= 0; + }); + if (state.sort === 'name') { + out.sort(function(a, b) { + var c = String(a.name || '').localeCompare(String(b.name || ''), 'da'); + return c || (String(a.pubkey) < String(b.pubkey) ? -1 : String(a.pubkey) > String(b.pubkey) ? 1 : 0); + }); + } + return out; } function transportPath(state, region) { return '/scope-audit/transport?window=' + encodeURIComponent(windowValue(state.window)) + @@ -63,6 +112,12 @@ 'Compares confirmed observer declarations with forwarding observed in the selected window. A declared scope without observed traffic does not prove a configuration fault. Observer coverage, quiet regions and configuration changes can explain gaps.', 'Short windows may contain little traffic; 7d may span configuration changes. Declarations older than 7d or with an unknown timestamp, unknown scopes and ambiguous hop attribution make the evidence incomplete.'] }, + location: { + columns: ['Node', 'Where it stands', 'Recommended here (meshguide.dk)', 'Default scope', 'Configured scopes'], + intro: ['Every repeater and room with an advertised position in Denmark: the scopes meshguide.dk recommends where it stands, next to the scopes it has. Information only: a node’s operator may have good reasons for scopes that differ from the recommendation.', + 'Default scope is the scope of the node’s own flood adverts. Configured scopes come from an observer report and are shown only when one exists. A scope name this instance cannot decode is shown as such. A recommendation is only as good as the position the node advertises.', + 'meshguide.dk has postal scopes only for Fyn and Sjælland; elsewhere the recommendation is its region scopes and dk. Results are cached for 30 seconds.'] + }, transport: { columns: ['Repeater', 'Declaration (separate)', 'Seen carrying', 'Carrier / non-carrier', 'Transport evidence'], intro: ['Every repeater seen forwarding flood traffic in the selected window, including repeaters never asked for a declaration. Choose a scope to see who was seen carrying it. The global region filter limits the population to observers in those regions; counts, rows and details all use it.', @@ -84,8 +139,9 @@ function add(parent, tag, text, cls) { var el = element(tag, text, cls); parent.appendChild(el); return el; } add(container, 'h3', 'Scope Audit'); var switcher = add(container, 'div', null, 'scope-audit-controls'); - var viewButtons = ['declared', 'transport'].map(function(v) { - var btn = add(switcher, 'button', v === 'declared' ? 'Declarations' : 'Transport', 'tab-btn'); btn.dataset.auditView = v; + var VIEW_LABELS = { declared: 'Declarations', transport: 'Transport', location: 'Location' }; + var viewButtons = ['declared', 'transport', 'location'].map(function(v) { + var btn = add(switcher, 'button', VIEW_LABELS[v], 'tab-btn'); btn.dataset.auditView = v; btn.addEventListener('click', function() { if (state.view === v) return; state.view = v; state.page = 0; save(); return load(state.window); @@ -94,10 +150,25 @@ }); var intro = add(container, 'div'); intro.id = 'scope-audit-intro'; var toolbar = add(container, 'div', null, 'scope-audit-controls'); - ['1h', '24h', '7d'].forEach(function(w) { + var windowButtons = ['1h', '24h', '7d'].map(function(w) { var btn = add(toolbar, 'button', w, 'tab-btn'); btn.dataset.win = w; btn.dataset.auditWindow = 'true'; btn.addEventListener('click', function() { options.onWindow(w); }); + return btn; }); + // Location filter and sort (#1035 M3); the list has no time window. + function selectControl(text, id, list, value, onChange) { + var lab = add(toolbar, 'label', text + ' '); lab.id = id + '-label'; + var sel = add(lab, 'select'); sel.id = id; + list.forEach(function(o) { var opt = add(sel, 'option', o.label); opt.value = o.key; }); + sel.value = value; + sel.addEventListener('change', function() { + if (!active || !container.isConnected) return; + onChange(sel.value); state.page = 0; save(); render(); + }); + return { label: lab, select: sel }; + } + var filterControl = selectControl('Show', 'scope-audit-location-filter', LOCATION_FILTERS, state.filter, function(v) { state.filter = pick(LOCATION_FILTERS, v); }); + var sortControl = selectControl('Sort by', 'scope-audit-location-sort', LOCATION_SORTS, state.sort, function(v) { state.sort = pick(LOCATION_SORTS, v); }); var scopeLabel = add(toolbar, 'label', 'Scope '); scopeLabel.id = 'scope-audit-scope-label'; var scopeInput = add(scopeLabel, 'input'); scopeInput.type = 'search'; scopeInput.id = 'scope-audit-scope'; scopeInput.value = state.scope; scopeInput.placeholder = 'e.g. dk-nord'; scopeInput.setAttribute('list', 'scope-audit-scope-list'); @@ -109,7 +180,8 @@ if (next === state.scope) return; state.scope = next; state.page = 0; save(); return load(state.window); }); - var label = add(toolbar, 'label', 'Search repeaters / scopes '); + var label = add(toolbar, 'label'); label.id = 'scope-audit-search-label'; + var labelText = add(label, 'span', 'Search repeaters / scopes '); var input = add(label, 'input'); input.type = 'search'; input.id = 'scope-audit-search'; input.value = state.query; input.placeholder = 'Name, public key or scope'; var refresh = add(toolbar, 'button', 'Refresh', 'tab-btn'); @@ -135,14 +207,19 @@ view.intro.forEach(function(t) { add(intro, 'p', t, 'text-muted'); }); header.textContent = ''; view.columns.forEach(function(t) { add(header, 'th', t); }); - table.className = 'data-table scope-audit-table' + (state.view === 'transport' ? ' scope-transport-table' : ''); + var location = state.view === 'location'; + table.className = 'data-table scope-audit-table' + (state.view === 'transport' ? ' scope-transport-table' : location ? ' scope-transport-table scope-location-table' : ''); rowNodes.forEach(function(cached) { cached.el.remove(); }); rowNodes.clear(); rows = []; summary.textContent = ''; population.textContent = ''; scopeLabel.hidden = state.view !== 'transport'; - container.classList.toggle('scope-audit-transport', state.view === 'transport'); + windowButtons.forEach(function(b) { b.hidden = location; }); + filterControl.label.hidden = sortControl.label.hidden = !location; + labelText.textContent = location ? 'Search nodes / places / scopes ' : 'Search repeaters / scopes '; + input.placeholder = location ? 'Name, key, postnummer or scope' : 'Name, public key or scope'; + container.classList.toggle('scope-audit-transport', state.view !== 'declared'); viewButtons.forEach(function(b) { b.classList.toggle('active', b.dataset.auditView === state.view); }); } - function save() { options.onState(state.query, state.page, state.view, state.scope); } + function save() { options.onState(state.query, state.page, state.view, state.scope, { filter: state.filter, sort: state.sort }); } previous.addEventListener('click', function() { state.page = Math.max(0, state.page - 1); save(); render(); }); next.addEventListener('click', function() { state.page++; save(); render(); }); input.addEventListener('input', function() { @@ -152,12 +229,54 @@ searchTimer = setTimeout(function() { if (active && container.isConnected) render(); }, 150); }); function cell(tr, labelText) { var td = add(tr, 'td'); td.dataset.label = labelText; return td; } - function nameCell(tr, r) { - var name = cell(tr, 'Repeater'); - var link = add(name, 'a', r.name || String(r.publicKey || '').slice(0, 16)); - link.href = '#/nodes/' + encodeURIComponent(String(r.publicKey || '')); + function nameCell(tr, r, pk) { + var key = String(pk != null ? pk : r.publicKey || ''); + var name = cell(tr, pk != null ? 'Node' : 'Repeater'); + var link = add(name, 'a', r.name || key.slice(0, 16)); + link.href = '#/nodes/' + encodeURIComponent(key); add(name, 'div', r.role || 'Repeater', 'text-muted'); } + function chipList(parent, names, cls) { + var box = add(parent, 'span', null, 'scope-check-chips'); + names.forEach(function(n) { add(box, 'span', n, 'badge-scope' + (cls ? ' ' + cls : '')); }); + return box; + } + function locLine(parent, text, names, cls, testid) { + if (!names.length) return; + var line = add(parent, 'div', null, 'scope-check-line'); line.dataset.testid = testid; + add(line, 'span', text + ': ', 'scope-check-label'); + chipList(line, names, cls); + } + function shortDate(v) { var d = new Date(v); return v && !isNaN(d.getTime()) ? d.toISOString().slice(0, 10) : ''; } + // Wording of the default-scope categories is the node page's (#1035 M2). + function defaultWords(status) { + var nsc = root.NodeScopeCheck; + return nsc && typeof nsc.defaultText === 'function' ? nsc.defaultText(status) : String(status || ''); + } + function locationRowElement(r) { + var pk = String(r.pubkey || ''), rec = r.recommendation || {}, d = r.default || {}, l = r.list || {}; + var tr = element('tr'); tr.dataset.publicKey = pk; + nameCell(tr, r, pk); + var where = cell(tr, 'Where it stands'); + add(where, 'div', [rec.postnummer, rec.postnummerName].filter(Boolean).join(' ')); + if (!rec.postalData) add(where, 'div', 'No postal scopes here', 'text-muted'); + var recommended = cell(tr, 'Recommended here (meshguide.dk)'); + chipList(recommended, scopeNames(rec.scopes)).dataset.testid = 'scope-location-recommended'; + var def = cell(tr, 'Default scope'); def.dataset.testid = 'scope-location-default'; + if (d.status === 'undecoded') add(def, 'span', 'cannot be decoded', 'badge-scope badge-scope-unknown'); + else if (d.scope) add(def, 'span', String(d.scope), 'badge-scope'); + add(def, 'div', defaultWords(d.status), 'scope-check-note'); + var conf = cell(tr, 'Configured scopes'); conf.dataset.testid = 'scope-location-list'; + if (!l.reported) { add(conf, 'div', 'Not reported by an observer', 'scope-check-note'); return tr; } + var listed = (l.listed || []).map(String), notListed = scopeNames(l.notListed); + add(conf, 'div', 'Has ' + listed.length + ' of ' + (listed.length + notListed.length) + ' recommended' + (l.wildcard ? ' · also *' : '')); + locLine(conf, 'Not in the list', notListed, 'scope-check-chip-muted', 'scope-location-not-listed'); + locLine(conf, 'Recommended elsewhere', (l.otherMeshguide || []).map(String), '', 'scope-location-other'); + locLine(conf, 'Not a meshguide.dk scope', (l.notMeshguide || []).map(String), '', 'scope-location-unknown'); + var when = shortDate(r.listReportedAt); + add(conf, 'div', 'Observer report' + (when ? ', ' + when : ''), 'scope-check-note'); + return tr; + } function rowElement(r) { var tr = element('tr'); tr.dataset.publicKey = String(r.publicKey || ''); nameCell(tr, r); @@ -218,28 +337,34 @@ return tr; } function render() { - var transport = state.view === 'transport'; - var filtered = (transport ? searchTransportRows : searchRows)(rows, state.query); + var transport = state.view === 'transport', location = state.view === 'location'; + var filtered = location ? locationRows(rows, state) : (transport ? searchTransportRows : searchRows)(rows, state.query); var pages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); if (state.page >= pages) { state.page = pages - 1; save(); } var visible = filtered.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE); var keep = new Set(); + function rowKey(r) { return String((location ? r.pubkey : r.publicKey) || ''); } visible.forEach(function(r) { - var key = String(r.publicKey || ''); keep.add(key); + var key = rowKey(r); keep.add(key); var signature = responseScope + '|' + JSON.stringify(r), cached = rowNodes.get(key); if (!cached || cached.signature !== signature) { - var tr = (transport ? transportRowElement : rowElement)(r); + var tr = (location ? locationRowElement : transport ? transportRowElement : rowElement)(r); if (cached) tbody.replaceChild(tr, cached.el); cached = { el: tr, signature: signature }; rowNodes.set(key, cached); } }); rowNodes.forEach(function(cached, key) { if (!keep.has(key)) { cached.el.remove(); rowNodes.delete(key); } }); visible.forEach(function(r, index) { - var node = rowNodes.get(String(r.publicKey || '')).el; + var node = rowNodes.get(rowKey(r)).el; if (tbody.children[index] !== node) tbody.insertBefore(node, tbody.children[index] || null); }); - pageLabel.textContent = filtered.length + ' of ' + rows.length + ' repeaters · Page ' + (state.page + 1) + ' of ' + pages; + pageLabel.textContent = filtered.length + ' of ' + rows.length + (location ? ' nodes' : ' repeaters') + ' · Page ' + (state.page + 1) + ' of ' + pages; previous.disabled = state.page === 0; next.disabled = state.page + 1 >= pages; + if (location) { + if (!filtered.length) message.textContent = rows.length ? 'No nodes match this search and filter.' : 'No repeater or room with an advertised position in Denmark.'; + else if (message.dataset.loaded) message.textContent = 'What meshguide.dk recommends where each node stands, next to what it has. Information only.'; + return; + } if (!filtered.length) message.textContent = rows.length ? 'No repeaters match this search.' : transport ? 'No repeater was seen forwarding flood traffic in this window and region.' : 'No confirmed observer declarations available. An unknown declaration is not the same as an empty declaration.'; else if (message.dataset.loaded) message.textContent = 'Observed forwarding in ' + state.window + '. Results are limited to available observer coverage.'; } @@ -263,22 +388,43 @@ scopeList.textContent = ''; (data.scopes || []).forEach(function(sc) { var o = add(scopeList, 'option'); o.value = String(sc.name); }); } + function showLocationSummary(data) { + var s = data.summary || {}; + summary.textContent = count(s.total) + ' repeaters and rooms with a position in Denmark · default scope: ' + + count(s.defaultRecommended) + ' dk (the recommended default) · ' + count(s.defaultInList) + ' in the list for here · ' + + count(s.defaultOtherMeshguide) + ' recommended elsewhere · ' + count(s.defaultNotMeshguide) + ' not a meshguide.dk scope · ' + + count(s.defaultUndecoded) + ' cannot be decoded · ' + count(s.defaultNone) + ' no scoped advert · configured list reported for ' + + count(s.listReported) + ' (' + count(s.listWithoutDk) + ' without dk)'; + population.textContent = 'Not listed: ' + count(s.outside) + ' with a position outside Denmark, ' + count(s.unpositioned) + + ' without an advertised position. Companions and sensors are not checked. '; + var src = data.source || {}; + var a = add(population, 'a', 'meshguide.dk ↗'); + a.href = /^https:\/\//.test(String(src.url || '')) ? String(src.url) : 'https://meshguide.dk/'; + a.setAttribute('target', '_blank'); a.setAttribute('rel', 'noopener noreferrer'); + if (src.commit) add(population, 'span', ' rules at commit ' + String(src.commit).slice(0, 7) + '.'); + var dagi = root.DagiFilter; + var credit = dagi && typeof dagi.creditElement === 'function' ? dagi.creditElement() : null; + if (credit) population.appendChild(credit); + } async function load(w, bust) { state.window = windowValue(w); applyView(); toolbar.querySelectorAll('[data-win]').forEach(function(b) { b.classList.toggle('active', b.dataset.win === state.window); }); var token = ++generation; if (!active) return; - var transport = state.view === 'transport'; + var transport = state.view === 'transport', location = state.view === 'location'; if (transport) save(); // a changed global region reaches the shareable link message.textContent = 'Loading scope audit…'; delete message.dataset.loaded; try { - var path = transport ? transportPath(state, regionParam()) : '/scope-audit?window=' + encodeURIComponent(state.window); + var path = location ? '/scope-check' : transport ? transportPath(state, regionParam()) : '/scope-audit?window=' + encodeURIComponent(state.window); var data = await options.api(path, { ttl: 30000, bust: !!bust, retry503: false }); if (token !== generation || !active || !container.isConnected) return; if (!data || data.error || !Array.isArray(data.rows)) throw new Error(data && data.error || 'Invalid audit response'); rows = data.rows; - if (transport) { + if (location) { + responseScope = ''; + showLocationSummary(data); + } else if (transport) { responseScope = normalizeScope(data.scope); minForwarded = count(data.minForwarded); showTransportSummary(data); } else { @@ -289,25 +435,33 @@ } catch (err) { if (token !== generation || !active || !container.isConnected) return; rows = []; render(); summary.textContent = ''; population.textContent = ''; - message.textContent = 'Failed to load scope audit: ' + String(err.message || err) + '. Use Refresh to retry.'; + message.textContent = location && (err.status === 403 || err.status === 404) + ? (err.status === 403 ? 'The operator keeps this list private.' : 'This list needs the DAGI areas, which are off on this instance.') + : 'Failed to load scope audit: ' + String(err.message || err) + '. Use Refresh to retry.'; } } applyView(); - return { load: load, syncState: function(hash) { clearTimeout(searchTimer); state = stateFromHash(hash); generation++; input.value = state.query; scopeInput.value = state.scope; applyView(); render(); }, setActive: function(value) { active = value; generation++; }, destroy: function() { active = false; generation++; clearTimeout(searchTimer); } }; + return { load: load, syncState: function(hash) { clearTimeout(searchTimer); state = stateFromHash(hash); generation++; input.value = state.query; scopeInput.value = state.scope; filterControl.select.value = state.filter; sortControl.select.value = state.sort; applyView(); render(); }, setActive: function(value) { active = value; generation++; }, destroy: function() { active = false; generation++; clearTimeout(searchTimer); } }; } // Hash after a view-state change. Transport-only params are dropped in the declared view; // a present region= is written back so a copied transport link carries it (#531 syncs only a present region=). - function hashWithState(hash, query, page, view, scope, region) { + // loc ({filter, sort}) is the Location view's state, written only there. + function hashWithState(hash, query, page, view, scope, region, loc) { var parts = String(hash || '').split('?'); var params = new URLSearchParams(parts[1] || ''); if (query) params.set('saq', query); else params.delete('saq'); if (page) params.set('sap', String(page)); else params.delete('sap'); - if (view === 'transport') params.set('sav', view); else params.delete('sav'); + if (view === 'transport' || view === 'location') params.set('sav', view); else params.delete('sav'); + var filter = view === 'location' && loc ? pick(LOCATION_FILTERS, loc.filter || '') : ''; + var sort = view === 'location' && loc ? pick(LOCATION_SORTS, loc.sort || '') : ''; + if (filter) params.set('slf', filter); else params.delete('slf'); + if (sort) params.set('sls', sort); else params.delete('sls'); if (view === 'transport' && scope) params.set('scope', scope); else params.delete('scope'); if (view === 'transport' && region) params.set('region', region); return parts[0] + (params.toString() ? '?' + params.toString() : ''); } var exported = { mount: mount, hashWithState: hashWithState, windowValue: windowValue, stateFromHash: stateFromHash, searchRows: searchRows, searchTransportRows: searchTransportRows, declarationAge: declarationAge, assessment: assessment, - normalizeScope: normalizeScope, transportPath: transportPath, transportEvidence: transportEvidence, pageSize: PAGE_SIZE }; + normalizeScope: normalizeScope, transportPath: transportPath, transportEvidence: transportEvidence, pageSize: PAGE_SIZE, + locationRows: locationRows, listWithoutDefault: listWithoutDefault, locationFilters: LOCATION_FILTERS, locationSorts: LOCATION_SORTS }; if (typeof module !== 'undefined' && module.exports) module.exports = exported; else root.ScopeAudit = exported; })(typeof window !== 'undefined' ? window : globalThis); diff --git a/public/style.css b/public/style.css index b895ff544..304a8b428 100644 --- a/public/style.css +++ b/public/style.css @@ -6809,6 +6809,21 @@ body.embed .warmup-pills { display: none !important; } } /* end #414 */ +/* #1035 M3 Scope Audit "Location" view (scope-audit.js). Information only, + so nothing here uses a status colour; chips are the node page's (M2). */ +.scope-location-table .scope-check-chips .badge-scope { font-size:11px; } +.scope-location-table .badge-scope.scope-check-chip-muted { background:transparent; color:var(--text-muted); box-shadow:inset 0 0 0 1px var(--border); } +.scope-location-table .scope-check-line { margin-top:4px; } +.scope-location-table .scope-check-label { color:var(--text-muted); } +.scope-location-table .scope-check-note { display:block; margin-top:2px; } +#scope-audit-population a { color:var(--link-color, var(--accent)); } +.scope-audit-controls select { max-width:100%; padding:6px 8px; background:var(--bg-secondary); color:var(--text); border:1px solid var(--border); border-radius:4px; } +@media (max-width: 640px) { + .scope-audit-transport .scope-audit-controls label, + .scope-audit-transport .scope-audit-controls select { width:100%; } +} +/* end #1035 M3 */ + /* Regions map: an observed-relay footprint, deliberately distinct from RF coverage. */ .regions-page { display: flex; flex-direction: column; height: 100%; min-height: 420px; padding: 16px; gap: 8px; } .regions-page h1, .regions-page p { margin: 0; } @@ -8042,3 +8057,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 0b9f52e48..447f6d3cd 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -368,7 +368,9 @@ {"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-1023-m2-hidden-hops-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":10,"measurementNote":"New suite; #1023 M2 a hidden node as a relay hop is shown redacted, on its own Go server (ports from 13900, a migrated copy of the fixture with hiddenNamePrefixes [\"🚫\"] and two seeded repeaters, a hidden and a visible one, relaying a channel packet): /api/packets serves the packet with resolved_path [null, visible]; a cold Packets deep link names the visible relay and the page holds neither the hidden key, its 8-char short form, name nor position; on Live a packet written while the page is open arrives over the WebSocket with the hidden hop null (top level and nested packet) and the page does not name it. About 10s locally; no CI duration measured yet. Assigned to shard 2, 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":[]}, + {"file":"test-issue-1035-m3-location-view-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":20,"measurementNote":"New suite; #1035 M3 the Scope Audit Location view on its own Go server through the #1055 harness (tests/e2e-1055-live.js, ports from 13900) seeded with test-fixtures/seed-1035-m3-location-nodes.sql: the cold #/analytics?tab=scopes&sub=audit&sav=location link at 1280x900 light and dark (one /api/scope-check request, the six Danish repeaters and rooms with recommended chips, default wording and observer list, the not-listed counts equal to the API, no time window, markup kept as text, the muted chip on the theme variable); filter, sort and search client-side with slf= and sls= in the URL and a reload restoring the filter; the Location button from Declarations writing sav=location; 375x560 touch light and dark from the Declarations view with a real tap, rows as cards inside the screen and no sideways scroll. 6 cases, about 20s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, + {"file":"test-issue-1023-m2-hidden-hops-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_MIGRATE_BIN":"./corescope-migrate"},"output":"e2e","meanSeconds":10,"measurementNote":"New suite; #1023 M2 a hidden node as a relay hop is shown redacted, on its own Go server (ports from 13900, a migrated copy of the fixture with hiddenNamePrefixes [\"🚫\"] and two seeded repeaters, a hidden and a visible one, relaying a channel packet): /api/packets serves the packet with resolved_path [null, visible]; a cold Packets deep link names the visible relay and the page holds neither the hidden key, its 8-char short form, name nor position; on Live a packet written while the page is open arrives over the WebSocket with the hidden hop null (top level and nested packet) and the page does not name it. About 10s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds.","secondsByExecution":[]} ] } diff --git a/test-1035-node-scope-check.js b/test-1035-node-scope-check.js new file mode 100644 index 000000000..eb2dbe6b5 --- /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 = '