diff --git a/cmd/server/db.go b/cmd/server/db.go index 8b9d793b1..8105a8355 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -863,6 +863,7 @@ func (db *DB) QueryGroupedPackets(q PacketQuery) (*PacketResult, error) { if q.Limit <= 0 { q.Limit = 50 } + hops := hiddenKeysPredicate(q.HiddenSenders) // #1023 M2 where, args := db.buildTransmissionWhere(q) w := "" @@ -976,9 +977,10 @@ func (db *DB) QueryGroupedPackets(q PacketQuery) (*PacketResult, error) { } // #165 — the displayed observation's resolved_path, as the in-memory // store sends it (groupedPageWithRP). + // #1023 M2: a hidden identity's hop is served as null. if resolvedPath.Valid { if rp := resolvedPathRaw(resolvedPath.String); rp != nil { - row["resolved_path"] = rp + row["resolved_path"] = hops.redactRaw(rp) } } packets = append(packets, row) @@ -2983,6 +2985,15 @@ func buildPacketPathResponseFromReduction( // deliberately no always-estimating exported wrapper: a caller that did // not state a policy would bypass the operator's #315 setting. func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled bool) (*PacketPathResponse, error) { + return db.getVisiblePacketPath(hash, maxEdgeKm, estimatesEnabled, nil) +} + +// getVisiblePacketPath is getPacketPath for /api/packets/{hash}/path (#1023 +// M2): a hidden identity's hop is left out like a hop that did not resolve +// (the branch keeps its hop count), an observation heard by a hidden +// identity is left out whole, and a visible hop's estimated position is +// not taken from a hidden neighbour. A nil hidden keeps everything. +func (db *DB) getVisiblePacketPath(hash string, maxEdgeKm float64, estimatesEnabled bool, hidden *hiddenPredicate) (*PacketPathResponse, error) { if !db.hasResolvedPath() { return nil, fmt.Errorf("resolved_path not available on this server") } @@ -3022,6 +3033,13 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo if !ok { continue } + // A hidden identity that is also an observer is left out whole, + // as filterPingScorePath drops its branch: its key and exact + // position must not be served as the observer. + if hidden.hidesIdentity(branch.observerPubkey, branch.observerName) { + continue + } + branch.resolvedPath = hidden.redactPath(branch.resolvedPath) red.fold(key, branch, ts.Valid, ts.Int64) } if err := rows.Err(); err != nil { @@ -3031,6 +3049,7 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo if len(red.best) == 0 { return &PacketPathResponse{Hash: hash, Branches: []PacketPathBranch{}, TxID: red.txID}, nil } + hiddenNeighbour := hidden.hidesNeighbour() pubkeySet := collectPacketPathPubkeys(red.first, red.best) pubkeys := make([]string, 0, len(pubkeySet)) @@ -3054,7 +3073,7 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo if !estimatesEnabled { return neighborEstimate{}, false } - _, nLat, nLon, nCount, nSpread, ok := db.nearestPositionedNeighbor(pk, maxEdgeKm) + _, nLat, nLon, nCount, nSpread, ok := db.nearestVisiblePositionedNeighbor(pk, maxEdgeKm, hiddenNeighbour) if !ok { return neighborEstimate{}, false } @@ -3619,6 +3638,19 @@ func pingBotReply(hops int, snr sql.NullFloat64, observer string, repeaterNames } func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region ...string) ([]map[string]interface{}, int, error) { + r := "" + if len(region) > 0 { + r = region[0] + } + return db.getVisibleChannelMessages(channelHash, limit, offset, r, nil) +} + +// getVisibleChannelMessages is GetChannelMessages for +// /api/channels/{hash}/messages (#1023 M2): the ping-bot reply does not +// name a hidden relay. Its hop is shown by its raw path prefix, as the +// Packets page shows a hop that did not resolve, and its key is not +// looked up. A nil hidden names every relay. +func (db *DB) getVisibleChannelMessages(channelHash string, limit, offset int, regionParam string, hidden *hiddenPredicate) ([]jsonObject, int, error) { if limit <= 0 { limit = 100 } @@ -3626,10 +3658,6 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . offset = 0 } - regionParam := "" - if len(region) > 0 { - regionParam = region[0] - } regionCodes := normalizeRegionCodes(regionParam) regionArgs := make([]interface{}, 0, len(regionCodes)) regionPlaceholders := "" @@ -3790,6 +3818,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . hops int snr sql.NullFloat64 resolvedPath []*string + pathHops []string // the raw path prefixes, for a hidden relay (#1023 M2) observers map[string]bool // observerPubkeys/firstPubkey/firstTS feed the "spread up to Nkm" // reply text -- the same farthest-from-first-hearer distance View @@ -3828,12 +3857,12 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . // reach can be tracked across every station that heard it. var hops int var entryPrefix string + var pathHops []string if pathJSON.Valid { - var h []string - if json.Unmarshal([]byte(pathJSON.String), &h) == nil { - hops = len(h) - if len(h) > 0 { - entryPrefix = h[0] + if json.Unmarshal([]byte(pathJSON.String), &pathHops) == nil { + hops = len(pathHops) + if len(pathHops) > 0 { + entryPrefix = pathHops[0] } } } @@ -3869,7 +3898,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . } } if hops > agg.hops { - agg.hops, agg.snr, agg.resolvedPath = hops, snr, resolvedPath + agg.hops, agg.snr, agg.resolvedPath, agg.pathHops = hops, snr, resolvedPath, pathHops } } continue @@ -3937,7 +3966,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . } if isPingTrigger(displayText) { agg := &pendingPing{ - hops: hops, snr: snr, resolvedPath: resolvedPath, + hops: hops, snr: snr, resolvedPath: resolvedPath, pathHops: pathHops, observers: map[string]bool{}, observerPubkeys: map[string]bool{}, } if observerName != "" { @@ -3965,7 +3994,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . pubkeySet := map[string]bool{} for _, p := range pendingPings { for _, pk := range p.resolvedPath { - if pk != nil && *pk != "" { + if pk != nil && *pk != "" && !hidden.hidesKey(*pk) { pubkeySet[*pk] = true } } @@ -4025,10 +4054,19 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . for txID, p := range pendingPings { var repeaterNames []string - for _, pk := range p.resolvedPath { + for i, pk := range p.resolvedPath { if pk == nil || *pk == "" { continue } + if hidden.hidesKey(*pk) { + // #1023 M2: the raw prefix, never the name or key. + prefix := "?" + if i < len(p.pathHops) && p.pathHops[i] != "" { + prefix = p.pathHops[i] + } + repeaterNames = append(repeaterNames, prefix) + continue + } if name := names[*pk]; name != "" { repeaterNames = append(repeaterNames, name) } else { diff --git a/cmd/server/hidden_hops.go b/cmd/server/hidden_hops.go new file mode 100644 index 000000000..491358a7c --- /dev/null +++ b/cmd/server/hidden_hops.go @@ -0,0 +1,173 @@ +package main + +import ( + "encoding/json" + "math" + "net/http" + "slices" + "strings" +) + +// Hidden identities as hops (#1023 M2). +// +// M1 leaves a hidden identity's own ADVERT and ANON_REQ packets out. The +// packets it relayed or sent stay served, but its full key must not appear +// in them: a resolved_path entry that names a hidden identity is served as +// null, exactly like a hop that did not resolve, and the packet-path and +// resolve-hops endpoints neither name, key nor position it. The rule and +// the set are M1's (hiddenPredicate over the hiddenPK snapshot, plus the +// live config's blacklists), so hiding still follows the identity's +// current state: renamed back, its hops are served again. The cost is one +// map lookup per hop of a served packet, nothing when no key is hidden, +// and a copy only of a path that has a hidden hop (resolved paths are +// shared with the LRU and must never be written). + +// hidesKey reports whether the full key of a hop, a path point or a +// resolve candidate belongs to a hidden identity: in hiddenPK or hidden by +// the live config (both blacklists). Any case. +func (p *hiddenPredicate) hidesKey(key string) bool { + if p == nil || key == "" { + return false + } + // Stored keys are lower-case (the ingestor normalises them), so the + // common lookup needs no strings.ToLower, which was 30 % of the cost. + if _, ok := p.snap.pk[key]; ok { + return true + } + if hasUpperASCII(key) { + if _, ok := p.snap.pk[strings.ToLower(key)]; ok { + return true + } + } + return identityHidden(p.cfg, key) +} + +// redactPath returns rp with every hidden hop set to nil. It returns rp +// itself when no hop is hidden, a new slice otherwise: rp may be shared. +func (p *hiddenPredicate) redactPath(rp []*string) []*string { + if p == nil { + return rp + } + for i, h := range rp { + if h != nil && p.hidesKey(*h) { + out := slices.Clone(rp) + for j := i; j < len(out); j++ { + if out[j] != nil && p.hidesKey(*out[j]) { + out[j] = nil + } + } + return out + } + } + return rp +} + +// redactRaw is redactPath for a stored resolved_path served as raw JSON +// (the grouped list and its SQL fallback): rm itself unless a hop is +// hidden, else the redacted list. +func (p *hiddenPredicate) redactRaw(rm json.RawMessage) interface{} { + if p == nil { + return rm + } + rp := unmarshalResolvedPath(string(rm)) + if out := p.redactPath(rp); len(out) > 0 && &out[0] != &rp[0] { + return out + } + return rm +} + +// redactBroadcast redacts a WebSocket message's resolved_path, top-level +// and in its nested packet. It reads the store's existing message shape +// (the poller builds each message fresh) through the jsonObject alias and +// adds no new untyped structure. +func (p *hiddenPredicate) redactBroadcast(m jsonObject) { + if p == nil { + return + } + if rp, ok := m["resolved_path"].([]*string); ok { + m["resolved_path"] = p.redactPath(rp) + } + if pkt, ok := m["packet"].(jsonObject); ok { + if rp, ok := pkt["resolved_path"].([]*string); ok { + pkt["resolved_path"] = p.redactPath(rp) + } + } +} + +// hidesIdentity reports whether a key or a name (a neighbour, an observer, +// a node filter) is a hidden identity: hidesKey, or a hidden-name prefix. +func (p *hiddenPredicate) hidesIdentity(pubkey, name string) bool { + return p != nil && (p.hidesKey(pubkey) || (p.cfg != nil && p.cfg.IsNameHidden(name))) +} + +// hidesNeighbour is the hidden test nearestVisiblePositionedNeighbor +// takes; nil when nothing is hidden. +func (p *hiddenPredicate) hidesNeighbour() func(pubkey, name string) bool { + if p == nil { + return nil + } + return p.hidesIdentity +} + +// hiddenHopPredicate is the store's predicate for hops: M1's row predicate, +// or nil when no key can be hidden (an empty hiddenPK and no blacklist), +// so serving a path then costs one pointer test. +func (s *PacketStore) hiddenHopPredicate() *hiddenPredicate { + p := s.hiddenRowPredicate() + if p == nil || len(p.snap.pk) > 0 || (p.cfg != nil && (p.cfg.HasNodeBlacklist() || len(p.cfg.obsBlacklistSet()) > 0)) { + return p + } + return nil +} + +// hiddenHops is the hop predicate of a request: the store's, or without a +// store the DB and config rule read now (an error fails the request). +func (s *Server) hiddenHops() (*hiddenPredicate, error) { + if s.store != nil { + return s.store.hiddenHopPredicate(), nil + } + return dbHiddenPredicate(s.db, s.cfg) +} + +// hiddenKeysPredicate is the hop predicate of the SQL fallbacks, built +// from the keys the caller resolved (PacketQuery.HiddenSenders); nil when +// there are none. +func hiddenKeysPredicate(keys []string) *hiddenPredicate { + if len(keys) == 0 { + return nil + } + pk := make(map[string]struct{}, len(keys)) + for _, k := range keys { + pk[strings.ToLower(k)] = struct{}{} + } + return &hiddenPredicate{snap: &hiddenIdentitySnapshot{pk: pk}, from: math.MinInt} +} + +// visibleNodeFilters drops the packet-list node filters (a key or a name, +// as resolveNodePubkey reads them) that name a hidden identity: listing a +// hidden node's packets would re-link the hops M2 serves as null, as M1's +// node detail answers 404 (#1023). Nothing hidden costs nothing; else one +// indexed nodes lookup per filter. ok is false when the error is written. +func (s *Server) visibleNodeFilters(w http.ResponseWriter, filters []string) (visible []string, ok bool) { + hops, err := s.hiddenHops() + if err != nil { + writeError(w, 500, err.Error()) + return nil, false + } + if hops == nil { + return filters, true + } + visible = filters[:0:0] + for _, f := range filters { + if hops.hidesIdentity(f, f) { + continue + } + if s.db != nil { + if pk := s.db.resolveNodePubkey(f); pk != f && hops.hidesKey(pk) { + continue + } + } + visible = append(visible, f) + } + return visible, true +} diff --git a/cmd/server/hidden_hops_1023_round2_test.go b/cmd/server/hidden_hops_1023_round2_test.go new file mode 100644 index 000000000..34a433ae3 --- /dev/null +++ b/cmd/server/hidden_hops_1023_round2_test.go @@ -0,0 +1,218 @@ +package main + +import ( + "encoding/json" + "net/url" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// #1023 M2, review round (PR #1094): the doors the first round left open. +// The ping-bot reply on the Channels page, the node filter of the packet +// list, a hidden identity that is also an observer on the packet path, and +// the WebSocket poller's same-poll ordering. + +const ( + hopPingHash = "b2d0000000000010" // "ping" on #test, relayed by hidPK, then visPK + hopObsPathHash = "b2d0000000000011" // GRP_TXT heard by obs1 and by hidPK as an observer +) + +// hopPingFixture is hopFixture plus a ping on #test relayed by the hidden +// node and then the visible TestRepeater, heard by obs1. +func hopPingFixture(t *testing.T, mode string) *hidFixture { + t.Helper() + name := "🚫HideMe" + if mode == "blacklist" || mode == "none" { + name = "HideMe" + } + return hidSetupWith(t, mode, name, func(db *DB) { + now := time.Now().Add(-5 * time.Minute) + res, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, decoded_json, channel_hash) + VALUES ('1500AABBCCDD', ?, ?, 1, 5, '{"type":"CHAN","channel":"#test","text":"Eve: ping","sender":"Eve"}', '#test')`, + hopPingHash, now.UTC().Format(time.RFC3339)) + if err != nil { + t.Fatal(err) + } + id, _ := res.LastInsertId() + hopObs(t, db, int(id), `["c0","aa"]`, hopRP(hidPK, visPK), now) + }) +} + +func hopBotReplyText(t *testing.T, body []byte) string { + t.Helper() + var res struct { + Messages []struct { + BotReply *struct { + Text string `json:"text"` + } `json:"botReply"` + } `json:"messages"` + } + if err := json.Unmarshal(body, &res); err != nil { + t.Fatalf("bad JSON: %v: %.300s", err, body) + } + for _, m := range res.Messages { + if m.BotReply != nil { + return m.BotReply.Text + } + } + t.Fatalf("no bot reply served: %.400s", body) + return "" +} + +// The ping-bot reply names the relays of a packet that stays served: a +// hidden relay is shown by its raw path prefix, as the Packets page shows +// an unresolved hop, never by its name or full key. +func TestHiddenHops1023_ChannelPingBotReply(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopPingFixture(t, mode) + w := f.get("/api/channels/" + url.PathEscape("#test") + "/messages") + if w.Code != 200 { + t.Fatalf("messages: %d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "channel messages", w.Body.String()) + if got, want := hopBotReplyText(t, w.Body.Bytes()), "2 hops (via c0 → TestRepeater)"; !strings.Contains(got, want) { + t.Errorf("bot reply = %q, want it to contain %q", got, want) + } + }) + } + t.Run("unnamed hidden relay", func(t *testing.T) { + f := hopPingFixture(t, "blacklist") + f.srv.db.conn.Exec(`UPDATE nodes SET name = NULL WHERE public_key = ?`, hidPK) + w := f.get("/api/channels/" + url.PathEscape("#test") + "/messages") + assertNoHiddenIdentity(t, "channel messages", w.Body.String()) + }) + t.Run("control", func(t *testing.T) { + f := hopPingFixture(t, "none") + w := f.get("/api/channels/" + url.PathEscape("#test") + "/messages") + if got, want := hopBotReplyText(t, w.Body.Bytes()), "2 hops (via HideMe → TestRepeater)"; !strings.Contains(got, want) { + t.Errorf("control bot reply = %q, want it to contain %q", got, want) + } + }) +} + +// /api/packets?node= must not re-link the packets the +// hidden identity relayed or sent: it answers an empty list, as M1's +// node detail answers 404. Store and SQL fallback, flat and grouped, and +// the multi-node filter. +func TestHiddenHops1023_NodeQueryByHiddenKey(t *testing.T) { + assertNoHopPackets := func(t *testing.T, label, body string) { + t.Helper() + for _, h := range []string{hopRelayHash, hopSenderHash} { + if strings.Contains(body, h) { + t.Errorf("%s lists %s: %.400s", label, h, body) + } + } + var res struct { + Total int `json:"total"` + } + json.Unmarshal([]byte(body), &res) + if res.Total != 0 { + t.Errorf("%s: total = %d, want 0", label, res.Total) + } + } + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + name := "HideMe" + if mode == "prefix" { + name = "🚫HideMe" + } + paths := []string{ + "/api/packets?limit=50&node=" + hidPK, + "/api/packets?limit=50&node=" + strings.ToUpper(hidPK), + "/api/packets?limit=50&groupByHash=true&node=" + hidPK, + "/api/packets?limit=50&node=" + url.QueryEscape(name), + "/api/packets?limit=50&nodes=" + hidPK, + } + for _, store := range []bool{true, false} { + if !store { + f.srv.store = nil + f.router = mux.NewRouter() + f.srv.RegisterRoutes(f.router) + } + for _, p := range paths { + w := f.get(p) + if w.Code != 200 { + t.Fatalf("%s: %d %s", p, w.Code, w.Body.String()) + } + assertNoHopPackets(t, p, w.Body.String()) + } + } + }) + } + t.Run("control", func(t *testing.T) { + f := hopFixture(t, "none") + for _, p := range []string{"/api/packets?limit=50&node=" + hidPK, "/api/packets?limit=50&nodes=" + hidPK} { + if body := f.get(p).Body.String(); !strings.Contains(body, hopSenderHash) { + t.Errorf("control %s lost the node's packets: %.400s", p, body) + } + } + }) +} + +// A hidden identity that is also an observer (observer id = its key) is +// not served on /api/packets/{hash}/path: its observation is left out +// whole, as the share card's filterPingScorePath drops its branch. The +// visible observer's branch stays. +func TestHiddenHops1023_HiddenObserverOnPath(t *testing.T) { + seed := func(t *testing.T) func(db *DB) { + return func(db *DB) { + res, err := db.conn.Exec(`INSERT INTO observers (id, name, iata) VALUES (?, 'Relay Obs', 'CPH')`, hidPK) + if err != nil { + t.Fatal(err) + } + idx, _ := res.LastInsertId() + now := time.Now().Add(-3 * time.Minute) + id := hopTx(t, db, hopObsPathHash, PayloadGRP_TXT, hopGrpJSON(), now) + hopObs(t, db, id, `["aa"]`, hopRP(visPK), now) + hopObsBy(t, db, int(idx), id, `["aa"]`, hopRP(visPK), now.Add(time.Second)) + } + } + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + name := "🚫HideMe" + if mode != "prefix" { + name = "HideMe" + } + f := hidSetupWith(t, mode, name, seed(t)) + w := f.get("/api/packets/" + hopObsPathHash + "/path") + if w.Code != 200 { + t.Fatalf("path: %d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "path", w.Body.String()) + if strings.Contains(w.Body.String(), "Relay Obs") { + t.Errorf("path names the hidden observer: %s", w.Body.String()) + } + if !strings.Contains(w.Body.String(), visPK) { + t.Errorf("visible branch lost: %s", w.Body.String()) + } + }) + } + t.Run("control", func(t *testing.T) { + f := hidSetupWith(t, "none", "HideMe", seed(t)) + if body := f.get("/api/packets/" + hopObsPathHash + "/path").Body.String(); !strings.Contains(body, "Relay Obs") { + t.Errorf("control path lost the observer: %s", body) + } + }) +} + +// The poller takes the hop predicate after M1's per-poll refresh: a node +// renamed to 🚫 by an advert in the same poll as a packet it relayed is +// already hidden as that packet's hop. +func TestHiddenHops1023_WSSamePollRename(t *testing.T) { + f := hidSetupWith(t, "prefix", "HideMe", func(db *DB) {}) + ws := newHidWS(f) + now := time.Now() + insertHidTx(t, f.srv.db, hidHashNew, 4, hidAdvertJSON("🚫HideMe"), now) + id := hopTx(t, f.srv.db, "b2d00000000000f3", PayloadGRP_TXT, hopGrpJSON(), now) + hopObs(t, f.srv.db, id, `["c0","aa"]`, hopRP(hidPK, visPK), now) + frames := ws.tick() + assertNoHiddenIdentity(t, "ws same poll", frames) + if !strings.Contains(frames, "b2d00000000000f3") || !strings.Contains(frames, visPK) { + t.Fatalf("relayed packet or its visible hop not broadcast: %.400s", frames) + } +} diff --git a/cmd/server/hidden_hops_1023_test.go b/cmd/server/hidden_hops_1023_test.go new file mode 100644 index 000000000..0b421f62a --- /dev/null +++ b/cmd/server/hidden_hops_1023_test.go @@ -0,0 +1,488 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// #1023 M2: a hidden identity (node blacklist, observer blacklist, or a +// current name with a hidden-name prefix) that relayed or sent a packet +// that is still served must not appear in it: its full key in +// resolved_path becomes null, the same as a hop that did not resolve, and +// the path and resolve-hops endpoints do not name, key or position it. +// The packets themselves stay. M1's fixture (hidSetup, hidPK named +// 🚫HideMe at 55.6137/12.5338) is reused; TestRepeater (visPK) is the +// visible control hop. + +const ( + visPK = "aabbccdd11223344" // seedTestData's TestRepeater + hopNoGPSPK = "ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12" // visible, no position of its own + hopRelayHash = "b2d0000000000001" // GRP_TXT relayed by hidPK, then visPK + hopSenderHash = "b2d0000000000002" // TXT_MSG sent by hidPK (srcHash c0) + hopNoGPSHash = "b2d0000000000003" // GRP_TXT relayed by hopNoGPSPK +) + +func hopGrpJSON() string { return `{"type":"CHAN","channel":"#test","text":"hops 1023"}` } +func hopTxtJSON() string { + return `{"type":"TXT_MSG","destHash":"aa","srcHash":"c0","mac":"1234","encryptedData":"ff00"}` +} + +// hopObs adds an observation of txID by obs1 with the given path and +// resolved path, and returns its id. +func hopObs(t testing.TB, db *DB, txID int, path, resolved string, at time.Time) int { + return hopObsBy(t, db, 1, txID, path, resolved, at) +} + +func hopObsBy(t testing.TB, db *DB, observerIdx, txID int, path, resolved string, at time.Time) int { + t.Helper() + res, err := db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, snr, rssi, path_json, timestamp, resolved_path) + VALUES (?, ?, 7.5, -95, ?, ?, ?)`, txID, observerIdx, path, at.Unix(), resolved) + if err != nil { + t.Fatalf("insert obs: %v", err) + } + id, _ := res.LastInsertId() + return int(id) +} + +func hopTx(t testing.TB, db *DB, hash string, pt int, decoded string, at time.Time) int { + t.Helper() + res, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, decoded_json) + VALUES ('1500AABBCCDD', ?, ?, 1, ?, ?)`, hash, at.UTC().Format(time.RFC3339), pt, decoded) + if err != nil { + t.Fatalf("insert tx %s: %v", hash, err) + } + id, _ := res.LastInsertId() + return int(id) +} + +func hopRP(keys ...string) string { + b, _ := json.Marshal(keys) + return string(b) +} + +// hopFixture is M1's fixture for mode plus the relayed and sent packets. +// Their observations are inserted before the store loads, so the store +// serves them from its LRU/SQL resolved paths. +func hopFixture(t *testing.T, mode string) *hidFixture { + t.Helper() + name := "🚫HideMe" + if mode == "blacklist" || mode == "none" { + name = "HideMe" + } + f := hidSetupWith(t, mode, name, func(db *DB) { + now := time.Now() + relay := hopTx(t, db, hopRelayHash, PayloadGRP_TXT, hopGrpJSON(), now.Add(-20*time.Minute)) + hopObs(t, db, relay, `["c0","aa"]`, hopRP(hidPK, visPK), now.Add(-20*time.Minute)) + sender := hopTx(t, db, hopSenderHash, PayloadTXT_MSG, hopTxtJSON(), now.Add(-10*time.Minute)) + hopObs(t, db, sender, `["c0"]`, hopRP(hidPK), now.Add(-10*time.Minute)) + }) + return f +} + +// hidSetupWith is hidSetup with extra rows written before the store loads. +func hidSetupWith(t *testing.T, mode, nodeName string, seed func(db *DB)) *hidFixture { + t.Helper() + db := setupTestDB(t) + seedTestData(t, db) + if _, err := db.conn.Exec(`INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, advert_count) + VALUES (?, ?, 'repeater', 55.6137, 12.5338, ?, '2026-01-01T00:00:00Z', 3)`, hidPK, nodeName, time.Now().UTC().Format(time.RFC3339)); err != nil { + t.Fatal(err) + } + seed(db) + cfg := &Config{Port: 3000} + switch mode { + case "prefix": + cfg.SetHiddenNamePrefixes([]string{"🚫"}) + case "blacklist": + cfg.SetNodeBlacklist([]string{hidPK}) + case "obs-blacklist": + cfg.ObserverBlacklist = []string{strings.ToUpper(hidPK)} + } + f := &hidFixture{ids: map[string]int{}, cfg: cfg} + f.srv = NewServer(db, cfg, NewHub()) + f.store = NewPacketStore(db, nil) + f.store.config = cfg + if err := f.store.Load(); err != nil { + t.Fatal(err) + } + if !f.store.WaitIndexesReady(5 * time.Second) { + t.Fatal("indexes not ready") + } + f.srv.store = f.store + f.router = mux.NewRouter() + f.srv.RegisterRoutes(f.router) + t.Cleanup(func() { db.Close() }) + return f +} + +var hopModes = []string{"prefix", "blacklist", "obs-blacklist"} + +// hopRPOf reads a resolved_path value from a decoded response. +func hopRPOf(t *testing.T, v interface{}) []interface{} { + t.Helper() + rp, ok := v.([]interface{}) + if !ok { + t.Fatalf("resolved_path = %#v, want a list", v) + } + return rp +} + +// assertHopRedacted checks a served resolved_path: the hidden first hop is +// null and the visible control hop (when the path has one) is kept. +func assertHopRedacted(t *testing.T, label string, v interface{}, want ...interface{}) { + t.Helper() + rp := hopRPOf(t, v) + if fmt.Sprintf("%v", rp) != fmt.Sprintf("%v", want) { + t.Errorf("%s: resolved_path = %v, want %v", label, rp, want) + } +} + +func hopFind(t *testing.T, body []byte, hash string) map[string]interface{} { + t.Helper() + var res struct { + Packets []map[string]interface{} `json:"packets"` + } + if err := json.Unmarshal(body, &res); err != nil { + t.Fatalf("bad JSON: %v: %.300s", err, body) + } + for _, p := range res.Packets { + if p["hash"] == hash { + return p + } + } + t.Fatalf("packet %s not served: %.400s", hash, body) + return nil +} + +func TestHiddenHops1023_PacketList(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + for _, path := range []string{"/api/packets?limit=50", "/api/packets?limit=50&groupByHash=true"} { + w := f.get(path) + if w.Code != 200 { + t.Fatalf("%s: %d", path, w.Code) + } + assertNoHiddenIdentity(t, path, w.Body.String()) + assertHopRedacted(t, path+" relay", hopFind(t, w.Body.Bytes(), hopRelayHash)["resolved_path"], nil, visPK) + assertHopRedacted(t, path+" sender", hopFind(t, w.Body.Bytes(), hopSenderHash)["resolved_path"], nil) + } + }) + } +} + +// The VCR (Live) and Packets with observations read the list with +// expand=observations: each observation's resolved_path is redacted too. +func TestHiddenHops1023_PacketListExpandVCR(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + w := f.get("/api/packets?limit=50&expand=observations") + assertNoHiddenIdentity(t, "expand", w.Body.String()) + p := hopFind(t, w.Body.Bytes(), hopRelayHash) + assertHopRedacted(t, "expand top", p["resolved_path"], nil, visPK) + obs, _ := p["observations"].([]interface{}) + if len(obs) == 0 { + t.Fatalf("no observations: %v", p) + } + for _, o := range obs { + assertHopRedacted(t, "expand obs", o.(map[string]interface{})["resolved_path"], nil, visPK) + } + }) + } +} + +// The packet detail (Packets' detail pane, and Live's replay of it). +func TestHiddenHops1023_PacketDetail(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + for _, hash := range []string{hopRelayHash, hopSenderHash} { + w := f.get("/api/packets/" + hash) + if w.Code != 200 { + t.Fatalf("detail %s: %d (the packet must stay)", hash, w.Code) + } + assertNoHiddenIdentity(t, "detail "+hash, w.Body.String()) + var d struct { + Packet map[string]interface{} `json:"packet"` + Observations []map[string]interface{} `json:"observations"` + } + json.Unmarshal(w.Body.Bytes(), &d) + want := []interface{}{nil, visPK} + if hash == hopSenderHash { + want = []interface{}{nil} + } + assertHopRedacted(t, "detail packet", d.Packet["resolved_path"], want...) + for _, o := range d.Observations { + assertHopRedacted(t, "detail obs", o["resolved_path"], want...) + } + } + }) + } +} + +// POST /api/packets/observations (enrichObsWithTx). +func TestHiddenHops1023_BatchObservations(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + w := f.do("POST", "/api/packets/observations", `{"hashes":["`+hopRelayHash+`"]}`) + if w.Code != 200 { + t.Fatalf("observations: %d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "observations", w.Body.String()) + if !strings.Contains(w.Body.String(), visPK) { + t.Fatalf("visible hop lost: %s", w.Body.String()) + } + }) + } +} + +// Observer analytics' recentPackets (enrichObsWithTx). +func TestHiddenHops1023_ObserverAnalytics(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + w := f.get("/api/observers/obs1/analytics?days=7") + if w.Code != 200 { + t.Fatalf("observer analytics: %d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "observer analytics", w.Body.String()) + if !strings.Contains(w.Body.String(), visPK) { + t.Fatalf("visible hop lost: %.400s", w.Body.String()) + } + }) + } +} + +// The WebSocket: a new transmission relayed by the hidden node, and a new +// observation of an existing transmission, are broadcast with the hidden +// hop null — in the frame's resolved_path and its nested packet. +func TestHiddenHops1023_WebSocket(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + ws := newHidWS(f) + now := time.Now() + id := hopTx(t, f.srv.db, "b2d00000000000f1", PayloadGRP_TXT, hopGrpJSON(), now) + hopObs(t, f.srv.db, id, `["c0","aa"]`, hopRP(hidPK, visPK), now) + frames := ws.tick() + hopObsBy(t, f.srv.db, 2, f.store.byHash[hopRelayHash].ID, `["c0","aa"]`, hopRP(hidPK, visPK), now) + frames += ws.tick() + assertNoHiddenIdentity(t, "ws", frames) + n := 0 + for _, line := range strings.Split(strings.TrimSpace(frames), "\n") { + var msg struct { + Data map[string]interface{} `json:"data"` + } + if json.Unmarshal([]byte(line), &msg) != nil || msg.Data["resolved_path"] == nil { + continue + } + n++ + assertHopRedacted(t, "ws frame", msg.Data["resolved_path"], nil, visPK) + pkt, _ := msg.Data["packet"].(map[string]interface{}) + assertHopRedacted(t, "ws nested packet", pkt["resolved_path"], nil, visPK) + } + if n != 2 { + t.Fatalf("want 2 frames with a resolved_path (new tx, new obs), got %d: %s", n, frames) + } + }) + } +} + +// The SQL fallback of the grouped list (no store). +func TestHiddenHops1023_SQLFallbackGrouped(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + f.srv.store = nil + f.router = mux.NewRouter() + f.srv.RegisterRoutes(f.router) + w := f.get("/api/packets?limit=50&groupByHash=true") + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "sql grouped", w.Body.String()) + assertHopRedacted(t, "sql grouped", hopFind(t, w.Body.Bytes(), hopRelayHash)["resolved_path"], nil, visPK) + }) + } +} + +// /api/packets/{hash}/path: the hidden hop is left out like a hop that did +// not resolve (the branch keeps its hop count), and a visible hop without +// a position of its own is not placed by the hidden neighbour's position. +func TestHiddenHops1023_PacketPath(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + f := hopFixture(t, mode) + w := f.get("/api/packets/" + hopRelayHash + "/path") + if w.Code != 200 { + t.Fatalf("path: %d %s", w.Code, w.Body.String()) + } + assertNoHiddenIdentity(t, "path", w.Body.String()) + var resp PacketPathResponse + json.Unmarshal(w.Body.Bytes(), &resp) + if len(resp.Branches) != 1 || resp.Branches[0].Hops != 2 { + t.Fatalf("branches = %+v, want one of 2 hops", resp.Branches) + } + pts := resp.Branches[0].Points + if len(pts) != 1 || pts[0].PublicKey != visPK { + t.Fatalf("points = %+v, want only the visible hop", pts) + } + }) + } +} + +func TestHiddenHops1023_PacketPathNoNeighbourPosition(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + name := "🚫HideMe" + if mode != "prefix" { + name = "HideMe" + } + f := hidSetupWith(t, mode, name, func(db *DB) { + db.conn.Exec(`INSERT INTO nodes (public_key, name, role) VALUES (?, 'NoGPS Relay', 'repeater')`, hopNoGPSPK) + now := time.Now() + id := hopTx(t, db, hopNoGPSHash, PayloadGRP_TXT, hopGrpJSON(), now) + hopObs(t, db, id, `["ab"]`, hopRP(hopNoGPSPK), now) + }) + // After the load: the store refuses neighbour edges without a graph. + f.srv.db.conn.Exec(`INSERT INTO neighbor_edges (node_a, node_b, count, last_seen) VALUES (?, ?, 40, '2026-01-01T00:00:00Z')`, hopNoGPSPK, hidPK) + w := f.get("/api/packets/" + hopNoGPSHash + "/path") + assertNoHiddenIdentity(t, "path estimate", w.Body.String()) + var resp PacketPathResponse + json.Unmarshal(w.Body.Bytes(), &resp) + if len(resp.Branches) != 1 || len(resp.Branches[0].Points) != 1 || resp.Branches[0].Points[0].PublicKey != hopNoGPSPK { + t.Fatalf("want the visible no-GPS hop kept: %s", w.Body.String()) + } + if p := resp.Branches[0].Points[0]; p.Lat != nil || p.Approx { + t.Errorf("visible hop placed from its hidden neighbour: %+v", p) + } + }) + } +} + +// resolve-hops: a hidden node is neither a candidate nor the bestCandidate +// (routes.go set BestCandidate to the affinity pick even after rejecting it +// as hidden), and its confidence tier is not reported. +func TestHiddenHops1023_ResolveHopsBestCandidate(t *testing.T) { + for _, mode := range hopModes { + t.Run(mode, func(t *testing.T) { + const hidDD = "dd1aaaaaaa" + srv, router := setupTestServer(t) + name := "Node-D1" + cfg := &Config{Port: 3000} + switch mode { + case "prefix": + name = "🚫Node-D1" + cfg.SetHiddenNamePrefixes([]string{"🚫"}) + case "blacklist": + cfg.SetNodeBlacklist([]string{hidDD}) + case "obs-blacklist": + cfg.ObserverBlacklist = []string{hidDD} + } + srv.cfg, srv.store.config = cfg, cfg + srv.db.conn.Exec("INSERT OR IGNORE INTO nodes (public_key, name, lat, lon, role) VALUES (?, ?, ?, ?, ?)", hidDD, name, 55.6137, 12.5338, "repeater") + srv.db.conn.Exec("INSERT OR IGNORE INTO nodes (public_key, name, lat, lon, role) VALUES (?, ?, ?, ?, ?)", "dd1bbbbbbb", "Node-D2", 38.0, -121.0, "repeater") + srv.db.conn.Exec("INSERT OR IGNORE INTO nodes (public_key, name, lat, lon, role) VALUES (?, ?, ?, ?, ?)", "dd1ccccccc", "Node-D3", 39.0, -120.0, "repeater") + srv.db.conn.Exec("INSERT OR IGNORE INTO nodes (public_key, name, lat, lon, role) VALUES (?, ?, ?, ?, ?)", "c0c0c0c0c0", "Context", 37.1, -122.1, "repeater") + srv.store.InvalidateNodeCache() + srv.store.rebuildHiddenIdentities() + graph := NewNeighborGraph() + for i := 0; i < 100; i++ { + graph.upsertEdge("c0c0c0c0c0", hidDD, "dd1", "obs1", nil, time.Now()) + } + graph.builtAt = time.Now() + srv.neighborGraph.Store(graph) + + rr := httptest.NewRecorder() + router.ServeHTTP(rr, httptest.NewRequest("GET", "/api/resolve-hops?hops=dd1&from_node=c0c0c0c0c0", nil)) + body := rr.Body.String() + if strings.Contains(body, hidDD) || strings.Contains(body, "Node-D1") || strings.Contains(body, "55.6137") { + t.Errorf("resolve-hops names the hidden node: %s", body) + } + var res ResolveHopsResponse + json.Unmarshal(rr.Body.Bytes(), &res) + hr := res.Resolved["dd1"] + if hr == nil || len(hr.Candidates) != 2 || hr.BestCandidate != nil || hr.Confidence != "ambiguous" { + t.Fatalf("want 2 visible candidates, no bestCandidate, ambiguous: %s", body) + } + }) + } +} + +// Control: with nothing hidden the same requests still name the node, so +// the redaction tests above cannot pass vacuously. +func TestHiddenHops1023_NothingHiddenControl(t *testing.T) { + f := hopFixture(t, "none") + w := f.get("/api/packets?limit=50") + assertHopRedacted(t, "control list", hopFind(t, w.Body.Bytes(), hopRelayHash)["resolved_path"], hidPK, visPK) + w = f.get("/api/packets/" + hopRelayHash + "/path") + if !strings.Contains(w.Body.String(), hidPK) { + t.Fatalf("control path lost the hop: %s", w.Body.String()) + } + ws := newHidWS(f) + id := hopTx(t, f.srv.db, "b2d00000000000f2", PayloadGRP_TXT, hopGrpJSON(), time.Now()) + hopObs(t, f.srv.db, id, `["c0","aa"]`, hopRP(hidPK, visPK), time.Now()) + if frames := ws.tick(); !strings.Contains(frames, hidPK) { + t.Fatalf("control ws lost the hop: %s", frames) + } +} + +// Hiding follows the identity's current state (owner decision, M1): renamed +// back, its hops are served again after the next rebuild. +func TestHiddenHops1023_RenameBack(t *testing.T) { + f := hopFixture(t, "prefix") + assertHopRedacted(t, "hidden", hopFind(t, f.get("/api/packets?limit=50").Body.Bytes(), hopRelayHash)["resolved_path"], nil, visPK) + f.srv.db.conn.Exec(`UPDATE nodes SET name = 'HideMe' WHERE public_key = ?`, hidPK) + f.store.rebuildHiddenIdentities() + assertHopRedacted(t, "renamed back", hopFind(t, f.get("/api/packets?limit=50").Body.Bytes(), hopRelayHash)["resolved_path"], hidPK, visPK) +} + +// redactPath never writes into the slice it is given: resolved paths come +// from the shared LRU. +func TestHiddenHops1023_RedactCopyOnWrite(t *testing.T) { + h, v := hidPK, visPK + rp := []*string{&h, &v} + p := &hiddenPredicate{snap: &hiddenIdentitySnapshot{pk: map[string]struct{}{hidPK: {}}}} + out := p.redactPath(rp) + if rp[0] == nil || *rp[0] != hidPK { + t.Fatal("redactPath changed its input") + } + if out[0] != nil || out[1] == nil || *out[1] != visPK { + t.Fatalf("redactPath = %v", out) + } + visible := []*string{&v} + if got := p.redactPath(visible); &got[0] != &visible[0] { + t.Error("a path with no hidden hop is copied") + } + var nilP *hiddenPredicate + if got := nilP.redactPath(rp); &got[0] != &rp[0] { + t.Error("a nil predicate copies") + } +} + +// A blacklist set after the snapshot was built is applied before the next +// rebuild: the live config is part of the rule. +func TestHiddenHops1023_BlacklistBeforeRebuild(t *testing.T) { + f := hopFixture(t, "none") + f.cfg.SetNodeBlacklist([]string{hidPK}) + w := f.get("/api/packets?limit=50") + assertNoHiddenIdentity(t, "list", w.Body.String()) + assertHopRedacted(t, "list", hopFind(t, w.Body.Bytes(), hopRelayHash)["resolved_path"], nil, visPK) +} + +// A hop key stored in upper case is the same identity. +func TestHiddenHops1023_UpperCaseHop(t *testing.T) { + up, v := strings.ToUpper(hidPK), visPK + p := &hiddenPredicate{snap: &hiddenIdentitySnapshot{pk: map[string]struct{}{hidPK: {}}}} + if out := p.redactPath([]*string{&up, &v}); out[0] != nil || out[1] == nil { + t.Fatalf("redactPath(upper-case hidden key) = %v", out) + } +} diff --git a/cmd/server/hidden_hops_bench_test.go b/cmd/server/hidden_hops_bench_test.go new file mode 100644 index 000000000..dbc92e54e --- /dev/null +++ b/cmd/server/hidden_hops_bench_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "fmt" + "testing" +) + +// #1023 M2 perf proof (AGENTS.md rule 0): redacting hidden hops is one map +// lookup per hop of a served packet, nothing when no key can be hidden. The +// store is M1's benchmark store (30K packets, 2K nodes, 50 named 🚫); the +// paths are 30K resolved paths of 1–8 hops over the same 2K keys, so about +// 2.5 % of hops (and more of the paths) belong to a hidden identity. + +func hopBenchPaths(n, nodes int) [][]*string { + keys := make([]*string, nodes) + for i := range keys { + k := fmt.Sprintf("%064x", i+1) + keys[i] = &k + } + paths := make([][]*string, n) + for i := range paths { + rp := make([]*string, 1+i%8) + for j := range rp { + if (i+j)%5 == 4 { + continue // an unresolved hop + } + rp[j] = keys[(i*7+j*13)%nodes] + } + paths[i] = rp + } + return paths +} + +// BenchmarkHiddenHopsRedact30K serves every one of 30K paths once: the +// cost of the list, the detail, the batch observations and the WebSocket +// summed over a 30K-packet store. +func BenchmarkHiddenHopsRedact30K(b *testing.B) { + s := hidBenchStore(b, 30000, 2000, 50, "off") + paths := hopBenchPaths(30000, 2000) + for _, m := range hidBenchModes { + hidBenchConfigure(s, m.prefixes) + b.Run(m.name, func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + hops := s.hiddenHopPredicate() + for _, rp := range paths { + _ = hops.redactPath(rp) + } + } + }) + } +} + +// BenchmarkHiddenHopsBroadcast is one poll's WebSocket batch at its cap +// (100 transmissions + 500 observations). +func BenchmarkHiddenHopsBroadcast600(b *testing.B) { + s := hidBenchStore(b, 30000, 2000, 50, "off") + paths := hopBenchPaths(600, 2000) + msgs := make([]map[string]interface{}, len(paths)) + for j := range msgs { + msgs[j] = map[string]interface{}{"packet": map[string]interface{}{}} + } + for _, m := range hidBenchModes { + hidBenchConfigure(s, m.prefixes) + b.Run(m.name, func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + // Each message carries its stored path again (the same + // two map writes in every mode), then the poll redacts. + for j, msg := range msgs { + msg["resolved_path"] = paths[j] + msg["packet"].(map[string]interface{})["resolved_path"] = paths[j] + } + hops := s.hiddenHopPredicate() + for _, msg := range msgs { + hops.redactBroadcast(msg) + } + } + }) + } +} + +// TestHiddenHopsRedactAllocs enforces the claim: with no hiding configured +// or nobody hidden the predicate is nil and serving 30K paths allocates +// nothing; with 50 hidden only the paths that have a hidden hop are copied. +// AllocsPerRun counts every goroutine's allocations, and on a busy CI +// runner under -race a full test run adds a few (37 on 1365 copies were +// seen), so the bound has a constant plus 10 % slack: still far below one +// allocation per hop (about 4.5 per path), the regression it guards. +func TestHiddenHopsRedactAllocs(t *testing.T) { + s := hidBenchStore(t, 30000, 2000, 50, "off") + paths := hopBenchPaths(30000, 2000) + run := func(prefixes []string) (allocs float64, copied int) { + hidBenchConfigure(s, prefixes) + hops := s.hiddenHopPredicate() + for _, rp := range paths { + if out := hops.redactPath(rp); len(rp) > 0 && &out[0] != &rp[0] { + copied++ + } + } + least := -1.0 + for trial := 0; trial < 3; trial++ { + a := testing.AllocsPerRun(3, func() { + hops := s.hiddenHopPredicate() + for _, rp := range paths { + _ = hops.redactPath(rp) + } + }) + if least < 0 || a < least { + least = a + } + } + return least, copied + } + for _, m := range hidBenchModes[:2] { + if a, c := run(m.prefixes); a > 5 || c != 0 { + t.Errorf("%s: %v allocs, %d paths copied; want none", m.name, a, c) + } + // Nothing can be hidden: no predicate, one pointer test per path. + if s.hiddenHopPredicate() != nil { + t.Errorf("%s: a hop predicate although no key can be hidden", m.name) + } + } + a, c := run(hidBenchModes[2].prefixes) + if c == 0 || a > float64(c)*1.1+5 { + t.Errorf("50 hidden: %v allocs for %d copied paths; want one per copied path", a, c) + } + if s.hiddenHopPredicate() == nil { + t.Fatal("50 hidden: nil predicate") + } +} diff --git a/cmd/server/hidden_identity_packets.go b/cmd/server/hidden_identity_packets.go index 06969734c..9e733a64f 100644 --- a/cmd/server/hidden_identity_packets.go +++ b/cmd/server/hidden_identity_packets.go @@ -465,12 +465,7 @@ func (p *hiddenPredicate) hidesUncovered(tx *StoreTx) bool { // the identity's current state. A row read from SQLite is not known to be // the newest, so its own name does not count. func (p *hiddenPredicate) hidesSender(key, name string, ownName bool) bool { - if key != "" { - if _, ok := p.snap.pk[key]; ok || identityHidden(p.cfg, key) { - return true - } - } - return ownName && p.cfg.IsNameHidden(name) + return p.hidesKey(key) || (ownName && p.cfg.IsNameHidden(name)) } // hidesRow applies the rule to a transmission row read from SQLite: its diff --git a/cmd/server/observer_analytics.go b/cmd/server/observer_analytics.go index da2c026e0..08ccfacd9 100644 --- a/cmd/server/observer_analytics.go +++ b/cmd/server/observer_analytics.go @@ -218,6 +218,7 @@ func buildRecentPackets(store *PacketStore, filtered []observerObs, limit int) [ return []map[string]interface{}{} } out := make([]map[string]interface{}, 0, limit) + hops := store.hiddenHopPredicate() // #1023 M2: once per request for i, obs := range filtered { if i >= limit { break @@ -225,7 +226,7 @@ func buildRecentPackets(store *PacketStore, filtered []observerObs, limit int) [ if _, ok := obs.ParsedTime(); !ok { continue } - out = append(out, store.enrichObsWithTx(obs.StoreObs, obs.obsTx)) + out = append(out, store.enrichObsWithTx(obs.StoreObs, obs.obsTx, hops)) } return out } diff --git a/cmd/server/resolved_index.go b/cmd/server/resolved_index.go index c8cafa8a7..491cfab3b 100644 --- a/cmd/server/resolved_index.go +++ b/cmd/server/resolved_index.go @@ -36,6 +36,10 @@ type resolvedPathJob struct { } func (s *PacketStore) applyResolvedPathJobs(jobs []resolvedPathJob) { + if len(jobs) == 0 { + return + } + hops := s.hiddenHopPredicate() // #1023 M2: served, so hidden hops are null for _, job := range jobs { var rp []*string if job.forTx { @@ -44,7 +48,7 @@ func (s *PacketStore) applyResolvedPathJobs(jobs []resolvedPathJob) { rp = s.fetchResolvedPathForObs(job.obsID) } if rp != nil { - job.set(rp) + job.set(hops.redactPath(rp)) } } } diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 4ea377251..4c8ac0afd 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -1517,6 +1517,17 @@ func (s *Server) handlePackets(w http.ResponseWriter, r *http.Request) { writeError(w, 400, nodesErr.Error()) return } + // #1023 M2: a hidden identity's key or name does not re-link the + // packets it relayed or sent; only the visible filters stay. + visible, ok := s.visibleNodeFilters(w, cleaned) + if !ok { + return + } + if len(visible) == 0 { + writeJSON(w, &PacketResult{Packets: []jsonObject{}, Limit: queryLimit(r, 50, s.cfg.ListLimits.PacketsMax), Offset: queryInt(r, "offset", 0)}) + return + } + cleaned = visible order := "DESC" if r.URL.Query().Get("order") == "asc" { order = "ASC" @@ -1564,6 +1575,17 @@ func (s *Server) handlePackets(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("order") == "asc" { q.Order = "ASC" } + if q.Node != "" { + // #1023 M2: as for nodes above; a hidden node lists nothing. + visible, ok := s.visibleNodeFilters(w, []string{q.Node}) + if !ok { + return + } + if len(visible) == 0 { + writeJSON(w, &PacketResult{Packets: []jsonObject{}, Limit: q.Limit, Offset: q.Offset}) + return + } + } if v := r.URL.Query().Get("type"); v != "" { t, _ := strconv.Atoi(v) q.Type = &t @@ -3590,6 +3612,20 @@ func (s *Server) handleResolveHops(w http.ResponseWriter, r *http.Request) { if s.store != nil { _, pm = s.store.getCachedNodesAndPM() } + // #1023 M2: a hidden identity (M1's rule: blacklists, a hidden current + // name, or a newest advert with one) is neither a candidate nor a pick. + // Without a store there is no prefix map and nothing to resolve. + var hiddenHops *hiddenPredicate + if pm != nil { + var err error + if hiddenHops, err = s.hiddenHops(); err != nil { + writeError(w, 500, "identity visibility lookup failed") + return + } + } + hidden := func(ni *nodeInfo) bool { + return hiddenHops.hidesKey(ni.PublicKey) || (s.cfg != nil && s.cfg.IsNameHidden(ni.Name)) + } for _, hop := range hops { if hop == "" { @@ -3603,13 +3639,9 @@ func (s *Server) handleResolveHops(w http.ResponseWriter, r *http.Request) { if pm != nil { if matched, ok := pm.m[hopLower]; ok { for _, ni := range matched { - // Skip blacklisted nodes from resolution results. - if s.cfg != nil && s.cfg.IsBlacklisted(ni.PublicKey) { - continue - } - // #1181: skip hidden-prefix nodes too. We have the - // name on ni so no extra DB lookup is needed. - if s.cfg != nil && s.cfg.IsNameHidden(ni.Name) { + // Skip hidden nodes (#742 blacklist, #1181 hidden-prefix + // name on ni, #1023 the shared hidden set). + if hidden(&ni) { continue } c := HopCandidate{Pubkey: ni.PublicKey} @@ -3680,9 +3712,13 @@ func (s *Server) handleResolveHops(w http.ResponseWriter, r *http.Request) { } // Use the resolved node as the default (best-effort pick). - // Skip if the best pick is blacklisted or has a hidden-prefix - // name (#1181). - if best != nil && !(s.cfg != nil && (s.cfg.IsBlacklisted(best.PublicKey) || s.cfg.IsNameHidden(best.Name))) { + // A hidden pick is dropped entirely: not the default, not the + // bestCandidate (it leaked here before #1023 M2), and its + // confidence tier is not reported. + if best != nil && hidden(best) { + best = nil + } + if best != nil { hr.Name = best.Name hr.Pubkey = best.PublicKey } @@ -3896,7 +3932,13 @@ func (s *Server) handleChannelMessages(w http.ResponseWriter, r *http.Request) { region := r.URL.Query().Get("region") // Prefer DB for full history (in-memory store has limited retention) if s.db != nil { - messages, total, err := s.db.GetChannelMessages(hash, limit, offset, region) + // #1023 M2: the ping-bot reply does not name a hidden relay. + hops, err := s.hiddenHops() + if err != nil { + writeError(w, 500, err.Error()) + return + } + messages, total, err := s.db.getVisibleChannelMessages(hash, limit, offset, region, hops) if err != nil { writeError(w, 500, err.Error()) return @@ -4250,7 +4292,13 @@ func (s *Server) handlePacketPath(w http.ResponseWriter, r *http.Request) { writeError(w, 404, "Not found") return } - resp, err := s.db.getPacketPath(hash, EstimateMaxEdgeKm, s.estimatedPositionsEnabled()) + // #1023 M2: nor does a hidden identity appear as one of its hops. + hops, err := s.hiddenHops() + if err != nil { + writeError(w, 500, err.Error()) + return + } + resp, err := s.db.getVisiblePacketPath(hash, EstimateMaxEdgeKm, s.estimatedPositionsEnabled(), hops) if err != nil { writeError(w, 500, err.Error()) return diff --git a/cmd/server/store.go b/cmd/server/store.go index 97ec54f32..ac970cc72 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -2737,9 +2737,10 @@ func (s *PacketStore) groupedPageWithRP(txs []*StoreTx, total, offset, limit int return res } rps := s.fetchResolvedPathsForObsIDs(ids) + hops := s.hiddenHopPredicate() // #1023 M2 for i, id := range ids { if rp := rps[id]; rp != nil { - res.Packets[i]["resolved_path"] = rp + res.Packets[i]["resolved_path"] = hops.redactRaw(rp) } } return res @@ -4867,10 +4868,14 @@ func snapObsTx(tx *StoreTx) obsTx { // keep JSON decode / enrichment off the hot lock, per #1481) should resolve // each observation's transmission (snapObsTx) during their RLock-held // snapshot and pass it in here. -func (s *PacketStore) enrichObsWithTx(obs *StoreObs, t obsTx) map[string]interface{} { +// +// hops is the request's hidden-hop predicate (#1023 M2), taken once by the +// caller (hiddenHopPredicate allocates when hiding is configured), not +// once per observation. +func (s *PacketStore) enrichObsWithTx(obs *StoreObs, t obsTx, hops *hiddenPredicate) map[string]interface{} { m := enrichObsFields(obs, t) if rp := s.fetchResolvedPathForObs(obs.ID); rp != nil { - m["resolved_path"] = rp + m["resolved_path"] = hops.redactPath(rp) } return m } diff --git a/cmd/server/websocket.go b/cmd/server/websocket.go index 921c64cb1..e65d165df 100644 --- a/cmd/server/websocket.go +++ b/cmd/server/websocket.go @@ -471,6 +471,8 @@ func (p *Poller) pollStore(lastID, lastObsID int) (int, int) { ids = append(ids, id) } hidden := p.store.hiddenTxIDs(ids) + // #1023 M2: the packets that stay carry no hidden identity as a hop. + hops := p.store.hiddenHopPredicate() if len(newTxs) > 0 { log.Printf("[broadcast] sending %d packets to %d clients (lastID now %d)", len(newTxs), p.hub.ClientCount(), lastID) } @@ -478,6 +480,7 @@ func (p *Poller) pollStore(lastID, lastObsID int) (int, int) { if _, h := hidden[ids[i]]; h { continue } + hops.redactBroadcast(tx) p.hub.Broadcast(WSMessage{ Type: "packet", Data: tx, @@ -487,6 +490,7 @@ func (p *Poller) pollStore(lastID, lastObsID int) (int, int) { if _, h := hidden[ids[len(newTxs)+i]]; h { continue } + hops.redactBroadcast(obs) p.hub.Broadcast(WSMessage{ Type: "packet", Data: obs, diff --git a/config.example.json b/config.example.json index 3f2e093ee..b667694c7 100644 --- a/config.example.json +++ b/config.example.json @@ -6,7 +6,7 @@ "nodeBlacklist": [], "_comment_nodeBlacklist": "Public keys of nodes to hide from all API responses. Use for trolls, offensive names, or nodes reporting false data that operators refuse to fix.", "hiddenNamePrefixes": ["🚫"], - "_comment_hiddenNamePrefixes": "Node name prefixes that mark a node as hidden from this dashboard (#1181). Mirrors a convention used by other MeshCore map dashboards: an operator who wants their node hidden renames it to start with one of these prefixes and sends an advert. A hidden node (also one in nodeBlacklist or observerBlacklist) is dropped from /api/nodes, /api/nodes/search and /api/nodes/{pubkey}, and its adverts and ANON_REQ packets, which carry its public key and an advert also its name and position, are not served by /api/packets (list, grouped, ?node=, ?nodes=), /api/packets/{hash} with its path and traces (they answer as an unknown packet), the batch observations, node health, observer analytics, the audio lab or the WebSocket, including the adverts sent before the rename (#1023). Hiding follows the current name: renamed back, the node and all its adverts are shown again (within about 30 s). Packet counts still include them and DB rows are preserved, so observation history (paths, hops, distances) stays intact for analytics. A hidden node can still be named as a relay hop in other packets and in some analytics views. The node is NOT hidden from the mesh itself — only from this dashboard: turn its position off on the device too. Set to [] to disable. Default: [\"🚫\"].", + "_comment_hiddenNamePrefixes": "Node name prefixes that mark a node as hidden from this dashboard (#1181). Mirrors a convention used by other MeshCore map dashboards: an operator who wants their node hidden renames it to start with one of these prefixes and sends an advert. A hidden node (also one in nodeBlacklist or observerBlacklist) is dropped from /api/nodes, /api/nodes/search and /api/nodes/{pubkey}, and its adverts and ANON_REQ packets, which carry its public key and an advert also its name and position, are not served by /api/packets (list, grouped, ?node=, ?nodes=), /api/packets/{hash} with its path and traces (they answer as an unknown packet), the batch observations, node health, observer analytics, the audio lab or the WebSocket, including the adverts sent before the rename (#1023). Hiding follows the current name: renamed back, the node and all its adverts are shown again (within about 30 s). Packet counts still include them and DB rows are preserved, so observation history (paths, hops, distances) stays intact for analytics. Packets it relayed or sent stay, but it is not named in them: its key in resolved_path is served as null like an unresolved hop, the packet path leaves it out (and places no other hop from its position, and leaves out what it heard as an observer), the Channels ping-bot reply shows its raw hop prefix, /api/packets?node= or ?nodes= with its key or name lists nothing, and resolve-hops never picks it (#1023 M2). It can still be named in some node and analytics views, and as the observer of packets it heard in the packet list. The node is NOT hidden from the mesh itself — only from this dashboard: turn its position off on the device too. Set to [] to disable. Default: [\"🚫\"].", "observerIATAWhitelist": [], "_comment_observerIATAWhitelist": "Global IATA region whitelist. When non-empty, only observers whose IATA code (from MQTT topic) matches are processed. Case-insensitive. Empty = allow all. Unlike per-source iataFilter, this applies across all MQTT sources. A dropped region is logged by the ingestor as one '[region-filter] dropping region \"XYZ\"' line, repeated at most every iataWarnIntervalSec while it keeps arriving.", "iataWarnIntervalSec": 21600, diff --git a/docs/api-spec.md b/docs/api-spec.md index b02217cc1..c5d55bd1b 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -1478,6 +1478,22 @@ updated. Hiding follows the current state: renamed back, all of the node's adverts are served again, within about 30 s. Counts (`/api/stats`, per-type analytics) still include them. +Packets a hidden identity relayed or sent stay served (#1023 M2), but its +full key is never in them: a `resolved_path` entry (top level, per +observation, grouped, SQL fallback, batch observations, node health, +observer analytics and the WebSocket frame with its nested `packet`) is +`null`, exactly like a hop that did not resolve. `/api/packets/:hash/path` +leaves the hop out of `points` (the branch's `hops` count is unchanged) and +never estimates another hop's position from it; an observation the hidden +identity heard as an observer is left out of it whole. `/api/resolve-hops` +lists it neither as a candidate nor as `bestCandidate`. The ping-bot reply +of `/api/channels/:hash/messages` (`botReply.text`) shows the hidden relay +by its raw path prefix, never by its name or key. `/api/packets?node=` and +`?nodes=` with a hidden identity's key or name answer an empty list (a +`nodes` list keeps its visible entries). Not yet covered (#1023 M3/M4): the +hidden identity as `observer_id`/`observer_name` of the packets it heard in +the list, and `/api/nodes/:pubkey/paths`. + --- ## GET /api/packets/timestamps diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index 869ff2cc2..ccf61a665 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -394,7 +394,7 @@ A hidden node is left out of the node list, search and node page. Its adverts an Hiding follows the node's current name. When the owner renames it back, all its adverts are shown again, also the ones from the hidden period. A rename back can take up to about 30 seconds to show. -Hiding is not deleting. Packet counts still include these packets, and the database keeps them until retention removes them. The node's adverts are still sent on the radio, so other maps and apps can show them; to stop publishing a position, turn the location off on the device as well. For now, a hidden node can still be named as a relay hop in other packets and in some analytics views. +Hiding is not deleting. Packet counts still include these packets, and the database keeps them until retention removes them. The node's adverts are still sent on the radio, so other maps and apps can show them; to stop publishing a position, turn the location off on the device as well. Packets the hidden node relayed or sent are still shown, but the node is not named in them: on the Packets page, in the packet detail and path, in the Channels ping-bot reply, on Live and in replays it shows as an unknown hop (its raw hop prefix), and the path map does not place a neighbouring hop from its position. Filtering the Packets page by its key or name (`?node=`, `?nodes=`) lists nothing. When the hidden node is also an observer, the packet path leaves out what it heard. For now, it can still be named in some node and analytics views, and as the observer of the packets it heard in the packet list. ## Areas diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 6a736227e..33cb8d44c 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -366,6 +366,7 @@ {"file":"test-issue-740-m3c-dagi-analytics-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":30,"measurementNote":"New suite; #740 M3c the existing Analytics tabs honour the DAGI selection, against the real server unmocked: at 375x560 touch in light and dark from a cold #/analytics?tab=rf with real taps only, the DAGI control beside Region/Area opens its bottom sheet, aar and a tap on Aarhus put kommune=0751 in the hash next to tab=rf and on the RF request, the notice shows the server's GET /api/analytics/dagi-unpositioned count, a tap on Channels says the filter does not apply there, and the clear takes it all away with no sideways scroll; at 1440x900 every tab that honours Area sends kommune=0751 on all its requests (never an unfiltered one first) with no 400, the ten tabs that cannot honour it say so in light and dark and send no DAGI param of their own, an unknown code is never sent and leaves the hash, the hash keeps kommune across a tab and a window change, and a second selection is a new request while the hidden count is asked for once. About 30 s locally; no CI duration measured yet. Assigned to shard 1, the lightest by the sum of meanSeconds."}, {"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-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":[]} ] } diff --git a/test-issue-1023-m2-hidden-hops-e2e.js b/test-issue-1023-m2-hidden-hops-e2e.js new file mode 100644 index 000000000..36ae161cc --- /dev/null +++ b/test-issue-1023-m2-hidden-hops-e2e.js @@ -0,0 +1,217 @@ +#!/usr/bin/env node +/** + * E2E (#1023 M2): a hidden node as a relay hop is shown redacted — as an + * unknown hop — on Packets and on Live, on a real Go server. + * + * The suite starts its own server (CORESCOPE_SERVER_BIN) on a migrated copy + * of test-fixtures/e2e-fixture.db (or E2E_FIXTURE_DB, a copy prepared as in + * CI) with hiddenNamePrefixes ["🚫"], seeded with two repeaters, a hidden + * one ("🚫E2E Hidden Relay", key 1a1023…) and a visible one ("E2E Visible + * Relay", key 1b1023…), and a channel packet relayed by both (path 1a, 1b; + * resolved_path [hidden, visible]). Nothing leaves the machine. + * + * Asserts: + * 1. API: /api/packets serves the packet, resolved_path [null, visible]. + * 2. Packets, desktop 1440x900, cold deep link to the packet: the detail + * names the visible relay, shows the hidden hop as its raw prefix, and + * the page holds neither the hidden key (or its 8-char short form + * that an unknown full key renders as), name nor position. + * 3. Live: a second packet relayed by both, written to the DB while Live + * is open, arrives over the WebSocket with resolved_path [null, + * visible] (top level and nested packet), and Live's page holds + * neither the hidden key, its short form, name nor position. + * 4. Channels, phone 375x560 with touch, cold start on #/home and real + * taps (bottom nav → Channels → #test): the server's ping-bot reply + * to a "ping" relayed by both reads "via 1a → E2E Visible Relay", and + * the page holds none of the needles (PR #1094 review finding 1). + * + * Usage: + * (cd cmd/server && go build -o ../../corescope-server .) + * (cd cmd/migrate && go build -o ../../corescope-migrate .) + * CORESCOPE_SERVER_BIN=./corescope-server CORESCOPE_MIGRATE_BIN=./corescope-migrate \ + * node test-issue-1023-m2-hidden-hops-e2e.js + * Optional: E2E_PORT_BASE (default 13900) is the first port tried; + * E2E_FIXTURE_DB is the fixture to copy; SCREENSHOT_DIR writes screenshots. + */ +'use strict'; + +const assert = require('assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawn, execFileSync } = require('child_process'); +const { chromium } = require('playwright'); +const { requiredFile, freePort, stop, delay } = require('./tests/e2e-1055-live'); + +const ROOT = __dirname; +const SHOTS = process.env.SCREENSHOT_DIR || ''; +// 1-byte prefixes 1a and 1b match no other node of the fixture or the CI +// seeds, so the server's own hop resolution (the WebSocket) picks these. +const HIDDEN = '1a1023a100000000000000000000000000000000000000000000000000000001'; +const VISIBLE = '1b1023b200000000000000000000000000000000000000000000000000000002'; +const HIDDEN_NAME = '🚫E2E Hidden Relay'; +const VISIBLE_NAME = 'E2E Visible Relay'; +// Never on any page or in any frame: the key, the short form an unknown +// full key is drawn as (hop-resolver serverHopEntry), the name, the position. +const NEEDLES = [HIDDEN, HIDDEN.slice(0, 8), 'E2E Hidden Relay', '56.1023', '10.1023']; + +// A GRP_TXT relayed by the hidden and then the visible repeater: header +// 0x15 (flood, GRP_TXT), path length 0x02 (two 1-byte hops 1a 1b). +function packetSQL(text, rawTail) { + return ` +INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, payload_version, decoded_json, channel_hash) + VALUES ('15021a1b11aabb${rawTail}', lower(hex(randomblob(8))), strftime('%Y-%m-%dT%H:%M:%SZ','now'), 1, 5, 0, + '{"type":"CHAN","channel":"#test","text":"${text}"}', '#test'); +INSERT INTO observations (transmission_id, observer_idx, direction, snr, rssi, score, path_json, timestamp, resolved_path) + VALUES (last_insert_rowid(), 1, 'rx', 6.5, -93, 0, '["1a","1b"]', CAST(strftime('%s','now') AS INTEGER), + '["${HIDDEN}","${VISIBLE}"]');`; +} + +const SEED = ` +INSERT OR REPLACE INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, advert_count) + VALUES ('${HIDDEN}', '${HIDDEN_NAME}', 'repeater', 56.1023, 10.1023, strftime('%Y-%m-%dT%H:%M:%SZ','now'), '2026-01-01T00:00:00Z', 4), + ('${VISIBLE}', '${VISIBLE_NAME}', 'repeater', 56.2023, 10.2023, strftime('%Y-%m-%dT%H:%M:%SZ','now'), '2026-01-01T00:00:00Z', 4); +${packetSQL('e2e 1023 hops packets', '00112233445566778899aabbccddeeff')} +${packetSQL('E2E Pinger: ping', '0f1e2d3c4b5a69788796a5b4c3d2e1f0')}`; + +function sqlite(db, sql) { + execFileSync('sqlite3', ['-cmd', '.timeout 5000', db], { input: sql, stdio: ['pipe', 'pipe', 'pipe'] }); +} + +async function startServer(serverBin, dir) { + fs.mkdirSync(dir, { recursive: true }); + const db = path.join(dir, 'fixture.db'); + fs.copyFileSync(process.env.E2E_FIXTURE_DB || path.join(ROOT, 'test-fixtures/e2e-fixture.db'), db); + execFileSync(requiredFile('CORESCOPE_MIGRATE_BIN'), ['-db', db], { stdio: 'pipe' }); + sqlite(db, SEED); + fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ mqtt: { brokers: [] }, hiddenNamePrefixes: ['🚫'] })); + const port = await freePort(); + const base = 'http://127.0.0.1:' + port; + let log = ''; + const child = spawn(serverBin, ['-config-dir', dir, '-db', db, '-public', path.join(ROOT, 'public'), '-port', String(port)], + { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'] }); + child.stdout.on('data', c => { log = (log + c).slice(-60000); }); + child.stderr.on('data', c => { log = (log + c).slice(-60000); }); + for (let n = 0; n < 300; n++) { + assert(child.exitCode === null && child.signalCode === null, 'server exited: ' + log); + try { + const r = await fetch(base + '/api/config/client', { signal: AbortSignal.timeout(2000) }); + if (r.ok) return { child, base, db, log: () => log }; + } catch (_) { /* not up yet */ } + await delay(100); + } + throw new Error('server startup timed out: ' + log); +} + +function assertClean(label, text) { + for (const n of NEEDLES) assert(!text.includes(n), label + ' contains ' + JSON.stringify(n)); +} + +// Waits for the packet whose decoded text is `text` in /api/packets. +async function findPacket(base, text) { + for (let n = 0; n < 100; n++) { + const r = await fetch(base + '/api/packets?limit=500'); + const body = await r.text(); + const p = (JSON.parse(body).packets || []).find(x => String(x.decoded_json || '').includes(text)); + if (p) return { p, body }; + await delay(100); + } + throw new Error('packet "' + text + '" not served'); +} + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + ': ' + (e && e.stack || e)); } +} + +async function main() { + const serverBin = requiredFile('CORESCOPE_SERVER_BIN'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-1023-m2-')); + const srv = await startServer(serverBin, dir); + const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined }); + console.log('#1023 M2 hidden hops E2E on ' + srv.base); + try { + let hash; + await step('API: the packet stays, the hidden hop is null', async () => { + const { p, body } = await findPacket(srv.base, 'e2e 1023 hops packets'); + hash = p.hash; + assert.deepEqual(p.resolved_path, [null, VISIBLE]); + assertClean('/api/packets', body); + }); + + await step('Packets: the detail names the visible relay and not the hidden one', async () => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); + const errors = []; + page.on('pageerror', e => errors.push(String(e))); + await page.goto(srv.base + '/#/packets/' + hash); + await page.waitForFunction(name => document.body.innerText.includes(name), VISIBLE_NAME, { timeout: 20000 }); + await delay(500); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, '1023-m2-packets.png') }); + assertClean('Packets page', await page.content()); + assertClean('Packets text', await page.evaluate(() => document.body.innerText)); + assert.deepEqual(errors, []); + await page.close(); + }); + + await step('Live: the WebSocket frame and the page do not name the hidden relay', async () => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); + const frames = []; + page.on('websocket', ws => ws.on('framereceived', f => { if (typeof f.payload === 'string') frames.push(f.payload); })); + await page.goto(srv.base + '/#/live'); + await page.waitForFunction(() => window._liveWSHandler && window._liveWSHandler(), null, { timeout: 20000 }); + await delay(1000); + sqlite(srv.db, packetSQL('e2e 1023 hops live', 'ffeeddccbbaa99887766554433221100')); + let frame; + for (let n = 0; n < 150 && !frame; n++) { + frame = frames.find(f => f.includes('e2e 1023 hops live')); + if (!frame) await delay(100); + } + assert(frame, 'no WebSocket frame for the live packet; frames: ' + frames.length + '\n' + srv.log().slice(-2000)); + const msg = JSON.parse(frame); + assert.deepEqual(msg.data.resolved_path, [null, VISIBLE]); + assert.deepEqual(msg.data.packet.resolved_path, [null, VISIBLE]); + for (const f of frames) assertClean('WebSocket frame', f); + await delay(1500); // let Live draw the packet + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, '1023-m2-live.png') }); + assertClean('Live page', await page.content()); + await page.close(); + }); + + await step('Channels (phone): the ping-bot reply shows the hidden relay as its prefix', async () => { + const ctx = await browser.newContext({ viewport: { width: 375, height: 560 }, hasTouch: true, isMobile: true }); + const page = await ctx.newPage(); + const errors = []; + page.on('pageerror', e => errors.push(String(e))); + await page.goto(srv.base + '/#/home'); + const gotIt = page.getByRole('button', { name: 'Got it' }); + const tab = page.locator('[data-bottom-nav-tab="channels"]'); + await tab.waitFor({ state: 'visible', timeout: 20000 }); + if (await gotIt.isVisible().catch(() => false)) await gotIt.tap(); + await tab.tap(); + const item = page.locator('.ch-item[data-hash="#test"], .ch-row[data-hash="#test"]').first(); + await item.waitFor({ state: 'visible', timeout: 20000 }); + if (await gotIt.isVisible().catch(() => false)) await gotIt.tap(); + await item.tap(); + const bubble = page.locator('.ch-bot-message .ch-msg-bubble').filter({ hasText: 'pong' }).first(); + await bubble.waitFor({ timeout: 20000 }); + const text = await bubble.innerText(); + assert(text.includes('via 1a → ' + VISIBLE_NAME), 'bot reply: ' + text); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, '1023-m2-channels-phone.png') }); + assertClean('Channels page', await page.content()); + assertClean('Channels text', await page.evaluate(() => document.body.innerText)); + const api = await (await fetch(srv.base + '/api/channels/' + encodeURIComponent('#test') + '/messages')).text(); + assertClean('/api/channels/#test/messages', api); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } finally { + await browser.close(); + await stop(srv.child); + fs.rmSync(dir, { recursive: true, force: true }); + } + console.log(`\n${passed} passed, ${failed} failed`); + process.exit(failed ? 1 : 0); +} + +main().catch(e => { console.error(e); process.exit(1); });