Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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} \
Expand Down
8 changes: 8 additions & 0 deletions cmd/server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions cmd/server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
210 changes: 210 additions & 0 deletions cmd/server/node_scope_check.go
Original file line number Diff line number Diff line change
@@ -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))
}
Loading
Loading