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/ingestor/main_test.go b/cmd/ingestor/main_test.go index c2ef1f5e2..e186e9d92 100644 --- a/cmd/ingestor/main_test.go +++ b/cmd/ingestor/main_test.go @@ -1238,3 +1238,44 @@ func TestHandleMessageAdvert_MatchedScopeUpdatesDefaultScope(t *testing.T) { t.Errorf("default_scope after matched-scope advert = %q (valid=%v), want #de", got.String, got.Valid) } } + +// TestHandleMessageAdvert_UndecodableScopeRowShape pins the row shape the +// server's node scope check (#1035 M2, cmd/server/node_scope_check.go, +// nodeFloodAdvertSQL) reads for "the scope cannot be decoded here": a real +// transport-flood ADVERT whose Code1 matches no configured region is stored +// as route_type 0, payload_type 4, from_pubkey = the advertiser and +// scope_name '' (scopeNameForDB), while nodes.default_scope of a node +// without an earlier named scope stays NULL (#1534 guard). The ingestor +// never writes '' to nodes.default_scope, so the server must take this +// state from transmissions (review F1 on #1106). The E2E seed +// test-fixtures/seed-1035-scope-check-nodes.sql writes rows of this shape. +func TestHandleMessageAdvert_UndecodableScopeRowShape(t *testing.T) { + store := newTestStore(t) + const rawHex = "10AABB00000046D62DE27D4C5194D7821FC5A34A45565DCC2537B300B9AB6275255CEFB65D840CE5C169C94C9AED39E8BCB6CB6EB0335497A198B33A1A610CD3B03D8DCFC160900E5244280323EE0B44CACAB8F02B5B38B91CFA18BD067B0B5E63E94CFC85F758A8530B9240933402E0E6B8F84D5252322D52" + const pubkey = "46d62de27d4c5194d7821fc5a34a45565dcc2537b300b9ab6275255cefb65d84" + if _, err := store.db.Exec(`INSERT INTO nodes (public_key, name) VALUES (?, 'Node1')`, pubkey); err != nil { + t.Fatalf("seed node: %v", err) + } + handleMessage(store, "test", MQTTSource{Name: "test"}, &mockMessage{ + topic: "meshcore/SJC/obs1/packets", + payload: []byte(`{"raw":"` + rawHex + `"}`), + }, nil, map[string][]byte{"#de": []byte("0123456789abcdef")}, &Config{}) + + var route, ptype int + var from, scope sql.NullString + if err := store.db.QueryRow(`SELECT route_type, payload_type, from_pubkey, scope_name FROM transmissions + WHERE from_pubkey = ? ORDER BY id DESC LIMIT 1`, pubkey).Scan(&route, &ptype, &from, &scope); err != nil { + t.Fatalf("read advert: %v", err) + } + if route != 0 || ptype != 4 || from.String != pubkey || !scope.Valid || scope.String != "" { + t.Errorf("undecodable flood advert stored as route=%d payload=%d from=%q scope=%q (valid=%v); want 0, 4, %s, '' (not NULL)", + route, ptype, from.String, scope.String, scope.Valid, pubkey) + } + var def sql.NullString + if err := store.db.QueryRow(`SELECT default_scope FROM nodes WHERE public_key = ?`, pubkey).Scan(&def); err != nil { + t.Fatalf("read default_scope: %v", err) + } + if def.Valid { + t.Errorf("nodes.default_scope = %q after an undecodable advert; want NULL", def.String) + } +} 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..b0c6c91cd --- /dev/null +++ b/cmd/server/node_scope_check.go @@ -0,0 +1,266 @@ +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 default scope (see nodeDefaultEvidence) 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, the node's newest flood +// advert (one probe of idx_transmissions_from_pubkey), 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" + +// Where the default scope shown comes from (NodeScopeCheckResponse.DefaultSource). +const ( + // DefaultSourceConfirmed: the firmware reported its default scope + // (nodes.default_scope_confirmed_at); "*" there is "no default set". + DefaultSourceConfirmed = "confirmed" + // DefaultSourceAdvert: the node's newest flood advert stored here. + DefaultSourceAdvert = "advert" + // DefaultSourceInferred: nodes.default_scope, which the ingestor infers + // from a scoped advert it could name (#1534), when no flood advert of + // the node is stored any more. + DefaultSourceInferred = "inferred" +) + +// NodeScopeCheckSource names where the rules come from. +type NodeScopeCheckSource struct { + Name string `json:"name"` + URL string `json:"url"` + Repo string `json:"repo"` + Commit string `json:"commit"` +} + +// NodeScopeCheckResponse is the endpoint's answer: M1's Verdict plus the +// times of the node-side evidence. +type NodeScopeCheckResponse struct { + Pubkey string `json:"pubkey"` + scopeguide.Verdict + // DefaultSource is where Default comes from (DefaultSource*); empty + // when nothing is known about the node's default scope. + DefaultSource string `json:"defaultSource,omitempty"` + // DefaultConfirmedAt is set when the firmware itself reported the + // default scope (nodes.default_scope_confirmed_at). + DefaultConfirmedAt string `json:"defaultConfirmedAt,omitempty"` + // DefaultAdvertAt is when the newest flood advert was first heard, + // with DefaultSource "advert". + DefaultAdvertAt string `json:"defaultAdvertAt,omitempty"` + // ListReportedAt is when an observer last reported the allow-list. + ListReportedAt string `json:"listReportedAt,omitempty"` + Source NodeScopeCheckSource `json:"source"` +} + +// nodeScopeRow is what the check reads about one node, typed at the +// boundary from its nodes row and its newest flood advert. +type nodeScopeRow struct { + Role string + Lat, Lon float64 + HasPosition bool + // DefaultScope is nodes.default_scope. The ingestor only ever writes a + // scope it could name there (shouldUpdateDefaultScope and + // UpdateNodeDefaultScope skip "", #1534), or the firmware's own report + // (DefaultConfirmedAt set, "*" = no default). It never holds the + // "cannot be decoded" state: that lives in transmissions.scope_name. + DefaultScope string + DefaultConfirmedAt string + // Advert is the node's newest flood advert, when one is stored. + Advert nodeFloodAdvert + // ListKnown: nodes.configured_scope is not NULL (an observer report). + ListKnown bool + List string + ListAt string +} + +// nodeFloodAdvert is a node's newest flood advert (route TRANSPORT_FLOOD or +// FLOOD, payload ADVERT). Its transmissions.scope_name is the ingestor's +// scopeNameForDB: NULL for an unscoped flood, "" for a transport code this +// instance has no region name for, "#name" for a named one. +type nodeFloodAdvert struct { + Seen bool + Scoped bool // scope_name not NULL + Scope string // scope_name ("" = cannot be decoded here) + At string // first_seen +} + +// nodeFloodAdvertSQL reads a node's newest flood advert. The "+" keeps the +// planner on idx_transmissions_from_pubkey (only ADVERTs carry from_pubkey, +// #1143) instead of the payload_type index, which would walk every advert. +// Ordered by ingest id, not first_seen (#1345). +const nodeFloodAdvertSQL = `SELECT scope_name, first_seen FROM transmissions + WHERE from_pubkey = ? AND +payload_type = 4 AND +route_type IN (0, 1) + ORDER BY id DESC LIMIT 1` + +// nodeFloodAdvert returns the newest flood advert of pubkey. A DB without +// transmissions.scope_name (#899) cannot tell, so it reads as none seen. +func (db *DB) nodeFloodAdvert(pubkey string) (nodeFloodAdvert, error) { + var a nodeFloodAdvert + if !db.hasScopeName() { + return a, nil + } + var scope, at sql.NullString + err := db.conn.QueryRow(nodeFloodAdvertSQL, pubkey).Scan(&scope, &at) + if err == sql.ErrNoRows { + return a, nil + } + if err != nil { + return a, err + } + a.Seen, a.Scoped, a.Scope, a.At = true, scope.Valid, scope.String, at.String + return a, nil +} + +// nodeDefaultEvidence picks the evidence for a node's default scope, +// strongest first (owner decision 9 on #1035, review F1 on #1106): +// 1. the firmware's own report (default_scope_confirmed_at): the ingestor +// never lets inference overwrite it, and neither does this; +// 2. the newest flood advert: unscoped = no default, scoped with a code +// this instance cannot name = "cannot be decoded", else its name; +// 3. nodes.default_scope, inferred from an older named advert; +// 4. nothing known (source ""). +func nodeDefaultEvidence(row nodeScopeRow) (node scopeguide.Node, source string) { + switch { + case strings.TrimSpace(row.DefaultConfirmedAt) != "": + node.DefaultScope, source = row.DefaultScope, DefaultSourceConfirmed + case row.Advert.Seen: + source = DefaultSourceAdvert + if row.Advert.Scoped { + node.DefaultScope = row.Advert.Scope + node.DefaultUndecoded = strings.TrimSpace(row.Advert.Scope) == "" + } + case strings.TrimSpace(row.DefaultScope) != "": + node.DefaultScope, source = row.DefaultScope, DefaultSourceInferred + } + return node, source +} + +// nodeScopeRow reads one node's row by primary key, typed at the +// boundary. The scope columns are optional (#899, #1865): a DB without them +// reads as "not known". ok is false when there is no such node. +func (db *DB) nodeScopeRow(pubkey string) (row nodeScopeRow, name string, ok bool, err error) { + cols := "name, role, lat, lon" + var nm, role, def, list, listAt, defAt sql.NullString + var lat, lon sql.NullFloat64 + args := []interface{}{&nm, &role, &lat, &lon} + if db.hasDefaultScope() { + cols += ", default_scope" + args = append(args, &def) + } + if db.hasConfiguredScope() { + cols += ", configured_scope, configured_scope_at" + args = append(args, &list, &listAt) + } + if db.hasDefaultScopeConfirmedAt() { + cols += ", default_scope_confirmed_at" + args = append(args, &defAt) + } + err = db.conn.QueryRow("SELECT "+cols+" FROM nodes WHERE public_key = ?", pubkey).Scan(args...) + if err == sql.ErrNoRows { + return row, "", false, nil + } + if err != nil { + return row, "", false, err + } + row.Role = role.String + if lat.Valid && lon.Valid && isValidNodePosition(lat.Float64, lon.Float64) { + row.Lat, row.Lon, row.HasPosition = lat.Float64, lon.Float64, true + } + row.DefaultScope = def.String + row.DefaultConfirmedAt = defAt.String + row.List, row.ListKnown = list.String, list.Valid + row.ListAt = listAt.String + return row, nm.String, true, nil +} + +// buildNodeScopeCheck is the pure part of the endpoint. +func buildNodeScopeCheck(g *scopeguide.Guide, idx *dagiIndex, pubkey string, row nodeScopeRow) NodeScopeCheckResponse { + var rec scopeguide.Recommendation + if row.HasPosition { + if p := idx.Lookup(row.Lat, row.Lon).Postnummer; p != nil { + rec = g.Recommend(row.Lat, row.Lon, p.Code) + } + } + node, source := nodeDefaultEvidence(row) + node.Role, node.Configured, node.ConfiguredReported = row.Role, row.List, row.ListKnown + v := g.Compare(rec, node) + if v.NotApplicable == scopeguide.NotApplicableOutside && !row.HasPosition { + v.NotApplicable = NotApplicablePosition + } + up := g.Upstream() + out := NodeScopeCheckResponse{ + Pubkey: pubkey, + Verdict: v, + Source: NodeScopeCheckSource{Name: "meshguide.dk", URL: meshguideScopesURL, Repo: up.Repo, Commit: up.Commit}, + } + if v.Applicable { + out.DefaultSource = source + switch source { + case DefaultSourceConfirmed: + out.DefaultConfirmedAt = row.DefaultConfirmedAt + case DefaultSourceAdvert: + out.DefaultAdvertAt = row.Advert.At + } + if v.List.Reported { + out.ListReportedAt = row.ListAt + } + } + return out +} + +func (s *Server) handleNodeScopeCheck(w http.ResponseWriter, r *http.Request) { + idx := s.dagiIndex() + if idx == nil { + writeError(w, http.StatusNotFound, "Not found") + return + } + pubkey := strings.ToLower(mux.Vars(r)["pubkey"]) + if !isHexPubkey(pubkey) { + writeError(w, http.StatusBadRequest, "invalid pubkey: expected 64 hex chars") + return + } + if s.cfg.IsBlacklisted(pubkey) { + writeError(w, http.StatusNotFound, "Not found") + return + } + g, err := scopeguide.Load() + if err != nil { + writeError(w, http.StatusServiceUnavailable, "scope guide unavailable") + return + } + row, name, found, err := s.db.nodeScopeRow(pubkey) + if err != nil { + writeError(w, http.StatusInternalServerError, "query failed") + return + } + if !found || s.cfg.IsNameHidden(name) { + writeError(w, http.StatusNotFound, "Not found") + return + } + if row.Advert, err = s.db.nodeFloodAdvert(pubkey); err != nil { + writeError(w, http.StatusInternalServerError, "query failed") + 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..7f1e55347 --- /dev/null +++ b/cmd/server/node_scope_check_test.go @@ -0,0 +1,530 @@ +package main + +import ( + "encoding/json" + "fmt" + "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 + scUnscopedPK = "5c00000000000000000000000000000000000000000000000000000000000010" // newest flood advert unscoped + scStarPK = "5c00000000000000000000000000000000000000000000000000000000000011" // firmware reported "*" +) + +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}, + // default_scope NULL: what the ingestor leaves after an undecodable advert. + {scAarhusPK, "SC Aarhus", "repeater", 56.1572, 10.2107, nil, "#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"}, + {scUnscopedPK, "SC Unscoped", "repeater", 56.1572, 10.2107, "#dk", nil, nil, nil}, + {scStarPK, "SC Star", "repeater", 56.1572, 10.2107, "*", nil, nil, "2026-12-02T11:00:00Z"}, +} + +// scAdvert is a transmissions row as the ingestor stores it +// (BuildPacketData + scopeNameForDB, pinned by the ingestor's +// TestHandleMessageAdvert_UndecodableScopeRowShape): route 0 TRANSPORT_FLOOD, +// 1 FLOOD, 2 DIRECT; payload 4 ADVERT; scope NULL = not transport-scoped, +// "" = a code this instance has no name for. Inserted in slice order, so a +// later row has the higher id (= newer, #1345). +type scAdvert struct { + pk string + route, ptyp int + scope interface{} + at string +} + +var scAdverts = []scAdvert{ + // Odense: an older unscoped flood, then a named one. + {scOdensePK, 1, 4, nil, "2026-12-01T09:00:00Z"}, + {scOdensePK, 0, 4, "#dk", "2026-12-02T09:00:00Z"}, + // Aarhus: a named flood, then one this instance cannot name (the + // newest flood advert), then a newer direct advert and a non-advert + // row, which do not count. + {scAarhusPK, 0, 4, "#dk-aarhus", "2026-12-01T09:00:00Z"}, + {scAarhusPK, 0, 4, "", "2026-12-02T07:30:00Z"}, + {scAarhusPK, 2, 4, nil, "2026-12-02T10:00:00Z"}, + {scAarhusPK, 1, 5, nil, "2026-12-02T10:30:00Z"}, + // Unscoped: default_scope still holds an older inference; the newest + // flood advert is unscoped. + {scUnscopedPK, 0, 4, "#dk", "2026-12-01T09:00:00Z"}, + {scUnscopedPK, 1, 4, nil, "2026-12-02T09:30:00Z"}, + // Star: the firmware's "*" outranks a newer advert. + {scStarPK, 0, 4, "", "2026-12-02T12:30: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) + } + } + if _, err := srv.db.conn.Exec(`ALTER TABLE transmissions ADD COLUMN scope_name TEXT`); err != nil { + t.Fatalf("alter transmissions add scope_name: %v", err) + } + srv.db.detectSchema() + for i, a := range scAdverts { + if _, err := srv.db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, from_pubkey, scope_name) + VALUES ('10', ?, ?, ?, ?, ?, ?)`, fmt.Sprintf("5c%014d", i), a.at, a.route, a.ptyp, a.pk, a.scope); err != nil { + t.Fatalf("seed advert %d: %v", i, err) + } + } + 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) + } + if v.DefaultSource != DefaultSourceAdvert || v.DefaultAdvertAt != "2026-12-02T09:00:00Z" || v.DefaultConfirmedAt != "" { + t.Errorf("default from the newest flood advert: source %q advertAt %q confirmedAt %q", v.DefaultSource, v.DefaultAdvertAt, v.DefaultConfirmedAt) + } + 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) + } + // No flood advert stored: the ingestor's inference (nodes.default_scope). + if v.DefaultSource != DefaultSourceInferred || v.DefaultAdvertAt != "" || v.DefaultConfirmedAt != "" { + t.Errorf("inferred default: source %q advertAt %q confirmedAt %q", v.DefaultSource, v.DefaultAdvertAt, v.DefaultConfirmedAt) + } + 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) + } + // The newest flood advert carries scope_name '' (a transport code this + // instance cannot name); nodes.default_scope is NULL, as the ingestor + // leaves it. The newer direct advert and non-advert row do not count. + if v.Default.Status != scopeguide.DefaultUndecoded || v.Default.Scope != "" { + t.Errorf("newest flood advert with scope_name '' must be undecoded: %+v", v.Default) + } + if v.DefaultSource != DefaultSourceAdvert || v.DefaultAdvertAt != "2026-12-02T07:30:00Z" { + t.Errorf("undecoded default: source %q advertAt %q", v.DefaultSource, v.DefaultAdvertAt) + } +} + +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 || v.DefaultSource != "" || v.DefaultAdvertAt != "" || v.DefaultConfirmedAt != "" { + t.Errorf("no advert and NULL default_scope must be none, source unknown: %+v", v) + } +} + +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) + } + if v.DefaultSource != DefaultSourceInferred { + t.Errorf("room default source %q", v.DefaultSource) + } + rr, v = getScopeCheck(t, h, scConfirmedPK) + mustOK(t, rr) + if v.DefaultConfirmedAt != "2026-12-02T12:00:00Z" || v.DefaultSource != DefaultSourceConfirmed || v.DefaultAdvertAt != "" { + t.Errorf("confirmed default: time %q source %q advertAt %q", v.DefaultConfirmedAt, v.DefaultSource, v.DefaultAdvertAt) + } +} + +// The newest flood advert outranks an older inference in nodes.default_scope: +// a node that now floods unscoped has no default scope. +func TestScopeCheckNewestFloodAdvertUnscoped(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scUnscopedPK) + mustOK(t, rr) + if v.Default.Status != scopeguide.DefaultNone || v.Default.Scope != "" { + t.Errorf("unscoped newest flood advert: %+v", v.Default) + } + if v.DefaultSource != DefaultSourceAdvert || v.DefaultAdvertAt != "2026-12-02T09:30:00Z" || v.DefaultConfirmedAt != "" { + t.Errorf("unscoped: source %q advertAt %q confirmedAt %q", v.DefaultSource, v.DefaultAdvertAt, v.DefaultConfirmedAt) + } +} + +// The firmware's own "*" ("no default region set") is a report: status +// none, with its time, and it outranks a newer advert, as in the ingestor. +func TestScopeCheckConfirmedStar(t *testing.T) { + _, h := setupScopeCheckServer(t, nil) + rr, v := getScopeCheck(t, h, scStarPK) + mustOK(t, rr) + if v.Default.Status != scopeguide.DefaultNone { + t.Errorf("confirmed *: %+v", v.Default) + } + if v.DefaultSource != DefaultSourceConfirmed || v.DefaultConfirmedAt != "2026-12-02T11:00:00Z" || v.DefaultAdvertAt != "" { + t.Errorf("confirmed *: source %q confirmedAt %q advertAt %q", v.DefaultSource, v.DefaultConfirmedAt, v.DefaultAdvertAt) + } +} + +// nodeDefaultEvidence is the whole precedence; the table pins each step. +func TestNodeDefaultEvidence(t *testing.T) { + for _, c := range []struct { + name string + row nodeScopeRow + scope string + undecoded bool + source string + }{ + {"nothing", nodeScopeRow{}, "", false, ""}, + {"inferred", nodeScopeRow{DefaultScope: "#dk"}, "#dk", false, DefaultSourceInferred}, + {"blank inferred is nothing", nodeScopeRow{DefaultScope: " "}, "", false, ""}, + {"advert named", nodeScopeRow{DefaultScope: "#old", Advert: nodeFloodAdvert{Seen: true, Scoped: true, Scope: "#dk"}}, "#dk", false, DefaultSourceAdvert}, + {"advert undecoded", nodeScopeRow{Advert: nodeFloodAdvert{Seen: true, Scoped: true}}, "", true, DefaultSourceAdvert}, + {"advert unscoped", nodeScopeRow{DefaultScope: "#old", Advert: nodeFloodAdvert{Seen: true}}, "", false, DefaultSourceAdvert}, + {"confirmed wins", nodeScopeRow{DefaultScope: "*", DefaultConfirmedAt: "2026-12-02T11:00:00Z", Advert: nodeFloodAdvert{Seen: true, Scoped: true, Scope: "#dk"}}, "*", false, DefaultSourceConfirmed}, + } { + n, src := nodeDefaultEvidence(c.row) + if n.DefaultScope != c.scope || n.DefaultUndecoded != c.undecoded || src != c.source { + t.Errorf("%s: scope %q undecoded %v source %q; want %q %v %q", c.name, n.DefaultScope, n.DefaultUndecoded, src, c.scope, c.undecoded, c.source) + } + } +} + +// The advert read must stay on the from_pubkey index, never a walk of all +// adverts through the payload_type index. +func TestNodeFloodAdvertUsesPubkeyIndex(t *testing.T) { + srv, _ := setupScopeCheckServer(t, nil) + for _, q := range []string{ + `CREATE INDEX IF NOT EXISTS idx_transmissions_payload_type ON transmissions(payload_type)`, + `CREATE INDEX IF NOT EXISTS idx_transmissions_from_pubkey ON transmissions(from_pubkey)`, + } { + if _, err := srv.db.conn.Exec(q); err != nil { + t.Fatal(err) + } + } + rows, err := srv.db.conn.Query("EXPLAIN QUERY PLAN "+nodeFloodAdvertSQL, scAarhusPK) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var plan []string + for rows.Next() { + var id, parent, unused int + var detail string + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { + t.Fatal(err) + } + plan = append(plan, detail) + } + if got := strings.Join(plan, " | "); !strings.Contains(got, "idx_transmissions_from_pubkey") { + t.Fatalf("plan %q does not use idx_transmissions_from_pubkey", got) + } +} + +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, + 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, + 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 5a2550741..435ac2398 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 default scope and, when an observer reported it, its configured allow-list. defaultSource says where the default comes from: confirmed (the firmware reported it, defaultConfirmedAt; * = none set), advert (the newest flood advert, defaultAdvertAt: unscoped = none, a transport code this instance has no region name for = undecoded) or inferred (nodes.default_scope from an earlier named advert); absent when nothing is known. Information only, never a verdict on the node. applicable is false with notApplicable role (companion, sensor), position (no advertised position) or outside (not in a DAGI postnummer). Rules from the vendored meshguide.dk commit named in source. 404 for an unknown, hidden or blacklisted node and while dagi.enabled is off.", Tag: "nodes"}, "GET /api/nodes/{pubkey}/declared-regions": {Summary: "Declared-region reports for a node", Description: "Issue #126. The regions this repeater told mobile collectors it lets flood, one report per answer, newest reported_at first, at most 100 (truncated=true when older reports exist). Each report: collector (an opaque number valid only within this response; collector keys and positions are never served), regions ([] = the repeater answered and floods nothing, with empty=true), truncated (the app's hint), reported_at (collector clock), ingested_at (ingest clock), repeater_clock (the repeater's RTC seconds as reported, or null), has_position. Reports are the collectors' claims, not authoritative. 404 unless clientRegions.enabled; 400 for a key that is not 64 hex; 404 for a blacklisted or hidden node. See docs/client-regions.md.", Tag: "nodes"}, "GET /api/reach-rank": {Summary: "Reach leaderboard", Description: "Nodes ranked by all-time neighbour count: distinct neighbours over valid neighbor_edges rows (both endpoints 64-hex pubkeys, not equal; within the ingestor's edge retention) — a historical count, not a measure of radio quality, range or traffic. Only nodes with a Reach page (node row, or named observer row) that are not blacklisted or hidden are ranked. Rank is competition ranking (1, 1, 3) with ties listed in pubkey order; a search or page never renumbers. Served from a shared snapshot (60s TTL, refreshed in the background) that also backs the Rank on /api/nodes/{pubkey}/reach; snapshot_at is when it was read.", Tag: "nodes", QueryParams: []paramMeta{ diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 1a5daec78..66d7e1441 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -504,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/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..763af604c --- /dev/null +++ b/public/node-scope-check.js @@ -0,0 +1,233 @@ +/* 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 default scope: the firmware's own report, else + * its newest flood advert, else the ingestor's inference from an older one; + * 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, after the DAGI config (one per + * page session, shared with every DAGI page): it says whether DAGI is on + * (off: no request, no card) and gives the credit line, however the page + * was reached. 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: 'scoped with a region this instance has no name for', + none: 'no default scope' + }; + + 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; + } + + /** defaultValue is the "Default scope" row: the scope (or "cannot be + * decoded"), how it relates to the recommendation and where it comes + * from (data.defaultSource, cmd/server/node_scope_check.go: the node's + * own report, its newest flood advert or an earlier scoped advert). */ + function defaultValue(data) { + var box = el('span'); + var d = data.default || {}; + var status = d.status; + var src = data.defaultSource; + var advertAt = data.defaultAdvertAt ? ' (' + shortDate(data.defaultAdvertAt) + ')' : ''; + var text, from = ''; + if (status === 'none' && !src) { + text = 'Not known: no flood advert from this node is stored here.'; + } else if (status === 'none' && src === 'advert') { + text = 'no default scope: the newest flood advert' + advertAt + ' was not scoped'; + } else if (status === 'undecoded' && src === 'advert') { + text = 'the newest flood advert' + advertAt + ' was scoped with a region this instance has no name for'; + } else { + text = defaultText(status); + if (src === 'confirmed') from = 'reported by the node' + (data.defaultConfirmedAt ? ', ' + shortDate(data.defaultConfirmedAt) : ''); + else if (src === 'advert') from = 'newest flood advert' + (data.defaultAdvertAt ? ', ' + shortDate(data.defaultAdvertAt) : ''); + else if (src === 'inferred') from = 'from an earlier scoped advert'; + } + if (status === 'undecoded') box.appendChild(el('span', 'badge-scope badge-scope-unknown', 'cannot be decoded')); + else if (d.scope) box.appendChild(el('span', 'badge-scope', d.scope)); + box.appendChild(el('span', 'scope-check-note', (box.firstChild ? ' ' : '') + text)); + if (from) box.appendChild(el('span', 'scope-check-note', ' (' + from + ')')); + 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), '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; + } + + /** dagiOn resolves whether DAGI is on, with its config (and so its + * credit) loaded: DagiFilter.enabled() fetches /api/config/dagi once per + * page session, so a cold deep link gets the credit too (review F3 on + * #1106) and an instance with DAGI off makes no /scope-check request + * (F7). Without DagiFilter the server's 404 decides. */ + function dagiOn() { + var D = root.DagiFilter; + if (!D || typeof D.enabled !== 'function') return Promise.resolve(true); + return D.enabled(); + } + + /** 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 dagiOn() + .then(function (on) { return on ? load(pk) : null; }) + .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/style.css b/public/style.css index b895ff544..f7e6609e3 100644 --- a/public/style.css +++ b/public/style.css @@ -8042,3 +8042,26 @@ body.embed .warmup-pills { display: none !important; } .st-an-stations .st-an-group { white-space: normal; } } /* end #1017 M7 */ + +/* #1035 M2 "Recommended scopes here (meshguide.dk)" (node-scope-check.js). + Information only, so nothing here uses a status colour. */ +.scope-check { font-size: 13px; color: var(--text); overflow-wrap: anywhere; } +.scope-check h4 .scope-check-note { text-transform: none; letter-spacing: 0; } +.scope-check h5 { margin: 12px 0 6px; font-size: 13px; color: var(--text); } +.scope-check-lead { margin: 0 0 6px; } +.scope-check-chips { display: inline-flex; flex-wrap: wrap; gap: 4px; vertical-align: middle; max-width: 100%; } +.scope-check-chips .badge-scope { font-size: 11px; } +.scope-check .badge-scope.scope-check-chip-muted { background: transparent; color: var(--text-muted); box-shadow: inset 0 0 0 1px var(--border); } +.scope-check-note { color: var(--text-muted); font-size: 12px; } +p.scope-check-note { margin: 6px 0 0; } +.scope-check-have { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 12px; margin: 0; } +.scope-check-have dt { color: var(--text-muted); } +.scope-check-have dd { margin: 0; min-width: 0; } +.scope-check-line { margin-top: 4px; } +.scope-check-label { color: var(--text-muted); } +.scope-check-foot a { color: var(--link-color, var(--accent)); } +@media (max-width: 480px) { + .scope-check-have { grid-template-columns: minmax(0, 1fr); gap: 2px; } + .scope-check-have dd { margin-bottom: 8px; } +} +/* end #1035 M2 */ diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 0b9f52e48..4b515b568 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -369,6 +369,7 @@ {"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":[]} ] } diff --git a/test-1035-node-scope-check.js b/test-1035-node-scope-check.js new file mode 100644 index 000000000..7dde0072a --- /dev/null +++ b/test-1035-node-scope-check.js @@ -0,0 +1,358 @@ +/** + * 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: 'scoped with a region this instance has no name for', + none: 'no default scope', + }; + 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 }, defaultSource: 'inferred' })), 'scope-check-default'); + assert.ok(def.textContent.endsWith(text + ' (from an earlier scoped advert)'), status + ': ' + def.textContent); + assert.strictEqual(M.defaultText(status), text); + } + assert.strictEqual(M.defaultText('bogus'), want.none); + assert.strictEqual(M.defaultText('constructor'), want.none, 'no prototype keys'); +}); + +// The server's answer for a newest flood advert with scope_name '' (the +// ingestor's "cannot be decoded", review F1 on #1106). +test('render: an undecodable newest flood advert reads "cannot be decoded" once, with its date', () => { + const { M } = world(); + const def = byTestId(M.render(answer({ default: { status: 'undecoded' }, defaultSource: 'advert', defaultAdvertAt: '2026-12-02T07:30:00Z' })), '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')); + assert.strictEqual(def.textContent, 'cannot be decoded the newest flood advert (2026-12-02) was scoped with a region this instance has no name for'); + assert.strictEqual(def.textContent.split('decoded').length, 2, 'said once (F6)'); +}); + +test('render: each source of the default says where it comes from', () => { + const { M } = world(); + const def = (over) => byTestId(M.render(answer(over)), 'scope-check-default').textContent; + assert.strictEqual(def({ defaultSource: 'advert', defaultAdvertAt: '2026-12-02T09:00:00Z' }), 'dk the recommended default scope (newest flood advert, 2026-12-02)'); + assert.strictEqual(def({ defaultSource: 'inferred' }), 'dk the recommended default scope (from an earlier scoped advert)'); + assert.strictEqual(def({ defaultSource: 'confirmed', defaultConfirmedAt: '2026-12-02T12:00:00Z' }), 'dk the recommended default scope (reported by the node, 2026-12-02)'); + // The firmware's "*". + assert.strictEqual(def({ default: { status: 'none' }, defaultSource: 'confirmed', defaultConfirmedAt: '2026-12-02T11:00:00Z' }), 'no default scope (reported by the node, 2026-12-02)'); + assert.strictEqual(def({ default: { status: 'none' }, defaultSource: 'advert', defaultAdvertAt: '2026-12-02T09:30:00Z' }), 'no default scope: the newest flood advert (2026-12-02) was not scoped'); + assert.strictEqual(def({ default: { status: 'none' } }), 'Not known: no flood advert from this node is stored here.'); +}); + +// Review R4 on #1106: a confirmation time is only shown with the node's own +// report, never next to a default from an advert or an unknown one. +test('render: a confirmation time only with the node\'s own report', () => { + const { M } = world(); + for (const over of [ + { default: { status: 'none' }, defaultConfirmedAt: '2026-12-02T12:00:00Z' }, + { default: { status: 'none' }, defaultSource: 'advert', defaultConfirmedAt: '2026-12-02T12:00:00Z' }, + { defaultSource: 'advert', defaultConfirmedAt: '2026-12-02T12:00:00Z' }, + { defaultSource: 'inferred', defaultConfirmedAt: '2026-12-02T12:00:00Z' }, + ]) { + const t = byTestId(M.render(answer(over)), 'scope-check-default').textContent; + assert.ok(!/reported by the node/.test(t), JSON.stringify(over) + ': ' + t); + } +}); + +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 = '