Files
meshcore-analyzer/cmd/server/node_resolve.go
T
efiten 22fe929da2 feat: opt-in mobile client-RX coverage (crowdsourced RF reach) + /api/nodes/resolve (#1728)
Implements #1727.

## What this adds

**Mobile client-RX coverage** — an opt-in, crowdsourced RF-coverage
feature. A roaming MeshCore **companion** radio (driven by the
open-source [corescope-rx](https://github.com/efiten/corescope-rx) PWA,
GPLv3) reports which nodes it heard directly, tagged with the phone's
GPS and the packet's SNR/RSSI. CoreScope ingests these into a new
`client_receptions` table and renders per-node **hex coverage** on the
Reach page, plus a standalone **Coverage dashboard** (`#/rx-coverage`)
with a top-mobile-observers leaderboard.

Also includes **`GET /api/nodes/resolve?prefix=<hex>`** — a read-only
node-name lookup by pubkey prefix (`{name, pubkey, ambiguous}`), used by
the companion app for friendly names.

## Opt-in — default OFF (zero impact on existing deployments)

The whole feature is gated behind one config flag, **disabled by
default**:

```jsonc
"clientRxCoverage": { "enabled": false }
```

When disabled (the default): the ingestor writes **no**
`client_receptions`; the three coverage endpoints return a clean
**404**; the UI hides the Coverage nav link, the `#/rx-coverage` route,
and the Reach-page toggle. `/api/nodes/resolve` is always available (not
coverage-specific).

## How it works

```
companion ──BLE 0x88 (snr+rssi+raw)──▶ corescope-rx PWA ──▶ MQTT meshcore/client/{pubkey}/packets
                                                                      │
                                          ingestor (gated) ──▶ client_receptions (GPS + SNR + heard-key)
                                                                      │
              server: pure-Go hex grid ──▶ GeoJSON ──▶ Reach hex overlay + Coverage dashboard
```

- **Direct-only capture:** records only what the companion heard itself
and directly — a 0-hop advert's pubkey, or `path[last]` (last forwarder)
for FLOOD routes; ≥2-byte path-hash required. Upstream hops discarded.
- **No new deps:** hexbins are a pure-Go pointy-top grid over Web
Mercator (`cmd/server/hexgrid.go`) computed at query time
(`CGO_ENABLED=0` / `modernc.org/sqlite` friendly); frontend uses the
existing Leaflet.
- **Trust:** companion pubkey = identity; an EMQX ACL binds each client
to publish only to its own `meshcore/client/{pubkey}/packets` topic.
Payload contract in `docs/client-rx-coverage.md`.

## How to enable / try it

1. In `config.json`, set `"clientRxCoverage": { "enabled": true }` and
restart server + ingestor.
2. Point an EMQX (or any broker) listener so a client can publish to
`meshcore/client/<pubkey>/packets`; the ingestor already subscribes
under `meshcore/#`.
3. Run the [corescope-rx](https://github.com/efiten/corescope-rx) PWA on
an Android phone paired (BLE) to a MeshCore companion — it captures
heard nodes + GPS and publishes.
4. View results: per-node Reach page → toggle **coverage**, or the
**Coverage** dashboard at `#/rx-coverage`.

## What's where

- **Ingestor:** `cmd/ingestor/client_reception.go` (ingest), `db.go`
(`client_receptions` + `client_observers` schema), `main.go` (gated
dispatch), `config.go` (flag).
- **Server:** `cmd/server/rx_coverage.go` + `rx_dashboard.go`
(endpoints, self-guard 404 when off), `hexgrid.go` (pure-Go grid),
`node_resolve.go` (resolve), `routes.go` / `types.go` / `config.go`
(wiring + flag + `/api/config/client` field).
- **Frontend:** `public/rx-coverage.js` (dashboard),
`node-reach-coverage.js` + `.css` (overlay), `node-reach.js` (Reach
toggle, flag-gated), `roles.js` (reads the flag, hides nav when off).
- **Docs:** `docs/client-rx-coverage.md`.

## Testing

- Go: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test
./...` — green, including new gate tests (`coverage_gate_test.go` in
both: off → no rows / 404, on → works) and the rx-coverage / resolve /
hexgrid suites.
- JS: `node test-coverage-gate.js`, `node test-node-reach-coverage.js`
(wired into CI). The Playwright `test-node-reach-coverage-e2e.js` is
wired into the e2e job and **skips when `clientRxCoverage` is
disabled**, so it's safe under the default-off config.

## Notes for reviewers

- The four new routes are registered in
`cmd/server/openapi_known_gaps.json` (the existing OpenAPI-completeness
ratchet), matching how other not-yet-spec'd routes are tracked. Happy to
write full OpenAPI spec entries instead if you prefer.
- Commits are split per layer (ingestor / server endpoints / resolve /
frontend / CI) for review.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Erwin Fiten <e.fiten@opteco.be>
2026-06-19 11:37:16 -07:00

77 lines
2.5 KiB
Go

package main
import (
"encoding/json"
"net/http"
"regexp"
"strings"
)
// ResolvePrefixResp is the tiny reply for /api/nodes/resolve — lets a client
// resolve a heard 2-3 byte path prefix (or full pubkey) to a node name without
// fetching the whole node list. Read-only.
type ResolvePrefixResp struct {
Prefix string `json:"prefix"`
Pubkey string `json:"pubkey,omitempty"`
Name string `json:"name,omitempty"`
Ambiguous bool `json:"ambiguous"`
}
var hexPrefixRe = regexp.MustCompile(`^[0-9a-f]{2,64}$`)
// minResolvePrefixHex is the shortest accepted prefix. 1-byte (2 hex) keys are
// never stored — the ingestor rejects heard keys shorter than 2 bytes — so the
// floor matches the data model and, by ruling out the 256 two-char prefixes,
// blunts trivial enumeration of every node name through this endpoint (#15).
const minResolvePrefixHex = 4
func (s *Server) handleResolvePrefix(w http.ResponseWriter, r *http.Request) {
pfx := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("prefix")))
if !hexPrefixRe.MatchString(pfx) {
http.Error(w, "prefix must be hex", http.StatusBadRequest)
return
}
if len(pfx) < minResolvePrefixHex {
http.Error(w, "prefix must be at least 4 hex chars", http.StatusBadRequest)
return
}
if s.db == nil || s.db.conn == nil {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
// LIMIT 2: we only need to know unique vs ambiguous. nodes.public_key is the
// PK and stored lowercase; pfx is validated hex so the LIKE pattern is safe.
rows, err := s.db.conn.Query(`SELECT public_key, COALESCE(name,'') FROM nodes WHERE public_key LIKE ? LIMIT 2`, pfx+"%")
if err != nil {
http.Error(w, "query failed", http.StatusInternalServerError)
return
}
defer rows.Close()
var pks, names []string
for rows.Next() {
var pk, nm string
if err := rows.Scan(&pk, &nm); err != nil {
http.Error(w, "scan failed", http.StatusInternalServerError)
return
}
pks = append(pks, pk)
names = append(names, nm)
}
resp := ResolvePrefixResp{Prefix: pfx}
switch len(pks) {
case 1:
// Parity with /api/nodes/search and /api/resolve-hops: never reveal the
// identity of a blacklisted or hidden-prefix node (#1181). Report it as
// not-found rather than leaking the name the rest of the API hides.
if !s.cfg.IsBlacklisted(pks[0]) && !s.cfg.IsNameHidden(names[0]) {
resp.Pubkey = pks[0]
resp.Name = names[0]
}
default:
resp.Ambiguous = len(pks) > 1 // 0 → not found (name empty), >1 → ambiguous
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}