diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1f8c5d2cf..51fd0f1e5 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -688,6 +688,7 @@ jobs: suite 2 test-issue-1639-observers-sort-e2e.js BASE_URL=$B suite 2 test-issue-748-node-analytics-coverage-e2e.js BASE_URL=$B suite 2 test-issue-2218-node-analytics-stale-e2e.js BASE_URL=$B + suite 2 test-node-analytics-heard-by-e2e.js BASE_URL=$B suite 2 test-issue-661-airtime-e2e.js BASE_URL=$B suite 1 test-health-status-e2e.js BASE_URL=$B suite 2 test-issue-1268-rf-params-e2e.js BASE_URL=$B @@ -796,6 +797,7 @@ jobs: suite 2 test-issue-1274-legend-coverage-e2e.js BASE_URL=$B suite 3 test-issue-1648-m5-icons-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 2 test-issue-1997-distance-building-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B + suite 3 test-analytics-direct-snr-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 1 test-channel-modal-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 1 test-issue-1522-trace-url-sync-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 2 test-marker-outline-weight.js CHROMIUM_REQUIRE=1 BASE_URL=$B @@ -809,6 +811,13 @@ jobs: # The lint rule that keeps network calls on CSApi (needs eslint). suite 1 test-lint-network-calls.js suite 3 test-table-sort.js + # jsdom suites for the map teardown races and vector zoom limits (#2428). + suite 2 test-map-teardown-races.js + suite 2 test-map-vector-leaflet-zoom.js + # The #2428 tile providers and the harness that serves their tiles: every + # tile host is stubbed in the browser, so the fixture server is enough. + suite 3 test-map-providers-e2e.js BASE_URL=$B + suite 3 test-map-providers-harness-e2e.js BASE_URL=$B suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B suite 1 test-nodes-export-e2e.js BASE_URL=$B diff --git a/.gitignore b/.gitignore index 5d3b6bfc0..785b4babf 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,4 @@ docs/superpowers/ # Environment-specific deploy scripts — live only on the deploy host, not tracked deploy-live.sh deploy-staging.sh +test-results/map-perf/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d14ce77a..d99b612fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ - Region filter frequency mode now shows a Region dropdown beside the Frequency one, so a deployment can be narrowed to one region of a network (`?region=910.525,SJC`). Choosing a frequency limits the Region list to regions with observers on it; quick picks work again in this mode. A frequency on its own gives the same results as before; IATA mode is unchanged. - Add region filter frequency mode (`regionFilter.mode: "frequency"`): the region dropdown on every page lists observer frequencies instead of IATA codes, so a multi-network deployment can be viewed one network at a time. Off by default; IATA mode is unchanged. - Add configurable observer-region reception frequency policy and admin Frequency panel, with per-radio status tracking, bounded freshness, unknown policy and no historical deletion. +- Merge upstream v3.19.0. Fork code now joins observers on the explicit `idx` key. Grouped writer commits (`db.batchCommitMs`) pass through a transaction the caller opens with its own `BEGIN` statement, so the v3.19 observers rebuild runs on a batched writer (before this the ingestor refused to start). Observation-cleanup archives name their columns and gain any column the source table gained (such as `observers.idx`), instead of refusing every cleanup after the rebuild. + +## [3.19.0] - 2026-11-24 + +See [docs/release-notes/v3.19.0.md](docs/release-notes/v3.19.0.md) for the full notes. 32 commits since v3.18.0: 14 fix, 8 feat, 5 test, 2 ci, 2 docs, 1 refactor. + +### Highlights +- **The ingestor rebuilds the analyzer `observers` table once** (#2407, #2445) - an explicit `idx` primary key; local indexes, triggers and views are kept. It refuses, and ingestor and server stop, on a column CoreScope did not create or a NULL `id`; v3.18.0 still starts then. **Check before upgrading if you changed `observers` by hand.** +- **The content-hash migration from #787 now runs, in the ingestor** (#2409) - only changes old installs with data from before April 18; restart the server if its log line asks. +- **`users.db` migrates to schema v10 with user accounts on** (#2429) - a v3.18.x binary refuses it afterwards, so keep the pre-upgrade copy for a rollback. +- **SNR per node from direct receptions only** (#2451, #2452, #2453, #2454) - Avg SNR, signal grade and "Heard By, direct" change; nodes nobody heard directly show no SNR. `topHops[].bestSnr`, `topHops[].medianSnr` and `hopsVsSnr` are removed from the API. +- **Planner Coverage tab** (#2406), **more map providers and your own tile servers** (#2434), **plain SMTP for account mail plus a test mail** (#2466), **repeater claims from mobile apps** (#2429, #2430). All opt-in. +- **Rows lost at startup** (#2408) and **ingest stopping after a broker restart** (#2413) are fixed. ## [3.18.0] - 2026-11-17 diff --git a/Dockerfile.web b/Dockerfile.web index e22799c95..69ef21b7c 100644 --- a/Dockerfile.web +++ b/Dockerfile.web @@ -18,10 +18,13 @@ COPY scripts/static/ scripts/static/ COPY deploy/static/ deploy/static/ # GIT_COMMIT is the cache buster on every asset (?v=); without one, the build # time, as the server does at start. CHANNEL beta, next or dev shows a badge. +# CORESCOPE_URL is the public URL for link previews (og:url, og:image); a +# static image cannot read it from requests, so without one og:url is left out. ARG GIT_COMMIT= ARG CHANNEL=static +ARG CORESCOPE_URL= RUN COMMIT="$(printf '%.12s' "${GIT_COMMIT:-$(date +%s)}")" \ - API_BASE=same-origin AUTH=true CHANNEL="$CHANNEL" OUT=/srv \ + API_BASE=same-origin AUTH=true CHANNEL="$CHANNEL" CORESCOPE_URL="$CORESCOPE_URL" OUT=/srv \ bash scripts/static/build.sh && \ rm /srv/_headers diff --git a/cmd/ingestor/README.md b/cmd/ingestor/README.md index 0ad2986b3..4afb201e5 100644 --- a/cmd/ingestor/README.md +++ b/cmd/ingestor/README.md @@ -118,7 +118,7 @@ go test -v ./... The Go ingestor creates the same v3 schema as the Node.js server: - `transmissions` — deduplicated by content hash -- `observations` — per-observer sightings with `observer_idx` (rowid reference) +- `observations` — per-observer sightings with `observer_idx` (references `observers.idx`) - `nodes` — mesh nodes discovered from adverts - `observers` — MQTT feed sources diff --git a/cmd/ingestor/advert_evidence_migration_race_test.go b/cmd/ingestor/advert_evidence_migration_race_test.go index b7965e111..2b3a7826a 100644 --- a/cmd/ingestor/advert_evidence_migration_race_test.go +++ b/cmd/ingestor/advert_evidence_migration_race_test.go @@ -19,7 +19,7 @@ func seedUnbackfilledAdvert(t *testing.T, canonical, observed string) (*Store, s t.Fatal(err) } if _, err := s.db.Exec(`INSERT INTO transmissions(id,hash,raw_hex,first_seen,payload_type,route_type) VALUES(1,'legacy-advert',?,'2026-01-01T00:00:00Z',4,?); - INSERT INTO observations(id,transmission_id,observer_idx,raw_hex,path_json,timestamp) VALUES(1,1,(SELECT rowid FROM observers WHERE id='fixture-observer'),?,'[]',1)`, canonical, int(canonical[1]-'0')&3, observed); err != nil { + INSERT INTO observations(id,transmission_id,observer_idx,raw_hex,path_json,timestamp) VALUES(1,1,(SELECT idx FROM observers WHERE id='fixture-observer'),?,'[]',1)`, canonical, int(canonical[1]-'0')&3, observed); err != nil { s.Close() t.Fatal(err) } @@ -142,7 +142,7 @@ func BenchmarkAdvertEvidenceLegacyPreservation(b *testing.B) { b.Fatal(err) } var observerIdx int64 - if err := s.db.QueryRow(`SELECT rowid FROM observers WHERE id='fixture-observer'`).Scan(&observerIdx); err != nil { + if err := s.db.QueryRow(`SELECT idx FROM observers WHERE id='fixture-observer'`).Scan(&observerIdx); err != nil { b.Fatal(err) } for _, state := range []string{"pending", "checkpointed", "complete"} { diff --git a/cmd/ingestor/advert_route_evidence_test.go b/cmd/ingestor/advert_route_evidence_test.go index bccbf8a11..3102dab2c 100644 --- a/cmd/ingestor/advert_route_evidence_test.go +++ b/cmd/ingestor/advert_route_evidence_test.go @@ -139,7 +139,7 @@ func TestAdvertRouteEvidenceBackfillResumeAndLiveUnion(t *testing.T) { if _, err := tx.Exec(`INSERT INTO transmissions(id,hash,raw_hex,first_seen,payload_type,route_type) VALUES(?,?, '1100aa','2026-01-01T00:00:00Z',4,1)`, id, fmt.Sprintf("history-%d", id)); err != nil { t.Fatal(err) } - if _, err := tx.Exec(`INSERT INTO observations(transmission_id,observer_idx,raw_hex,path_json,timestamp) VALUES(?,(SELECT rowid FROM observers WHERE id='fixture-observer'),'1200aa','[]',1)`, id); err != nil { + if _, err := tx.Exec(`INSERT INTO observations(transmission_id,observer_idx,raw_hex,path_json,timestamp) VALUES(?,(SELECT idx FROM observers WHERE id='fixture-observer'),'1200aa','[]',1)`, id); err != nil { t.Fatal(err) } } diff --git a/cmd/ingestor/batch_commit.go b/cmd/ingestor/batch_commit.go index f5398cd52..7dcf4973d 100644 --- a/cmd/ingestor/batch_commit.go +++ b/cmd/ingestor/batch_commit.go @@ -178,6 +178,12 @@ func (b *batchConn) before(ctx context.Context, kind stmtKind) error { if b.depth > 0 { return nil // inside an application transaction: run as-is } + if !b.outer && !b.c.AutoCommit() { + // The caller opened its own transaction with a plain BEGIN statement + // (e.g. dbschema's observers rebuild on a pinned connection): run + // as-is until its own COMMIT or ROLLBACK ends it. + return nil + } switch { case kind == kindControl: return b.commit() diff --git a/cmd/ingestor/batch_commit_test.go b/cmd/ingestor/batch_commit_test.go index 3044cfac6..b23e42e51 100644 --- a/cmd/ingestor/batch_commit_test.go +++ b/cmd/ingestor/batch_commit_test.go @@ -156,3 +156,55 @@ func TestBatchCommitClassify(t *testing.T) { } } } + +// A transaction the caller opens with a plain BEGIN statement on a pinned +// connection (dbschema's observers rebuild does this) runs as-is: its writes +// do not open the shared batch, and its own ROLLBACK or COMMIT ends it. +func TestBatchCommitCallerBeginStatementRunsAsIs(t *testing.T) { + s, path := openBatchTestStore(t, maxBatchCommit) + defer s.Close() + ctx := context.Background() + if _, err := s.db.Exec("INSERT INTO batch_probe VALUES (1)"); err != nil { + t.Fatal(err) // leaves the shared batch open + } + conn, err := s.db.Conn(ctx) + if err != nil { + t.Fatal(err) + } + for _, end := range []string{"ROLLBACK", "COMMIT"} { + for _, q := range []string{"BEGIN IMMEDIATE", "INSERT INTO batch_probe VALUES (2)", end} { + if _, err := conn.ExecContext(ctx, q); err != nil { + t.Fatalf("%s: %v", q, err) + } + } + } + conn.Close() + // BEGIN committed the open batch first; ROLLBACK dropped only its own row. + if n := committed(t, path); n != 2 { + t.Fatalf("committed rows = %d, want 2", n) + } +} + +// A pre-v3.19 observers table (implicit rowid only) is rebuilt when the +// ingestor opens with grouped commits, as the WAN aggregate does. +func TestBatchCommitOpenRebuildsLegacyObservers(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy.db") + raw, err := sql.Open("sqlite3", path) + if err != nil { + t.Fatal(err) + } + if _, err := raw.Exec(`CREATE TABLE observers (id TEXT PRIMARY KEY, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, packet_count INTEGER DEFAULT 0); + INSERT INTO observers (id, name) VALUES ('a', 'A'), ('b', 'B'); DELETE FROM observers WHERE id = 'a'`); err != nil { + t.Fatal(err) + } + raw.Close() + s, err := OpenStoreWithBatchCommit(path, 300, "NORMAL", time.Second, 0) + if err != nil { + t.Fatalf("open legacy DB with grouped commits: %v", err) + } + defer s.Close() + var idx int64 + if err := s.db.QueryRow("SELECT idx FROM observers WHERE id = 'b'").Scan(&idx); err != nil || idx != 2 { + t.Fatalf("observer b idx = %d, %v; want its old rowid 2", idx, err) + } +} diff --git a/cmd/ingestor/client_reception.go b/cmd/ingestor/client_reception.go index f3e73609d..12276fa34 100644 --- a/cmd/ingestor/client_reception.go +++ b/cmd/ingestor/client_reception.go @@ -172,54 +172,36 @@ type ClientReception struct { // deriveHeardKey applies the RX capture HARD RULE: record only what the // companion heard itself and directly. // - direction must be "rx". -// - payload type must not repurpose the header path bytes (TRACE stores -// per-hop SNR there, not node hashes — packetpath.PathBytesAreHops). -// - hops present AND a FLOOD route → the directly-heard node is the LAST hop -// (path[len-1] = the forwarder that just transmitted; each FLOOD forwarder -// appends its hash to the end). 1-byte (2 hex char) prefixes are rejected. -// - hops present on a DIRECT route → NOT attributable: direct forwarders -// consume the next hop from the FRONT (firmware Mesh.cpp removeSelfFromPath), -// so path[len-1] is the route's destination-side end, not who was heard. -// - hops empty + isAdvert → the 0-hop advertiser, by its full pubkey. -// - hops empty + isDiscoverResp → the 0-hop responder, by its pubkey (8 or -// 32 bytes — CTL_TYPE_NODE_DISCOVER_RESP always carries an 8-byte prefix -// or the full 32-byte key; anything else is rejected outright, not -// truncated). A node-discover reply is always a direct, zero-hop RX — +// - the path and advert part is the shared rule, packetpath.HeardKey: last +// hop of a flood route (at least 2 bytes), or the 0-hop advertiser; never +// a direct route with a path, never TRACE. +// - hops empty + isDiscoverResp: the 0-hop responder, by its pubkey (8 or +// 32 bytes; CTL_TYPE_NODE_DISCOVER_RESP always carries an 8-byte prefix +// or the full 32-byte key, anything else is rejected outright, not +// truncated). A node-discover reply is always a direct, zero-hop RX, // stronger identification than a path hash, since it carries the // responder's own identity rather than an inferred forwarder. -// - otherwise → not attributable (ok=false). +// - otherwise: not attributable (ok=false). // // Returns (heardKey lowercased, keylenBytes, src, ok). func deriveHeardKey(direction string, routeType, payloadType int, hops []string, advertPubkey string, isAdvert bool, isDiscoverResp bool, discoverPubkey string) (string, int, string, bool) { if !strings.EqualFold(direction, "rx") { return "", 0, "", false } - if !packetpath.PathBytesAreHops(byte(payloadType)) { - return "", 0, "", false - } + last, pk := "", "" if len(hops) > 0 { - // FLOOD routes (TRANSPORT_FLOOD 0, FLOOD 1) APPEND each forwarder's hash to - // the END of the path, so path[last] is the immediate RF transmitter. DIRECT - // routes (2, 3) consume the next hop from the FRONT, so path[last] is the - // route's destination-side end, NOT who was heard. - if routeType != packetpath.RouteTransportFlood && routeType != packetpath.RouteFlood { // direct route: path[last] is not the transmitter - return "", 0, "", false - } - last := strings.ToLower(strings.TrimSpace(hops[len(hops)-1])) - keylen := len(last) / 2 - if keylen < 2 { // exclude 1-byte (collision-prone), matching Reach - return "", 0, "", false - } - return last, keylen, "rxlog", true + last = hops[len(hops)-1] + } + if isAdvert { + pk = advertPubkey } - if isAdvert && advertPubkey != "" { - pk := strings.ToLower(strings.TrimSpace(advertPubkey)) - return pk, len(pk) / 2, "advert", true + if key, src, ok := packetpath.HeardKey(routeType, byte(payloadType), last, pk); ok { + return key, len(key) / 2, src, true } - if isDiscoverResp && discoverPubkey != "" { + if len(hops) == 0 && isDiscoverResp && discoverPubkey != "" && packetpath.PathBytesAreHops(byte(payloadType)) { pk := strings.ToLower(strings.TrimSpace(discoverPubkey)) keylen := len(pk) / 2 - if keylen != 8 && keylen != 32 { // discover pubkeys are always 8B (prefix) or 32B (full) — no floor, an exact set + if keylen != 8 && keylen != 32 { // discover pubkeys are always 8B (prefix) or 32B (full), no floor, an exact set return "", 0, "", false } return pk, keylen, "discover", true diff --git a/cmd/ingestor/client_reception_test.go b/cmd/ingestor/client_reception_test.go index c29662bf4..0b92435c9 100644 --- a/cmd/ingestor/client_reception_test.go +++ b/cmd/ingestor/client_reception_test.go @@ -823,3 +823,40 @@ func TestHandleClientPacketRejectsNonHexPubkey(t *testing.T) { t.Fatalf("non-hex pubkey must write nothing, got %d receptions, %d observers", nRecept, nObs) } } + +// TestDeriveHeardKey_MatchesPacketpath pins deriveHeardKey to the shared +// packetpath.HeardKey rule for every case that rule covers. +func TestDeriveHeardKey_MatchesPacketpath(t *testing.T) { + cases := []struct { + name string + routeType int + payloadType int + lastHop string + advertPubkey string + }{ + {"flood, 2-byte last hop", packetpath.RouteFlood, 0x05, "BB11", ""}, + {"transport flood counts as flood", packetpath.RouteTransportFlood, 0x05, "bb11", ""}, + {"3-byte last hop", packetpath.RouteFlood, 0x05, "bbccdd", ""}, + {"1-byte last hop refused", packetpath.RouteFlood, 0x05, "BB", ""}, + {"direct route with a path refused", packetpath.RouteDirect, 0x05, "bb11", ""}, + {"transport direct with a path refused", packetpath.RouteTransportDirect, 0x05, "bb11", ""}, + {"TRACE refused even on flood", packetpath.RouteFlood, packetpath.PayloadTRACE, "bb11", ""}, + {"0-hop advert on flood", packetpath.RouteFlood, 0x04, "", "ABCDEF01"}, + {"0-hop advert on direct (sendZeroHop)", packetpath.RouteDirect, 0x04, "", "abcdef01"}, + {"empty path, no advert pubkey", packetpath.RouteFlood, 0x05, "", ""}, + {"TRACE with empty path refused", packetpath.RouteFlood, packetpath.PayloadTRACE, "", "abcdef01"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var hops []string + if c.lastHop != "" { + hops = []string{"aa", c.lastHop} + } + wantKey, wantSrc, wantOK := packetpath.HeardKey(c.routeType, byte(c.payloadType), c.lastHop, c.advertPubkey) + key, keylen, src, ok := deriveHeardKey("rx", c.routeType, c.payloadType, hops, c.advertPubkey, c.advertPubkey != "", false, "") + if key != wantKey || src != wantSrc || ok != wantOK || keylen != len(wantKey)/2 { + t.Errorf("deriveHeardKey = (%q, %d, %q, %v), HeardKey = (%q, %q, %v)", key, keylen, src, ok, wantKey, wantSrc, wantOK) + } + }) + } +} diff --git a/cmd/ingestor/db.go b/cmd/ingestor/db.go index 6b02f4680..2a653c272 100644 --- a/cmd/ingestor/db.go +++ b/cmd/ingestor/db.go @@ -94,8 +94,9 @@ type Store struct { hopMaintMu sync.Mutex // serializes the hop index backfill and trim stmtUpsertNode *sql.Stmt stmtIncrementAdvertCount *sql.Stmt - stmtUpsertObserver *sql.Stmt - stmtGetObserverRowid *sql.Stmt + stmtUpdateObserver *sql.Stmt // UpsertObserverAt fast path; see upsertObserver + stmtUpsertObserver *sql.Stmt // its INSERT fallback for a new observer + stmtGetObserverIdx *sql.Stmt stmtUpdateObserverLastSeen *sql.Stmt stmtUpdateNodeTelemetry *sql.Stmt stmtTouchNodeLastSeen *sql.Stmt @@ -161,7 +162,7 @@ var testBatchCommit time.Duration // OpenStoreWithBatchCommit also groups writer commits into one per // batchCommit (batch_commit.go). 0 keeps one commit per write. -func OpenStoreWithBatchCommit(dbPath string, sampleIntervalSec int, synchronous string, batchCommit time.Duration, checkpointPages int) (*Store, error) { +func OpenStoreWithBatchCommit(dbPath string, sampleIntervalSec int, synchronous string, batchCommit time.Duration, checkpointPages int) (_ *Store, err error) { dsn, err := dbschema.WriterDSNWithSynchronous(dbPath, synchronous) if err != nil { return nil, err @@ -183,6 +184,13 @@ func OpenStoreWithBatchCommit(dbPath string, sampleIntervalSec int, synchronous if err != nil { return nil, fmt.Errorf("opening db: %w", err) } + // Every failure from here on must release the database: a leaked handle + // keeps the file open (on Windows it cannot even be deleted). + defer func() { + if err != nil { + db.Close() + } + }() if err := db.Ping(); err != nil { return nil, fmt.Errorf("pinging db: %w", err) @@ -326,7 +334,8 @@ func applySchema(db *sql.DB) error { ); CREATE TABLE IF NOT EXISTS observers ( - id TEXT PRIMARY KEY, + idx INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, last_seen TEXT, @@ -597,23 +606,14 @@ func applySchema(db *sql.DB) error { } } - // Create/rebuild packets_v view (v3 schema: observer_idx → observers.rowid) - // The Go server reads this view; without it fresh installs get "no such table: packets_v". - db.Exec(`DROP VIEW IF EXISTS packets_v`) - _, vErr := db.Exec(` - CREATE VIEW packets_v AS - SELECT o.id, COALESCE(o.raw_hex, t.raw_hex) AS raw_hex, - datetime(o.timestamp, 'unixepoch') AS timestamp, - obs.id AS observer_id, obs.name AS observer_name, - o.direction, o.snr, o.rssi, o.score, t.hash, t.route_type, - t.payload_type, t.payload_version, o.path_json, t.decoded_json, - t.created_at - FROM observations o - JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx AND (obs.inactive IS NULL OR obs.inactive = 0) - `) - if vErr != nil { - return fmt.Errorf("packets_v view: %w", vErr) + // Create/rebuild packets_v view (v3 schema: observer_idx → observers.idx). + // cmd/server does not read it; external SQLite readers do, and without it + // fresh installs get "no such table: packets_v". On a legacy observers table + // (implicit rowid only) it joins on the rowid until dbschema.Apply's + // observers rebuild recreates it on idx, so it stays readable if the + // rebuild refuses. + if err := dbschema.EnsurePacketsView(db); err != nil { + return fmt.Errorf("packets_v view: %w", err) } // One-time migration: recalculate advert_count to count unique transmissions only @@ -879,6 +879,10 @@ func applySchema(db *sql.DB) error { // Backfill: set last_packet_at = last_seen only for observers that actually have // observation rows (packet_count alone is unreliable — UpsertObserver sets it to 1 // on INSERT even for status-only observers). + // Deliberately rowid, not idx: this runs in applySchema, before + // dbschema.Apply rebuilds a legacy observers table with an explicit idx. + // Within one DB the two are the same value (idx is the INTEGER PRIMARY + // KEY, i.e. the rowid alias), and only rowid exists on a legacy table. res, err := db.Exec(`UPDATE observers SET last_packet_at = last_seen WHERE last_packet_at IS NULL AND rowid IN (SELECT DISTINCT observer_idx FROM observations WHERE observer_idx IS NOT NULL)`) @@ -1108,6 +1112,29 @@ func (s *Store) prepareStatements() error { return err } + // Same SET as stmtUpsertObserver's DO UPDATE, args in the same order, + // with the id last for the WHERE. + s.stmtUpdateObserver, err = s.db.Prepare(` + UPDATE observers SET + name = COALESCE(?, name), + iata = COALESCE(?, iata), + last_seen = MAX(MIN(COALESCE(last_seen, ''), ?), ?), + packet_count = packet_count + 1, + model = COALESCE(?, model), + firmware = COALESCE(?, firmware), + client_version = COALESCE(?, client_version), + radio = COALESCE(?, radio), + battery_mv = COALESCE(?, battery_mv), + uptime_secs = COALESCE(?, uptime_secs), + noise_floor = COALESCE(?, noise_floor), + can_relay = COALESCE(?, can_relay), + can_relay_seen = CASE WHEN ? IS NULL THEN can_relay_seen ELSE 1 END + WHERE id = ? + `) + if err != nil { + return err + } + s.stmtUpsertObserver, err = s.db.Prepare(` INSERT INTO observers (id, name, iata, last_seen, first_seen, packet_count, model, firmware, client_version, radio, battery_mv, uptime_secs, noise_floor, can_relay, can_relay_seen) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, 1), CASE WHEN ? IS NULL THEN 0 ELSE 1 END) @@ -1130,19 +1157,19 @@ func (s *Store) prepareStatements() error { return err } - s.stmtGetObserverRowid, err = s.db.Prepare("SELECT rowid FROM observers WHERE id = ?") + s.stmtGetObserverIdx, err = s.db.Prepare("SELECT idx FROM observers WHERE id = ?") if err != nil { return err } - // Args: ingestNow, rxTime, ingestNow, rxTime, rowid + // Args: ingestNow, rxTime, ingestNow, rxTime, idx // MIN(existing, ingestNow) clamps any future value already in the DB before // taking MAX with rxTime, so the guard never locks in a past bug's stale future. s.stmtUpdateObserverLastSeen, err = s.db.Prepare(` UPDATE observers SET last_seen = MAX(MIN(COALESCE(last_seen, ''), ?), ?), last_packet_at = MAX(MIN(COALESCE(last_packet_at, ''), ?), ?) - WHERE rowid = ?`) + WHERE idx = ?`) if err != nil { return err } @@ -1268,15 +1295,15 @@ func (s *Store) insertTransmission(data *PacketData, updateObserver bool) (bool, // Resolve observer_idx and update last_seen var observerIdx *int64 if data.ObserverID != "" { - var rowid int64 - err := tx.Stmt(s.stmtGetObserverRowid).QueryRow(data.ObserverID).Scan(&rowid) + var idx int64 + err := tx.Stmt(s.stmtGetObserverIdx).QueryRow(data.ObserverID).Scan(&idx) if err == nil { - observerIdx = &rowid + observerIdx = &idx // observer.last_seen and last_packet_at answer "when did the analyzer // last hear from this observer" — both are ingest-time questions. // Per-packet rxTime is stored separately on observations/transmissions // using envelope time (see InsertTransmission above). See #1465. - _, _ = tx.Stmt(s.stmtUpdateObserverLastSeen).Exec(ingestNow, ingestNow, ingestNow, ingestNow, rowid) + _, _ = tx.Stmt(s.stmtUpdateObserverLastSeen).Exec(ingestNow, ingestNow, ingestNow, ingestNow, idx) } } @@ -1483,13 +1510,10 @@ func (s *Store) UpsertObserverAt(id, name, iata string, meta *ObserverMeta, last } normalizedIATA := strings.TrimSpace(strings.ToUpper(iata)) - model, firmware, clientVersion, radio, batteryMv, uptimeSecs, noiseFloor, canRelay := observerMetaColumns(meta) + u := observerUpsert{id: id, name: name, iata: normalizedIATA, lastSeen: lastSeen, ingestNow: ingestNow} + u.model, u.firmware, u.clientVersion, u.radio, u.batteryMv, u.uptimeSecs, u.noiseFloor, u.canRelay = observerMetaColumns(meta) - _, err := s.stmtUpsertObserver.Exec( - id, name, normalizedIATA, lastSeen, lastSeen, model, firmware, clientVersion, radio, batteryMv, uptimeSecs, noiseFloor, canRelay, canRelay, - name, normalizedIATA, ingestNow, lastSeen, model, firmware, clientVersion, radio, batteryMv, uptimeSecs, noiseFloor, canRelay, canRelay, - ) - if err != nil { + if err := s.upsertObserver(u); err != nil { s.Stats.WriteErrors.Add(1) return err } @@ -1500,6 +1524,51 @@ func (s *Store) UpsertObserverAt(id, name, iata string, meta *ObserverMeta, last return nil } +// observerUpsert is one UpsertObserverAt write, shared by its UPDATE fast path +// and its INSERT fallback. +type observerUpsert struct { + id, name, iata, lastSeen, ingestNow string + + model, firmware, clientVersion, radio, batteryMv, uptimeSecs, noiseFloor, canRelay interface{} +} + +// upsertObserver writes u with an UPDATE, and INSERTs only when no row has +// that id. observers.idx is AUTOINCREMENT, and SQLite advances +// sqlite_sequence for every INSERT it attempts, even one ON CONFLICT turns +// into an update: as a plain upsert this would write the sequence page again +// for every ingested packet. The fallback keeps its ON CONFLICT, so a row +// created between the two statements is updated, not an error. +func (s *Store) upsertObserver(u observerUpsert) error { + updated, err := s.updateObserver(u) + if err != nil || updated { + return err + } + return s.insertObserver(u) +} + +// updateObserver applies u to an existing row and reports whether there was +// one. +func (s *Store) updateObserver(u observerUpsert) (bool, error) { + res, err := s.stmtUpdateObserver.Exec( + u.name, u.iata, u.ingestNow, u.lastSeen, u.model, u.firmware, u.clientVersion, u.radio, u.batteryMv, u.uptimeSecs, u.noiseFloor, u.canRelay, u.canRelay, + u.id, + ) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n > 0, err +} + +// insertObserver is the INSERT ... ON CONFLICT DO UPDATE fallback. +func (s *Store) insertObserver(u observerUpsert) error { + _, err := s.stmtUpsertObserver.Exec( + u.id, u.name, u.iata, u.lastSeen, u.lastSeen, u.model, u.firmware, u.clientVersion, u.radio, u.batteryMv, u.uptimeSecs, u.noiseFloor, u.canRelay, u.canRelay, + u.name, u.iata, u.ingestNow, u.lastSeen, u.model, u.firmware, u.clientVersion, u.radio, u.batteryMv, u.uptimeSecs, u.noiseFloor, u.canRelay, u.canRelay, + ) + return err +} + // UpsertObserverRetained applies the metadata from a RETAINED status message // without treating it as a sign of life. The broker replays retained messages // on every subscribe, so an ingestor restart would otherwise stamp last_seen @@ -2211,10 +2280,7 @@ func (s *Store) LogStats() { // bytes being SNR, so neither proves a hop transmitted. Same rule as the // server's certain liveness (cmd/server/certain_heard.go relayHopHexLen). func pathHopsTransmitted(data *PacketData) bool { - if !packetpath.PathBytesAreHops(byte(data.PayloadType)) { - return false - } - return data.RouteType == packetpath.RouteFlood || data.RouteType == packetpath.RouteTransportFlood + return packetpath.PathHopsTransmitted(data.RouteType, byte(data.PayloadType)) } // touchRelayNodesLocked refreshes nodes.last_seen for nodes observed as @@ -2354,7 +2420,7 @@ func (s *Store) RemoveStaleObservers(observerDays int) (int64, error) { // the second stage of observer retention: the soft-delete hides the observer, // this reclaims the row after its packets have aged out via packetDays. // -// observations.observer_idx is a bare rowid with no foreign key, so deleting a +// observations.observer_idx is a bare observers.idx with no foreign key, so deleting a // still-referenced observer silently orphans history — packets_v stops resolving // the observer and the packets are mis-attributed. The three NOT EXISTS guards // are what make the delete safe; they are correctness, not defensive padding. @@ -2372,7 +2438,7 @@ func (s *Store) PurgeStaleObservers(purgeDays int) (int64, error) { DELETE FROM observers WHERE inactive = 1 AND last_seen < ? - AND NOT EXISTS (SELECT 1 FROM observations o WHERE o.observer_idx = observers.rowid) + AND NOT EXISTS (SELECT 1 FROM observations o WHERE o.observer_idx = observers.idx) AND NOT EXISTS (SELECT 1 FROM observer_metrics m WHERE m.observer_id = observers.id) AND NOT EXISTS (SELECT 1 FROM dropped_packets d WHERE d.observer_id = observers.id)`, cutoff) if err != nil { @@ -2645,9 +2711,40 @@ func (s *Store) RecordNaiveSkew(observerID string, deltaSec int64, now time.Time } nowStr := now.UTC().Format(time.RFC3339) cutoff := now.Add(-24 * time.Hour).UTC().Format(time.RFC3339) - // One INSERT-or-UPDATE round trip. ON CONFLICT path resets the rolling - // counter when the previous event is older than the 24h window, otherwise - // increments it. + // UPDATE first, INSERT only for an unknown observer, for the same reason + // as upsertObserver: an attempted INSERT advances sqlite_sequence. + updated, err := s.updateNaiveSkew(observerID, deltaSec, nowStr, cutoff) + if err != nil || updated { + return err + } + return s.insertNaiveSkew(observerID, deltaSec, nowStr, cutoff) +} + +// updateNaiveSkew records a naive-clock event on an existing observer and +// reports whether there was one. The rolling counter resets to 1 when the +// previous event is older than the 24h window (cutoff), otherwise increments. +func (s *Store) updateNaiveSkew(observerID string, deltaSec int64, nowStr, cutoff string) (bool, error) { + res, err := s.db.Exec(` + UPDATE observers SET + clock_skew_seconds = ?, + clock_last_naive_at = ?, + clock_skew_count_24h = CASE + WHEN clock_last_naive_at IS NULL OR clock_last_naive_at < ? + THEN 1 + ELSE COALESCE(clock_skew_count_24h, 0) + 1 + END + WHERE id = ? + `, deltaSec, nowStr, cutoff, observerID) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n > 0, err +} + +// insertNaiveSkew is RecordNaiveSkew's INSERT ... ON CONFLICT DO UPDATE +// fallback for an observer that has no row yet. +func (s *Store) insertNaiveSkew(observerID string, deltaSec int64, nowStr, cutoff string) error { _, err := s.db.Exec(` INSERT INTO observers (id, clock_skew_seconds, clock_skew_count_24h, clock_last_naive_at) VALUES (?, ?, 1, ?) diff --git a/cmd/ingestor/db_test.go b/cmd/ingestor/db_test.go index 9cd4fbfef..710f7ae4e 100644 --- a/cmd/ingestor/db_test.go +++ b/cmd/ingestor/db_test.go @@ -2111,7 +2111,7 @@ func TestPerObservationRawHex(t *testing.T) { rows, err := store.db.Query(` SELECT o.raw_hex, obs.id FROM observations o - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx ORDER BY o.id ASC `) if err != nil { diff --git a/cmd/ingestor/neighbor_builder.go b/cmd/ingestor/neighbor_builder.go index c66d4fc27..00b6535cf 100644 --- a/cmd/ingestor/neighbor_builder.go +++ b/cmd/ingestor/neighbor_builder.go @@ -188,6 +188,7 @@ func (s *Store) buildAndPersistNeighborEdges(trust *packetpath.TrustConfig) (int } rows, err := s.db.Query(`SELECT + t.route_type, t.payload_type, t.decoded_json, COALESCE(t.from_pubkey, ''), @@ -196,7 +197,7 @@ func (s *Store) buildAndPersistNeighborEdges(trust *packetpath.TrustConfig) (int o.timestamp FROM observations o JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE o.timestamp > ? AND o.direction IS NOT 'tx' -- the observer's own transmission, not a reception (#667) ORDER BY o.timestamp @@ -208,12 +209,20 @@ func (s *Store) buildAndPersistNeighborEdges(trust *packetpath.TrustConfig) (int var edges []edgeRow for rows.Next() { - var payloadType sql.NullInt64 + var routeType, payloadType sql.NullInt64 var decodedJSON, fromPubkey, pathJSON, observerID string var epochTs int64 - if err := rows.Scan(&payloadType, &decodedJSON, &fromPubkey, &pathJSON, &observerID, &epochTs); err != nil { + if err := rows.Scan(&routeType, &payloadType, &decodedJSON, &fromPubkey, &pathJSON, &observerID, &epochTs); err != nil { continue } + // Same rule as the server's neighbour graph: only a path that lists + // transmitted hops names a neighbour (packetpath.PathHopsTransmitted), + // and an empty path only when it proves the originator was heard. + // A NULL route type or payload type proves nothing. + if !routeType.Valid || !payloadType.Valid { + continue + } + rt, pt := int(routeType.Int64), byte(payloadType.Int64) isAdvert := payloadType.Valid && payloadType.Int64 == int64(payloadADVERT) isAnonReq := payloadType.Valid && payloadType.Int64 == int64(payloadAnonReq) // #1777: ANON_REQ's ephemeralPubKey is as trustworthy an originator @@ -233,11 +242,14 @@ func (s *Store) buildAndPersistNeighborEdges(trust *packetpath.TrustConfig) (int path := parsePathArray(pathJSON) if len(path) == 0 { - if hasFullOriginator && fromNode != "" && fromNode != observerPK && observerPK != "" { + if packetpath.EmptyPathHeardOriginator(rt, pt) && hasFullOriginator && fromNode != "" && fromNode != observerPK && observerPK != "" { edges = append(edges, canonEdge(fromNode, observerPK, ts)) } continue } + if !packetpath.PathHopsTransmitted(rt, pt) { + continue + } if hasFullOriginator && fromNode != "" { if resolved, ok := resolvePrefix(prefixIdx, path[0], trust); ok && resolved != fromNode { edges = append(edges, canonEdge(fromNode, resolved, ts)) diff --git a/cmd/ingestor/neighbor_builder_delta_test.go b/cmd/ingestor/neighbor_builder_delta_test.go index 4e530953e..f8882a318 100644 --- a/cmd/ingestor/neighbor_builder_delta_test.go +++ b/cmd/ingestor/neighbor_builder_delta_test.go @@ -49,7 +49,7 @@ func TestNeighborEdgesBuilderDeltaScan(t *testing.T) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } diff --git a/cmd/ingestor/neighbor_builder_test.go b/cmd/ingestor/neighbor_builder_test.go index a78c09369..2ed3e6f55 100644 --- a/cmd/ingestor/neighbor_builder_test.go +++ b/cmd/ingestor/neighbor_builder_test.go @@ -2,6 +2,7 @@ package main import ( "path/filepath" + "strings" "testing" "github.com/meshcore-analyzer/packetpath" @@ -44,7 +45,7 @@ func TestNeighborEdgesBuilderUpsertsFromObservations(t *testing.T) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } @@ -118,7 +119,7 @@ func TestNeighborEdgesBuilderUpsertsFromAnonReqEphemeralPubKey(t *testing.T) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } @@ -190,7 +191,7 @@ func TestNeighborEdgesBuilderExcludesOtherNonAdvertTypes(t *testing.T) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } @@ -250,7 +251,7 @@ func seedTrustFixture(t *testing.T, store *Store, hop string) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } res, err := store.db.Exec( @@ -354,7 +355,7 @@ func TestNeighborEdgesBuilderSkipsOwnTransmissions(t *testing.T) { t.Fatal(err) } var obsRowid int64 - if err := store.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsRowid); err != nil { t.Fatal(err) } res, err := store.db.Exec( @@ -384,3 +385,66 @@ func TestNeighborEdgesBuilderSkipsOwnTransmissions(t *testing.T) { t.Fatalf("a tx observation produced %d neighbor_edges rows, want 0", got) } } + +// The persisted edges follow the same rule as the server's neighbor graph: +// TRACE path bytes are SNR values, and a direct route carries the REMAINING +// route (removeSelfFromPath), so neither names a node next to the observer +// or the originator. A zero hop on a direct route (sendZeroHop) does. +func TestNeighborEdgesBuilderSkipsTraceAndDirectRoutePaths(t *testing.T) { + store, err := OpenStore(filepath.Join(t.TempDir(), "route.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + defer store.Close() + if _, err := store.db.Exec(`INSERT INTO nodes (public_key, name) VALUES (?, ?), (?, ?), (?, ?)`, + "aaaaaaaaaa", "originator", "bbbbbbbbbb", "hop", "cccccccccc", "zero-hop-advertiser"); err != nil { + t.Fatal(err) + } + if _, err := store.db.Exec(`INSERT INTO observers (id, name) VALUES (?, ?)`, "obs-1", "observer-1"); err != nil { + t.Fatal(err) + } + var obsIdx int64 + if err := store.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, "obs-1").Scan(&obsIdx); err != nil { + t.Fatal(err) + } + add := func(hash string, routeType, payloadType int, from, path string) { + t.Helper() + res, err := store.db.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, payload_version, decoded_json, from_pubkey) + VALUES ('', ?, '2026-01-01T00:00:00Z', ?, ?, 0, '{}', ?)`, hash, routeType, payloadType, from) + if err != nil { + t.Fatal(err) + } + id, _ := res.LastInsertId() + if _, err := store.db.Exec(`INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp) VALUES (?, ?, ?, ?)`, + id, obsIdx, path, int64(1735689600)); err != nil { + t.Fatal(err) + } + } + add("trace", RouteFlood, PayloadTRACE, "", `["bb"]`) + add("direct-advert", RouteDirect, payloadADVERT, "aaaaaaaaaa", `["bb"]`) + add("transport-direct-txt", RouteTransportDirect, PayloadTXT_MSG, "", `["bb"]`) + add("zero-hop", RouteDirect, payloadADVERT, "cccccccccc", `[]`) + // sendDirect's last leg: empty path after removeSelfFromPath, sent by the forwarder. + add("direct-anon-req-empty", RouteDirect, payloadAnonReq, "aaaaaaaaaa", `[]`) + + if _, err := store.buildAndPersistNeighborEdges(trustAllPrefixes()); err != nil { + t.Fatalf("buildAndPersistNeighborEdges: %v", err) + } + rows, err := store.db.Query(`SELECT node_a, node_b FROM neighbor_edges ORDER BY node_a, node_b`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var got []string + for rows.Next() { + var a, b string + if err := rows.Scan(&a, &b); err != nil { + t.Fatal(err) + } + got = append(got, a+"|"+b) + } + want := []string{"cccccccccc|obs-1"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("edges = %v, want %v (only the zero-hop advertiser↔observer)", got, want) + } +} diff --git a/cmd/ingestor/observation_cleanup.go b/cmd/ingestor/observation_cleanup.go index 39722ba1d..16c2b3793 100644 --- a/cmd/ingestor/observation_cleanup.go +++ b/cmd/ingestor/observation_cleanup.go @@ -41,8 +41,12 @@ func ensureCleanupSchema(tx *sql.Tx) error { } } - // Refuse unsafe archive layouts after a future source schema migration. No - // delete happens until every archive can store every current column. + // A source table that gained a column since its archive was created (for + // example observers.idx, added by the v3.19 rebuild) gets that column added + // to the archive; older archive rows hold NULL there. Archive and restore + // name their columns, so column order does not matter. Anything else, such + // as missing leading archive keys, is refused: no delete happens until + // every archive can store every current column. for _, p := range [][3]string{{"observations", "observation_cleanup_obs", "observer_key"}, {"transmissions", "observation_cleanup_tx", ""}, {"observers", "observation_cleanup_observers", ""}, {"observation_radios", "observation_cleanup_radios", ""}, {"advert_route_evidence", "observation_cleanup_advert", ""}} { live, e := cleanupColumns(tx, p[0]) if e != nil { @@ -52,17 +56,46 @@ func ensureCleanupSchema(tx *sql.Tx) error { if e != nil { return e } - expected := append([]string{"cleanup_id"}, live...) + keys := []string{"cleanup_id"} if p[2] != "" { - expected = append([]string{"cleanup_id", p[2]}, live...) + keys = append(keys, p[2]) } - if strings.Join(expected, ",") != strings.Join(arch, ",") { + if len(arch) < len(keys) || strings.Join(arch[:len(keys)], ",") != strings.Join(keys, ",") { return fmt.Errorf("archive schema mismatch for %s; archive migration required before cleanup", p[0]) } + have := make(map[string]bool, len(arch)) + for _, c := range arch { + have[c] = true + } + for _, c := range live { + if have[c] { + continue + } + if _, e := tx.Exec(`ALTER TABLE "` + p[1] + `" ADD COLUMN ` + quotedColumns([]string{c})); e != nil { + return fmt.Errorf("add %s.%s to cleanup archive: %w", p[0], c, e) + } + } } return nil } +// archiveInsert copies rows of a live table into its cleanup archive by +// column name. prefix holds the archive's leading key columns, filled from +// prefixExprs; from is the SELECT's FROM/WHERE tail, with alias naming the +// live table in it. +func archiveInsert(tx *sql.Tx, verb, live, archive, alias string, prefix, prefixExprs []string, from string, args []interface{}) error { + cols, err := cleanupColumns(tx, live) + if err != nil { + return err + } + src := append([]string{}, prefixExprs...) + for _, c := range cols { + src = append(src, alias+"."+quotedColumns([]string{c})) + } + _, err = tx.Exec(verb+` INTO `+archive+` (`+quotedColumns(append(append([]string{}, prefix...), cols...))+`) SELECT `+strings.Join(src, ",")+` `+from, args...) + return err +} + func cleanupColumns(tx *sql.Tx, table string) ([]string, error) { rows, err := tx.Query(`PRAGMA table_info("` + table + `")`) if err != nil { @@ -217,7 +250,7 @@ func (s *Store) processObservationCleanup(req prunequeue.CleanupRequest, between func cleanupDeleteBatch(tx *sql.Tx, req prunequeue.CleanupRequest, cursor int64) (int64, int64, error) { where, args := req.Selection.Where() args = append(args, cursor, cleanupBatchSize) - rows, err := tx.Query(`SELECT o.id FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE `+where+` AND o.id>? ORDER BY o.id LIMIT ?`, args...) + rows, err := tx.Query(`SELECT o.id FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE `+where+` AND o.id>? ORDER BY o.id LIMIT ?`, args...) if err != nil { return 0, 0, err } @@ -228,14 +261,19 @@ func cleanupDeleteBatch(tx *sql.Tx, req prunequeue.CleanupRequest, cursor int64) ph, a := idList(ids) backupArgs := append([]interface{}{req.ID}, a...) // Complete backup rows and sparse radio metadata are written before delete. - for _, q := range []string{ - `INSERT OR IGNORE INTO observation_cleanup_observers SELECT ?,ob.* FROM observers ob WHERE ob.rowid IN (SELECT observer_idx FROM observations WHERE id IN (` + ph + `))`, - `INSERT OR IGNORE INTO observation_cleanup_tx SELECT ?,t.* FROM transmissions t WHERE t.id IN (SELECT transmission_id FROM observations WHERE id IN (` + ph + `))`, - `INSERT INTO observation_cleanup_obs SELECT ?,ob.id,o.* FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE o.id IN (` + ph + `)`, - `INSERT OR IGNORE INTO observation_cleanup_radios SELECT ?,r.* FROM observation_radios r WHERE observation_id IN (` + ph + `)`, - `INSERT OR IGNORE INTO observation_cleanup_advert SELECT ?,e.* FROM advert_route_evidence e WHERE tx_id IN (SELECT transmission_id FROM observations WHERE id IN (` + ph + `))`, + one := []string{"cleanup_id"} + for _, q := range []struct { + verb, live, archive, alias string + prefix, exprs []string + from string + }{ + {"INSERT OR IGNORE", "observers", "observation_cleanup_observers", "ob", one, []string{"?"}, `FROM observers ob WHERE ob.idx IN (SELECT observer_idx FROM observations WHERE id IN (` + ph + `))`}, + {"INSERT OR IGNORE", "transmissions", "observation_cleanup_tx", "t", one, []string{"?"}, `FROM transmissions t WHERE t.id IN (SELECT transmission_id FROM observations WHERE id IN (` + ph + `))`}, + {"INSERT", "observations", "observation_cleanup_obs", "o", []string{"cleanup_id", "observer_key"}, []string{"?", "ob.id"}, `FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE o.id IN (` + ph + `)`}, + {"INSERT OR IGNORE", "observation_radios", "observation_cleanup_radios", "r", one, []string{"?"}, `FROM observation_radios r WHERE observation_id IN (` + ph + `)`}, + {"INSERT OR IGNORE", "advert_route_evidence", "observation_cleanup_advert", "e", one, []string{"?"}, `FROM advert_route_evidence e WHERE tx_id IN (SELECT transmission_id FROM observations WHERE id IN (` + ph + `))`}, } { - if _, err = tx.Exec(q, backupArgs...); err != nil { + if err = archiveInsert(tx, q.verb, q.live, q.archive, q.alias, q.prefix, q.exprs, q.from, backupArgs); err != nil { return 0, 0, fmt.Errorf("archive rows: %w", err) } } @@ -307,6 +345,16 @@ func cleanupRestoreBatch(tx *sql.Tx, req prunequeue.CleanupRequest, cursor int64 if err != nil { return 0, 0, err } + // idx is the observer's key; a restored observer gets a fresh one (an + // archived idx may belong to another observer by now). Observations are + // re-linked by observer id below. + kept := bc[:0] + for _, c := range bc { + if c != "idx" { + kept = append(kept, c) + } + } + bc = kept bs := make([]string, len(bc)) for i, c := range bc { bs[i] = `b."` + c + `"` @@ -332,7 +380,7 @@ func cleanupRestoreBatch(tx *sql.Tx, req prunequeue.CleanupRequest, cursor int64 case "transmission_id": source = append(source, "t.id") case "observer_idx": - source = append(source, "ob.rowid") + source = append(source, "ob.idx") default: source = append(source, `b."`+c+`"`) } @@ -342,7 +390,7 @@ func cleanupRestoreBatch(tx *sql.Tx, req prunequeue.CleanupRequest, cursor int64 return 0, 0, err } n, _ := res.RowsAffected() - _, err = tx.Exec(`INSERT OR IGNORE INTO observation_radios(observation_id,radio_id) SELECT r.observation_id,r.radio_id FROM observation_cleanup_radios r JOIN observations o ON o.id=r.observation_id JOIN observation_cleanup_obs b ON b.cleanup_id=r.cleanup_id AND b.id=o.id JOIN observers ob ON ob.rowid=o.observer_idx AND ob.id=b.observer_key JOIN observation_cleanup_tx bt ON bt.cleanup_id=b.cleanup_id AND bt.id=b.transmission_id JOIN transmissions t ON t.id=o.transmission_id AND t.hash=bt.hash WHERE o.timestamp=b.timestamp AND COALESCE(o.path_json,'')=COALESCE(b.path_json,'') AND COALESCE(o.raw_hex,'')=COALESCE(b.raw_hex,'') AND r.cleanup_id=? AND r.observation_id IN (`+ph+`)`, args...) + _, err = tx.Exec(`INSERT OR IGNORE INTO observation_radios(observation_id,radio_id) SELECT r.observation_id,r.radio_id FROM observation_cleanup_radios r JOIN observations o ON o.id=r.observation_id JOIN observation_cleanup_obs b ON b.cleanup_id=r.cleanup_id AND b.id=o.id JOIN observers ob ON ob.idx=o.observer_idx AND ob.id=b.observer_key JOIN observation_cleanup_tx bt ON bt.cleanup_id=b.cleanup_id AND bt.id=b.transmission_id JOIN transmissions t ON t.id=o.transmission_id AND t.hash=bt.hash WHERE o.timestamp=b.timestamp AND COALESCE(o.path_json,'')=COALESCE(b.path_json,'') AND COALESCE(o.raw_hex,'')=COALESCE(b.raw_hex,'') AND r.cleanup_id=? AND r.observation_id IN (`+ph+`)`, args...) if err != nil { return 0, 0, err } diff --git a/cmd/ingestor/observation_cleanup_test.go b/cmd/ingestor/observation_cleanup_test.go index e2631a506..628e9ce91 100644 --- a/cmd/ingestor/observation_cleanup_test.go +++ b/cmd/ingestor/observation_cleanup_test.go @@ -225,7 +225,7 @@ func TestObservationCleanupPartialFailureRecoverableAndObserverRestored(t *testi if e != nil || rr.Restored != 500 { t.Fatalf("partial restore %+v %v", rr, e) } - if n := cleanupCount(t, s, "SELECT count(*) FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE ob.id='bad'"); n != 500 { + if n := cleanupCount(t, s, "SELECT count(*) FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE ob.id='bad'"); n != 500 { t.Fatalf("observer restore total %d", n) } } @@ -235,7 +235,9 @@ func TestObservationCleanupSchemaMismatchFailsClosed(t *testing.T) { if e := s.WriterTx("test", ensureCleanupSchema); e != nil { t.Fatal(e) } - if _, e := s.db.Exec(`ALTER TABLE observations ADD COLUMN future_metadata TEXT`); e != nil { + // An archive whose leading key columns are not the expected ones cannot be + // trusted to restore: no delete happens. + if _, e := s.db.Exec(`ALTER TABLE observation_cleanup_obs RENAME COLUMN observer_key TO renamed_key`); e != nil { t.Fatal(e) } r, e := s.ProcessObservationCleanup(cleanupReq(3)) @@ -246,6 +248,38 @@ func TestObservationCleanupSchemaMismatchFailsClosed(t *testing.T) { t.Fatalf("deleted despite mismatch %d", n) } } + +// A source column added after the archive was created (as observers.idx is by +// the v3.19 rebuild) is added to the archive, archived and restored. +func TestObservationCleanupArchiveGainsNewSourceColumn(t *testing.T) { + s := cleanupTestStore(t) + cleanupSeed(t, s, 3) + if e := s.WriterTx("test", ensureCleanupSchema); e != nil { + t.Fatal(e) + } + // Simulate an archive made before observers had idx, plus a new column. + if _, e := s.db.Exec(`ALTER TABLE observation_cleanup_observers DROP COLUMN idx; ALTER TABLE observations ADD COLUMN future_metadata TEXT; UPDATE observations SET future_metadata='kept-' || id`); e != nil { + t.Fatal(e) + } + req := cleanupReq(3) + r, e := s.ProcessObservationCleanup(req) + if e != nil || r.Deleted != 3 { + t.Fatalf("cleanup %+v %v", r, e) + } + if n := cleanupCount(t, s, "SELECT count(*) FROM observation_cleanup_obs WHERE future_metadata LIKE 'kept-%'"); n != 3 { + t.Fatalf("archived new column %d", n) + } + if n := cleanupCount(t, s, "SELECT count(*) FROM observation_cleanup_observers WHERE idx IS NOT NULL"); n == 0 { + t.Fatalf("observer idx not archived") + } + rr, e := s.ProcessObservationCleanup(prunequeue.CleanupRequest{ID: "fe0123", RequestedAt: time.Now().UTC(), RestoreID: req.ID}) + if e != nil || rr.Restored != 3 { + t.Fatalf("restore %+v %v", rr, e) + } + if n := cleanupCount(t, s, "SELECT count(*) FROM observations WHERE future_metadata LIKE 'kept-%'"); n != 4 { + t.Fatalf("restored new column %d", n) + } +} func TestObservationCleanupRestoreDoesNotOverwriteNewObservationRadio(t *testing.T) { s := cleanupTestStore(t) cleanupSeed(t, s, 3) @@ -308,7 +342,7 @@ func TestObservationCleanupSelectionUsesObserverIndex(t *testing.T) { sel.To = 9999 where, args := sel.Where() args = append(args, 0, cleanupBatchSize) - rows, e := s.db.Query(`EXPLAIN QUERY PLAN SELECT o.id FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE `+where+` AND o.id>? ORDER BY o.id LIMIT ?`, args...) + rows, e := s.db.Query(`EXPLAIN QUERY PLAN SELECT o.id FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE `+where+` AND o.id>? ORDER BY o.id LIMIT ?`, args...) if e != nil { t.Fatal(e) } diff --git a/cmd/ingestor/observer_purge_test.go b/cmd/ingestor/observer_purge_test.go index 5a8f672f2..1282a3b5d 100644 --- a/cmd/ingestor/observer_purge_test.go +++ b/cmd/ingestor/observer_purge_test.go @@ -6,7 +6,7 @@ import ( ) // staleObserver inserts an observer already soft-deleted (inactive = 1) with -// last_seen ageDays in the past, and returns its rowid. +// last_seen ageDays in the past, and returns its idx. func staleObserver(t *testing.T, s *Store, id string) int64 { t.Helper() if err := s.UpsertObserver(id, id, "LAX", nil); err != nil { @@ -16,11 +16,11 @@ func staleObserver(t *testing.T, s *Store, id string) int64 { if _, err := s.db.Exec(`UPDATE observers SET last_seen = ?, inactive = 1 WHERE id = ?`, old, id); err != nil { t.Fatal(err) } - var rowid int64 - if err := s.db.QueryRow(`SELECT rowid FROM observers WHERE id = ?`, id).Scan(&rowid); err != nil { + var idx int64 + if err := s.db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, id).Scan(&idx); err != nil { t.Fatal(err) } - return rowid + return idx } func observerExists(t *testing.T, s *Store, id string) bool { @@ -48,12 +48,12 @@ func TestPurgeStaleObserversDeletesUnreferencedRow(t *testing.T) { } } -// Regression: an observer whose rowid is still referenced by observations must +// Regression: an observer whose idx is still referenced by observations must // survive the purge — deleting it orphans observations.observer_idx, which // breaks the packets_v join and mis-attributes historical packets. func TestPurgeStaleObserversKeepsObserverWithObservations(t *testing.T) { store := newTestStore(t) - rowid := staleObserver(t, store, "obs-referenced") + idx := staleObserver(t, store, "obs-referenced") if _, err := store.db.Exec( `INSERT INTO transmissions (id, raw_hex, hash, first_seen) VALUES (1, 'AA', 'h1', ?)`, @@ -62,7 +62,7 @@ func TestPurgeStaleObserversKeepsObserverWithObservations(t *testing.T) { t.Fatal(err) } if _, err := store.db.Exec( - `INSERT INTO observations (transmission_id, observer_idx, timestamp) VALUES (1, ?, 0)`, rowid, + `INSERT INTO observations (transmission_id, observer_idx, timestamp) VALUES (1, ?, 0)`, idx, ); err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func TestPurgeStaleObserversKeepsObserverWithObservations(t *testing.T) { var orphans int if err := store.db.QueryRow( `SELECT COUNT(*) FROM observations WHERE observer_idx IS NOT NULL - AND observer_idx NOT IN (SELECT rowid FROM observers)`, + AND observer_idx NOT IN (SELECT idx FROM observers)`, ).Scan(&orphans); err != nil { t.Fatal(err) } diff --git a/cmd/ingestor/observer_upsert_bench_test.go b/cmd/ingestor/observer_upsert_bench_test.go new file mode 100644 index 000000000..e6e517994 --- /dev/null +++ b/cmd/ingestor/observer_upsert_bench_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "fmt" + "io" + "log" + "os" + "testing" + "time" +) + +// BenchmarkUpsertObserverAtExisting measures the per-packet observer upsert +// for observers that already have a row, on a store opened by OpenStore (WAL, +// synchronous=FULL, the real observers table), spread over 500 observers. +// +// "default" keeps the store's pragmas, so ns/op is the wall time per call. +// "no-autocheckpoint" turns the automatic checkpoint off so the WAL keeps +// every frame, and reports wal-frames/op: what each call wrote. +// +// go test -run '^$' -bench BenchmarkUpsertObserverAtExisting -benchtime 20000x . +func BenchmarkUpsertObserverAtExisting(b *testing.B) { + // OpenStore logs, and the lines would split the benchmark's result line. + log.SetOutput(io.Discard) + defer log.SetOutput(os.Stderr) + for _, autoCheckpoint := range []bool{true, false} { + name := "default" + if !autoCheckpoint { + name = "no-autocheckpoint" + } + b.Run(name, func(b *testing.B) { + s, err := OpenStore(b.TempDir() + "/bench.db") + if err != nil { + b.Fatal(err) + } + s.WaitForAsyncMigrations() + defer s.Close() + + const observers = 500 + ids := make([]string, observers) + for i := range ids { + ids[i] = fmt.Sprintf("obs-%03d", i) + if err := s.UpsertObserverAt(ids[i], ids[i], "sjc", nil, "2026-01-01T00:00:00Z"); err != nil { + b.Fatal(err) + } + } + if !autoCheckpoint { + if _, err := s.db.Exec(`PRAGMA wal_autocheckpoint = 0`); err != nil { + b.Fatal(err) + } + } + if _, err := s.db.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`); err != nil { + b.Fatal(err) + } + meta := &ObserverMeta{BatteryMv: new(int)} + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + *meta.BatteryMv = 3700 + i%100 + ts := base.Add(time.Duration(i) * time.Second).Format(time.RFC3339) + if err := s.UpsertObserverAt(ids[i%observers], ids[i%observers], "sjc", meta, ts); err != nil { + b.Fatal(err) + } + } + b.StopTimer() + + if !autoCheckpoint { + var busy, frames, done int + if err := s.db.QueryRow(`PRAGMA wal_checkpoint(PASSIVE)`).Scan(&busy, &frames, &done); err != nil { + b.Fatal(err) + } + b.ReportMetric(float64(frames)/float64(b.N), "wal-frames/op") + } + }) + } +} diff --git a/cmd/ingestor/observer_upsert_sequence_test.go b/cmd/ingestor/observer_upsert_sequence_test.go new file mode 100644 index 000000000..044d890bc --- /dev/null +++ b/cmd/ingestor/observer_upsert_sequence_test.go @@ -0,0 +1,315 @@ +package main + +import ( + "database/sql" + "fmt" + "reflect" + "testing" + "time" +) + +// observers.idx is INTEGER PRIMARY KEY AUTOINCREMENT, and SQLite advances +// sqlite_sequence for every INSERT it attempts — including one that ON +// CONFLICT turns into an update. The observer upserts run per ingested +// packet, so they must take an UPDATE when the row exists and INSERT only +// for a new observer: otherwise every packet writes the sequence page too. + +func observersSeq(t *testing.T, db *sql.DB) int64 { + t.Helper() + var seq int64 + if err := db.QueryRow(`SELECT seq FROM sqlite_sequence WHERE name = 'observers'`).Scan(&seq); err != nil { + t.Fatalf("read observers sequence: %v", err) + } + return seq +} + +func observerIdx(t *testing.T, db *sql.DB, id string) int64 { + t.Helper() + var idx int64 + if err := db.QueryRow(`SELECT idx FROM observers WHERE id = ?`, id).Scan(&idx); err != nil { + t.Fatalf("idx of %s: %v", id, err) + } + return idx +} + +func TestUpsertObserverAtLeavesSequenceAlone(t *testing.T) { + s := newTestStore(t) + if err := s.UpsertObserverAt("obs-a", "A", "sjc", nil, "2026-01-01T00:00:00Z"); err != nil { + t.Fatal(err) + } + seq := observersSeq(t, s.db) + + const n = 1000 + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for i := 1; i <= n; i++ { + ts := base.Add(time.Duration(i) * time.Second).Format(time.RFC3339) + if err := s.UpsertObserverAt("obs-a", "A", "sjc", nil, ts); err != nil { + t.Fatalf("upsert %d: %v", i, err) + } + } + if got := observersSeq(t, s.db); got != seq { + t.Fatalf("observers sequence moved %d -> %d over %d upserts of an existing observer", seq, got, n) + } + var count int + var lastSeen string + if err := s.db.QueryRow(`SELECT packet_count, last_seen FROM observers WHERE id = 'obs-a'`).Scan(&count, &lastSeen); err != nil { + t.Fatal(err) + } + if want := base.Add(n * time.Second).Format(time.RFC3339); count != n+1 || lastSeen != want { + t.Fatalf("obs-a packet_count=%d last_seen=%s, want %d / %s", count, lastSeen, n+1, want) + } + if got := s.Stats.ObserverUpserts.Load(); got != n+1 { + t.Fatalf("ObserverUpserts = %d, want %d", got, n+1) + } + + var maxIdx int64 + if err := s.db.QueryRow(`SELECT MAX(idx) FROM observers`).Scan(&maxIdx); err != nil { + t.Fatal(err) + } + if err := s.UpsertObserverAt("obs-b", "B", "sjc", nil, "2026-01-02T00:00:00Z"); err != nil { + t.Fatal(err) + } + if got := observerIdx(t, s.db, "obs-b"); got != maxIdx+1 { + t.Fatalf("new observer idx = %d, want %d", got, maxIdx+1) + } + var count2 int + if err := s.db.QueryRow(`SELECT packet_count FROM observers WHERE id = 'obs-b'`).Scan(&count2); err != nil || count2 != 1 { + t.Fatalf("new observer packet_count = %d (%v), want 1", count2, err) + } +} + +func TestRecordNaiveSkewLeavesSequenceAlone(t *testing.T) { + s := newTestStore(t) + if err := s.UpsertObserverAt("obs-a", "A", "sjc", nil, "2026-01-01T00:00:00Z"); err != nil { + t.Fatal(err) + } + seq := observersSeq(t, s.db) + + const n = 1000 + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + for i := 0; i < n; i++ { + if err := s.RecordNaiveSkew("obs-a", -3600, now.Add(time.Duration(i)*time.Second)); err != nil { + t.Fatalf("skew %d: %v", i, err) + } + } + if got := observersSeq(t, s.db); got != seq { + t.Fatalf("observers sequence moved %d -> %d over %d skew records of an existing observer", seq, got, n) + } + var count int + if err := s.db.QueryRow(`SELECT clock_skew_count_24h FROM observers WHERE id = 'obs-a'`).Scan(&count); err != nil || count != n { + t.Fatalf("obs-a clock_skew_count_24h = %d (%v), want %d", count, err, n) + } + + // An observer the analyzer has not seen yet still gets a row. + if err := s.RecordNaiveSkew("obs-new", 7200, now); err != nil { + t.Fatal(err) + } + var skew sql.NullInt64 + var newCount int + var lastNaive string + if err := s.db.QueryRow(`SELECT clock_skew_seconds, clock_skew_count_24h, clock_last_naive_at FROM observers WHERE id = 'obs-new'`). + Scan(&skew, &newCount, &lastNaive); err != nil { + t.Fatalf("unknown observer row: %v", err) + } + if skew.Int64 != 7200 || newCount != 1 || lastNaive != now.Format(time.RFC3339) { + t.Fatalf("unknown observer row: skew=%v count=%d last=%s", skew, newCount, lastNaive) + } + if got := observerIdx(t, s.db, "obs-new"); got != seq+1 { + t.Fatalf("new observer idx = %d, want %d", got, seq+1) + } +} + +// observerRowCols is every observers column but the two keys, which differ by +// construction between the rows an equivalence case compares. +const observerRowCols = `name, iata, last_seen, first_seen, packet_count, model, firmware, + client_version, radio, battery_mv, uptime_secs, noise_floor, inactive, last_packet_at, + clock_skew_seconds, clock_skew_count_24h, clock_last_naive_at, can_relay, can_relay_seen` + +func observerRow(t *testing.T, db *sql.DB, id string) []string { + t.Helper() + rows := dumpQuery(t, db, `SELECT `+observerRowCols+` FROM observers WHERE id = '`+id+`'`) + if len(rows) != 1 { + t.Fatalf("observer %s: %d rows", id, len(rows)) + } + return rows +} + +// seedObserverPair inserts two observers, "upd" and "old", with identical +// columns. +func seedObserverPair(t *testing.T, db *sql.DB, vals []any) { + t.Helper() + for _, id := range []string{"upd", "old"} { + args := append([]any{id}, vals...) + if _, err := db.Exec(`INSERT INTO observers (id, `+observerRowCols+`) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + } +} + +func boolp(b bool) *bool { return &b } + +// The UPDATE fast path leaves an existing observer exactly as the INSERT ... +// ON CONFLICT DO UPDATE statement (still the fallback) does. +func TestUpdateObserverMatchesUpsert(t *testing.T) { + const now = "2026-06-01T12:00:00Z" + full := []any{"Old name", "SJC", "2026-06-01T10:00:00Z", "2026-01-01T00:00:00Z", 7, + "L1", "1.15", "cv1", "sx1262", 3700, 99, -110.5, 0, "2026-06-01T09:00:00Z", + -30, 2, "2026-06-01T08:00:00Z", 1, 0} + with := func(i int, v any) []any { + out := append([]any(nil), full...) + out[i] = v + return out + } + cases := []struct { + name string + seed []any + obsName string + meta *ObserverMeta + lastSeen string + want map[int]string // column index -> expected value, beyond equivalence + }{ + {"nil meta keeps every column", full, "New name", nil, "2026-06-01T11:00:00Z", + map[int]string{0: "New name", 2: "2026-06-01T11:00:00Z", 4: "8", 5: "L1", 17: "1", 18: "0"}}, + {"empty strings overwrite, nil fields keep", full, "", &ObserverMeta{Model: strp(""), Firmware: strp("1.16")}, "2026-06-01T11:00:00Z", + map[int]string{0: "", 5: "", 6: "1.16", 7: "cv1"}}, + {"NULL columns take meta", []any{nil, nil, nil, nil, 0, nil, nil, nil, nil, nil, nil, nil, 0, nil, nil, 0, nil, 1, 0}, + "N", &ObserverMeta{Model: strp("L2")}, "2026-06-01T11:00:00Z", + map[int]string{0: "N", 2: "2026-06-01T11:00:00Z", 5: "L2"}}, + {"last_seen does not move backwards", full, "N", nil, "2026-06-01T09:00:00Z", + map[int]string{2: "2026-06-01T10:00:00Z"}}, + {"future last_seen clamps to ingest time", with(2, "2027-01-01T00:00:00Z"), "N", nil, "2026-06-01T11:00:00Z", + map[int]string{2: now}}, + {"NULL packet_count stays NULL", with(4, nil), "N", nil, "2026-06-01T11:00:00Z", + map[int]string{4: ""}}, + {"can_relay unset keeps seen=1 state", with(18, 1), "N", nil, "2026-06-01T11:00:00Z", + map[int]string{17: "1", 18: "1"}}, + {"repeat:off", full, "N", &ObserverMeta{CanRelay: boolp(false)}, "2026-06-01T11:00:00Z", + map[int]string{17: "0", 18: "1"}}, + {"repeat:on after off", with(17, 0), "N", &ObserverMeta{CanRelay: boolp(true)}, "2026-06-01T11:00:00Z", + map[int]string{17: "1", 18: "1"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestStore(t) + seedObserverPair(t, s.db, tc.seed) + seeded := observerRow(t, s.db, "old") + + u := observerUpsert{name: tc.obsName, iata: "SJC", lastSeen: tc.lastSeen, ingestNow: now} + u.model, u.firmware, u.clientVersion, u.radio, u.batteryMv, u.uptimeSecs, u.noiseFloor, u.canRelay = observerMetaColumns(tc.meta) + u.id = "upd" + updated, err := s.updateObserver(u) + if err != nil || !updated { + t.Fatalf("updateObserver = %v, %v; want true, nil", updated, err) + } + u.id = "old" + if err := s.insertObserver(u); err != nil { + t.Fatal(err) + } + + got, want := observerRow(t, s.db, "upd"), observerRow(t, s.db, "old") + if !reflect.DeepEqual(got, want) { + t.Fatalf("UPDATE path differs from the upsert:\nseed =%v\nupdate=%v\nupsert=%v", seeded, got, want) + } + cols := dumpQueryCols(t, s.db, `SELECT `+observerRowCols+` FROM observers WHERE id = 'upd'`) + for i, v := range tc.want { + if cols[i] != v { + t.Errorf("column %d = %q, want %q (row %v)", i, cols[i], v, got) + } + } + }) + } + + t.Run("unknown observer", func(t *testing.T) { + s := newTestStore(t) + updated, err := s.updateObserver(observerUpsert{id: "nobody", name: "N", lastSeen: now, ingestNow: now}) + if err != nil || updated { + t.Fatalf("updateObserver on a missing row = %v, %v; want false, nil", updated, err) + } + var n int + if err := s.db.QueryRow(`SELECT COUNT(*) FROM observers`).Scan(&n); err != nil || n != 0 { + t.Fatalf("observers rows = %d (%v), want 0", n, err) + } + }) +} + +// The UPDATE fast path of RecordNaiveSkew leaves an existing observer exactly +// as the INSERT ... ON CONFLICT DO UPDATE fallback does. +func TestUpdateNaiveSkewMatchesUpsert(t *testing.T) { + now := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC) + nowStr := now.Format(time.RFC3339) + cutoff := now.Add(-24 * time.Hour).Format(time.RFC3339) + cases := []struct { + name string + lastNaive any + count any + wantCount string + }{ + {"first event", nil, 0, "1"}, + {"previous event outside 24h resets", "2026-05-30T12:00:00Z", 9, "1"}, + {"previous event inside 24h increments", "2026-06-01T11:00:00Z", 9, "10"}, + {"previous event exactly at the cutoff increments", cutoff, 9, "10"}, + {"NULL count inside 24h", "2026-06-01T11:00:00Z", nil, "1"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestStore(t) + seedObserverPair(t, s.db, []any{"N", "SJC", "2026-06-01T10:00:00Z", "2026-01-01T00:00:00Z", 3, + nil, nil, nil, nil, nil, nil, nil, 0, nil, 120, tc.count, tc.lastNaive, 1, 0}) + + updated, err := s.updateNaiveSkew("upd", -3600, nowStr, cutoff) + if err != nil || !updated { + t.Fatalf("updateNaiveSkew = %v, %v; want true, nil", updated, err) + } + if err := s.insertNaiveSkew("old", -3600, nowStr, cutoff); err != nil { + t.Fatal(err) + } + got, want := observerRow(t, s.db, "upd"), observerRow(t, s.db, "old") + if !reflect.DeepEqual(got, want) { + t.Fatalf("UPDATE path differs from the upsert:\nupdate=%v\nupsert=%v", got, want) + } + cols := dumpQueryCols(t, s.db, `SELECT clock_skew_seconds, clock_skew_count_24h, clock_last_naive_at FROM observers WHERE id = 'upd'`) + if cols[0] != "-3600" || cols[1] != tc.wantCount || cols[2] != nowStr { + t.Fatalf("skew columns = %v, want [-3600 %s %s]", cols, tc.wantCount, nowStr) + } + }) + } + + t.Run("unknown observer", func(t *testing.T) { + s := newTestStore(t) + updated, err := s.updateNaiveSkew("nobody", 60, nowStr, cutoff) + if err != nil || updated { + t.Fatalf("updateNaiveSkew on a missing row = %v, %v; want false, nil", updated, err) + } + }) +} + +// dumpQueryCols returns the single row of query as one string per column. +func dumpQueryCols(t *testing.T, db *sql.DB, query string) []string { + t.Helper() + rows, err := db.Query(query) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + cols, _ := rows.Columns() + if !rows.Next() { + t.Fatalf("%s: no row", query) + } + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + if err := rows.Scan(ptrs...); err != nil { + t.Fatal(err) + } + out := make([]string, len(vals)) + for i, v := range vals { + if b, ok := v.([]byte); ok { + v = string(b) + } + out[i] = fmt.Sprintf("%v", v) + } + return out +} diff --git a/cmd/ingestor/observers_idx_openstore_test.go b/cmd/ingestor/observers_idx_openstore_test.go new file mode 100644 index 000000000..79c1177c4 --- /dev/null +++ b/cmd/ingestor/observers_idx_openstore_test.go @@ -0,0 +1,222 @@ +package main + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// legacyObserversTableDDL is the observers table as the previous release left +// it: every canonical column, but the implicit rowid instead of idx. +const legacyObserversTableDDL = `CREATE TABLE observers ( + id TEXT PRIMARY KEY, + name TEXT, + iata TEXT, + last_seen TEXT, + first_seen TEXT, + packet_count INTEGER DEFAULT 0, + model TEXT, + firmware TEXT, + client_version TEXT, + radio TEXT, + battery_mv INTEGER, + uptime_secs INTEGER, + noise_floor REAL, + inactive INTEGER DEFAULT 0, + last_packet_at TEXT DEFAULT NULL, + clock_skew_seconds INTEGER DEFAULT NULL, + clock_skew_count_24h INTEGER DEFAULT 0, + clock_last_naive_at TEXT DEFAULT NULL, + can_relay INTEGER DEFAULT 1, + can_relay_seen INTEGER DEFAULT 0 +)` + +// legacyStoreDB builds a database as an upgrade from the previous release +// finds it: a full ingestor schema (every migration recorded) whose observers +// table is still the legacy rowid shape, with observations pointing at those +// rowids. mutate then makes the table one the rebuild must refuse. +func legacyStoreDB(t *testing.T, mutate ...string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "legacy.db") + s, err := OpenStore(path) + if err != nil { + t.Fatal(err) + } + s.WaitForAsyncMigrations() + if err := s.Close(); err != nil { + t.Fatal(err) + } + + db, err := sql.Open("sqlite3", path+"?_journal_mode=WAL") + if err != nil { + t.Fatal(err) + } + defer db.Close() + stmts := []string{ + `DROP VIEW packets_v`, + `DROP TABLE observers`, + `DELETE FROM sqlite_sequence WHERE name = 'observers'`, + legacyObserversTableDDL, + `CREATE INDEX idx_observers_last_seen ON observers(last_seen)`, + `INSERT INTO observers (id, name) VALUES ('a', 'A'), ('b', 'B'), ('c', 'C')`, + `DELETE FROM observers WHERE id = 'b'`, + `INSERT INTO transmissions (id, raw_hex, hash, first_seen) VALUES (1, 'aa', 'h1', '2026-01-01T00:00:00Z')`, + `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp) VALUES (1, 1, '[]', 1000), (1, 3, '[]', 1001), (1, 2, '[]', 1002)`, + } + stmts = append(stmts, mutate...) + for _, q := range stmts { + if _, err := db.Exec(q); err != nil { + t.Fatalf("legacy fixture %q: %v", q, err) + } + } + // The legacy-shape view, on the rowid join, as the previous release had it. + if _, err := db.Exec(`CREATE VIEW packets_v AS + SELECT o.id, obs.id AS observer_id FROM observations o + JOIN transmissions t ON t.id = o.transmission_id + LEFT JOIN observers obs ON obs.rowid = o.observer_idx`); err != nil { + t.Fatal(err) + } + return path +} + +func dumpQuery(t *testing.T, db *sql.DB, query string) []string { + t.Helper() + rows, err := db.Query(query) + if err != nil { + t.Fatalf("%s: %v", query, err) + } + defer rows.Close() + cols, _ := rows.Columns() + var out []string + for rows.Next() { + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + if err := rows.Scan(ptrs...); err != nil { + t.Fatal(err) + } + out = append(out, fmt.Sprintf("%v", vals)) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return out +} + +// observersSnapshot is what a refused rebuild must leave as it found it. +func observersSnapshot(t *testing.T, path string) (table, rows, links []string) { + t.Helper() + db, err := sql.Open("sqlite3", path+"?mode=ro") + if err != nil { + t.Fatal(err) + } + defer db.Close() + table = dumpQuery(t, db, `SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'observers'`) + rows = dumpQuery(t, db, `SELECT rowid, * FROM observers ORDER BY rowid`) + // packets_v must answer a full read, joining observations to the same + // observers as before. + links = dumpQuery(t, db, `SELECT id, COALESCE(observer_id, '') FROM packets_v ORDER BY id`) + var n int + if err := db.QueryRow(`SELECT COUNT(*) FROM packets_v`).Scan(&n); err != nil || n != 3 { + t.Fatalf("SELECT COUNT(*) FROM packets_v = %d (%v), want 3", n, err) + } + return table, rows, links +} + +// A legacy observers table the rebuild cannot convert without losing data +// makes OpenStore fail, and leaves the table, its rows and packets_v as they +// were. +func TestOpenStoreRefusesUnconvertibleObservers(t *testing.T) { + cases := []struct { + name string + mutate []string + wantErr string + }{ + {"unknown column", []string{ + `ALTER TABLE observers ADD COLUMN operator_note TEXT`, + `UPDATE observers SET operator_note = 'keep me'`, + }, "operator_note"}, + {"null id", []string{ + `INSERT INTO observers (id, name) VALUES (NULL, 'ghost')`, + }, "NULL id"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + path := legacyStoreDB(t, tc.mutate...) + table, rows, links := observersSnapshot(t, path) + if want := []string{"[1 a]", "[2 c]", "[3 ]"}; !reflect.DeepEqual(links, want) { + t.Fatalf("fixture links = %v, want %v", links, want) + } + + s, err := OpenStore(path) + if err == nil { + s.Close() + t.Fatal("OpenStore accepted an observers table the rebuild must refuse") + } + if !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("OpenStore err = %v, want mention of %q", err, tc.wantErr) + } + + gotTable, gotRows, gotLinks := observersSnapshot(t, path) + if !reflect.DeepEqual(table, gotTable) { + t.Errorf("observers table changed:\nbefore=%v\nafter=%v", table, gotTable) + } + if !reflect.DeepEqual(rows, gotRows) { + t.Errorf("observers rows changed:\nbefore=%v\nafter=%v", rows, gotRows) + } + if !reflect.DeepEqual(links, gotLinks) { + t.Errorf("packets_v links changed:\nbefore=%v\nafter=%v", links, gotLinks) + } + }) + } +} + +// openFDsOn counts this process's open file descriptors on path or its +// -wal/-shm siblings. ok is false where /proc/self/fd is unavailable. +func openFDsOn(t *testing.T, path string) (n int, ok bool) { + t.Helper() + entries, err := os.ReadDir("/proc/self/fd") + if err != nil { + return 0, false + } + for _, e := range entries { + target, err := os.Readlink(filepath.Join("/proc/self/fd", e.Name())) + if err != nil { + continue // the fd ReadDir itself used, closed by now + } + if target == path || target == path+"-wal" || target == path+"-shm" { + n++ + } + } + return n, true +} + +// A failed OpenStore closes the database it opened. A leaked handle keeps +// the file open: on Windows the caller cannot even delete it (the temp dir +// cleanup of TestOpenStoreRefusesUnconvertibleObservers failed there). +func TestOpenStoreClosesDBOnFailure(t *testing.T) { + path := legacyStoreDB(t, `ALTER TABLE observers ADD COLUMN operator_note TEXT`) + // Descriptors are only countable where /proc/self/fd exists (Linux); the + // removal at the end observes the leak on Windows. + n, countable := openFDsOn(t, path) + if countable && n != 0 { + t.Fatalf("fixture left %d descriptor(s) open on the database", n) + } + s, err := OpenStore(path) + if err == nil { + s.Close() + t.Fatal("OpenStore accepted an observers table the rebuild must refuse") + } + if n, _ := openFDsOn(t, path); countable && n != 0 { + t.Fatalf("failed OpenStore left %d descriptor(s) open on the database (%v)", n, err) + } + if rerr := os.Remove(path); rerr != nil { + t.Fatalf("database file cannot be removed after the failed OpenStore, a handle is still open: %v", rerr) + } +} diff --git a/cmd/ingestor/observers_idx_test.go b/cmd/ingestor/observers_idx_test.go new file mode 100644 index 000000000..9d8ecc8d1 --- /dev/null +++ b/cmd/ingestor/observers_idx_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "database/sql" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "testing" + + _ "github.com/mattn/go-sqlite3" +) + +// observations.observer_idx references observers.idx, an explicit INTEGER +// PRIMARY KEY. Joining or looking up observers by the hidden implicit rowid +// instead is what dump-and-reload silently renumbers (and Postgres lacks), so +// no non-test ingestor or dbschema source may do it. +func TestNoObserversRowidInSource(t *testing.T) { + forbidden := regexp.MustCompile(`(?i)\.rowid\b|rowid\s+FROM\s+observers\b|observers\.rowid\b`) + var checked int + for _, dir := range []string{".", filepath.Join("..", "..", "internal", "dbschema")} { + files, err := filepath.Glob(filepath.Join(dir, "*.go")) + if err != nil { + t.Fatal(err) + } + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + checked++ + for i, line := range strings.Split(string(src), "\n") { + if forbidden.MatchString(line) { + t.Errorf("%s:%d references the implicit observers rowid; use observers.idx: %s", f, i+1, strings.TrimSpace(line)) + } + } + } + } + if checked < 10 { + t.Fatalf("source guard scanned only %d files — wrong working directory?", checked) + } +} + +type columnInfo struct { + Name, Type string + NotNull, PK int + Default sql.NullString +} + +func observersShape(t *testing.T, db *sql.DB) ([]columnInfo, []string) { + t.Helper() + rows, err := db.Query(`SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info('observers') ORDER BY cid`) + if err != nil { + t.Fatal(err) + } + var cols []columnInfo + for rows.Next() { + var c columnInfo + if err := rows.Scan(&c.Name, &c.Type, &c.NotNull, &c.Default, &c.PK); err != nil { + t.Fatal(err) + } + cols = append(cols, c) + } + rows.Close() + var idx []string + irows, err := db.Query(`SELECT name || ':' || COALESCE(sql, '') FROM sqlite_master WHERE type = 'index' AND tbl_name = 'observers' ORDER BY name`) + if err != nil { + t.Fatal(err) + } + for irows.Next() { + var s string + if err := irows.Scan(&s); err != nil { + t.Fatal(err) + } + idx = append(idx, s) + } + irows.Close() + return cols, idx +} + +// A fresh install (applySchema's CREATE TABLE) and an upgraded legacy DB +// (dbschema's rebuild) must end up with the identical observers table, and an +// upgraded DB must keep each observation linked to its observer through the +// ingestor's own lookup path. +func TestFreshObserversMatchesRebuiltShape(t *testing.T) { + fresh, err := OpenStore(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatalf("OpenStore fresh: %v", err) + } + defer fresh.Close() + + legacyPath := filepath.Join(t.TempDir(), "legacy.db") + raw, err := sql.Open("sqlite3", legacyPath) + if err != nil { + t.Fatal(err) + } + for _, s := range []string{ + `CREATE TABLE observers (id TEXT PRIMARY KEY, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, packet_count INTEGER DEFAULT 0, model TEXT, firmware TEXT, client_version TEXT, radio TEXT, battery_mv INTEGER, uptime_secs INTEGER, noise_floor REAL, inactive INTEGER DEFAULT 0, last_packet_at TEXT DEFAULT NULL)`, + `INSERT INTO observers (id, name) VALUES ('gone', 'G'), ('keep-a', 'A'), ('keep-b', 'B')`, + `DELETE FROM observers WHERE id = 'gone'`, // rowid 1 freed: a dump-and-reload would renumber the rest + } { + if _, err := raw.Exec(s); err != nil { + t.Fatalf("%s: %v", s, err) + } + } + raw.Close() + + legacy, err := OpenStore(legacyPath) + if err != nil { + t.Fatalf("OpenStore legacy: %v", err) + } + defer legacy.Close() + + freshCols, freshIdx := observersShape(t, fresh.db) + legacyCols, legacyIdx := observersShape(t, legacy.db) + if !reflect.DeepEqual(freshCols, legacyCols) { + t.Errorf("observers columns differ:\nfresh =%+v\nrebuilt =%+v", freshCols, legacyCols) + } + if !reflect.DeepEqual(freshIdx, legacyIdx) { + t.Errorf("observers indexes differ:\nfresh =%v\nrebuilt =%v", freshIdx, legacyIdx) + } + + for want, id := range map[int64]string{2: "keep-a", 3: "keep-b"} { + var got int64 + if err := legacy.stmtGetObserverIdx.QueryRow(id).Scan(&got); err != nil || got != want { + t.Errorf("idx of %s = %d (%v), want its legacy rowid %d", id, got, err, want) + } + } + var name string + if err := legacy.db.QueryRow(`SELECT name FROM observers WHERE idx = 3`).Scan(&name); err != nil || name != "B" { + t.Errorf("observer at idx 3 = %q (%v), want B", name, err) + } +} diff --git a/cmd/server/admin_mail_test_handler.go b/cmd/server/admin_mail_test_handler.go new file mode 100644 index 000000000..7ab5cbd3f --- /dev/null +++ b/cmd/server/admin_mail_test_handler.go @@ -0,0 +1,35 @@ +package main + +import ( + "net/http" + "strconv" + + "github.com/meshcore-analyzer/users" +) + +// mailTestJSON answers POST /api/admin/mail/test. +type mailTestJSON struct { + OK bool `json:"ok"` + Provider string `json:"provider"` + MessageID string `json:"messageId,omitempty"` + Error string `json:"error,omitempty"` +} + +// handleAdminMailTest sends a fixed test mail to the calling admin's own +// address through the configured provider. The address is never taken from +// the request, so the route cannot mail anyone else; any body is ignored. +func (s *Server) handleAdminMailTest(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) { + a := s.auth + if !a.allow(w, r, a.mailTest, "user:"+strconv.FormatInt(actor.ID, 10)) { + return + } + provider := a.set.provider + id, err := a.sendMailID(r.Context(), actor, "test", a.testMail(actor)) + if err != nil { + a.audit(idPtr(actor.ID), "mail.test", nil, map[string]string{"provider": provider, "result": "failed"}) + writeJSONStatus(w, http.StatusBadGateway, mailTestJSON{Provider: provider, Error: redactAddrs(err)}) + return + } + a.audit(idPtr(actor.ID), "mail.test", nil, map[string]string{"provider": provider, "result": "ok"}) + writeJSON(w, mailTestJSON{OK: true, Provider: provider, MessageID: id}) +} diff --git a/cmd/server/admin_mail_test_handler_test.go b/cmd/server/admin_mail_test_handler_test.go new file mode 100644 index 000000000..7cf383fb0 --- /dev/null +++ b/cmd/server/admin_mail_test_handler_test.go @@ -0,0 +1,163 @@ +package main + +import ( + "encoding/json" + "errors" + "strconv" + "strings" + "testing" +) + +const mailTestPath = "/api/admin/mail/test" + +func testMailRows(t *testing.T, f *authFixture, uid int64) int { + t.Helper() + recs, err := f.st.MailForUser(uid, 100) + if err != nil { + t.Fatal(err) + } + n := 0 + for _, r := range recs { + if r.Purpose == "test" { + n++ + } + } + return n +} + +func TestAdminMailTestSendsToOwnAddress(t *testing.T) { + f, boss, _ := adminFixture(t) + w := f.do("POST", mailTestPath, map[string]string{"to": "x@evil.test"}, as(boss)) + expectStatus(t, w, 200) + got := decode[mailTestJSON](t, w) + if !got.OK || got.Provider != "fake" || got.MessageID == "" || got.Error != "" { + t.Fatalf("answer = %+v", got) + } + m, id, ok := f.fake.Last() + if !ok || m.To != "boss@example.org" || !strings.Contains(m.Subject, "Test mail") || id != got.MessageID { + t.Fatalf("last mail = %+v (id %q)", m, id) + } + if !strings.Contains(m.Text, "scope.example.org") || !strings.Contains(m.Text, "fake") { + t.Fatalf("mail text does not name host and provider: %q", m.Text) + } + if n := testMailRows(t, f, boss.me.ID); n != 1 { + t.Fatalf("test mail log rows = %d, want 1", n) + } + rows := auditOf(t, f, boss.me.ID, "mail.test") + if len(rows) != 1 || rows[0].Detail["provider"] != "fake" || rows[0].Detail["result"] != "ok" || len(rows[0].Detail) != 2 { + t.Fatalf("audit rows = %+v", rows) + } +} + +func TestAdminMailTestFailureReturnsProviderError(t *testing.T) { + f, boss, _ := adminFixture(t) + f.fake.SetSendErr(errors.New("535 5.7.8 authentication failed")) + w := f.do("POST", mailTestPath, nil, as(boss)) + expectStatus(t, w, 502) + got := decode[mailTestJSON](t, w) + if got.OK || got.Provider != "fake" || !strings.Contains(got.Error, "535") || got.MessageID != "" { + t.Fatalf("answer = %+v", got) + } + rows := auditOf(t, f, boss.me.ID, "mail.test") + if len(rows) != 1 || rows[0].Detail["result"] != "failed" || rows[0].Detail["provider"] != "fake" { + t.Fatalf("audit rows = %+v", rows) + } + if n := testMailRows(t, f, boss.me.ID); n != 0 { + t.Fatalf("test mail log rows = %d, want 0", n) + } +} + +func TestAdminMailTestRedactsAddressesInError(t *testing.T) { + f, boss, _ := adminFixture(t) + f.fake.SetSendErr(errors.New("550 rejected boss@example.org")) + w := f.do("POST", mailTestPath, nil, as(boss)) + expectStatus(t, w, 502) + if got := decode[mailTestJSON](t, w); strings.Contains(got.Error, "boss@example.org") || !strings.Contains(got.Error, "550") { + t.Fatalf("error not redacted: %q", got.Error) + } +} + +func TestAdminMailTestRateLimited(t *testing.T) { + f, boss, _ := adminFixture(t) + for i := 0; i < 3; i++ { + expectStatus(t, f.do("POST", mailTestPath, nil, as(boss)), 200) + } + sent := len(f.fake.Sent()) + w := f.do("POST", mailTestPath, nil, as(boss)) + expectStatus(t, w, 429) + if ra, err := strconv.Atoi(w.Header().Get("Retry-After")); err != nil || ra < 1 { + t.Fatalf("Retry-After = %q, want >= 1", w.Header().Get("Retry-After")) + } + if n := len(auditOf(t, f, boss.me.ID, "mail.test")); n != 3 { + t.Fatalf("mail.test audit rows = %d, want 3", n) + } + if n := testMailRows(t, f, boss.me.ID); n != 3 { + t.Fatalf("test mail log rows = %d, want 3", n) + } + if n := len(f.fake.Sent()); n != sent { + t.Fatalf("sent = %d after the 429, want %d", n, sent) + } +} + +func TestAdminMailTestNonAdmin(t *testing.T) { + f, boss, uma := adminFixture(t) + expectStatus(t, f.do("POST", mailTestPath, nil, as(uma)), 403) + expectStatus(t, f.do("POST", mailTestPath, nil), 401) + expectStatus(t, f.do("POST", mailTestPath, nil, as(&client{cookie: boss.cookie})), 403) + if n := len(auditOf(t, f, boss.me.ID, "mail.test")) + len(auditOf(t, f, uma.me.ID, "mail.test")); n != 0 { + t.Fatalf("mail.test audit rows = %d, want 0", n) + } +} + +func TestAdminStatsMailDeliveryStatus(t *testing.T) { + f, boss, _ := adminFixture(t) + w := f.do("GET", "/api/admin/stats", nil, as(boss)) + expectStatus(t, w, 200) + if !decode[adminStatsJSON](t, w).MailDeliveryStatus { + t.Fatal("fake provider: mailDeliveryStatus = false, want true") + } + if !strings.Contains(w.Body.String(), `"mailDeliveryStatus":true`) { + t.Fatalf("field missing from JSON: %s", w.Body.String()) + } + f.srv.auth.set.provider = "smtp" + w = f.do("GET", "/api/admin/stats", nil, as(boss)) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"mailDeliveryStatus":false`) { + t.Fatalf("smtp provider: %s", w.Body.String()) + } +} + +func TestAdminUserDetailMailDeliveryStatus(t *testing.T) { + f, boss, uma := adminFixture(t) + w := f.do("GET", userPath(uma.me.ID, ""), nil, as(boss)) + expectStatus(t, w, 200) + if !decode[adminUserDetailJSON](t, w).MailDeliveryStatus { + t.Fatal("fake provider: mailDeliveryStatus = false, want true") + } + f.srv.auth.set.provider = "smtp" + w = f.do("GET", userPath(uma.me.ID, ""), nil, as(boss)) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"mailDeliveryStatus":false`) { + t.Fatalf("smtp provider: %s", w.Body.String()) + } +} + +func TestOpenAPIListsMailTest(t *testing.T) { + f := newAuthFixture(t) + raw, err := json.Marshal(buildOpenAPISpec(f.router, "test")) + if err != nil { + t.Fatal(err) + } + var spec map[string]interface{} + if err := json.Unmarshal(raw, &spec); err != nil { + t.Fatal(err) + } + item := asMap(t, asMap(t, spec["paths"], "paths")[mailTestPath], mailTestPath) + op := asMap(t, item["post"], "post") + if s, _ := op["summary"].(string); s == "" || s == mailTestPath { + t.Fatalf("no summary for POST %s: %v", mailTestPath, op) + } + if _, ok := routeDescriptions()["POST "+mailTestPath]; !ok { + t.Fatalf("routeDescriptions has no POST %s", mailTestPath) + } +} diff --git a/cmd/server/admin_stats_handlers.go b/cmd/server/admin_stats_handlers.go index aa39fe5d9..6334d7807 100644 --- a/cmd/server/admin_stats_handlers.go +++ b/cmd/server/admin_stats_handlers.go @@ -57,6 +57,9 @@ type adminStatsJSON struct { Mail7d mailCountsJSON `json:"mail7d"` Guessing []guessedAccountJSON `json:"guessing"` Notify *adminNotifyJSON `json:"notify,omitempty"` + // MailDeliveryStatus is false when the provider cannot report what + // became of a mail after it was accepted (smtp). + MailDeliveryStatus bool `json:"mailDeliveryStatus"` } func adminStatsFrom(st users.Stats) adminStatsJSON { @@ -83,6 +86,7 @@ func (s *Server) handleAdminStats(w http.ResponseWriter, _ *http.Request, _ *use return } out := adminStatsFrom(st) + out.MailDeliveryStatus = s.auth.deliveryStatus() if s.auth.notify != nil { total, _, err := s.auth.st.NotifyMailCounts(s.auth.notify.now().Add(-24 * time.Hour)) if err != nil { diff --git a/cmd/server/admin_users_handlers.go b/cmd/server/admin_users_handlers.go index 5a23e5ec0..73db131e8 100644 --- a/cmd/server/admin_users_handlers.go +++ b/cmd/server/admin_users_handlers.go @@ -129,7 +129,8 @@ func (s *Server) handleAdminUserDetail(w http.ResponseWriter, r *http.Request, _ if err != nil { log.Printf("[users] admin latest mail: %v", err) } - d := adminUserDetailJSON{User: a.adminRow(*u, last), Sessions: []sessionJSON{}, Mail: []mailJSON{}, Audit: []auditJSON{}} + d := adminUserDetailJSON{User: a.adminRow(*u, last), Sessions: []sessionJSON{}, Mail: []mailJSON{}, Audit: []auditJSON{}, + MailDeliveryStatus: a.deliveryStatus()} list, err := a.st.ListSessions(u.ID) if err != nil { adminStoreFail(w, "list sessions", u.ID, err) diff --git a/cmd/server/auth_handlers.go b/cmd/server/auth_handlers.go index 1ee47c2bd..55082a28a 100644 --- a/cmd/server/auth_handlers.go +++ b/cmd/server/auth_handlers.go @@ -4,7 +4,9 @@ import ( "errors" "log" "net/http" + "slices" "strconv" + "strings" "time" "github.com/meshcore-analyzer/mailer" @@ -233,20 +235,53 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { } } -// handleDeviceToken issues a CoreDrive RX device token. No Origin check: -// the token is returned in the body and nothing is stored in a browser, -// so login CSRF does not apply, and RX may run on another origin. +// requestedDeviceScopes returns the scopes a device-token request asks for: +// rx when it names none (CoreDrive RX, and every client from before scopes +// could be requested), otherwise its list without repeats, in deviceScopes +// order. An empty list or an unknown scope is a *users.ValidationError. +func requestedDeviceScopes(req []string) ([]string, error) { + if req == nil { + return []string{deviceScopeRX}, nil + } + if len(req) == 0 { + return nil, &users.ValidationError{Msg: "scopes must name at least one scope"} + } + want := make(map[string]bool, len(req)) + for _, sc := range req { + if !slices.Contains(deviceScopes, sc) { + return nil, &users.ValidationError{Msg: "unknown scope: " + sc} + } + want[sc] = true + } + out := make([]string, 0, len(want)) + for _, sc := range deviceScopes { + if want[sc] { + out = append(out, sc) + } + } + return out, nil +} + +// handleDeviceToken issues a device token (CoreDrive RX, or a client that +// asks for repeater scopes). No Origin check: the token is returned in the +// body and nothing is stored in a browser, so login CSRF does not apply, +// and the client may run on another origin. func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { a := s.auth var req deviceTokenRequest if !decodeJSON(w, r, &req) { return } + // Checked before the password, so a malformed request costs no attempt. + scopes, err := requestedDeviceScopes(req.Scopes) + if writeValidation(w, err) { + return + } u := a.verifyLogin(w, r, req.Email, req.Password) if u == nil { return } - raw, sess, err := a.st.CreateDeviceSession(u.ID, req.DeviceName, []string{deviceScopeRX}, r.UserAgent()) + raw, sess, err := a.st.CreateDeviceSession(u.ID, req.DeviceName, scopes, r.UserAgent()) if err != nil { log.Printf("[users] device token for user #%d: %v", u.ID, err) writeError(w, http.StatusInternalServerError, "internal error") @@ -254,8 +289,9 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { } _ = a.st.TouchLogin(u.ID) writeJSON(w, deviceTokenResponse{Token: raw, ExpiresAt: rfc3339(sess.ExpiresAt), - User: deviceTokenUser{ID: u.ID, DisplayName: u.DisplayName}}) - a.auditAsync(nil, "user.login", idPtr(u.ID), map[string]string{"via": "device", "device": sess.Label}) + User: deviceTokenUser{ID: u.ID, DisplayName: u.DisplayName}, Scopes: sess.Scopes}) + a.auditAsync(nil, "user.login", idPtr(u.ID), map[string]string{"via": "device", "device": sess.Label, + "scopes": strings.Join(sess.Scopes, ",")}) } // handleLogout ends the caller's session: with a bearer header it revokes @@ -289,11 +325,12 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { } // handleMe answers the caller; a device token gets no CSRF token (it never -// needs one). +// needs one) and its scopes. func (s *Server) handleMe(w http.ResponseWriter, _ *http.Request, u *users.User, sess *users.Session) { me := meFrom(u, sess) if sess.Kind == users.SessionKindDevice { me.CSRFToken = "" + me.Scopes = sess.Scopes } writeJSON(w, me) } diff --git a/cmd/server/auth_mail.go b/cmd/server/auth_mail.go index 339a882d9..46e6ebb67 100644 --- a/cmd/server/auth_mail.go +++ b/cmd/server/auth_mail.go @@ -103,6 +103,15 @@ func (a *authService) activationMail(u *users.User, token string) mailer.Message actionLabel: "Activate my account", actionURL: a.link("activate", token)}) } +// testMail is the admin's test mail: no link, no token, only the host and +// the provider it went through. +func (a *authService) testMail(u *users.User) mailer.Message { + return a.render(u.Email, u.DisplayName, "test", mailContent{ + subject: "Test mail", greeting: "Hello " + u.DisplayName + ",", + paragraphs: []string{"This is a test mail from " + a.set.baseURL.Host + ", sent through " + a.set.provider + + " by an admin. No action is needed."}}) +} + func (a *authService) resetMail(u *users.User, token string) mailer.Message { return a.render(u.Email, u.DisplayName, "reset", mailContent{ subject: "Reset your password", greeting: "Hello " + u.DisplayName + ",", @@ -147,15 +156,21 @@ func redactAddrs(err error) string { // sendMail sends msg and records it in the mail log. The error is logged // (without tokens) and returned so the caller can answer 503. func (a *authService) sendMail(ctx context.Context, u *users.User, purpose string, msg mailer.Message) error { + _, err := a.sendMailID(ctx, u, purpose, msg) + return err +} + +// sendMailID is sendMail that also returns the provider's message id. +func (a *authService) sendMailID(ctx context.Context, u *users.User, purpose string, msg mailer.Message) (string, error) { id, err := a.mail.Send(ctx, msg) if err != nil { log.Printf("[users] mail %s for user #%d failed: %s", purpose, u.ID, redactAddrs(err)) - return err + return "", err } if _, err := a.st.LogMail(idPtr(u.ID), msg.To, purpose, id); err != nil { log.Printf("[users] mail log for user #%d: %v", u.ID, err) } - return nil + return id, nil } // ingestMailEvents records provider events and flags undeliverable addresses. diff --git a/cmd/server/auth_routes.go b/cmd/server/auth_routes.go index ce08aa785..654c5bd4b 100644 --- a/cmd/server/auth_routes.go +++ b/cmd/server/auth_routes.go @@ -56,6 +56,7 @@ func (s *Server) registerAuthRoutes(r *mux.Router) { r.HandleFunc("/api/admin/users/{id}/mail/{mailId}/refresh", s.withAdmin(s.handleAdminMailRefresh)).Methods("POST") r.HandleFunc("/api/admin/audit", s.withAdmin(s.handleAdminAudit)).Methods("GET") r.HandleFunc("/api/admin/stats", s.withAdmin(s.handleAdminStats)).Methods("GET") + r.HandleFunc("/api/admin/mail/test", s.withAdmin(s.handleAdminMailTest)).Methods("POST") r.HandleFunc("/api/admin/users-backup", s.withAdmin(s.handleAdminUsersBackup)).Methods("GET") if s.auth.set.proposals.enabled { s.registerProposalRoutes(r) diff --git a/cmd/server/auth_service.go b/cmd/server/auth_service.go index 94adc3780..1000427a2 100644 --- a/cmd/server/auth_service.go +++ b/cmd/server/auth_service.go @@ -1,6 +1,7 @@ package main import ( + "context" "log" "os" "path/filepath" @@ -26,6 +27,7 @@ type authService struct { settingsPut *rateLimiter // PUT /api/account/settings, per user companion *rateLimiter // companion challenge + link, per IP and per user repeater *rateLimiter // repeater edit, claim and unclaim, per user + mailTest *rateLimiter // admin test mail, per admin // approved is the snapshot of approved hashtag channel names, filled at // construction and reloaded from users.db after every proposal decision. @@ -64,6 +66,7 @@ func newAuthService(set *userMgmtSettings, st *users.Store, m mailer.Mailer) *au settingsPut: newRateLimiter(60, time.Hour), companion: newRateLimiter(60, time.Hour), repeater: newRateLimiter(120, time.Hour), + mailTest: newRateLimiter(3, 10*time.Minute), stop: make(chan struct{}), now: time.Now, } @@ -109,11 +112,20 @@ func (s *Server) initUserManagement(measurementDBPath string) error { m = &mailer.Fake{} case "postal": m = mailer.NewPostal(set.postalBaseURL, set.postalAPIKey, set.fromEmail, set.fromName) + case "smtp": + m = mailer.NewSMTP(set.smtp) default: m = mailer.NewBrevo(set.brevoAPIKey, set.fromEmail, set.fromName) } s.auth = newAuthService(set, st, m) s.auth.logStartup() + if sm, ok := m.(*mailer.SMTP); ok { + s.auth.wg.Add(1) + go func() { + defer s.auth.wg.Done() + s.checkSMTPAtStartup(sm) + }() + } s.auth.wg.Add(1) go func() { defer s.auth.wg.Done() @@ -147,6 +159,34 @@ func (s *Server) closeUserManagement() { }) } +// deliveryStatus reports whether the provider can tell what became of a mail +// after it was accepted. Plain SMTP cannot. +func (a *authService) deliveryStatus() bool { + return a.set.provider != "smtp" +} + +// checkSMTPAtStartup connects and authenticates without sending anything, and +// logs the outcome. A failure does not stop the server. The check is cancelled +// when user management shuts down. +func (s *Server) checkSMTPAtStartup(m *mailer.SMTP) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if s.auth != nil { + go func() { + select { + case <-s.auth.stop: + cancel() + case <-ctx.Done(): + } + }() + } + if err := m.Check(ctx); err != nil { + log.Printf("[mail] SMTP check failed: %v", err) + return + } + log.Printf("[mail] SMTP ready: %s", m.Describe()) +} + func (a *authService) logStartup() { log.Printf("[users] user management enabled: db=%s, %d config admin(s), webhook=%v", absForLog(a.set.dbPath), len(a.set.adminEmails), a.set.webhookSecret != "") diff --git a/cmd/server/auth_service_smtp_test.go b/cmd/server/auth_service_smtp_test.go new file mode 100644 index 000000000..ec4f381f4 --- /dev/null +++ b/cmd/server/auth_service_smtp_test.go @@ -0,0 +1,113 @@ +package main + +import ( + "bufio" + "bytes" + "fmt" + "log" + "net" + "path/filepath" + "strings" + "testing" + + "github.com/meshcore-analyzer/mailer" +) + +func TestDeliveryStatusFalseOnlyForSMTP(t *testing.T) { + for provider, want := range map[string]bool{"brevo": true, "postal": true, "fake": true, "smtp": false} { + a := &authService{set: &userMgmtSettings{provider: provider}} + if got := a.deliveryStatus(); got != want { + t.Errorf("%s: deliveryStatus = %v, want %v", provider, got, want) + } + } +} + +// closedPort returns a local port nothing listens on. +func closedPort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := l.Addr().(*net.TCPAddr).Port + l.Close() + return port +} + +func captureLogBuf(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + prev := log.Writer() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev) }) + return &buf +} + +func TestStartupSMTPCheckLogsAndContinues(t *testing.T) { + const secret = "s3cret-smtp-pw" + port := closedPort(t) + buf := captureLogBuf(t) + + // the check itself, synchronous + srv := &Server{cfg: &Config{}} + srv.checkSMTPAtStartup(mailer.NewSMTP(mailer.SMTPConfig{ + Host: "127.0.0.1", Port: port, TLS: "none", User: "u", Password: secret, + FromEmail: "noreply@example.org", FromName: "CoreScope", + })) + if out := buf.String(); !strings.Contains(out, "[mail] SMTP check failed:") || strings.Contains(out, secret) { + t.Fatalf("log = %q", out) + } + + // initUserManagement still returns nil and the check goroutine is tracked + buf.Reset() + srv = &Server{cfg: &Config{UserManagement: &UserManagementConfig{ + Enabled: true, PublicBaseURL: testBase, + Mail: UserMailConfig{Provider: "smtp", SMTPHost: "127.0.0.1", SMTPPort: port, SMTPTLS: "none", + SMTPUser: "u", SMTPPassword: secret, FromEmail: "noreply@example.org"}, + }}} + if err := srv.initUserManagement(filepath.Join(t.TempDir(), "meshcore.db")); err != nil { + t.Fatal(err) + } + srv.closeUserManagement() // waits for the check goroutine + if out := buf.String(); !strings.Contains(out, "[mail] SMTP check failed:") || strings.Contains(out, secret) { + t.Fatalf("log after init = %q", out) + } +} + +func TestStartupSMTPCheckLogsReady(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + go func() { + c, err := l.Accept() + if err != nil { + return + } + defer c.Close() + fmt.Fprint(c, "220 fake ESMTP\r\n") + r := bufio.NewReader(c) + for { + line, err := r.ReadString('\n') + if err != nil { + return + } + if strings.ToUpper(strings.TrimSpace(line)) == "QUIT" { + fmt.Fprint(c, "221 bye\r\n") + return + } + fmt.Fprint(c, "250 ok\r\n") + } + }() + port := l.Addr().(*net.TCPAddr).Port + buf := captureLogBuf(t) + srv := &Server{cfg: &Config{}} + srv.checkSMTPAtStartup(mailer.NewSMTP(mailer.SMTPConfig{ + Host: "127.0.0.1", Port: port, TLS: "none", FromEmail: "noreply@example.org", FromName: "CoreScope", + })) + want := fmt.Sprintf("[mail] SMTP ready: 127.0.0.1:%d (none)", port) + if !strings.Contains(buf.String(), want) { + t.Fatalf("log = %q, want %q", buf.String(), want) + } +} diff --git a/cmd/server/auth_session.go b/cmd/server/auth_session.go index b27b04a43..da88c62a3 100644 --- a/cmd/server/auth_session.go +++ b/cmd/server/auth_session.go @@ -14,26 +14,94 @@ const ( csrfHeader = "X-CS-CSRF" ) -// deviceScopeRX is the scope of CoreDrive RX device tokens: the routes -// bearerScopeFor lists. -const deviceScopeRX = "rx" - -// bearerScopeFor returns the scope a device token needs on path, or "" -// when no device token may use it (spec: /api/auth/me, /api/auth/logout, -// /api/account/companions*, /api/account/settings). -func bearerScopeFor(path string) string { +// Device-token scopes. A token holds the scopes it asked for at +// POST /api/auth/device-token (deviceScopeRX when it asked for none). +const ( + // deviceScopeRX is CoreDrive RX: account settings and companion linking. + deviceScopeRX = "rx" + // deviceScopeRepeaterClaim claims a repeater and removes the caller's own + // claim. + deviceScopeRepeaterClaim = "repeater:claim" + // deviceScopeRepeaterEdit edits a repeater's details, still only where + // CanEditRepeater allows the account to. + deviceScopeRepeaterEdit = "repeater:edit" +) + +// deviceScopes are the scopes a client may request, in a fixed order. +var deviceScopes = []string{deviceScopeRX, deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} + +// repeaterRoute splits /api/repeaters/{pubkey}/{what} and returns what +// ("info" or "claim"), or "" for any other path. The pubkey segment is only +// checked to be non-empty; the handler validates it. +func repeaterRoute(path string) string { + rest, ok := strings.CutPrefix(path, "/api/repeaters/") + if !ok { + return "" + } + pk, what, ok := strings.Cut(rest, "/") + if !ok || pk == "" || (what != "info" && what != "claim") { + return "" + } + return what +} + +// bearerScopesFor returns the scopes that let a device token use method on +// path (any one of them is enough), or nil when no device token may use it. +// Any device token may read and end its own login; RX routes need rx; +// repeater claims need repeater:claim and repeater edits repeater:edit. A +// read of one repeater's details takes either repeater scope (it adds the +// caller's canEdit and claimedByMe), and so does the list of the caller's +// own claims (My repeaters), which an app cannot build from the public +// catalog: claimers there are display names, and a claimed repeater may +// have left the node list. +func bearerScopesFor(method, path string) []string { switch { - case path == "/api/auth/me", path == "/api/auth/logout", path == "/api/account/settings", - path == "/api/account/companions", strings.HasPrefix(path, "/api/account/companions/"): - return deviceScopeRX + case path == "/api/auth/me", path == "/api/auth/logout": + return deviceScopes + case path == "/api/account/repeaters": + if method == http.MethodGet || method == http.MethodHead { + return []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} + } + return nil + case path == "/api/account/settings", path == "/api/account/companions", + strings.HasPrefix(path, "/api/account/companions/"): + return []string{deviceScopeRX} } - return "" + switch repeaterRoute(path) { + case "claim": + if method == http.MethodPost || method == http.MethodDelete { + return []string{deviceScopeRepeaterClaim} + } + case "info": + switch method { + case http.MethodPut: + return []string{deviceScopeRepeaterEdit} + case http.MethodGet, http.MethodHead: + return []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} + } + } + return nil } -// bearerCORSPath reports whether path takes cross-origin writes from an -// allowlisted origin: the device-token login and the bearer routes. +// bearerCORSPath reports whether path takes cross-origin bearer requests +// from an allowlisted origin: the device-token login and the bearer routes. +// It is judged on the path alone, since a preflight names the method only in +// a header: the repeater routes count whatever the method, and every other +// route by the scopes a GET needs. That covers the My repeaters list, which +// takes a token for GET and HEAD only. func bearerCORSPath(path string) bool { - return path == "/api/auth/device-token" || bearerScopeFor(path) != "" + return path == "/api/auth/device-token" || repeaterRoute(path) != "" || + len(bearerScopesFor(http.MethodGet, path)) > 0 +} + +// hasAnyScope reports whether sess holds at least one of scopes. +func hasAnyScope(sess *users.Session, scopes []string) bool { + for _, sc := range scopes { + if sess.HasScope(sc) { + return true + } + } + return false } // bearerToken returns the token of an "Authorization: Bearer" header and @@ -69,7 +137,7 @@ func (a *authService) bearerUser(r *http.Request, tok string) (*users.User, *use if err != nil || u.Status != users.StatusActive { return nil, nil, http.StatusUnauthorized } - if need := bearerScopeFor(r.URL.Path); need == "" || !sess.HasScope(need) { + if need := bearerScopesFor(r.Method, r.URL.Path); len(need) == 0 || !hasAnyScope(sess, need) { return nil, nil, http.StatusForbidden } if time.Since(sess.LastSeenAt) > 24*time.Hour { @@ -147,6 +215,25 @@ func isSafeMethod(m string) bool { return m == http.MethodGet || m == http.Metho type authedHandler func(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) +// optionalUser returns the caller of a route that also answers anonymously +// (the read of one repeater's details), or nils for an anonymous one. A +// bearer that does not resolve to an active device token with a scope for +// the route counts as anonymous: an auth proxy may add its own +// Authorization header (see bearerToken), and a visitor behind it must still +// get the public view. A client learns its token is gone from /api/auth/me +// or the 401 on its next write. Otherwise the cookie session decides, as +// for currentUser. +func (s *Server) optionalUser(w http.ResponseWriter, r *http.Request) (*users.User, *users.Session) { + tok, ok := bearerToken(r) + if !ok { + return s.auth.currentUser(w, r) + } + if u, sess, code := s.auth.bearerUser(r, tok); code == 0 { + return u, sess + } + return nil, nil +} + // withUser requires a logged-in active user. A request with an // Authorization: Bearer header and no session cookie is judged on that // device token alone (scope check, no CSRF: browsers never attach it on diff --git a/cmd/server/auth_types.go b/cmd/server/auth_types.go index f5c8c98c2..dedc26bf3 100644 --- a/cmd/server/auth_types.go +++ b/cmd/server/auth_types.go @@ -20,6 +20,9 @@ type meResponse struct { DisplayName string `json:"displayName"` Role users.Role `json:"role"` CSRFToken string `json:"csrfToken"` + // Scopes: a device token's granted scopes, so an app can check what it + // holds after an update or a restore; absent for a browser session. + Scopes []string `json:"scopes,omitempty"` } type registerRequest struct { @@ -37,6 +40,8 @@ type deviceTokenRequest struct { Email string `json:"email"` Password string `json:"password"` DeviceName string `json:"deviceName"` + // Scopes the token asks for; omitted means ["rx"] (CoreDrive RX). + Scopes []string `json:"scopes"` } type deviceTokenUser struct { @@ -48,6 +53,7 @@ type deviceTokenResponse struct { Token string `json:"token"` ExpiresAt string `json:"expiresAt"` User deviceTokenUser `json:"user"` + Scopes []string `json:"scopes"` } type companionChallengeRequest struct { @@ -131,6 +137,9 @@ type sessionJSON struct { ExpiresAt string `json:"expiresAt"` UserAgent string `json:"userAgent"` Current bool `json:"current"` + // Scopes of a device token (rx, repeater:claim, repeater:edit); absent + // for a web session, which has full access. + Scopes []string `json:"scopes,omitempty"` } type mailEventJSON struct { @@ -183,6 +192,9 @@ type adminUserDetailJSON struct { RepeaterClaims []repeaterClaimRefJSON `json:"repeaterClaims"` Mail []mailJSON `json:"mail"` Audit []auditJSON `json:"audit"` + // MailDeliveryStatus is false when the provider cannot report delivery + // events (smtp): mail shows as sent and there is nothing to refresh. + MailDeliveryStatus bool `json:"mailDeliveryStatus"` } func rfc3339(t time.Time) string { return t.UTC().Format(time.RFC3339) } @@ -201,7 +213,7 @@ func meFrom(u *users.User, sess *users.Session) meResponse { func sessionToJSON(s users.Session, currentID int64) sessionJSON { return sessionJSON{ID: s.ID, Kind: s.Kind, Label: s.Label, CreatedAt: rfc3339(s.CreatedAt), LastSeenAt: rfc3339(s.LastSeenAt), - ExpiresAt: rfc3339(s.ExpiresAt), UserAgent: s.UserAgent, Current: s.ID == currentID} + ExpiresAt: rfc3339(s.ExpiresAt), UserAgent: s.UserAgent, Current: s.ID == currentID, Scopes: s.Scopes} } func mailToJSON(m users.MailRecord) mailJSON { diff --git a/cmd/server/bounded_load_test.go b/cmd/server/bounded_load_test.go index ef383d549..47b9426c5 100644 --- a/cmd/server/bounded_load_test.go +++ b/cmd/server/bounded_load_test.go @@ -162,7 +162,7 @@ func createTestDBWithAgedPackets(t *testing.T, numRecent, numOld int) string { } execOrFail(`CREATE TABLE transmissions (id INTEGER PRIMARY KEY, raw_hex TEXT, hash TEXT, first_seen TEXT, route_type INTEGER, payload_type INTEGER, payload_version INTEGER, decoded_json TEXT)`) execOrFail(`CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_id TEXT, observer_name TEXT, direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT)`) - execOrFail(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + execOrFail(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) execOrFail(`CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL)`) execOrFail(`CREATE TABLE schema_version (version INTEGER)`) execOrFail(`INSERT INTO schema_version (version) VALUES (1)`) @@ -331,7 +331,7 @@ func createTestDBAt(tb testing.TB, dbPath string, numTx int) { direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT )`) - execOrFail(`CREATE TABLE IF NOT EXISTS observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + execOrFail(`CREATE TABLE IF NOT EXISTS observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) execOrFail(`CREATE TABLE IF NOT EXISTS nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL @@ -398,7 +398,7 @@ func createTestDBWithObs(tb testing.TB, dbPath string, numTx int) { id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_id TEXT, observer_name TEXT, direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT )`) - execOrFail(`CREATE TABLE IF NOT EXISTS observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + execOrFail(`CREATE TABLE IF NOT EXISTS observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) execOrFail(`CREATE TABLE IF NOT EXISTS nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL diff --git a/cmd/server/cache_control_api_test.go b/cmd/server/cache_control_api_test.go index ecf8d1686..8b14d23d2 100644 --- a/cmd/server/cache_control_api_test.go +++ b/cmd/server/cache_control_api_test.go @@ -66,7 +66,7 @@ func TestStaticAssetsDoNotEmitBareNoStore(t *testing.T) { _, router := setupTestServer(t) // Wire the SPA handler exactly the way main.go does for non-/api paths. fs := http.FileServer(http.Dir(dir)) - router.PathPrefix("/").Handler(spaHandler(dir, fs)) + router.PathPrefix("/").Handler(spaHandler(dir, fs, "")) cases := []struct { path string diff --git a/cmd/server/chunked_load.go b/cmd/server/chunked_load.go index ae5345c70..fff2a7895 100644 --- a/cmd/server/chunked_load.go +++ b/cmd/server/chunked_load.go @@ -421,7 +421,7 @@ func (s *PacketStore) LoadChunked(chunkSize int) error { o.snr, o.rssi, o.score, o.path_json, strftime('%Y-%m-%dT%H:%M:%fZ', o.timestamp, 'unixepoch')` + obsRawHexCol + rpCol + scopeNameCol + ` FROM (SELECT * FROM transmissions t2 ` + whereClause + ` ORDER BY t2.id ASC LIMIT ` + fmt.Sprintf("%d", chunkSize) + `) AS t LEFT JOIN observations o ON o.transmission_id = t.id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx ORDER BY t.id ASC, o.timestamp DESC` } else { chunkSQL = `SELECT t.id, t.raw_hex, t.hash, t.first_seen, t.route_type, diff --git a/cmd/server/chunked_load_id_zero_test.go b/cmd/server/chunked_load_id_zero_test.go index 7b1fb87e7..7c37c6716 100644 --- a/cmd/server/chunked_load_id_zero_test.go +++ b/cmd/server/chunked_load_id_zero_test.go @@ -48,7 +48,7 @@ func createTestDBWithIDZero(tb testing.TB, dbPath string, extraTx int) { direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT )`, - `CREATE TABLE IF NOT EXISTS observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`, + `CREATE TABLE IF NOT EXISTS observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`, `CREATE TABLE IF NOT EXISTS nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL diff --git a/cmd/server/chunked_load_oldest_test.go b/cmd/server/chunked_load_oldest_test.go index 8b3edce7f..d9d816a99 100644 --- a/cmd/server/chunked_load_oldest_test.go +++ b/cmd/server/chunked_load_oldest_test.go @@ -50,7 +50,7 @@ func createTestDBReverseTime(tb testing.TB, dbPath string, numTx int) { direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT )`, - `CREATE TABLE IF NOT EXISTS observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`, + `CREATE TABLE IF NOT EXISTS observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`, `CREATE TABLE IF NOT EXISTS nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL diff --git a/cmd/server/config_map_tiles_test.go b/cmd/server/config_map_tiles_test.go new file mode 100644 index 000000000..168084ce5 --- /dev/null +++ b/cmd/server/config_map_tiles_test.go @@ -0,0 +1,157 @@ +package main + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "testing" +) + +// The server must hand map.tiles to the browser untouched: the browser +// validates it, so a server-side refactor that drops or rewrites a field would +// silently break operators' self-hosted tile servers. + +const mapTilesFullJSON = `{ + "darkDefault": "custom-ours-vec", + "lightDefault": "custom-ours", + "providers": { + "carto": {"enabled": true, "key": "k", "domain": "corp"}, + "eox": {"enabled": false}, + "osmfr": {"enabled": true}, + "openfreemap": {"enabled": false}, + "hillshade": {"enabled": true, "url": "https://mirror.example.org/terrarium/{z}/{x}/{y}.png"} + }, + "custom": [ + {"id": "ours", "label": "Our tile server", "type": "light", "category": "street", + "format": "raster", "url": "https://{s}.tiles.example.org/{z}/{x}/{y}.png", + "attribution": "(c) OpenStreetMap contributors", "maxZoom": 19, "maxNativeZoom": 18, + "subdomains": "abc", "overlay": false}, + {"id": "ours-vec", "label": "Our vector style", "type": "dark", "category": "topo", + "format": "vector", "url": "/styles/dark.json", + "attribution": "(c) Example", "maxZoom": 22, "maxNativeZoom": 14, + "subdomains": "", "overlay": true}, + {"id": "x", "label": "", "type": "bogus", "category": "??", + "format": "raster", "url": "javascript:alert(1)", + "attribution": "a", + "maxZoom": -5, "maxNativeZoom": 1e9, "subdomains": "}{", "overlay": "yes", "extra": {"n": null}} + ] +}` + +// clientConfigFor loads a config the way the server does (LoadConfig, which +// runs migrateDeprecatedConfig) and fetches /api/config/client. +func clientConfigFor(t *testing.T, configJSON string) map[string]interface{} { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := LoadConfig(dir) + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + srv, router := setupTestServer(t) + srv.cfg = cfg + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil)) + if w.Code != 200 { + t.Fatalf("status %d: %s", w.Code, w.Body.String()) + } + var out map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + return out +} + +func mustDecodeObject(t *testing.T, s string) map[string]interface{} { + t.Helper() + var m map[string]interface{} + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("fixture: %v", err) + } + return m +} + +func tilesOf(t *testing.T, resp map[string]interface{}) map[string]interface{} { + t.Helper() + m, ok := resp["map"].(map[string]interface{}) + if !ok { + t.Fatalf("response map is %T, want object", resp["map"]) + } + tiles, ok := m["tiles"].(map[string]interface{}) + if !ok { + t.Fatalf("response map.tiles is %T, want object", m["tiles"]) + } + return tiles +} + +func TestClientConfigMapTilesPassThrough(t *testing.T) { + cases := []struct { + name string + tiles string + }{ + {"full new shape with hostile entry", mapTilesFullJSON}, + {"empty custom list", `{"custom": []}`}, + {"providers only", `{"providers": {"eox": {"enabled": false}, "hillshade": {"enabled": false}}}`}, + {"unknown future keys", `{"futureKey": {"a": [1, 2, 3]}, "custom": [{"id": "z", "newField": true}]}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + want := mustDecodeObject(t, tc.tiles) + resp := clientConfigFor(t, `{"map": {"center": [1, 2], "zoom": 7, "tiles": `+tc.tiles+`}}`) + got := tilesOf(t, resp) + if !reflect.DeepEqual(got, want) { + g, _ := json.MarshalIndent(got, "", " ") + w, _ := json.MarshalIndent(want, "", " ") + t.Fatalf("map.tiles changed.\n got: %s\nwant: %s", g, w) + } + m := resp["map"].(map[string]interface{}) + if m["zoom"] != float64(7) { + t.Errorf("map.zoom = %v, want 7", m["zoom"]) + } + }) + } +} + +func TestClientConfigLegacyTilesMigrateWithoutClobberingCustom(t *testing.T) { + custom := `[{"id": "ours", "label": "Ours", "format": "raster", "url": "https://t.example.org/{z}/{x}/{y}.png"}]` + cfgJSON := `{ + "mapDarkTileProvider": "legacy-dark", + "tiles": {"lightDefault": "legacy-light", "custom": [{"id": "legacy"}], "legacyOnly": "x"}, + "map": {"tiles": {"lightDefault": "new-light", "custom": ` + custom + `}} + }` + tiles := tilesOf(t, clientConfigFor(t, cfgJSON)) + + wantCustom := mustDecodeObject(t, `{"c": `+custom+`}`)["c"] + if !reflect.DeepEqual(tiles["custom"], wantCustom) { + t.Errorf("map.tiles.custom clobbered by legacy tiles: %v", tiles["custom"]) + } + if tiles["lightDefault"] != "new-light" { + t.Errorf("explicit map.tiles.lightDefault overridden: %v", tiles["lightDefault"]) + } + if tiles["darkDefault"] != "legacy-dark" { + t.Errorf("mapDarkTileProvider not migrated to darkDefault: %v", tiles["darkDefault"]) + } + if tiles["legacyOnly"] != "x" { + t.Errorf("legacy tiles key not migrated: %v", tiles["legacyOnly"]) + } +} + +func TestClientConfigLegacyTilesOnlyMigrate(t *testing.T) { + tiles := tilesOf(t, clientConfigFor(t, `{"mapDarkTileProvider": "legacy-dark", "tiles": {"lightDefault": "legacy-light"}}`)) + if tiles["darkDefault"] != "legacy-dark" || tiles["lightDefault"] != "legacy-light" { + t.Errorf("legacy keys not migrated into map.tiles: %v", tiles) + } +} + +// Documents today's behaviour: with no map block the server still answers with +// a map object whose tiles is an empty object (migrateDeprecatedConfig). +func TestClientConfigAbsentMapStillUsable(t *testing.T) { + resp := clientConfigFor(t, `{}`) + tiles := tilesOf(t, resp) + if len(tiles) != 0 { + t.Errorf("absent map: tiles = %v, want empty object", tiles) + } +} diff --git a/cmd/server/cors.go b/cmd/server/cors.go index 42b8ad83a..81e104b24 100644 --- a/cmd/server/cors.go +++ b/cmd/server/cors.go @@ -121,10 +121,13 @@ const corsExposedHeaders = "Retry-After, X-CoreScope-Load-Status" // /api/packets/observations, /api/paths/inspect; see simple_post_test.go). // Same-origin writes (admin UI, API-key holders on the canonical origin) are // unaffected — they never go through the preflight path. -// The exception is the bearer routes of companion linking (bearerCORSPath, -// only with user management on), which also allow POST, PUT, DELETE and the -// Authorization header, for every listed origin: each deployment under a -// wildcard entry included. +// The exception is the bearer routes (bearerCORSPath, only with user +// management on): the device-token login, the token's own session, account +// settings, companion linking, the My repeaters list, and the repeater claim +// and details routes. They also allow POST, PUT, DELETE and the Authorization +// header, for every listed origin: each deployment under a wildcard entry included, +// so with "*" in corsAllowedOrigins any origin may send token-bearing writes +// to them. No cookies go with those requests, so a write needs the token. // Credentialed CORS is intentionally NOT enabled. func (s *Server) corsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -175,9 +178,10 @@ func (s *Server) corsMiddleware(next http.Handler) http.Handler { } w.Header().Set("Access-Control-Expose-Headers", corsExposedHeaders) if s.auth != nil && bearerCORSPath(r.URL.Path) { - // Companion linking: CoreDrive RX on an allowlisted origin logs in - // and writes with a device token in Authorization. Still no - // credentials: nothing rides on cookies. + // Device-token clients on an allowlisted origin: CoreDrive RX + // (companion linking) and mobile apps (repeater claims and + // details) log in and write with a device token in Authorization. + // Still no credentials: nothing rides on cookies. w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") } else { diff --git a/cmd/server/coverage_test.go b/cmd/server/coverage_test.go index e65566da3..a3c6b78c9 100644 --- a/cmd/server/coverage_test.go +++ b/cmd/server/coverage_test.go @@ -35,7 +35,7 @@ func setupTestDBv2(t *testing.T) *DB { battery_mv INTEGER, temperature_c REAL, foreign_advert INTEGER DEFAULT 0 ); CREATE TABLE observers ( - id TEXT PRIMARY KEY, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, + idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, packet_count INTEGER DEFAULT 0, model TEXT, firmware TEXT, client_version TEXT, radio TEXT, battery_mv INTEGER, uptime_secs INTEGER, noise_floor REAL, inactive INTEGER DEFAULT 0 diff --git a/cmd/server/db.go b/cmd/server/db.go index b5e0caf04..983a3cd3e 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -384,7 +384,7 @@ func (db *DB) transmissionBaseSQL() (selectCols, observerJoin string) { SELECT id FROM observations WHERE transmission_id = t.id ORDER BY length(COALESCE(path_json,'')) DESC LIMIT 1 ) - LEFT JOIN observers obs ON obs.rowid = o.observer_idx` + LEFT JOIN observers obs ON obs.idx = o.observer_idx` } else { selectCols = `t.id, t.raw_hex, t.hash, t.first_seen, t.route_type, t.payload_type, t.decoded_json, COALESCE((SELECT COUNT(*) FROM observations WHERE transmission_id = t.id), 0) AS observation_count, @@ -849,13 +849,13 @@ func (db *DB) QueryGroupedPackets(q PacketQuery) (*PacketResult, error) { COALESCE((SELECT MAX(strftime('%%Y-%%m-%%dT%%H:%%M:%%fZ', oi.timestamp, 'unixepoch')) FROM observations oi WHERE oi.transmission_id = t.id), t.first_seen) AS latest, obs.id AS observer_id, obs.name AS observer_name, COALESCE(obs.iata, '') AS observer_iata, o.snr, o.rssi, o.path_json, - COALESCE((SELECT GROUP_CONCAT(DISTINCT obi.iata) FROM observations oi JOIN observers obi ON obi.rowid = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.iata IS NOT NULL AND obi.iata != ''), '') AS distinct_iatas`+scopeNameCol+` + COALESCE((SELECT GROUP_CONCAT(DISTINCT obi.iata) FROM observations oi JOIN observers obi ON obi.idx = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.iata IS NOT NULL AND obi.iata != ''), '') AS distinct_iatas`+scopeNameCol+` FROM transmissions t LEFT JOIN observations o ON o.id = ( SELECT id FROM observations WHERE transmission_id = t.id ORDER BY length(COALESCE(path_json,'')) DESC LIMIT 1 ) - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx %s ORDER BY latest DESC LIMIT ? OFFSET ?`, w) } else { querySQL = fmt.Sprintf(`SELECT t.hash, t.first_seen, t.raw_hex, t.decoded_json, t.payload_type, t.route_type, @@ -1056,7 +1056,7 @@ func (db *DB) buildTransmissionWhere(q PacketQuery) ([]string, []interface{}) { placeholders := strings.Repeat("?,", len(ids)) placeholders = placeholders[:len(placeholders)-1] if db.isV3 { - where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.rowid = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.id IN ("+placeholders+")"+directionFilter+")") + where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.idx = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.id IN ("+placeholders+")"+directionFilter+")") } else { where = append(where, "EXISTS (SELECT 1 FROM observations oi WHERE oi.transmission_id = t.id AND oi.observer_id IN ("+placeholders+")"+directionFilter+")") } @@ -1069,14 +1069,14 @@ func (db *DB) buildTransmissionWhere(q PacketQuery) ([]string, []interface{}) { if q.Region != "" && db.regionByFrequency { cond, condArgs := db.regionWhere("obi", q.Region) if db.isV3 { - where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.rowid = oi.observer_idx WHERE oi.transmission_id = t.id AND "+cond+")") + where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.idx = oi.observer_idx WHERE oi.transmission_id = t.id AND "+cond+")") } else { where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.id = oi.observer_id WHERE oi.transmission_id = t.id AND "+cond+")") } args = append(args, condArgs...) } else if q.Region != "" { if db.isV3 { - where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.rowid = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.iata = ?)") + where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.idx = oi.observer_idx WHERE oi.transmission_id = t.id AND obi.iata = ?)") } else { where = append(where, "EXISTS (SELECT 1 FROM observations oi JOIN observers obi ON obi.id = oi.observer_id WHERE oi.transmission_id = t.id AND obi.iata = ?)") } @@ -1246,7 +1246,7 @@ func (db *DB) GetNodes(nq NodeQuery) ([]map[string]interface{}, int, map[string] if err != nil { return nil, 0, nil, err } - joinCond := "obs.rowid = o.observer_idx" + joinCond := "obs.idx = o.observer_idx" if !db.isV3 { joinCond = "obs.id = o.observer_id" } @@ -1495,7 +1495,7 @@ func (db *DB) getObservationsForTransmissions(txIDs []int) map[int][]map[string] querySQL = fmt.Sprintf(`SELECT o.transmission_id, o.id, obs.id AS observer_id, obs.name AS observer_name, COALESCE(obs.iata, '') AS observer_iata, o.direction, o.snr, o.rssi, o.path_json, strftime('%%Y-%%m-%%dT%%H:%%M:%%fZ', o.timestamp, 'unixepoch') AS obs_timestamp FROM observations o - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE o.transmission_id IN (%s) ORDER BY o.timestamp DESC`, strings.Join(placeholders, ",")) } else { @@ -1850,7 +1850,7 @@ func (db *DB) GetTraces(hash string) ([]map[string]interface{}, error) { o.snr, o.rssi, o.path_json FROM observations o JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE t.hash = ? ORDER BY o.timestamp ASC` } else { @@ -1974,17 +1974,17 @@ func (db *DB) GetChannels(region ...string) ([]map[string]interface{}, error) { MAX(t.first_seen) AS last_activity, (SELECT t2.decoded_json FROM transmissions t2 JOIN observations o2 ON o2.transmission_id = t2.id - LEFT JOIN observers obs2 ON obs2.rowid = o2.observer_idx + LEFT JOIN observers obs2 ON obs2.idx = o2.observer_idx WHERE t2.channel_hash = t.channel_hash AND t2.payload_type = 5 - AND obs2.rowid IS NOT NULL AND %s + AND obs2.idx IS NOT NULL AND %s ORDER BY t2.first_seen DESC LIMIT 1) AS sample_json FROM transmissions t JOIN observations o ON o.transmission_id = t.id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE t.payload_type = 5 AND t.channel_hash IS NOT NULL AND t.channel_hash NOT LIKE 'enc_%%' - AND obs.rowid IS NOT NULL AND %s + AND obs.idx IS NOT NULL AND %s GROUP BY t.channel_hash ORDER BY last_activity DESC`, inRegion("obs2"), inRegion("obs")) } else { @@ -2121,10 +2121,10 @@ func (db *DB) GetEncryptedChannels(region ...string) ([]map[string]interface{}, MAX(t.first_seen) AS last_activity FROM transmissions t JOIN observations o ON o.transmission_id = t.id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE t.payload_type = 5 AND t.channel_hash LIKE 'enc_%%' - AND obs.rowid IS NOT NULL AND %s + AND obs.idx IS NOT NULL AND %s GROUP BY t.channel_hash ORDER BY last_activity DESC`, inRegion("obs")) } else { @@ -2260,7 +2260,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . if db.isV3 { regionFilter = fmt.Sprintf(` AND EXISTS ( SELECT 1 FROM observations o - JOIN observers obs ON obs.rowid = o.observer_idx + JOIN observers obs ON obs.idx = o.observer_idx WHERE o.transmission_id = t.id AND %s)`, regionCond) } else { @@ -2362,7 +2362,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region . obs.id, obs.name, o.snr, o.path_json, o.timestamp` + scopeNameCol + ` FROM observations o JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE t.id IN (` + strings.Join(idPlaceholders, ",") + `) ORDER BY o.id ASC` } else { @@ -2578,7 +2578,7 @@ func (db *DB) GetObserverPacketCounts(sinceEpoch int64) map[string]int { if db.isV3 { rows, err = db.conn.Query(`SELECT obs.id, COUNT(*) as cnt FROM observations o - JOIN observers obs ON obs.rowid = o.observer_idx + JOIN observers obs ON obs.idx = o.observer_idx WHERE o.timestamp > ? GROUP BY obs.id`, sinceEpoch) } else { diff --git a/cmd/server/db_test.go b/cmd/server/db_test.go index 0a3f68d62..3f19ff1a7 100644 --- a/cmd/server/db_test.go +++ b/cmd/server/db_test.go @@ -42,7 +42,7 @@ func setupTestDB(t testing.TB) *DB { ); CREATE TABLE observers ( - id TEXT PRIMARY KEY, + idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, last_seen TEXT, @@ -1248,7 +1248,7 @@ func setupTestDBV2(t *testing.T) *DB { ); CREATE TABLE observers ( - id TEXT PRIMARY KEY, + idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, last_seen TEXT, @@ -2219,8 +2219,8 @@ func TestPerObservationRawHexEnrich(t *testing.T) { db.conn.Exec(`INSERT INTO observers (id, name) VALUES ('obs-b', 'Observer B')`) var rowA, rowB int64 - db.conn.QueryRow(`SELECT rowid FROM observers WHERE id='obs-a'`).Scan(&rowA) - db.conn.QueryRow(`SELECT rowid FROM observers WHERE id='obs-b'`).Scan(&rowB) + db.conn.QueryRow(`SELECT idx FROM observers WHERE id='obs-a'`).Scan(&rowA) + db.conn.QueryRow(`SELECT idx FROM observers WHERE id='obs-b'`).Scan(&rowB) // Insert transmission with raw_hex txHex := "deadbeef" diff --git a/cmd/server/direct_heard.go b/cmd/server/direct_heard.go index 8c0cf0535..61c910241 100644 --- a/cmd/server/direct_heard.go +++ b/cmd/server/direct_heard.go @@ -6,30 +6,31 @@ // file existed, and it is the only one for which the SNR and RSSI printed // next to an observer belong to the node the row names. // -// The rule follows the firmware: +// The rule is packetpath.HeardKey, shared with the ingestor's client +// receptions: the last hop of a flood route, or the advertiser of a zero-hop +// ADVERT (flood, or direct via Mesh::sendZeroHop). It refuses three things, +// each because it can name the wrong node: // -// - Flood routes build the path up as they travel: a forwarding repeater -// appends its own hash before retransmitting (Mesh.cpp:349). The last -// hop is therefore the node whose transmission the observer received. -// - Direct routes carry the REMAINING route, not the travelled one. A -// forwarder matches itself against the head of the path and calls -// removeSelfFromPath (Mesh.cpp:89,103) before retransmitting, so the -// node the observer heard is not in the path at all. Direct routes -// therefore never attribute. -// - An empty flood path means the observer received the originator's own -// transmission. Only ADVERTs carry the originator's pubkey in the -// clear, so other payload types with an empty path attribute to nobody. -// - A hop prefix that matches more than one node attributes to nobody. -// Path hop sizes are chosen by the originator (Packet.h:83, -// Mesh.cpp:649) and default to one byte, so a hop often matches many -// candidates. resolveWithContext guesses in that case; this file does -// not. The gate matches resolvePathForObsColdLoad: under-attribute -// rather than credit the wrong node. +// - a 1-byte last hop: a node CoreScope does not know can share that byte, +// so even a prefix with one known candidate is not proof; +// - TRACE: its path bytes carry per-hop SNR, not node hashes; +// - a zero-hop ADVERT whose signature failed to verify: the pubkey in it +// is not proven to belong to the transmitter. +// +// Direct routes with a path never attribute: a forwarder calls +// removeSelfFromPath (Mesh.cpp:89,103) before retransmitting, so the path +// left behind is the remaining route. A hop prefix of 2 bytes or more that +// matches more than one node, or that a retired repeater shares, also +// attributes to nobody: under-attribute rather than credit the wrong node, +// as resolvePathForObsColdLoad and uniqueHopPrefix do. package main import ( "sort" "strings" + "time" + + "github.com/meshcore-analyzer/packetpath" ) // directHeardAgg accumulates one observer's direct receptions of one node. @@ -40,6 +41,18 @@ type directHeardAgg struct { SNRCount int RSSISum float64 RSSICount int + // Hours holds hourly reception counts and SNR histograms, keyed by hours + // since the Unix epoch. Recent holds the newest receptions (at most + // heardRecentMax after the pass), oldest first. + Hours map[int32]*heardHour + Recent []heardSample + + // lastKey/lastHour skip the map lookup for consecutive receptions in + // the same hour, the common case in a time-ordered store. + lastKey int32 + lastHour *heardHour + // recentHead is the next slot to overwrite once Recent is full. + recentHead int } // directHeardIndex maps node pubkey (lowercase) to observer id to aggregate. @@ -101,49 +114,41 @@ func advertOriginPubkey(tx *StoreTx) string { // directHeardNode returns the lowercase pubkey of the node whose // transmission this observation received off the air, or "" when that cannot -// be established. See the package comment for the rule and its firmware -// grounding. +// be established. See the package comment for the rule. func directHeardNode(tx *StoreTx, obs *StoreObs, pm *prefixMap) string { - if tx == nil || obs == nil || tx.RouteType == nil { + if tx == nil || obs == nil || tx.RouteType == nil || tx.PayloadType == nil { return "" } hop := lastPathHop(obs.PathJSON) - switch *tx.RouteType { - case RouteFlood, RouteTransportFlood: - // Handled below: empty path means the originator, otherwise the last - // hop is whoever was heard. - case RouteDirect, RouteTransportDirect: - // A direct route normally says nothing about the transmitter, because - // the forwarder calls removeSelfFromPath before retransmitting - // (firmware Mesh.cpp) and the path left behind is the REMAINING route. - // - // The exception is a zero hop. Mesh::sendZeroHop sets ROUTE_TYPE_DIRECT - // (its transport overload ROUTE_TYPE_TRANSPORT_DIRECT) and path_len = 0, - // commented there as "path_len of zero means Zero Hop". Repeaters send - // their periodic local advert that way (simple_repeater/MyMesh.cpp, the - // next_local_advert branch and sendSelfAdvertisement with flood=false), - // and so do companions. An ADVERT arriving on a direct route with an - // empty path therefore cannot have been forwarded: the observer heard - // the advertiser's own transmission, and the advert carries its pubkey - // in the clear. That is the strongest direct-RF evidence there is. - // - // Anything else direct still says nothing: a non-empty path is the - // remaining route, and advertOriginPubkey returns "" for every payload - // type other than ADVERT. - if hop == "" { - return advertOriginPubkey(tx) + adv := "" + if hop == "" { + // advertOriginPubkey checks the type first, so signatureFailed (which + // may parse DecodedJSON) only runs for ADVERTs. + if pk := advertOriginPubkey(tx); pk != "" && !tx.signatureFailed() { + adv = pk } - return "" - default: + } + key, src, ok := packetpath.HeardKey(*tx.RouteType, byte(*tx.PayloadType), hop, adv) + if !ok { return "" } - if hop == "" { - return advertOriginPubkey(tx) + if src == "advert" { + return key } if pm == nil { return "" } - candidates := pm.relayCandidates(hop) + // A retired repeater (moved to inactive_nodes) may still relay on this + // prefix, so the one active candidate is not proven (uniqueHopPrefix). + if _, shared := pm.retired[key]; shared { + return "" + } + // key is already lower case: look it up directly instead of through + // relayCandidates, which lower-cases again on every observation. + candidates, found := pm.relay[key] + if !found { + candidates = pm.m[key] + } if len(candidates) != 1 { return "" } @@ -183,11 +188,60 @@ func buildDirectHeardIndex(packets []*StoreTx, pm *prefixMap) directHeardIndex { agg.RSSISum += *obs.RSSI agg.RSSICount++ } + if t, ok := obs.ParsedTime(); ok { + agg.addReception(t, obs.SNR, obs.RSSI) + } + } + } + for _, byObs := range idx { + for _, agg := range byObs { + agg.trimRecent() } } return idx } +// addReception records one timed reception in the hourly histogram and the +// ring. Once the ring is full each reception overwrites the oldest; +// trimRecent restores arrival order after the pass. +func (a *directHeardAgg) addReception(t time.Time, snr, rssi *float64) { + if a.Hours == nil { + a.Hours = make(map[int32]*heardHour, 8) + } + key := int32(t.Unix() / 3600) + h := a.lastHour + if h == nil || a.lastKey != key { + h = a.Hours[key] + if h == nil { + h = &heardHour{Bins: make([]snrBin, 0, 8)} + a.Hours[key] = h + } + a.lastKey, a.lastHour = key, h + } + h.N++ + if snr != nil { + h.addSNR(*snr) + } + smp := newHeardSample(t, snr, rssi) + if len(a.Recent) < heardRecentMax { + a.Recent = append(a.Recent, smp) + return + } + a.Recent[a.recentHead] = smp + a.recentHead = (a.recentHead + 1) % heardRecentMax +} + +// trimRecent puts a wrapped ring back in arrival order, oldest first. +func (a *directHeardAgg) trimRecent() { + if a.recentHead == 0 { + return + } + r := make([]heardSample, 0, len(a.Recent)) + r = append(r, a.Recent[a.recentHead:]...) + a.Recent = append(r, a.Recent[:a.recentHead]...) + a.recentHead = 0 +} + // computeDirectHeard rebuilds the whole index from the current store. Run by // a background recomputer rather than per request: the reference deployment // holds 232,928 transmissions and 2,887,861 observations, and one node's @@ -305,3 +359,21 @@ func buildDirectObserverRows(byObs map[string]*directHeardAgg, nonRelay, seen ma }) return rows } + +// directAvgSNR is a node's SNR over its direct receptions: the mean of every +// sample across all observers that heard it on air. Nil when no observer +// reported an SNR for a direct reception. Relayed copies never count, the +// SNR on those belongs to whichever node transmitted the copy last. +func directAvgSNR(byObs map[string]*directHeardAgg) *float64 { + var sum float64 + var n int + for _, agg := range byObs { + sum += agg.SNRSum + n += agg.SNRCount + } + if n == 0 { + return nil + } + v := sum / float64(n) + return &v +} diff --git a/cmd/server/direct_heard_test.go b/cmd/server/direct_heard_test.go index d93702513..54159327e 100644 --- a/cmd/server/direct_heard_test.go +++ b/cmd/server/direct_heard_test.go @@ -1,7 +1,9 @@ package main import ( + "strconv" "testing" + "time" ) // Coverage for the direct-RF attribution rule behind the node detail @@ -177,6 +179,36 @@ func TestDirectHeardNode(t *testing.T) { pathJSON: `["BB11"]`, want: "", }, + { + name: "unique one-byte last hop credits nobody", + tx: dhTx(RouteFlood, PayloadTXT_MSG, ""), + pathJSON: `["66","BB"]`, + want: "", + }, + { + name: "TRACE flood with a unique two-byte last hop credits nobody", + tx: dhTx(RouteFlood, PayloadTRACE, ""), + pathJSON: `["BB11"]`, + want: "", + }, + { + name: "zero-hop advert with a failed signature credits nobody", + tx: dhTx(RouteFlood, PayloadADVERT, `{"type":"ADVERT","pubKey":"`+dhUnique+`","signatureValid":false}`), + pathJSON: `[]`, + want: "", + }, + { + name: "zero-hop advert with a valid signature credits the advertiser", + tx: dhTx(RouteFlood, PayloadADVERT, `{"type":"ADVERT","pubKey":"`+dhUnique+`","signatureValid":true}`), + pathJSON: `[]`, + want: dhUnique, + }, + { + name: "missing payload type credits nobody", + tx: &StoreTx{RouteType: dhRoute(RouteFlood)}, + pathJSON: `["BB11"]`, + want: "", + }, } for _, tc := range cases { @@ -334,3 +366,131 @@ func TestBuildDirectHeardIndex_SkipsOwnTransmissions(t *testing.T) { t.Fatalf("rx copy of the forwarded packet = %#v, want Count 1", a) } } + +// BenchmarkBuildDirectHeardIndex_MixedHops runs the compute pass over 50,000 +// transmissions with 10 observations each: mixed 1-, 2- and 3-byte last +// hops, 5% zero-hop adverts. +func BenchmarkBuildDirectHeardIndex_MixedHops(b *testing.B) { + pm := buildPrefixMap(directHeardNodes) + advert := `{"type":"ADVERT","pubKey":"` + dhUnique + `","signatureValid":true}` + paths := []string{`["66","BB"]`, `["66","A4"]`, `["66","BB11"]`, `["66","A433"]`, `["66","BB1122"]`, `["9999"]`} + packets := make([]*StoreTx, 0, 50000) + for i := 0; i < 50000; i++ { + var tx *StoreTx + path := paths[i%len(paths)] + if i%20 == 0 { + tx = dhTx(RouteFlood, PayloadADVERT, advert) + path = `[]` + } else { + tx = dhTx(RouteFlood, PayloadTXT_MSG, "") + } + for j := 0; j < 10; j++ { + snr := float64((i+j)%40) - 20 + tx.Observations = append(tx.Observations, &StoreObs{ObserverID: "obs" + strconv.Itoa(j), PathJSON: path, SNR: &snr, Timestamp: benchObsTime(i*10 + j)}) + } + packets = append(packets, tx) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + buildDirectHeardIndex(packets, pm) + } +} + +// TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold pins that the +// signature check runs for ADVERTs only: the compute pass walks every +// observation, and a zero-hop message must not parse and cache its decoded +// JSON (signatureFailed parses when the text holds a \u escape). +func TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold(t *testing.T) { + pm := buildPrefixMap(directHeardNodes) + tx := dhTx(RouteFlood, PayloadTXT_MSG, `{"type":"TXT_MSG","text":"caf\u00e9"}`) + obs := &StoreObs{ObserverID: "obs1", PathJSON: `[]`} + if got := directHeardNode(tx, obs, pm); got != "" { + t.Fatalf("directHeardNode = %q, want \"\"", got) + } + if tx.parsedDecoded != nil { + t.Fatalf("decoded JSON was parsed for a zero-hop non-advert") + } +} + +// TestDirectHeardNode_RetiredPrefixCreditsNobody: a hop whose prefix a +// retired repeater (moved to inactive_nodes, still able to relay) shares is +// no proof the one active candidate transmitted, as in uniqueHopPrefix. +func TestDirectHeardNode_RetiredPrefixCreditsNobody(t *testing.T) { + pm := buildPrefixMap(directHeardNodes) + pm.retired = map[string]struct{}{"bb11": {}} + tx := dhTx(RouteFlood, PayloadTXT_MSG, "") + if got := directHeardNode(tx, &StoreObs{ObserverID: "obs1", PathJSON: `["66","BB11"]`}, pm); got != "" { + t.Fatalf("directHeardNode = %q, want \"\" for a hop shared with a retired node", got) + } + if got := directHeardNode(tx, &StoreObs{ObserverID: "obs1", PathJSON: `["66","BB1122"]`}, pm); got != dhUnique { + t.Fatalf("directHeardNode = %q, want %q: the 3-byte hop is not retired", got, dhUnique) + } +} + +// TestBuildDirectHeardIndex_HoursAndRecent: the pass keeps hourly SNR +// histograms and a ring of the newest receptions per (node, observer). +func TestBuildDirectHeardIndex_HoursAndRecent(t *testing.T) { + pm := buildPrefixMap(directHeardNodes) + h := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) + snr := func(v float64) *float64 { return &v } + mk := func(at time.Time, s *float64) *StoreTx { + tx := dhTx(RouteFlood, PayloadTXT_MSG, "") + tx.Observations = []*StoreObs{{ObserverID: "obs1", PathJSON: `["BB11"]`, SNR: s, Timestamp: at.Format(time.RFC3339)}} + return tx + } + packets := []*StoreTx{ + mk(h.Add(5*time.Minute), snr(-4.5)), + mk(h.Add(10*time.Minute), snr(-4.5)), + mk(h.Add(70*time.Minute), snr(2)), + mk(h.Add(80*time.Minute), nil), + } + agg := buildDirectHeardIndex(packets, pm)[dhUnique]["obs1"] + if agg == nil { + t.Fatal("no aggregate for obs1") + } + if len(agg.Hours) != 2 { + t.Fatalf("hours = %d, want 2", len(agg.Hours)) + } + var n uint32 + var hist snrHist + for _, x := range agg.Hours { + n += x.N + hist.addHour(x) + } + if n != 4 || hist.total != 3 { + t.Fatalf("receptions %d (want 4), SNR samples %d (want 3)", n, hist.total) + } + if len(agg.Recent) != 4 || agg.Recent[3].T != uint32(h.Add(80*time.Minute).Unix()) { + t.Fatalf("recent = %+v, want 4 entries, newest last", agg.Recent) + } + + packets = packets[:0] + for i := 0; i < 600; i++ { + packets = append(packets, mk(h.Add(time.Duration(i)*time.Second), snr(1))) + } + agg = buildDirectHeardIndex(packets, pm)[dhUnique]["obs1"] + if len(agg.Recent) != heardRecentMax || agg.Recent[0].T != uint32(h.Add(100*time.Second).Unix()) || agg.Recent[len(agg.Recent)-1].T != uint32(h.Add(599*time.Second).Unix()) { + t.Fatalf("ring holds %d entries from %d to %d, want the newest 500", len(agg.Recent), agg.Recent[0].T, agg.Recent[len(agg.Recent)-1].T) + } +} + +// directAvgSNR is the node-level SNR the health endpoints report: the mean +// over every direct reception that carried an SNR, across all observers. +func TestDirectAvgSNR(t *testing.T) { + if got := directAvgSNR(nil); got != nil { + t.Fatalf("no direct observers: avgSnr = %v, want nil", *got) + } + noSignal := map[string]*directHeardAgg{"a": {Count: 4}} + if got := directAvgSNR(noSignal); got != nil { + t.Fatalf("direct observers without SNR samples: avgSnr = %v, want nil", *got) + } + byObs := map[string]*directHeardAgg{ + "a": {Count: 3, SNRSum: 30, SNRCount: 3}, // 10 dB x3 + "b": {Count: 1, SNRSum: -2, SNRCount: 1}, // -2 dB x1 + "c": {Count: 5}, // no samples, no weight + } + got := directAvgSNR(byObs) + if got == nil || *got != 7 { + t.Fatalf("avgSnr = %v, want 7 (28 over 4 samples)", got) + } +} diff --git a/cmd/server/heard_by.go b/cmd/server/heard_by.go new file mode 100644 index 000000000..91c276831 --- /dev/null +++ b/cmd/server/heard_by.go @@ -0,0 +1,171 @@ +package main + +import ( + "math" + "sort" + "strings" + "time" +) + +// The node analytics "Heard by observers" list: per fixed observer that +// heard the node directly, the reception count and SNR spread in the +// window, read from the direct-heard snapshot (see heard_snr.go). + +const ( + // heardChangeMinDays is the shortest window that shows the change + // column (last 24 h against the rest of the window). + heardChangeMinDays = 3 + // heardChangeMinCount is the fewest SNR receptions each part needs. + heardChangeMinCount = 3 + // snrTrendMax caps snrTrend to the newest receptions in the window. + snrTrendMax = 500 +) + +func hourKey(t time.Time) int32 { return int32(t.Unix() / 3600) } + +// heardByRows builds one row per observer heard in [from, now], sorted by +// median SNR (best first), rows without an SNR last, then by observer id. +// The window is cut at hour granularity: the hour holding from counts. +func heardByRows(byObs map[string]*directHeardAgg, from, now time.Time) []HeardByObserver { + fromKey := hourKey(from) + splitKey := hourKey(now.Add(-24 * time.Hour)) + showChange := now.Sub(from) >= heardChangeMinDays*24*time.Hour + rows := make([]HeardByObserver, 0, len(byObs)) + for id, agg := range byObs { + var all, recent, earlier snrHist + count := 0 + for k, h := range agg.Hours { + if k < fromKey { + continue + } + count += int(h.N) + all.addHour(h) + if !showChange { + continue + } + if k >= splitKey { + recent.addHour(h) + } else { + earlier.addHour(h) + } + } + if count == 0 { + continue + } + row := HeardByObserver{ObserverID: id, ObserverName: agg.ObserverName, Count: count} + row.MedianSNR = quantilePtr(&all, 0.5) + row.P10SNR = quantilePtr(&all, 0.1) + row.P90SNR = quantilePtr(&all, 0.9) + if showChange && recent.total >= heardChangeMinCount && earlier.total >= heardChangeMinCount { + row.RecentMedianSNR = quantilePtr(&recent, 0.5) + row.EarlierMedianSNR = quantilePtr(&earlier, 0.5) + } + rows = append(rows, row) + } + sort.Slice(rows, func(i, j int) bool { + a, b := rows[i].MedianSNR, rows[j].MedianSNR + if (a == nil) != (b == nil) { + return a != nil + } + if a != nil && *a != *b { + return *a > *b + } + return rows[i].ObserverID < rows[j].ObserverID + }) + return rows +} + +func quantilePtr(h *snrHist, q float64) *float64 { + v, ok := h.quantile(q) + if !ok { + return nil + } + return &v +} + +// heardSnrTrend returns the newest max direct receptions with an SNR at or +// after from, across all observers, oldest first. +func heardSnrTrend(byObs map[string]*directHeardAgg, from time.Time, max int) []SnrTrendEntry { + type ref struct { + id string + smp heardSample + } + fromT := uint32(from.Unix()) + refs := make([]ref, 0, 64) + for id, agg := range byObs { + for _, smp := range agg.Recent { + if smp.T >= fromT && smp.SNR != math.MinInt8 { + refs = append(refs, ref{id, smp}) + } + } + } + sort.Slice(refs, func(i, j int) bool { + if refs[i].smp.T != refs[j].smp.T { + return refs[i].smp.T < refs[j].smp.T + } + return refs[i].id < refs[j].id + }) + if len(refs) > max { + refs = refs[len(refs)-max:] + } + out := make([]SnrTrendEntry, 0, len(refs)) + for _, r := range refs { + e := SnrTrendEntry{ + Timestamp: time.Unix(int64(r.smp.T), 0).UTC().Format(time.RFC3339), + SNR: float64(r.smp.SNR) / 4, + ObserverID: r.id, + ObserverName: strOrNil(byObs[r.id].ObserverName), + } + if r.smp.RSSI != math.MinInt16 { + e.RSSI = float64(r.smp.RSSI) + } + out = append(out, e) + } + return out +} + +// signalFromMedians averages the per-observer median SNRs, so each observer +// counts once however often it heard the node. Rows without a median are +// left out. +func signalFromMedians(rows []HeardByObserver) (mean, stddev float64, grade string) { + var vals []float64 + for _, r := range rows { + if r.MedianSNR != nil { + vals = append(vals, *r.MedianSNR) + } + } + if len(vals) > 0 { + for _, v := range vals { + mean += v + } + mean /= float64(len(vals)) + var sq float64 + for _, v := range vals { + sq += (v - mean) * (v - mean) + } + stddev = math.Sqrt(sq / float64(len(vals))) + } + return mean, stddev, signalGradeFor(mean, stddev) +} + +// signalGradeFor maps a mean SNR and its spread to the node analytics grade. +func signalGradeFor(mean, stddev float64) string { + switch { + case mean > 15 && stddev < 2: + return "A" + case mean > 15: + return "A-" + case mean > 12 && stddev < 3: + return "B+" + case mean > 8: + return "B" + case mean > 3: + return "C" + } + return "D" +} + +// directHeardFor returns the snapshot's observers for one node. +func directHeardFor(idx directHeardIndex, pubkey string) map[string]*directHeardAgg { + return idx[strings.ToLower(pubkey)] +} diff --git a/cmd/server/heard_by_test.go b/cmd/server/heard_by_test.go new file mode 100644 index 000000000..3eaeff8c4 --- /dev/null +++ b/cmd/server/heard_by_test.go @@ -0,0 +1,132 @@ +package main + +import ( + "testing" + "time" +) + +// hbAgg builds an aggregate from (time, snr) receptions; snr nil = no SNR. +func hbAgg(name string, recs ...hbRec) *directHeardAgg { + a := &directHeardAgg{ObserverName: name} + for _, r := range recs { + a.Count++ + a.addReception(r.at, r.snr, nil) + } + a.trimRecent() + return a +} + +type hbRec struct { + at time.Time + snr *float64 +} + +func hbF(v float64) *float64 { return &v } + +func hbRecs(at time.Time, vals ...float64) []hbRec { + out := make([]hbRec, 0, len(vals)) + for i, v := range vals { + out = append(out, hbRec{at: at.Add(time.Duration(i) * time.Minute), snr: hbF(v)}) + } + return out +} + +var hbNow = time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) + +func TestHeardByRows_SortAndQuantiles(t *testing.T) { + at := hbNow.Add(-2 * time.Hour) + byObs := map[string]*directHeardAgg{ + "obsB": hbAgg("B", hbRecs(at, -12, -11, -10)...), + "obsA": hbAgg("A", hbRecs(at, 8, 9, 10)...), + "obsC": hbAgg("C", hbRec{at: at}, hbRec{at: at.Add(time.Minute)}), + } + rows := heardByRows(byObs, hbNow.Add(-7*24*time.Hour), hbNow) + if len(rows) != 3 || rows[0].ObserverID != "obsA" || rows[1].ObserverID != "obsB" || rows[2].ObserverID != "obsC" { + t.Fatalf("order = %+v, want obsA, obsB, obsC", rows) + } + a := rows[0] + if a.ObserverName != "A" || a.Count != 3 || *a.MedianSNR != 9 || *a.P10SNR != 8 || *a.P90SNR != 10 { + t.Fatalf("obsA = %+v, want count 3, median 9, p10 8, p90 10", a) + } + if c := rows[2]; c.MedianSNR != nil || c.P10SNR != nil || c.Count != 2 { + t.Fatalf("obsC = %+v, want count 2 and no median", c) + } +} + +func TestHeardByRows_ChangeColumn(t *testing.T) { + recent := hbRecs(hbNow.Add(-3*time.Hour), 2, 2, 2) + earlier := hbRecs(hbNow.Add(-72*time.Hour), 6, 6, 6) + rows := heardByRows(map[string]*directHeardAgg{"obsA": hbAgg("A", append(earlier, recent...)...)}, hbNow.Add(-7*24*time.Hour), hbNow) + if r := rows[0]; r.RecentMedianSNR == nil || *r.RecentMedianSNR != 2 || r.EarlierMedianSNR == nil || *r.EarlierMedianSNR != 6 { + t.Fatalf("change medians = %v, %v; want 2, 6", r.RecentMedianSNR, r.EarlierMedianSNR) + } + + rows = heardByRows(map[string]*directHeardAgg{"obsA": hbAgg("A", append(earlier, recent[:2]...)...)}, hbNow.Add(-7*24*time.Hour), hbNow) + if r := rows[0]; r.RecentMedianSNR != nil || r.EarlierMedianSNR != nil { + t.Fatalf("2 recent receptions: change medians = %v, %v; want both nil", r.RecentMedianSNR, r.EarlierMedianSNR) + } + + rows = heardByRows(map[string]*directHeardAgg{"obsA": hbAgg("A", recent...)}, hbNow.Add(-24*time.Hour), hbNow) + if r := rows[0]; r.RecentMedianSNR != nil || r.EarlierMedianSNR != nil { + t.Fatalf("24 h window: change medians = %v, %v; want both nil", r.RecentMedianSNR, r.EarlierMedianSNR) + } +} + +func TestHeardByRows_WindowCut(t *testing.T) { + from := hbNow.Add(-24 * time.Hour) + recs := append(hbRecs(from.Add(-2*time.Hour), -20), hbRecs(hbNow.Add(-time.Hour), 4)...) + rows := heardByRows(map[string]*directHeardAgg{"obsA": hbAgg("A", recs...)}, from, hbNow) + if len(rows) != 1 || rows[0].Count != 1 || *rows[0].MedianSNR != 4 || *rows[0].P10SNR != 4 { + t.Fatalf("rows = %+v, want one reception at 4 dB", rows) + } + + rows = heardByRows(map[string]*directHeardAgg{"obsA": hbAgg("A", hbRecs(from.Add(-2*time.Hour), 1)...)}, from, hbNow) + if len(rows) != 0 { + t.Fatalf("observer heard only before the window is listed: %+v", rows) + } +} + +func TestHeardSnrTrend_CapAndOrder(t *testing.T) { + from := hbNow.Add(-7 * 24 * time.Hour) + var a, b []hbRec + a = append(a, hbRec{at: from.Add(-time.Hour), snr: hbF(-30)}) + for i := 0; i < 350; i++ { + a = append(a, hbRec{at: hbNow.Add(-time.Duration(2*i) * time.Minute), snr: hbF(1)}) + b = append(b, hbRec{at: hbNow.Add(-time.Duration(2*i+1) * time.Minute), snr: hbF(2)}) + } + // Receptions arrive oldest first in the store. + for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { + a[i], a[j] = a[j], a[i] + } + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + byObs := map[string]*directHeardAgg{"obsA": hbAgg("A", a...), "obsB": hbAgg("B", b...)} + trend := heardSnrTrend(byObs, from, snrTrendMax) + if len(trend) != snrTrendMax { + t.Fatalf("len = %d, want %d", len(trend), snrTrendMax) + } + if trend[len(trend)-1].Timestamp != hbNow.Format(time.RFC3339) { + t.Fatalf("newest = %s, want %s", trend[len(trend)-1].Timestamp, hbNow.Format(time.RFC3339)) + } + for i := 1; i < len(trend); i++ { + if trend[i].Timestamp < trend[i-1].Timestamp { + t.Fatalf("not ascending at %d: %s after %s", i, trend[i].Timestamp, trend[i-1].Timestamp) + } + } + for _, e := range trend { + if e.SNR == -30.0 { + t.Fatal("a reception before the window is in snrTrend") + } + } +} + +func TestSignalFromMedians(t *testing.T) { + rows := []HeardByObserver{{MedianSNR: hbF(16)}, {MedianSNR: hbF(16)}, {Count: 5}} + if mean, sd, grade := signalFromMedians(rows); mean != 16 || sd != 0 || grade != "A" { + t.Fatalf("got %v, %v, %s; want 16, 0, A", mean, sd, grade) + } + if mean, _, grade := signalFromMedians(nil); mean != 0 || grade != "D" { + t.Fatalf("no rows: got %v, %s; want 0, D", mean, grade) + } +} diff --git a/cmd/server/heard_snr.go b/cmd/server/heard_snr.go new file mode 100644 index 000000000..65564ba57 --- /dev/null +++ b/cmd/server/heard_snr.go @@ -0,0 +1,110 @@ +package main + +import ( + "math" + "time" +) + +// SNR detail kept per (node, observer) by the direct-heard pass, so the node +// analytics page can show median, spread and change over time of what an +// observer received from the node itself, without a per-request scan. +// +// SNR is binned at 0.25 dB: the firmware reports SNR as a signed byte in +// quarter dB, so the bins lose nothing. + +// heardRecentMax bounds the ring of newest receptions per (node, observer) +// that feeds snrTrend. +const heardRecentMax = 500 + +// snrBin is one non-empty histogram bin: Bin is the quarter-dB value offset +// by 128, N the number of receptions in it. +type snrBin struct { + Bin uint8 + N uint32 +} + +// heardHour holds one hour of direct receptions: N counts all of them, Bins +// only those with an SNR. Sparse because an hour has few distinct values. +type heardHour struct { + N uint32 + Bins []snrBin +} + +// heardSample is one reception in the ring: unix seconds, SNR in quarter dB +// (math.MinInt8 when absent), RSSI in dBm (math.MinInt16 when absent). +type heardSample struct { + T uint32 + SNR int8 + RSSI int16 +} + +// snrQuarterBin rounds snr to 0.25 dB, clamps it to the signed-byte range +// and offsets it by 128. +func snrQuarterBin(snr float64) uint8 { + q := math.Round(snr * 4) + q = math.Max(-128, math.Min(127, q)) + return uint8(int(q) + 128) +} + +// binSNR is the dB value of a bin. +func binSNR(b uint8) float64 { + return float64(int(b)-128) / 4 +} + +// addSNR counts one SNR value in the hour's histogram. +func (h *heardHour) addSNR(snr float64) { + b := snrQuarterBin(snr) + for i := range h.Bins { + if h.Bins[i].Bin == b { + h.Bins[i].N++ + return + } + } + h.Bins = append(h.Bins, snrBin{Bin: b, N: 1}) +} + +// newHeardSample packs one reception for the ring. +func newHeardSample(t time.Time, snr, rssi *float64) heardSample { + s := heardSample{T: uint32(t.Unix()), SNR: math.MinInt8, RSSI: math.MinInt16} + if snr != nil { + // -128 is the "absent" marker, so a real value clamps to -127. + s.SNR = int8(math.Max(-127, math.Min(127, math.Round(*snr*4)))) + } + if rssi != nil { + s.RSSI = int16(math.Max(-32767, math.Min(32767, math.Round(*rssi)))) + } + return s +} + +// snrHist merges hourly histograms for one window. +type snrHist struct { + counts [256]uint32 + total uint32 +} + +func (h *snrHist) addHour(x *heardHour) { + for _, b := range x.Bins { + h.counts[b.Bin] += b.N + h.total += b.N + } +} + +// quantile returns the nearest-rank q-quantile, or ok == false when the +// histogram is empty. +func (h *snrHist) quantile(q float64) (float64, bool) { + if h.total == 0 { + return 0, false + } + rank := uint32(math.Ceil(q * float64(h.total))) + if rank < 1 { + rank = 1 + } + var seen uint32 + for b, n := range h.counts { + seen += n + if seen >= rank { + return binSNR(uint8(b)), true + } + } + return binSNR(255), true +} diff --git a/cmd/server/heard_snr_test.go b/cmd/server/heard_snr_test.go new file mode 100644 index 000000000..9c3c42a29 --- /dev/null +++ b/cmd/server/heard_snr_test.go @@ -0,0 +1,36 @@ +package main + +import "testing" + +func TestSnrQuarterBin(t *testing.T) { + cases := []struct{ in, want float64 }{ + {-7.25, -7.25}, + {13.1, 13.0}, + {99, 31.75}, + {-99, -32}, + } + for _, c := range cases { + if got := binSNR(snrQuarterBin(c.in)); got != c.want { + t.Errorf("binSNR(snrQuarterBin(%v)) = %v, want %v", c.in, got, c.want) + } + } +} + +func TestSnrHistQuantile(t *testing.T) { + var h snrHist + if _, ok := h.quantile(0.5); ok { + t.Fatal("empty histogram must report ok == false") + } + x := &heardHour{} + for _, v := range []float64{-10, -5, 0, 5, 10} { + x.N++ + x.addSNR(v) + } + h.addHour(x) + for _, c := range []struct{ q, want float64 }{{0.5, 0}, {0.1, -10}, {0.9, 10}} { + got, ok := h.quantile(c.q) + if !ok || got != c.want { + t.Errorf("quantile(%v) = %v, %v; want %v", c.q, got, ok, c.want) + } + } +} diff --git a/cmd/server/helpers_test.go b/cmd/server/helpers_test.go index f146ffc53..c000f2ccc 100644 --- a/cmd/server/helpers_test.go +++ b/cmd/server/helpers_test.go @@ -306,7 +306,7 @@ func TestSpaHandler(t *testing.T) { os.WriteFile(filepath.Join(dir, "style.css"), []byte("body{}"), 0644) fs := http.FileServer(http.Dir(dir)) - handler := spaHandler(dir, fs) + handler := spaHandler(dir, fs, "") t.Run("existing JS file with cache control", func(t *testing.T) { req := httptest.NewRequest("GET", "/app.js", nil) @@ -408,7 +408,7 @@ func TestSpaHandlerCacheBust(t *testing.T) { os.WriteFile(filepath.Join(dir, "index.html"), []byte(htmlWithBust), 0644) fs := http.FileServer(http.Dir(dir)) - handler := spaHandler(dir, fs) + handler := spaHandler(dir, fs, "") t.Run("__BUST__ is replaced with a Unix timestamp", func(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) @@ -455,7 +455,7 @@ func TestSpaHandlerBustsEveryTopLevelPage(t *testing.T) { dir := t.TempDir() os.WriteFile(filepath.Join(dir, "index.html"), []byte(``), 0644) os.WriteFile(filepath.Join(dir, "tool.html"), []byte(``), 0644) - handler := spaHandler(dir, http.FileServer(http.Dir(dir))) + handler := spaHandler(dir, http.FileServer(http.Dir(dir)), "") get := func(p string) *httptest.ResponseRecorder { w := httptest.NewRecorder() diff --git a/cmd/server/hot_startup_test.go b/cmd/server/hot_startup_test.go index 238369c3c..82619de3e 100644 --- a/cmd/server/hot_startup_test.go +++ b/cmd/server/hot_startup_test.go @@ -37,7 +37,7 @@ func createTestDBMultiDay(t *testing.T, numDays, txPerDay int) string { } execOrFail(`CREATE TABLE transmissions (id INTEGER PRIMARY KEY, raw_hex TEXT, hash TEXT, first_seen TEXT, route_type INTEGER, payload_type INTEGER, payload_version INTEGER, decoded_json TEXT)`) execOrFail(`CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_id TEXT, observer_name TEXT, direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT, raw_hex TEXT)`) - execOrFail(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + execOrFail(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) execOrFail(`CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL)`) execOrFail(`CREATE TABLE schema_version (version INTEGER)`) execOrFail(`INSERT INTO schema_version (version) VALUES (1)`) diff --git a/cmd/server/issue1189_distinct_iatas_test.go b/cmd/server/issue1189_distinct_iatas_test.go index 3a096fe95..7196ed9c8 100644 --- a/cmd/server/issue1189_distinct_iatas_test.go +++ b/cmd/server/issue1189_distinct_iatas_test.go @@ -36,7 +36,7 @@ func TestQueryGroupedPacketsReturnsDistinctIATAs(t *testing.T) { // One transmission with 3 observations (SJC, SFO, no-IATA). db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, decoded_json) VALUES ('AABB', 'deadbeefcafef00d', ?, 1, 4, '{}')`, now.Format(time.RFC3339)) - // v3 schema: observer_idx = observers.rowid (auto-assigned 1,2,3 in insert order). + // v3 schema: observer_idx = observers.idx (auto-assigned 1,2,3 in insert order). db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, snr, rssi, path_json, timestamp) VALUES (1, 1, 12.0, -80, '["aa"]', ?)`, recentEpoch) db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, snr, rssi, path_json, timestamp) diff --git a/cmd/server/issue1809_bg_load_race_test.go b/cmd/server/issue1809_bg_load_race_test.go index eca19727c..96d156275 100644 --- a/cmd/server/issue1809_bg_load_race_test.go +++ b/cmd/server/issue1809_bg_load_race_test.go @@ -164,7 +164,7 @@ func seedTestDBRows(t *testing.T, dbPath string, numTx, obsPerTx int, rowTimes f path_json TEXT, timestamp TEXT, raw_hex TEXT )`) // PREFLIGHT: async=true reason="unit-test fixture seeder" - execOrFail(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + execOrFail(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) // PREFLIGHT: async=true reason="unit-test fixture seeder" execOrFail(`CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL)`) // PREFLIGHT: async=true reason="unit-test fixture seeder" diff --git a/cmd/server/load_graph_invariant_test.go b/cmd/server/load_graph_invariant_test.go index 07ae649f0..0830d9782 100644 --- a/cmd/server/load_graph_invariant_test.go +++ b/cmd/server/load_graph_invariant_test.go @@ -49,7 +49,7 @@ func TestLoad_PanicsWhenGraphNotLoadedAndEdgesExist(t *testing.T) { path_json TEXT, timestamp TEXT, raw_hex TEXT, resolved_path TEXT )`) // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" - exec(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + exec(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" exec(`CREATE TABLE nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, diff --git a/cmd/server/loadchunk_ambiguous_prefix_test.go b/cmd/server/loadchunk_ambiguous_prefix_test.go index 3c0e1596b..8cb70a634 100644 --- a/cmd/server/loadchunk_ambiguous_prefix_test.go +++ b/cmd/server/loadchunk_ambiguous_prefix_test.go @@ -54,7 +54,7 @@ func createTestDBAmbiguousPrefix(t *testing.T, relayA, relayB, hop, firstSeen st resolved_path TEXT )`) // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" - exec(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + exec(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" exec(`CREATE TABLE nodes ( public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, diff --git a/cmd/server/loadchunk_pathjson_fallback_test.go b/cmd/server/loadchunk_pathjson_fallback_test.go index 9d28b6203..74b16eda6 100644 --- a/cmd/server/loadchunk_pathjson_fallback_test.go +++ b/cmd/server/loadchunk_pathjson_fallback_test.go @@ -56,7 +56,7 @@ func createTestDBPathJSONNoResolvedPath(t *testing.T, relayPubkey, hopPrefix, fi resolved_path TEXT )`) // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" - exec(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + exec(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) // Production nodes schema uses public_key (not pubkey) — getAllNodes / // buildPrefixMap reads public_key, role, advert_count, first_seen. // PREFLIGHT: async=true reason="test fixture, in-memory tmpdir DB" diff --git a/cmd/server/loadchunk_resolved_path_1558_test.go b/cmd/server/loadchunk_resolved_path_1558_test.go index 9cd83ecd5..b52eadd5b 100644 --- a/cmd/server/loadchunk_resolved_path_1558_test.go +++ b/cmd/server/loadchunk_resolved_path_1558_test.go @@ -47,7 +47,7 @@ func createTestDBWithResolvedPath(t *testing.T, numTx int, relayPubkeys []string raw_hex TEXT, resolved_path TEXT )`) - exec(`CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`) + exec(`CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`) exec(`CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL)`) exec(`CREATE TABLE schema_version (version INTEGER)`) exec(`INSERT INTO schema_version (version) VALUES (1)`) diff --git a/cmd/server/main.go b/cmd/server/main.go index e33c215a3..59cdd31bb 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -433,7 +433,7 @@ func main() { absPublic, _ := filepath.Abs(publicDir) if _, err := os.Stat(absPublic); err == nil { fs := http.FileServer(http.Dir(absPublic)) - router.PathPrefix("/").Handler(wsOrStatic(hub, spaHandler(absPublic, fs))) + router.PathPrefix("/").Handler(wsOrStatic(hub, spaHandler(absPublic, fs, os.Getenv(siteURLEnv)))) log.Printf("[static] serving %s", absPublic) } else { log.Printf("[static] directory %s not found — API-only mode", absPublic) @@ -664,21 +664,40 @@ func main() { // spaHandler serves static files, falling back to index.html for SPA routes. // It reads index.html once at creation time and replaces the __BUST__ placeholder // with a Unix timestamp so browsers fetch fresh JS/CSS after each server restart. -func spaHandler(root string, fs http.Handler) http.Handler { +// siteURL is CORESCOPE_URL (see site_url.go): when valid, __CORESCOPE_URL__ is +// replaced with it at the same time; otherwise og:url is dropped then and each +// response fills in the rest with the origin the request reached. +func spaHandler(root string, fs http.Handler, siteURL string) http.Handler { // Pre-process every top-level page, index.html and the tool pages // (area-map.html, geofilter-builder.html): replace __BUST__ with a // cache-bust timestamp, so each loads the scripts of this start. bustValue := fmt.Sprintf("%d", time.Now().Unix()) pages := bustPages(root, bustValue) + if siteURL = resolveConfiguredSiteURL(siteURL); siteURL != "" { + for p, body := range pages { + pages[p] = []byte(strings.ReplaceAll(string(body), siteURLPlaceholder, siteURL)) + } + log.Printf("[static] site URL: %s", siteURL) + } else { + for p, body := range pages { + pages[p] = withoutOGURL(body) + } + log.Printf("[static] site URL: %s unset or invalid, no og:url and using each request's origin", siteURLEnv) + } indexHTML, ok := pages["/index.html"] if !ok { log.Printf("[static] warning: could not read index.html for cache-bust") indexHTML = []byte("

CoreScope

index.html not found

") } log.Printf("[static] cache-bust value: %s (%d pages)", bustValue, len(pages)) - servePage := func(w http.ResponseWriter, body []byte) { + // no-store also keeps a page filled in with one request's origin out of + // any shared cache. + servePage := func(w http.ResponseWriter, r *http.Request, body []byte) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + if siteURL == "" { + body = withSiteURL(body, r) + } w.Write(body) } @@ -696,18 +715,18 @@ func spaHandler(root string, fs http.Handler) http.Handler { // Serve the pre-processed index.html for the root, and each // pre-processed page (/index.html included) at its own path if r.URL.Path == "/" { - servePage(w, indexHTML) + servePage(w, r, indexHTML) return } if page, ok := pages[r.URL.Path]; ok { - servePage(w, page) + servePage(w, r, page) return } path := filepath.Join(root, r.URL.Path) if _, err := os.Stat(path); os.IsNotExist(err) { // SPA fallback — serve pre-processed index.html - servePage(w, indexHTML) + servePage(w, r, indexHTML) return } // Disable caching for JS/CSS/HTML diff --git a/cmd/server/multibyte_capability_test.go b/cmd/server/multibyte_capability_test.go index 53267533f..90165f05b 100644 --- a/cmd/server/multibyte_capability_test.go +++ b/cmd/server/multibyte_capability_test.go @@ -31,7 +31,7 @@ func setupCapabilityTestDB(t *testing.T) *DB { advert_count INTEGER DEFAULT 0, battery_mv INTEGER, temperature_c REAL )`) conn.Exec(`CREATE TABLE observers ( - id TEXT PRIMARY KEY, name TEXT, iata TEXT, last_seen TEXT, + idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, packet_count INTEGER DEFAULT 0, model TEXT, firmware TEXT, client_version TEXT, radio TEXT, battery_mv INTEGER, uptime_secs INTEGER diff --git a/cmd/server/my_repeaters.go b/cmd/server/my_repeaters.go new file mode 100644 index 000000000..a16209219 --- /dev/null +++ b/cmd/server/my_repeaters.go @@ -0,0 +1,145 @@ +package main + +import ( + "log" + "net/http" + "sort" + "strings" + "time" + + "github.com/meshcore-analyzer/users" +) + +// myRepeaterJSON is one repeater the caller claimed, for My account, My +// repeaters: enough to spot one that went quiet without opening each node. +type myRepeaterJSON struct { + Pubkey string `json:"pubkey"` + Name string `json:"name"` // "" when unnamed or in neither nodes nor inactive_nodes + Known bool `json:"known"` // false when the node is in neither nodes nor inactive_nodes + // Inactive: retention moved the node to inactive_nodes (silent longer + // than retention.nodeDays); name, role and lastHeard come from there. + Inactive bool `json:"inactive"` + Role string `json:"role"` // as stored, lowercase; "" when not known + // ClaimedAt is the caller's own claim. + ClaimedAt string `json:"claimedAt"` + // LastHeard is the newer of the node's last advert and the last + // transmission certainly from it (the node page's Last Heard); null when + // neither is known. + LastHeard *string `json:"lastHeard"` + // LastRelayed is the last time its hop prefix was seen relaying. The + // prefix can be shared with other repeaters, so it only marks a silent + // repeater as uncertain, never as heard. + LastRelayed *string `json:"lastRelayed"` + // Status is the saved repeater status (active, maintenance, + // decommissioned); null when none is saved. + Status *string `json:"status"` + // Comaintainers are the other active claimers, by display name. + Comaintainers []string `json:"comaintainers"` +} + +type myRepeatersJSON struct { + Repeaters []myRepeaterJSON `json:"repeaters"` +} + +// handleMyRepeaters lists the repeaters the caller claimed, by name (then +// pubkey). A node retention moved to inactive_nodes is read from there and +// marked inactive; a claim of a node in neither table is kept as known: false. +func (s *Server) handleMyRepeaters(w http.ResponseWriter, _ *http.Request, u *users.User, _ *users.Session) { + claims, err := s.auth.st.RepeaterClaimsByUser(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + out := myRepeatersJSON{Repeaters: make([]myRepeaterJSON, 0, len(claims))} + if len(claims) == 0 { + writeJSON(w, out) + return + } + pks := make([]string, len(claims)) + for i, c := range claims { + pks[i] = c.Pubkey + } + nodes := map[string]notifyNode{} + inactive := map[string]notifyNode{} + if s.db != nil { + if nodes, err = s.db.NotifyNodes(pks, false); err != nil { + log.Printf("[users] my repeaters %d: nodes: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + var missing []string + for _, pk := range pks { + if _, ok := nodes[pk]; !ok { + missing = append(missing, pk) + } + } + if len(missing) > 0 { + if inactive, err = s.db.InactiveNodeBasics(missing); err != nil { + log.Printf("[users] my repeaters %d: inactive nodes: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + } + } + infos, err := s.auth.st.RepeaterInfoOfUserRepeaters(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: info: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + claimers, err := s.auth.st.RepeaterClaimsOfUserRepeaters(u.ID) + if err != nil { + log.Printf("[users] my repeaters %d: claims: %v", u.ID, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + heard := map[string]time.Time{} + var relay map[string]RepeaterRelayInfo + if s.store != nil { + heard, _ = s.store.LastHeardMap(pks) + relay = s.store.GetRepeaterRelayInfoMap(s.cfg.GetHealthThresholds().RelayActiveHours) + } + for _, c := range claims { + nd, known := nodes[c.Pubkey] + gone := false + if !known { + nd, gone = inactive[c.Pubkey] + known = gone + } + r := myRepeaterJSON{Pubkey: c.Pubkey, Name: nd.Name, Known: known, Inactive: gone, Role: strings.ToLower(nd.Role), + ClaimedAt: rfc3339(c.ClaimedAt), Comaintainers: []string{}} + last, _ := parseRelayTS(nd.LastSeen) + if t, ok := heard[c.Pubkey]; ok && t.After(last) { + last = t + } + if !last.IsZero() { + ts := last.UTC().Format(time.RFC3339) + r.LastHeard = &ts + } + if info, ok := lookupRelayInfo(relay, c.Pubkey); ok { + r.LastRelayed = stringPtrOrNil(info.LastRelayed) + } + if info, ok := infos[c.Pubkey]; ok { + r.Status = stringPtrOrNil(info.Status) + } + for _, o := range claimers[c.Pubkey] { + if o.UserID != u.ID { + r.Comaintainers = append(r.Comaintainers, o.DisplayName) + } + } + out.Repeaters = append(out.Repeaters, r) + } + sort.SliceStable(out.Repeaters, func(i, j int) bool { + a, b := out.Repeaters[i], out.Repeaters[j] + if an, bn := strings.ToLower(a.Name), strings.ToLower(b.Name); an != bn { + // Named repeaters first, then the unnamed by pubkey. + if an == "" || bn == "" { + return bn == "" + } + return an < bn + } + return a.Pubkey < b.Pubkey + }) + writeJSON(w, out) +} diff --git a/cmd/server/my_repeaters_test.go b/cmd/server/my_repeaters_test.go new file mode 100644 index 000000000..7bcd1987a --- /dev/null +++ b/cmd/server/my_repeaters_test.go @@ -0,0 +1,210 @@ +package main + +import ( + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/users" +) + +const rpkGone = "dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44" + +func TestMyRepeatersEmpty(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + w := f.do("GET", "/api/account/repeaters", nil, as(alice)) + expectStatus(t, w, http.StatusOK) + if strings.TrimSpace(w.Body.String()) != `{"repeaters":[]}` { + t.Fatalf("body = %s", w.Body.String()) + } +} + +func TestMyRepeatersList(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + carol := f.registerAndActivate(t, "carol@example.org", "Carol", pw) + const rpkNamed = "ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55ee55" + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET name = 'Zulu Hill', last_seen = '2026-11-01T10:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + if _, err := f.srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role, last_seen) VALUES (?, 'alpha peak', 'repeater', NULL)`, rpkNamed); err != nil { + t.Fatal(err) + } + // Alice claims three: two known (one co-maintained, one with details), + // and one that has left the analyzer database since. + for _, pk := range []string{rpkA, rpkNamed, rpkGone} { + if _, err := f.st.ClaimRepeater(alice.me.ID, pk); err != nil { + t.Fatal(err) + } + } + for _, uid := range []int64{bob.me.ID, carol.me.ID} { + if _, err := f.st.ClaimRepeater(uid, rpkA); err != nil { + t.Fatal(err) + } + } + if err := f.st.SetStatus(carol.me.ID, users.StatusDisabled); err != nil { + t.Fatal(err) + } + if _, err := f.st.SaveRepeaterInfo(alice.me.ID, rpkA, users.RepeaterEdit{Status: users.RepeaterStatusMaintenance}); err != nil { + t.Fatal(err) + } + + w := f.do("GET", "/api/account/repeaters", nil, as(alice)) + expectStatus(t, w, http.StatusOK) + got := decode[myRepeatersJSON](t, w).Repeaters + var order []string + for _, r := range got { + order = append(order, r.Pubkey) + } + // Named first, by name ignoring case; then unnamed by pubkey. + if want := []string{rpkNamed, rpkA, rpkGone}; !slices.Equal(order, want) { + t.Fatalf("order = %v, want %v", order, want) + } + named, zulu, gone := got[0], got[1], got[2] + if !named.Known || named.Name != "alpha peak" || named.LastHeard != nil || named.Status != nil || len(named.Comaintainers) != 0 { + t.Errorf("unheard repeater = %+v", named) + } + if !zulu.Known || zulu.Role != "repeater" || zulu.LastHeard == nil || *zulu.LastHeard != "2026-11-01T10:00:00Z" { + t.Errorf("heard repeater = %+v", zulu) + } + if zulu.Status == nil || *zulu.Status != "maintenance" { + t.Errorf("status = %v", zulu.Status) + } + // Bob is listed; Alice herself and the disabled Carol are not. + if !slices.Equal(zulu.Comaintainers, []string{"Bob"}) { + t.Errorf("comaintainers = %v", zulu.Comaintainers) + } + if gone.Known || gone.Inactive || gone.Name != "" || gone.ClaimedAt == "" { + t.Errorf("departed repeater = %+v", gone) + } + if strings.Contains(w.Body.String(), "@") { + t.Errorf("body leaks an email: %s", w.Body.String()) + } + + // Bob sees only his own claim, with Alice as the other maintainer. + b := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(bob))).Repeaters + if len(b) != 1 || b[0].Pubkey != rpkA || !slices.Equal(b[0].Comaintainers, []string{"Alice"}) { + t.Fatalf("Bob's list = %+v", b) + } + // Unclaiming through the existing route takes it off the list. + expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, as(bob)), http.StatusOK) + if b := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(bob))).Repeaters; len(b) != 0 { + t.Fatalf("after unclaim = %+v", b) + } +} + +// A browser session or a device token with a repeater scope lists the +// caller's claims; an rx-only token and no login do not. +func TestMyRepeatersAccess(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + expectStatus(t, f.do("GET", "/api/account/repeaters", nil), http.StatusUnauthorized) + rx := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token + expectStatus(t, f.do("GET", "/api/account/repeaters", nil, bearer(rx)), http.StatusForbidden) + for _, scope := range []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} { + tok := f.scopedToken(t, "alice@example.org", scope, scope) + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, bearer(tok))).Repeaters + if len(got) != 1 || got[0].Pubkey != rpkA { + t.Errorf("%s token: got %+v, want alice's one claim", scope, got) + } + } + // Bob's repeater token lists Bob's claims, not Alice's. + bobTok := f.scopedToken(t, "bob@example.org", "bob", deviceScopeRepeaterClaim) + if got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, bearer(bobTok))).Repeaters; len(got) != 0 { + t.Errorf("bob's token listed %+v", got) + } +} + +// Without the analyzer database (auth-only fixture) the claims still list, +// as not known. +func TestMyRepeatersWithoutAnalyzerDB(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 1 || got[0].Known || got[0].LastHeard != nil { + t.Fatalf("list = %+v", got) + } +} + +// A repeater silent past retention.nodeDays sits in inactive_nodes, not +// nodes: it still lists by name with its last advert, marked inactive. +func TestMyRepeatersInactiveNode(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + const rpkOld = "ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66ff66" + for _, q := range []string{ + `CREATE TABLE IF NOT EXISTS inactive_nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, last_seen TEXT)`, + `INSERT INTO inactive_nodes (public_key, name, role, last_seen) VALUES ('` + rpkOld + `', 'Old Tower', 'Repeater', '2026-10-01T08:00:00Z')`, + } { + if _, err := f.srv.db.conn.Exec(q); err != nil { + t.Fatal(err) + } + } + // The claim route already accepts it (RepeaterKnown reads inactive_nodes). + expectStatus(t, f.do("POST", repPath(rpkOld, "claim"), nil, as(alice)), http.StatusOK) + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkGone); err != nil { + t.Fatal(err) + } + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 2 { + t.Fatalf("list = %+v", got) + } + old, gone := got[0], got[1] + if old.Pubkey != rpkOld || !old.Known || !old.Inactive || old.Name != "Old Tower" || old.Role != "repeater" || + old.LastHeard == nil || *old.LastHeard != "2026-10-01T08:00:00Z" { + t.Errorf("inactive repeater = %+v", old) + } + if gone.Pubkey != rpkGone || gone.Known || gone.Inactive { + t.Errorf("unknown repeater = %+v", gone) + } +} + +// The production path: a packet store whose certain-heard entry is newer +// than the node's last advert, and a relay entry for its prefix. +func TestMyRepeatersUsesPacketStore(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET name = 'Zulu Hill', last_seen = '2026-11-01T10:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + ps := NewPacketStore(nil, nil) + heard := time.Date(2026, 11, 3, 12, 30, 0, 0, time.UTC) + ps.certainHeard = map[string]string{rpkA: heard.Format(time.RFC3339)} + ps.repeaterRelayCache = map[string]RepeaterRelayInfo{rpkA: {LastRelayed: "2026-11-05T09:15:00Z", RelayActive: true, WindowHours: 24}} + f.srv.store = ps + + got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if len(got) != 1 { + t.Fatalf("list = %+v", got) + } + r := got[0] + if r.LastHeard == nil || *r.LastHeard != "2026-11-03T12:30:00Z" { + t.Errorf("lastHeard = %v, want the certain-heard time over the older advert", r.LastHeard) + } + if r.LastRelayed == nil || *r.LastRelayed != "2026-11-05T09:15:00Z" { + t.Errorf("lastRelayed = %v", r.LastRelayed) + } + + // An advert newer than the certain-heard entry wins. + if _, err := f.srv.db.conn.Exec(`UPDATE nodes SET last_seen = '2026-11-04T00:00:00Z' WHERE public_key = ?`, rpkA); err != nil { + t.Fatal(err) + } + got = decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, as(alice))).Repeaters + if got[0].LastHeard == nil || *got[0].LastHeard != "2026-11-04T00:00:00Z" { + t.Errorf("lastHeard = %v, want the newer advert", got[0].LastHeard) + } +} diff --git a/cmd/server/neighbor_api_test.go b/cmd/server/neighbor_api_test.go index e3ab0b96c..8ecbe80e3 100644 --- a/cmd/server/neighbor_api_test.go +++ b/cmd/server/neighbor_api_test.go @@ -476,7 +476,7 @@ func TestBuildNodeInfoMap_ObserverEnrichment(t *testing.T) { // Create tables for _, stmt := range []string{ "CREATE TABLE nodes (public_key TEXT, name TEXT, role TEXT, lat REAL, lon REAL)", - "CREATE TABLE observers (id TEXT, name TEXT, iata TEXT, inactive INTEGER)", + "CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)", "INSERT INTO nodes VALUES ('AAAA1111', 'Repeater-1', 'repeater', 0, 0)", "INSERT INTO observers (id, name, iata) VALUES ('BBBB2222', 'Observer-Alpha', '')", "INSERT INTO observers (id, name, iata) VALUES ('AAAA1111', 'Obs-also-repeater', '')", @@ -550,7 +550,7 @@ func TestBuildNodeInfoMap_FirstSeenIsCached(t *testing.T) { defer rw.Close() for _, stmt := range []string{ "CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, advert_count INTEGER)", - "CREATE TABLE observers (id TEXT, name TEXT, iata TEXT, inactive INTEGER)", + "CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)", "INSERT INTO nodes VALUES ('AAAA1111', 'Repeater-1', 'repeater', 0, 0, '', '2024-01-01T00:00:00Z', 0)", } { if _, err := rw.Exec(stmt); err != nil { @@ -617,7 +617,7 @@ func TestGetAllNodes_FirstSeenSchemaFallback(t *testing.T) { defer rw.Close() for _, stmt := range []string{ "CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, advert_count INTEGER)", - "CREATE TABLE observers (id TEXT, name TEXT, iata TEXT, inactive INTEGER)", + "CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)", "INSERT INTO nodes VALUES ('BBBB2222', 'Repeater-2', 'repeater', 0, 0, '2024-02-02T00:00:00Z', 3)", } { if _, err := rw.Exec(stmt); err != nil { diff --git a/cmd/server/neighbor_dedup_test.go b/cmd/server/neighbor_dedup_test.go index 5ab9a050e..bcb39c9d0 100644 --- a/cmd/server/neighbor_dedup_test.go +++ b/cmd/server/neighbor_dedup_test.go @@ -227,6 +227,7 @@ func TestPhase1EdgeCollection_Unchanged(t *testing.T) { }} tx := &StoreTx{ ID: 1, + RouteType: ngIntPtr(RouteFlood), PayloadType: &payloadType, DecodedJSON: `{"pubKey":"aaaa1111"}`, Observations: obs, @@ -317,11 +318,11 @@ func TestIntegration_DualPrefixSingleNeighbor(t *testing.T) { // Observation 1: 1-byte prefix "b0" (ambiguous — matches both B and B2). obs1 := []*StoreObs{{ObserverID: "cccc3333cccc3333", PathJSON: `["b0"]`, Timestamp: ts}} - tx1 := &StoreTx{ID: 1, PayloadType: &pt, DecodedJSON: `{"pubKey":"aaaa1111aaaa1111"}`, Observations: obs1} + tx1 := &StoreTx{ID: 1, RouteType: ngIntPtr(RouteFlood), PayloadType: &pt, DecodedJSON: `{"pubKey":"aaaa1111aaaa1111"}`, Observations: obs1} // Observation 2: 4-byte prefix "b0b1" (unique — resolves to NodeB). obs2 := []*StoreObs{{ObserverID: "cccc3333cccc3333", PathJSON: `["b0b1"]`, Timestamp: ts}} - tx2 := &StoreTx{ID: 2, PayloadType: &pt, DecodedJSON: `{"pubKey":"aaaa1111aaaa1111"}`, Observations: obs2} + tx2 := &StoreTx{ID: 2, RouteType: ngIntPtr(RouteFlood), PayloadType: &pt, DecodedJSON: `{"pubKey":"aaaa1111aaaa1111"}`, Observations: obs2} store := ngTestStore([]nodeInfo{nodeA, nodeB, nodeB2, observer}, []*StoreTx{tx1, tx2}) graph := BuildFromStore(store) diff --git a/cmd/server/neighbor_graph.go b/cmd/server/neighbor_graph.go index 57273f156..956e49434 100644 --- a/cmd/server/neighbor_graph.go +++ b/cmd/server/neighbor_graph.go @@ -312,6 +312,20 @@ func BuildFromStoreWithOptions(store *PacketStore, opts BuildOptions) *NeighborG // Phase 1: Extract edges from every transmission + observation. for _, p := range packets { tx := p.tx + // Only a path that lists transmitted hops names a neighbour + // (packetpath.PathHopsTransmitted: flood, not TRACE), and an empty + // path only when it proves the originator was heard + // (packetpath.EmptyPathHeardOriginator). A missing route or payload + // type proves nothing. + if tx.RouteType == nil || tx.PayloadType == nil { + continue + } + rt, pt := *tx.RouteType, byte(*tx.PayloadType) + hopsTransmitted := packetpath.PathHopsTransmitted(rt, pt) + emptyHeardOrigin := packetpath.EmptyPathHeardOriginator(rt, pt) + if !hopsTransmitted && !emptyHeardOrigin { + continue + } isAdvert := tx.PayloadType != nil && *tx.PayloadType == PayloadADVERT isAnonReq := tx.PayloadType != nil && *tx.PayloadType == PayloadANON_REQ // #1777: ANON_REQ's ephemeralPubKey is a full Ed25519 pubkey — the @@ -337,21 +351,26 @@ func BuildFromStoreWithOptions(store *PacketStore, opts BuildOptions) *NeighborG if len(path) == 0 { // Zero-hop - if hasFullOriginator && fromLower != "" { + if emptyHeardOrigin && hasFullOriginator && fromLower != "" { if fromLower != observerPK { // self-edge guard g.upsertEdge(fromLower, observerPK, "", observerPK, obs.SNR, parseTimestamp(obs.Timestamp)) } } continue } + if !hopsTransmitted { + continue + } - // Edge 1: originator ↔ path[0] — ADVERT and ANON_REQ only (#1777) + // Edge 1: originator ↔ path[0] — ADVERT and ANON_REQ only (#1777). + // No SNR: the observer measured its reception of path[last], not + // the originator's link to path[0]. if hasFullOriginator && fromLower != "" { firstHop := cachedToLower(lowerCache, path[0]) if fromLower != firstHop { // self-edge guard (shouldn't happen but spec says check) if packetpath.MeetsPathTrust(len(path[0])/2, opts.PathTrust) { candidates := pm.m[firstHop] - g.upsertEdgeWithCandidates(fromLower, firstHop, candidates, observerPK, obs.SNR, parseTimestamp(obs.Timestamp), lowerCache) + g.upsertEdgeWithCandidates(fromLower, firstHop, candidates, observerPK, nil, parseTimestamp(obs.Timestamp), lowerCache) } } } diff --git a/cmd/server/neighbor_graph_test.go b/cmd/server/neighbor_graph_test.go index 194ca96c7..c61e21ca1 100644 --- a/cmd/server/neighbor_graph_test.go +++ b/cmd/server/neighbor_graph_test.go @@ -48,6 +48,7 @@ func ngFloatPtr(v float64) *float64 { return &v } func ngMakeTx(id int, payloadType int, decodedJSON string, obs []*StoreObs) *StoreTx { tx := &StoreTx{ ID: id, + RouteType: ngIntPtr(RouteFlood), PayloadType: ngIntPtr(payloadType), DecodedJSON: decodedJSON, Observations: obs, @@ -1053,3 +1054,151 @@ func TestBuildNeighborGraph_SkipsOwnTransmissions(t *testing.T) { } } } + +// ─── Direct-reception rule (SNR belongs to the node the observer heard) ────── + +func ngMakeRoutedTx(id, routeType, payloadType int, decodedJSON string, obs []*StoreObs) *StoreTx { + tx := ngMakeTx(id, payloadType, decodedJSON, obs) + tx.RouteType = ngIntPtr(routeType) + return tx +} + +func ngEdge(g *NeighborGraph, a, b string) *NeighborEdge { + for _, e := range g.AllEdges() { + if (e.NodeA == a && e.NodeB == b) || (e.NodeA == b && e.NodeB == a) { + return e + } + } + return nil +} + +var ngDirectNodes = []nodeInfo{ + {Role: "repeater", PublicKey: "aaaa1111", Name: "NodeX"}, + {Role: "repeater", PublicKey: "r1aabbcc", Name: "R1"}, + {Role: "repeater", PublicKey: "r2bbccdd", Name: "R2"}, + {Role: "repeater", PublicKey: "obs00001", Name: "Observer"}, +} + +// TRACE reuses the path bytes for per-hop SNR values (packetpath.PathBytesAreHops), +// so they name no node and must build no edge. +func TestBuildNeighborGraph_TraceBuildsNoEdges(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteFlood, PayloadTRACE, "", []*StoreObs{ + ngMakeObs("obs00001", `["r1aa"]`, nowStr, ngFloatPtr(-10)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if n := len(g.AllEdges()); n != 0 { + t.Fatalf("TRACE built %d edges, want 0", n) + } +} + +// A direct route carries the REMAINING route: a forwarder removes itself +// before retransmitting (firmware Mesh.cpp removeSelfFromPath), so the last +// element is a node still to come, not the one the observer heard. +func TestBuildNeighborGraph_DirectRouteNoObserverEdge(t *testing.T) { + for _, rt := range []int{RouteDirect, RouteTransportDirect} { + tx := ngMakeRoutedTx(1, rt, PayloadTXT_MSG, "", []*StoreObs{ + ngMakeObs("obs00001", `["r1aa"]`, nowStr, ngFloatPtr(-10)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if e := ngEdge(g, "obs00001", "r1aabbcc"); e != nil { + t.Errorf("route %d: observer↔remaining-route hop edge built: %+v", rt, e) + } + } +} + +// ANON_REQ may travel on a direct route; its path[0] is then the next node +// to forward, not a neighbour of the originator. +func TestBuildNeighborGraph_DirectRouteNoOriginatorEdge(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteDirect, PayloadANON_REQ, ngEphemeralPubKeyJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `["r1aa"]`, nowStr, ngFloatPtr(-10)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if e := ngEdge(g, "aaaa1111", "r1aabbcc"); e != nil { + t.Errorf("direct-route ANON_REQ built originator↔path[0] edge: %+v", e) + } +} + +// A zero-hop ADVERT on a direct route (Mesh::sendZeroHop) was heard straight +// from the advertiser: that edge and its SNR stay. +func TestBuildNeighborGraph_DirectZeroHopAdvertKeepsSNR(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteDirect, PayloadADVERT, ngFromNodeJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `[]`, nowStr, ngFloatPtr(-7)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + e := ngEdge(g, "aaaa1111", "obs00001") + if e == nil { + t.Fatal("zero-hop direct ADVERT: originator↔observer edge missing") + } + if e.SNRCount != 1 || e.AvgSNR() != -7 { + t.Errorf("zero-hop edge SNR = %v over %d, want -7 over 1", e.AvgSNR(), e.SNRCount) + } +} + +// The SNR on an observation was measured by the observer on its reception of +// the last hop. It belongs to observer↔path[last], never to +// originator↔path[0], which the observer did not hear. +func TestBuildNeighborGraph_OriginatorEdgeCarriesNoSNR(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteFlood, PayloadADVERT, ngFromNodeJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `["r1aa","r2bb"]`, nowStr, ngFloatPtr(-4)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + orig := ngEdge(g, "aaaa1111", "r1aabbcc") + if orig == nil { + t.Fatal("originator↔path[0] edge missing") + } + if orig.SNRCount != 0 { + t.Errorf("originator↔path[0] carries %d SNR samples (avg %v), want none", orig.SNRCount, orig.AvgSNR()) + } + last := ngEdge(g, "obs00001", "r2bbccdd") + if last == nil { + t.Fatal("observer↔path[last] edge missing") + } + if last.SNRCount != 1 || last.AvgSNR() != -4 { + t.Errorf("observer↔path[last] SNR = %v over %d, want -4 over 1", last.AvgSNR(), last.SNRCount) + } +} + +// Mesh::sendDirect leaves an empty path after the last forwarder's +// removeSelfFromPath, so a direct-route ANON_REQ with an empty path was +// transmitted by that forwarder, not by the originator. +func TestBuildNeighborGraph_DirectAnonReqEmptyPathNoEdge(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteDirect, PayloadANON_REQ, ngEphemeralPubKeyJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `[]`, nowStr, ngFloatPtr(-7)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if e := ngEdge(g, "aaaa1111", "obs00001"); e != nil { + t.Errorf("direct ANON_REQ with an empty path built originator↔observer: %+v", e) + } +} + +func TestBuildNeighborGraph_DirectAdvertWithPathNoEdge(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteDirect, PayloadADVERT, ngFromNodeJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `["r1aa"]`, nowStr, ngFloatPtr(-7)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if n := len(g.AllEdges()); n != 0 { + t.Errorf("direct ADVERT with a path built %d edges, want 0", n) + } +} + +func TestBuildNeighborGraph_TransportFloodBuildsEdges(t *testing.T) { + tx := ngMakeRoutedTx(1, RouteTransportFlood, PayloadADVERT, ngFromNodeJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `["r1aa","r2bb"]`, nowStr, ngFloatPtr(-4)), + }) + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if ngEdge(g, "aaaa1111", "r1aabbcc") == nil || ngEdge(g, "obs00001", "r2bbccdd") == nil { + t.Errorf("transport flood should build originator↔path[0] and observer↔path[last], got %d edges", len(g.AllEdges())) + } +} + +// A transmission without a route type proves nothing about adjacency. +func TestBuildNeighborGraph_UnknownRouteTypeBuildsNoEdges(t *testing.T) { + tx := ngMakeTx(1, PayloadADVERT, ngFromNodeJSON("aaaa1111"), []*StoreObs{ + ngMakeObs("obs00001", `["r1aa"]`, nowStr, ngFloatPtr(-4)), + }) + tx.RouteType = nil + g := BuildFromStore(ngTestStore(ngDirectNodes, []*StoreTx{tx})) + if n := len(g.AllEdges()); n != 0 { + t.Errorf("nil route type built %d edges, want 0", n) + } +} diff --git a/cmd/server/neighbor_recomputer_test.go b/cmd/server/neighbor_recomputer_test.go index cdcf7b8f6..dc33dcf69 100644 --- a/cmd/server/neighbor_recomputer_test.go +++ b/cmd/server/neighbor_recomputer_test.go @@ -102,7 +102,7 @@ func TestServerStartupRequiresMigratedSchema(t *testing.T) { for _, s := range []string{ `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, hash TEXT, payload_type INTEGER)`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER)`, - `CREATE TABLE observers (id TEXT PRIMARY KEY, name TEXT, inactive INTEGER)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, inactive INTEGER)`, `CREATE TABLE nodes (public_key TEXT PRIMARY KEY)`, `CREATE TABLE inactive_nodes (public_key TEXT PRIMARY KEY)`, } { diff --git a/cmd/server/node_analytics_coverage_test.go b/cmd/server/node_analytics_coverage_test.go index f0baf5c4c..9fecc1e18 100644 --- a/cmd/server/node_analytics_coverage_test.go +++ b/cmd/server/node_analytics_coverage_test.go @@ -1,9 +1,16 @@ package main import ( + "context" "fmt" + "os" + "os/exec" + "regexp" + "runtime" + "strings" "testing" "time" + _ "time/tzdata" // TZ=Etc/GMT-2 in the child, without the host's zoneinfo ) const coverageNodePK = "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" @@ -130,10 +137,34 @@ func TestNodeAnalyticsCoverageEmptyStore(t *testing.T) { // TestNodeAnalyticsWindowIgnoresLocalZone: the window bound is compared as a // string with UTC FirstSeen values, so it must be formatted in UTC. With a // +02:00 local zone the old code dropped the oldest two hours of a 7d range. +// +// The zone is set by running this test again in a child process with +// TZ=Etc/GMT-2 (UTC+2): assigning time.Local here would race with any timer +// still running in the test binary (time.Now reads it), which the race +// detector reports as a failure of whichever test is running. func TestNodeAnalyticsWindowIgnoresLocalZone(t *testing.T) { - saved := time.Local - time.Local = time.FixedZone("UTC+2", 2*3600) - t.Cleanup(func() { time.Local = saved }) + if os.Getenv("CS_TEST_LOCAL_ZONE_CHILD") != "1" { + if runtime.GOOS == "windows" { + t.Skip("Go takes the local zone from the OS on Windows and ignores TZ") + } + // A hung child fails here with its output, not at the parent's timeout. + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.v") + cmd.Env = append(os.Environ(), "CS_TEST_LOCAL_ZONE_CHILD=1", "TZ=Etc/GMT-2") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("child run with TZ=Etc/GMT-2 failed: %v\n%s", err, out) + } + // A pattern that matched nothing would also exit 0. + if !strings.Contains(string(out), "--- PASS: "+t.Name()) { + t.Fatalf("child run did not run %s:\n%s", t.Name(), out) + } + return + } + if _, off := time.Now().Zone(); off != 2*3600 { + t.Fatalf("child local zone offset %d s, want 7200 (TZ=Etc/GMT-2)", off) + } ps := setupCoverageStore(t, 10*24) a, err := ps.GetNodeAnalytics(coverageNodePK, 7) diff --git a/cmd/server/node_analytics_heard_by_test.go b/cmd/server/node_analytics_heard_by_test.go new file mode 100644 index 000000000..5850ec4bb --- /dev/null +++ b/cmd/server/node_analytics_heard_by_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "encoding/json" + "net/http/httptest" + "testing" + "time" +) + +// nodeAnalyticsSignal is the part of the analytics response these tests read. +type nodeAnalyticsSignal struct { + HeardBy []HeardByObserver `json:"heardBy"` + SnrTrend []SnrTrendEntry `json:"snrTrend"` + ComputedStats ComputedNodeStats `json:"computedStats"` +} + +// heardByTestServer seeds two repeaters and direct-heard evidence, then +// publishes the direct-heard snapshot the analytics endpoint reads. +func heardByTestServer(t *testing.T) *httptest.Server { + t.Helper() + srv, router := setupTestServer(t) + srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role) VALUES + ('c7d1000000000000000000000000000000000000000000000000000000000001', 'TwoByte', 'repeater'), + ('e5a9000000000000000000000000000000000000000000000000000000000002', 'OneByteOnly', 'repeater')`) + srv.store.InvalidateNodeCache() + + at := time.Now().UTC().Add(-2 * time.Hour) + add := func(path, observer string, snr float64) { + tx := dhTx(RouteFlood, PayloadTXT_MSG, "") + v := snr + tx.Observations = []*StoreObs{{ObserverID: observer, ObserverName: observer + "-name", PathJSON: path, SNR: &v, Timestamp: at.Format(time.RFC3339)}} + at = at.Add(time.Minute) + srv.store.packets = append(srv.store.packets, tx) + } + srv.store.mu.Lock() + add(`["C7D1"]`, "obsA", 5) + add(`["C7D1"]`, "obsA", 6) + add(`["C7D1"]`, "obsA", 7) + add(`["C7"]`, "obsB", 20) // 1-byte hop: not proof of who sent it + add(`["C7D1","99AA"]`, "obsC", 15) // relayed onward: obsC heard 99AA + add(`["E5"]`, "obsA", 12) + srv.store.mu.Unlock() + srv.store.publishDirectHeard(srv.store.computeDirectHeard()) + + ts := httptest.NewServer(router) + t.Cleanup(ts.Close) + return ts +} + +func getNodeAnalyticsSignal(t *testing.T, ts *httptest.Server, pk string) nodeAnalyticsSignal { + t.Helper() + res, err := ts.Client().Get(ts.URL + "/api/nodes/" + pk + "/analytics?days=7") + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 200 { + t.Fatalf("status %d", res.StatusCode) + } + var body nodeAnalyticsSignal + if err := json.NewDecoder(res.Body).Decode(&body); err != nil { + t.Fatal(err) + } + return body +} + +func TestNodeAnalytics_HeardByDirectOnly(t *testing.T) { + ts := heardByTestServer(t) + + body := getNodeAnalyticsSignal(t, ts, "c7d1000000000000000000000000000000000000000000000000000000000001") + if len(body.HeardBy) != 1 || body.HeardBy[0].ObserverID != "obsA" || *body.HeardBy[0].MedianSNR != 6 || body.HeardBy[0].Count != 3 { + t.Fatalf("heardBy = %+v, want only obsA, 3 receptions, median 6", body.HeardBy) + } + if body.HeardBy[0].ObserverName != "obsA-name" { + t.Fatalf("observer name = %q", body.HeardBy[0].ObserverName) + } + if s := body.ComputedStats; s.UniqueObservers != 1 || s.SnrMean != 6 { + t.Fatalf("uniqueObservers %d, snrMean %v; want 1, 6", s.UniqueObservers, s.SnrMean) + } + if len(body.SnrTrend) != 3 { + t.Fatalf("snrTrend has %d entries, want 3", len(body.SnrTrend)) + } + for _, e := range body.SnrTrend { + if e.ObserverID != "obsA" { + t.Fatalf("snrTrend entry from %v, want only obsA", e.ObserverID) + } + } + + body = getNodeAnalyticsSignal(t, ts, "e5a9000000000000000000000000000000000000000000000000000000000002") + if len(body.HeardBy) != 0 || len(body.SnrTrend) != 0 { + t.Fatalf("1-byte only: heardBy %+v, snrTrend %d entries; want both empty", body.HeardBy, len(body.SnrTrend)) + } + if s := body.ComputedStats; s.UniqueObservers != 0 || s.SignalGrade != "D" || s.SnrMean != 0 { + t.Fatalf("1-byte only: stats %+v; want 0 observers, grade D, snrMean 0", s) + } +} diff --git a/cmd/server/node_health_direct_rf_test.go b/cmd/server/node_health_direct_rf_test.go index 5084df7a4..df732b243 100644 --- a/cmd/server/node_health_direct_rf_test.go +++ b/cmd/server/node_health_direct_rf_test.go @@ -86,6 +86,83 @@ func TestNodeHealth_RelayedObserverIsNotHeardBy(t *testing.T) { } } +// The node-level stats.avgSnr on /health and /bulk-health must come from +// direct receptions only. A relayed copy carries the SNR of whichever node +// last transmitted it, so adding one with an extreme SNR must not move the +// number. +func TestNodeHealth_AvgSnrIgnoresRelayedCopies(t *testing.T) { + srv, router := setupTestServer(t) + const nodePubkey = "aabbccdd11223344" // seeded by seedTestData + srv.store.publishDirectHeard(srv.store.computeDirectHeard()) + + avgSnr := func(url string, pick func(map[string]interface{}) map[string]interface{}) interface{} { + t.Helper() + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, url, nil)) + if w.Code != http.StatusOK { + t.Fatalf("%s: expected 200, got %d (body: %s)", url, w.Code, w.Body.String()) + } + var body interface{} + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("%s: json: %v", url, err) + } + var node map[string]interface{} + switch b := body.(type) { + case map[string]interface{}: + node = b + case []interface{}: + for _, raw := range b { + if m, ok := raw.(map[string]interface{}); ok && m["public_key"] == nodePubkey { + node = m + } + } + } + if node == nil { + t.Fatalf("%s: node %s missing from response", url, nodePubkey) + } + stats, _ := pick(node)["stats"].(map[string]interface{}) + if stats == nil { + t.Fatalf("%s: stats missing", url) + } + return stats["avgSnr"] + } + self := func(m map[string]interface{}) map[string]interface{} { return m } + healthURL := "/api/nodes/" + nodePubkey + "/health" + bulkURL := "/api/nodes/bulk-health?limit=500" + + beforeHealth := avgSnr(healthURL, self) + beforeBulk := avgSnr(bulkURL, self) + + now := time.Now().UTC().Format(time.RFC3339) + routeFlood := RouteFlood + payload := PayloadTXT_MSG + snr := -99.0 + relayed := &StoreTx{ + Hash: "directrf-avgsnr-relayed", FirstSeen: now, + RouteType: &routeFlood, PayloadType: &payload, SNR: &snr, + ObservationCount: 1, ObserverID: "farawayobserver", ObserverName: "FarAway", + Observations: []*StoreObs{{ + ObserverID: "farawayobserver", ObserverName: "FarAway", + PathJSON: `["AABB","1234","5678"]`, SNR: &snr, + }}, + } + srv.store.mu.Lock() + if srv.store.byNode == nil { + srv.store.byNode = make(map[string][]*StoreTx) + } + srv.store.byNode[nodePubkey] = append(srv.store.byNode[nodePubkey], relayed) + srv.store.packets = append(srv.store.packets, relayed) + srv.store.mu.Unlock() + srv.store.publishDirectHeard(srv.store.computeDirectHeard()) + + if got := avgSnr(healthURL, self); got != beforeHealth { + t.Fatalf("/health avgSnr moved from %v to %v after a relayed copy", beforeHealth, got) + } + if got := avgSnr(bulkURL, self); got != beforeBulk { + t.Fatalf("/bulk-health avgSnr moved from %v to %v after a relayed copy", beforeBulk, got) + } +} + // The walk runs over every observation in the store on each recompute pass. // The reference deployment holds 2.9M of them; this pins that a full pass // stays well inside one recompute interval. @@ -111,7 +188,8 @@ func BenchmarkBuildDirectHeardIndex(b *testing.B) { for i := 0; i < txCount; i++ { obsList := make([]*StoreObs, 0, perTx) for j := 0; j < perTx; j++ { - obsList = append(obsList, &StoreObs{ObserverID: "obs", PathJSON: path}) + snr := float64((i+j)%40) - 20 + obsList = append(obsList, &StoreObs{ObserverID: "obs", PathJSON: path, SNR: &snr, Timestamp: benchObsTime(i*perTx + j)}) } packets = append(packets, &StoreTx{ RouteType: &routeFlood, @@ -126,6 +204,11 @@ func BenchmarkBuildDirectHeardIndex(b *testing.B) { _ = hopCount } +// benchObsTime spreads benchmark observations over 7 days, one every 0.2 s. +func benchObsTime(i int) string { + return time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(i) * 200 * time.Millisecond).Format(time.RFC3339) +} + func hexDigit(v int) byte { if v < 10 { return byte('0' + v) diff --git a/cmd/server/node_reach.go b/cmd/server/node_reach.go index d6ed64f2a..3cfa5402a 100644 --- a/cmd/server/node_reach.go +++ b/cmd/server/node_reach.go @@ -16,6 +16,7 @@ import ( "github.com/gorilla/mux" "github.com/meshcore-analyzer/dbschema" + "github.com/meshcore-analyzer/packetpath" "golang.org/x/sync/singleflight" ) @@ -34,6 +35,7 @@ var reachScanRowLimit = 200000 // uppercase hex hop prefixes (as stored in observations.path_json). SNR is a // value + validity flag (not *float64) to avoid a heap escape per row. type pathRow struct { + routeType int // header route type; -1 when the transmission has none observerPK string // lowercase pubkey of the observer (may be "") fromPubkey string // lowercase originator pubkey (may be "") payloadType int @@ -75,6 +77,12 @@ func attributeDirections(rows []pathRow, ourTokens map[string]bool, ourPK string if n == 0 { continue } + // Only a flood path lists hops that transmitted, in order. A + // direct-route path is the remaining route and TRACE path bytes are + // SNR values, so neither says who heard whom. + if !packetpath.PathHopsTransmitted(r.routeType, byte(r.payloadType)) { + continue + } hit := false for i, tok := range r.path { if !ourTokens[tok] { @@ -775,10 +783,10 @@ func reachScanSQL(nTokens int) string { for i := range likes { likes[i] = "o.path_json LIKE ?" } - return `SELECT LOWER(COALESCE(obs.id,'')), LOWER(COALESCE(t.from_pubkey,'')), COALESCE(t.payload_type,0), o.path_json, o.snr + return `SELECT LOWER(COALESCE(obs.id,'')), LOWER(COALESCE(t.from_pubkey,'')), COALESCE(t.route_type,-1), COALESCE(t.payload_type,0), o.path_json, o.snr FROM observations o CROSS JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE o.timestamp >= ? AND (` + strings.Join(likes, " OR ") + `) LIMIT ?` } @@ -843,9 +851,9 @@ func (s *Server) readReachRows(ctx context.Context, q string, args []interface{} var skipped int // malformed/empty rows discarded — surfaced below so ingest bugs aren't silent for rows.Next() { var oid, fpk, pj string - var pt int + var rt, pt int var snr sql.NullFloat64 - if err := rows.Scan(&oid, &fpk, &pt, &pj, &snr); err != nil { + if err := rows.Scan(&oid, &fpk, &rt, &pt, &pj, &snr); err != nil { skipped++ continue } @@ -854,7 +862,7 @@ func (s *Server) readReachRows(ctx context.Context, q string, args []interface{} skipped++ continue } - pr := pathRow{observerPK: observerPublicKey(oid), fromPubkey: fpk, payloadType: pt, path: path} + pr := pathRow{routeType: rt, observerPK: observerPublicKey(oid), fromPubkey: fpk, payloadType: pt, path: path} if snr.Valid { pr.snr = snr.Float64 pr.snrValid = true @@ -902,10 +910,10 @@ func (s *Server) scanReachRowsIndexed(ctx context.Context, tokens map[string]boo args = append(args, tok) } args = append(args, sinceEpoch, reachScanRowLimit) - q := `SELECT LOWER(COALESCE(obs.id,'')), LOWER(COALESCE(t.from_pubkey,'')), COALESCE(t.payload_type,0), o.path_json, o.snr + q := `SELECT LOWER(COALESCE(obs.id,'')), LOWER(COALESCE(t.from_pubkey,'')), COALESCE(t.route_type,-1), COALESCE(t.payload_type,0), o.path_json, o.snr FROM observations o JOIN transmissions t ON t.id = o.transmission_id - LEFT JOIN observers obs ON obs.rowid = o.observer_idx + LEFT JOIN observers obs ON obs.idx = o.observer_idx WHERE o.id IN (SELECT observation_id FROM observation_hops WHERE hop IN (` + strings.Join(marks, ",") + `) AND timestamp >= ?) LIMIT ?` return s.readReachRows(ctx, q, args) diff --git a/cmd/server/node_reach_bench_test.go b/cmd/server/node_reach_bench_test.go index bbf24a347..63aae2112 100644 --- a/cmd/server/node_reach_bench_test.go +++ b/cmd/server/node_reach_bench_test.go @@ -29,8 +29,8 @@ func benchReachDB(b *testing.B, nObs, matchEvery int, lowerHops bool) *DB { b.Fatal(err) } schema := []string{ - `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, hash TEXT, first_seen TEXT, payload_type INTEGER, from_pubkey TEXT)`, - `CREATE TABLE observers (id TEXT PRIMARY KEY, name TEXT, inactive INTEGER)`, + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, hash TEXT, first_seen TEXT, payload_type INTEGER, from_pubkey TEXT, route_type INTEGER DEFAULT 1)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, inactive INTEGER)`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, snr REAL, path_json TEXT, timestamp INTEGER)`, `CREATE INDEX idx_obs_ts ON observations(timestamp)`, } @@ -160,7 +160,7 @@ func TestScanReachRows_ErrorReturn(t *testing.T) { t.Fatalf("open: %v", err) } // PREFLIGHT: async=true reason="test-only in-memory scratch schema, immediately closed" - if _, err := conn.Exec(`CREATE TABLE observations (id INTEGER); CREATE TABLE transmissions (id INTEGER); CREATE TABLE observers (rowid INTEGER, id TEXT, inactive INTEGER)`); err != nil { + if _, err := conn.Exec(`CREATE TABLE observations (id INTEGER); CREATE TABLE transmissions (id INTEGER); CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, inactive INTEGER)`); err != nil { t.Fatalf("schema: %v", err) } conn.Close() // force QueryContext to fail diff --git a/cmd/server/node_reach_cancellation_test.go b/cmd/server/node_reach_cancellation_test.go index 21444b95d..f237d1845 100644 --- a/cmd/server/node_reach_cancellation_test.go +++ b/cmd/server/node_reach_cancellation_test.go @@ -94,8 +94,8 @@ func (c *reachFailureConn) QueryContext(_ context.Context, query string, _ []dri return r, nil case strings.Contains(query, "FROM observations o"): return &reachFailureRows{ - columns: []string{"observer", "originator", "type", "path", "snr"}, - values: [][]driver.Value{{"", "", int64(5), `["01FA"]`, float64(-7)}}, + columns: []string{"observer", "originator", "route", "type", "path", "snr"}, + values: [][]driver.Value{{"", "", int64(RouteFlood), int64(5), `["01FA"]`, float64(-7)}}, done: func() { f.scans++ }, }, nil case strings.HasPrefix(query, "SELECT since FROM "): diff --git a/cmd/server/node_reach_endpoint_test.go b/cmd/server/node_reach_endpoint_test.go index a7fc6d4aa..f02d0eb19 100644 --- a/cmd/server/node_reach_endpoint_test.go +++ b/cmd/server/node_reach_endpoint_test.go @@ -67,8 +67,8 @@ func newReachIntegrationDB(t *testing.T, obsPath string) (*DB, string) { now := time.Now().Unix() stmts := []string{ `CREATE TABLE nodes (public_key TEXT, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, advert_count INTEGER)`, - `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER)`, - `CREATE TABLE observers (id TEXT, inactive INTEGER)`, + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER, route_type INTEGER DEFAULT 1)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, inactive INTEGER)`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, snr REAL, path_json TEXT, timestamp INTEGER)`, `CREATE TABLE neighbor_edges (node_a TEXT, node_b TEXT, count INTEGER)`, } diff --git a/cmd/server/node_reach_hops_bench_test.go b/cmd/server/node_reach_hops_bench_test.go index d3580ff10..7f00a1608 100644 --- a/cmd/server/node_reach_hops_bench_test.go +++ b/cmd/server/node_reach_hops_bench_test.go @@ -34,8 +34,8 @@ func BenchmarkScanReachRows(b *testing.B) { defer conn.Close() conn.SetMaxOpenConns(1) for _, s := range []string{ - `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER)`, - `CREATE TABLE observers (id TEXT, inactive INTEGER)`, + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER, route_type INTEGER DEFAULT 1)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, inactive INTEGER)`, `INSERT INTO observers (id) VALUES ('OBS1')`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, snr REAL, path_json TEXT, timestamp INTEGER)`, `CREATE INDEX idx_observations_timestamp ON observations(timestamp)`, diff --git a/cmd/server/node_reach_test.go b/cmd/server/node_reach_test.go index fef55896c..6f20838b2 100644 --- a/cmd/server/node_reach_test.go +++ b/cmd/server/node_reach_test.go @@ -19,8 +19,8 @@ func newReachScanTestDB(t *testing.T) *DB { t.Fatal(err) } stmts := []string{ - `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER)`, - `CREATE TABLE observers (id TEXT, inactive INTEGER)`, + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY, from_pubkey TEXT, payload_type INTEGER, route_type INTEGER DEFAULT 1)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, inactive INTEGER)`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, snr REAL, path_json TEXT, timestamp INTEGER)`, `INSERT INTO observers (id) VALUES ('OBS1')`, // rowid 1 `INSERT INTO transmissions (id, from_pubkey, payload_type) VALUES (1,'FF00',4),(2,'',5),(3,'',5)`, @@ -339,3 +339,27 @@ func TestReachScanStartsFromObservationsTimeIndex(t *testing.T) { t.Fatalf("reach scan must start from observations by timestamp; plan: %q", steps) } } + +// Only a path that lists transmitted hops says who heard whom +// (packetpath.PathHopsTransmitted). A direct-route path is the remaining +// route and TRACE path bytes are SNR values: neither may add direction +// counts or an observer SNR. +func TestAttributeDirections_SkipsDirectRouteAndTrace(t *testing.T) { + unique := map[string]string{"AA": "aa00", "BB": "bb00"} + rows := []pathRow{ + {routeType: RouteDirect, observerPK: "obs1", payloadType: 2, path: []string{"AA", "01FA"}, snr: 9, snrValid: true}, + {routeType: RouteTransportDirect, observerPK: "obs1", payloadType: 2, path: []string{"AA", "01FA", "BB"}}, + {routeType: RouteFlood, observerPK: "obs2", payloadType: PayloadTRACE, path: []string{"01FA"}, snr: 9, snrValid: true}, + {routeType: -1, observerPK: "obs3", payloadType: 2, path: []string{"01FA"}, snr: 9, snrValid: true}, + } + d := attributeDirections(rows, map[string]bool{"01FA": true}, "01fa326b", testResolver(unique)) + if d.relay != 0 || len(d.we) != 0 || len(d.they) != 0 || len(d.obs) != 0 { + t.Fatalf("non-flood rows were attributed: relay=%d we=%v they=%v obs=%v", d.relay, d.we, d.they, d.obs) + } + d = attributeDirections([]pathRow{ + {routeType: RouteFlood, observerPK: "obs1", payloadType: 2, path: []string{"AA", "01FA"}, snr: 9, snrValid: true}, + }, map[string]bool{"01FA": true}, "01fa326b", testResolver(unique)) + if a := d.obs["obs1"]; a.count != 1 || a.snrN != 1 { + t.Fatalf("flood row not attributed: %+v", d.obs) + } +} diff --git a/cmd/server/notify_handlers_test.go b/cmd/server/notify_handlers_test.go index 796b3aed5..b78faa16b 100644 --- a/cmd/server/notify_handlers_test.go +++ b/cmd/server/notify_handlers_test.go @@ -210,7 +210,7 @@ func TestClientConfigAdvertisesNotifications(t *testing.T) { srv.auth = a w := httptest.NewRecorder() router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil)) - if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"notifications":true,"companionLinking":true}`) { + if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"notifications":true,"companionLinking":true,"repeaterTokens":true}`) { t.Fatalf("client config = %s", w.Body.String()) } } diff --git a/cmd/server/observation_cleanup.go b/cmd/server/observation_cleanup.go index 41ef80545..faa20957c 100644 --- a/cmd/server/observation_cleanup.go +++ b/cmd/server/observation_cleanup.go @@ -60,14 +60,14 @@ func (s *Server) handleCleanupCapabilities(w http.ResponseWriter, r *http.Reques func (s *Server) cleanupPreview(ctx context.Context, sel prunequeue.CleanupSelection) (cleanupPreview, error) { p := cleanupPreview{Selection: sel, MaxObservationID: sel.MaxObservationID, RestartRequired: true} where, args := sel.Where() - q := `SELECT COUNT(*),COUNT(DISTINCT o.transmission_id) FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE ` + where + q := `SELECT COUNT(*),COUNT(DISTINCT o.transmission_id) FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE ` + where if e := s.db.conn.QueryRowContext(ctx, q, args...).Scan(&p.Count, &p.Transmissions); e != nil { return p, e } // Count only transmissions whose ENTIRE retained observation set is selected. // Index on transmission_id bounds this anti-join to the selected observer's // transmissions; no per-observation HTTP or unbounded result materialization. - q = `WITH selected AS (SELECT o.id,o.transmission_id FROM observations o JOIN observers ob ON ob.rowid=o.observer_idx WHERE ` + where + `) SELECT COUNT(*) FROM (SELECT DISTINCT transmission_id FROM selected) t WHERE NOT EXISTS (SELECT 1 FROM observations other WHERE other.transmission_id=t.transmission_id AND NOT EXISTS (SELECT 1 FROM selected x WHERE x.id=other.id))` + q = `WITH selected AS (SELECT o.id,o.transmission_id FROM observations o JOIN observers ob ON ob.idx=o.observer_idx WHERE ` + where + `) SELECT COUNT(*) FROM (SELECT DISTINCT transmission_id FROM selected) t WHERE NOT EXISTS (SELECT 1 FROM observations other WHERE other.transmission_id=t.transmission_id AND NOT EXISTS (SELECT 1 FROM selected x WHERE x.id=other.id))` e := s.db.conn.QueryRowContext(ctx, q, args...).Scan(&p.ExclusiveTransmissions) return p, e } @@ -222,8 +222,8 @@ func (s *Server) handleCleanupObservers(w http.ResponseWriter, r *http.Request) ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() rows, err := s.db.conn.QueryContext(ctx, `SELECT ob.id, COALESCE(ob.name,''),COALESCE(ob.iata,''), - (SELECT COUNT(*) FROM observations o WHERE o.observer_idx=ob.rowid), - COALESCE((SELECT MAX(o.timestamp) FROM observations o WHERE o.observer_idx=ob.rowid),0) + (SELECT COUNT(*) FROM observations o WHERE o.observer_idx=ob.idx), + COALESCE((SELECT MAX(o.timestamp) FROM observations o WHERE o.observer_idx=ob.idx),0) FROM observers ob WHERE instr(lower(COALESCE(ob.name,'')),lower(?))>0 OR instr(lower(ob.id),lower(?))>0 ORDER BY lower(COALESCE(ob.name,'')),ob.id LIMIT 51`, term, term) if err != nil { diff --git a/cmd/server/observation_cleanup_test.go b/cmd/server/observation_cleanup_test.go index a80a6d8e6..823ee8425 100644 --- a/cmd/server/observation_cleanup_test.go +++ b/cmd/server/observation_cleanup_test.go @@ -20,7 +20,7 @@ func cleanupTestServer(t *testing.T) *Server { t.Fatal(e) } t.Cleanup(func() { db.Close() }) - _, e = db.Exec(`CREATE TABLE observers(id TEXT, name TEXT, iata TEXT); CREATE TABLE observations(id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, timestamp INTEGER); INSERT INTO observers VALUES('bad','Bad','SMF'),('good','Good','SMF'); INSERT INTO observations VALUES(1,10,1,100),(2,10,2,100),(3,11,1,200);`) + _, e = db.Exec(`CREATE TABLE observers(idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT); CREATE TABLE observations(id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_idx INTEGER, timestamp INTEGER); INSERT INTO observers(id,name,iata) VALUES('bad','Bad','SMF'),('good','Good','SMF'); INSERT INTO observations VALUES(1,10,1,100),(2,10,2,100),(3,11,1,200);`) if e != nil { t.Fatal(e) } diff --git a/cmd/server/observer_comparison.go b/cmd/server/observer_comparison.go index 4952cb7c5..9c8a1562c 100644 --- a/cmd/server/observer_comparison.go +++ b/cmd/server/observer_comparison.go @@ -86,7 +86,7 @@ func (db *DB) queryObserverComparison(ctx context.Context, ids []string, since, if !db.isV3 { return nil, errors.New("reception comparison requires v3 numeric timestamps") } - observerCol, join := "obs.id", "obs.rowid=o.observer_idx" + observerCol, join := "obs.id", "obs.idx=o.observer_idx" lo, hi := float64(since.UnixNano())/1e9, float64(until.UnixNano())/1e9 stamp := "o.timestamp" raw := "NULL" diff --git a/cmd/server/observer_radio_feed_test.go b/cmd/server/observer_radio_feed_test.go index cec6f29e8..34e6ce72d 100644 --- a/cmd/server/observer_radio_feed_test.go +++ b/cmd/server/observer_radio_feed_test.go @@ -48,7 +48,7 @@ func TestScopedObserverAPIKeepsSeparateRecordsAndNodeLocations(t *testing.T) { } } // Reach queries project only the node endpoint, never the observer filter. - rows, err := srv.readReachRows(context.Background(), `SELECT ?, 'cd', 4, '["ab"]', NULL`, []interface{}{key + "@bay@SFO"}) + rows, err := srv.readReachRows(context.Background(), `SELECT ?, 'cd', 1, 4, '["ab"]', NULL`, []interface{}{key + "@bay@SFO"}) if err != nil || len(rows) != 1 || rows[0].observerPK != key { t.Fatalf("reach rows=%+v, err=%v", rows, err) } diff --git a/cmd/server/observers_rowid_guard_test.go b/cmd/server/observers_rowid_guard_test.go new file mode 100644 index 000000000..9a99753ad --- /dev/null +++ b/cmd/server/observers_rowid_guard_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// observers.rowid must not be used: observations.observer_idx holds +// observers.idx, the explicit key column. A bare rowid is not part of the +// schema: a dump-and-reload renumbers it, and VACUUM may (SQLite documents +// that it can change the rowid of tables without an INTEGER PRIMARY KEY). +func TestNoObserversRowidInServerSources(t *testing.T) { + re := regexp.MustCompile(`\.rowid\b|rowid FROM observers`) + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(b), "\n") { + if re.MatchString(line) { + t.Errorf("%s:%d uses rowid on observers; use idx: %s", f, i+1, strings.TrimSpace(line)) + } + } + } +} diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index f118f2503..ae07e224c 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -85,9 +85,9 @@ func routeDescriptions() map[string]routeMeta { "POST /api/auth/register": {Summary: "Register an account", Description: "Creates a pending account and mails an activation link. The response is identical whether or not the address is already registered.", Tag: "users"}, "POST /api/auth/activate": {Summary: "Activate an account", Description: "Request body {token, password}: the mailed activation token and the account password chosen at (the newest) registration. A wrong password answers 401 and leaves the token usable; attempts are rate-limited per account. On success consumes the token, activates the account and starts a session.", Tag: "users"}, "POST /api/auth/login": {Summary: "Log in", Description: "Email + password. Sets the cs_session cookie. Rate-limited per IP and per address.", Tag: "users"}, - "POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX)", Description: "Body {email, password, deviceName}. 200 {token, expiresAt, user: {id, displayName}}. The token is a bearer credential (Authorization: Bearer ), valid 90 days and extended on use, limited to /api/auth/me, /api/auth/logout, /api/account/settings and /api/account/companions*; other account routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"}, + "POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX, mobile clients)", Description: "Body {email, password, deviceName, scopes}. scopes is optional: omitted (or null) means [\"rx\"], what CoreDrive RX gets; otherwise a non-empty list of rx, repeater:claim and repeater:edit (400 for an empty list or any other value, checked before the password). 200 {token, expiresAt, user: {id, displayName}, scopes} with the granted scopes, repeats removed, in that order. The token is a bearer credential (Authorization: Bearer ), valid 90 days and extended on use. Every device token may use /api/auth/me and /api/auth/logout; rx adds /api/account/settings and /api/account/companions*; repeater:claim adds POST and DELETE /api/repeaters/{pubkey}/claim; repeater:edit adds PUT /api/repeaters/{pubkey}/info; either repeater scope adds the caller fields on GET /api/repeaters/{pubkey}/info and opens GET /api/account/repeaters. Other routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device, plus the scopes) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"}, "POST /api/auth/logout": {Summary: "Log out", Description: "With the cs_session cookie (Origin must be publicBaseUrl): ends that browser session and clears the cookie. With Authorization: Bearer : revokes that device token.", Tag: "users"}, - "GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty.", Tag: "users", Session: true}, + "GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty and scopes lists the token's granted scopes (absent for a browser session).", Tag: "users", Session: true}, "POST /api/auth/forgot": {Summary: "Request a password reset", Tag: "users"}, "POST /api/auth/reset": {Summary: "Reset the password", Description: "Consumes the mailed reset token and ends all sessions of the user.", Tag: "users"}, "PATCH /api/account": {Summary: "Update profile", Tag: "users", Session: true}, @@ -95,27 +95,28 @@ func routeDescriptions() map[string]routeMeta { "POST /api/account/password": {Summary: "Change password", Tag: "users", Session: true}, "POST /api/account/email": {Summary: "Request an address change", Tag: "users", Session: true}, "POST /api/account/confirm-email": {Summary: "Confirm an address change", Tag: "users"}, - "GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current}]. kind is web (a browser) or device (a CoreDrive RX device token); label is the device name, empty for web sessions. DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true}, + "GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current, scopes}]. kind is web (a browser) or device (a device token: CoreDrive RX or another app); label is the device name, empty for web sessions; scopes lists a device token's scopes (absent for web sessions). DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true}, "DELETE /api/account/sessions/{id}": {Summary: "Revoke one own session", Tag: "users", Session: true}, "GET /api/account/settings": {Summary: "Get own synced settings", Description: "Returns {revision, generation, doc, allowlist}. doc is {v: 1, keys: {: }} or null at revision 0. generation is a random id of the stored document (empty at revision 0); revisions restart at 1 after a DELETE, the generation does not repeat. allowlist lists the keys the server accepts: {key, kind: set|scalar, id?}, where id names the field that identifies an item of a set (absent: the item itself).", Tag: "users", Session: true}, "PUT /api/account/settings": {Summary: "Replace own synced settings", Description: "Body {baseRevision, baseGeneration, doc}. 200 {revision, generation}. 409 {revision, generation, doc} when baseRevision is not the stored revision or, with a stored document, baseGeneration is not its generation. baseRevision 0 without a stored document starts a new generation. 400 when doc is not {v: 1, keys} or holds a key that is never synced or not allowlisted. 413 above 256 KiB. 429 above 60 PUT requests per hour per user.", Tag: "users", Session: true}, "DELETE /api/account/settings": {Summary: "Delete own synced settings", Description: "Removes the stored document; the next PUT (baseRevision 0) starts a new one in a new generation.", Tag: "users", Session: true}, "POST /api/account/companions/challenge": {Summary: "Start linking a companion", Description: "Body {pubkey} (64 hex). 200 {challenge, expiresAt, host}: host is what to sign (the host of userManagement.publicBaseUrl); challenge is 32 random bytes as hex, single use, valid 5 minutes, bound to the caller and the pubkey. 400 malformed pubkey; 429 above 60 challenge + link requests per hour per user and per IP. Accepts a device token (Authorization: Bearer).", Tag: "users", Session: true}, "POST /api/account/companions": {Summary: "Link a companion", Description: "Body {pubkey, challenge, signature, name}. signature is the companion's Ed25519 signature (64 bytes, hex) over the UTF-8 string \"corescope-link:\" + host of userManagement.publicBaseUrl + \":\" + challenge. The challenge is consumed in every case. 200 {pubkey, name, linkedAt}. The synced settings (meshcore-my-nodes) are not touched: a companion is not a node to monitor. A companion linked to another account moves to the caller (the newest proof wins); both get a companion.transfer audit row and the previous owner a mail (a security notice, sent whatever the node notification settings are). 400 malformed pubkey or signature, or a signature that does not verify; 410 challenge missing, expired, used, or bound to another user or pubkey; 429 rate limited. Accepts a device token.", Tag: "users", Session: true}, + "GET /api/account/repeaters": {Summary: "List own claimed repeaters", Description: "{repeaters: [{pubkey, name, known, inactive, role, claimedAt, lastHeard, lastRelayed, status, comaintainers}]} for My account, My repeaters: named repeaters first by name, then the unnamed by pubkey. inactive is true when retention moved the node to inactive_nodes (silent longer than retention.nodeDays); its name, role and last advert are read from there. known is false only when the node is in neither nodes nor inactive_nodes (the claim stays). lastHeard is the newer of the last advert and the last transmission certainly from the node, or null; lastRelayed is the last time its hop prefix was seen relaying (it may be shared with other repeaters), or null. status is the saved repeater status or null. comaintainers are the other active claimers' display names. A browser session or a device token with repeater:claim or repeater:edit; an rx-only token answers 403.", Tag: "users", Session: true}, "GET /api/account/companions": {Summary: "List own linked companions", Description: "[{pubkey, name, linkedAt, lastSeenAt}], newest link first. lastSeenAt is the newest client reception of that companion (rx_at as stored) or null. Accepts a device token.", Tag: "users", Session: true}, "DELETE /api/account/companions/{pubkey}": {Summary: "Unlink an own companion", Description: "204. Stored coverage stays. 400 malformed pubkey, 404 not linked to the caller. Accepts a device token.", Tag: "users", Session: true}, "GET /api/account/observer-login": {Summary: "Own observer MQTT login", Description: "{login: null} or {login: {username, createdAt, revoked}, observers: [{pubkey, name, lastSeenAt}]}. observers are the pubkeys bound to the caller (the first time an observer publishes with the login); name and lastSeenAt come from the analyzer observers (empty name and null lastSeenAt when unknown). Never contains the password, its hash or its ciphertext. Routes exist only when userManagement.observerLogins is enabled. Not available to device tokens.", Tag: "users", Session: true}, "POST /api/account/observer-login": {Summary: "Request an observer MQTT login", Description: "Generates a username and password, stores the password hashed and sealed, and mails the credentials to the account address in five formats (meshcoretomqtt, Gessaman or Dutch-MeshCore observer firmware, Home Assistant meshcore-ha, OpenHop, plain). 201 {sent: true}: the response never carries the credentials. 409 when the caller already has a login, 403 when it was revoked, 503 when the mail could not be sent (the login exists; use resend) or the feature failed to load.", Tag: "users", Session: true}, "POST /api/account/observer-login/resend": {Summary: "Mail the observer MQTT credentials again", Description: "Mails the same credentials again. 200 {sent: true}. 404 without a login, 403 when revoked, 429 after 3 credential mails in 24 hours (the first mail counts; Retry-After in seconds), 503 when the mail fails.", Tag: "users", Session: true}, - "PUT /api/repeaters/{pubkey}/info": {Summary: "Edit a repeater's community details", Description: "Body is a full replace, omitted fields are cleared, and an unchanged body is a no-op: {heightM (null = unknown, 0 to 300), gainDbi (omitted = 0, -10 to 30), status (active|maintenance|decommissioned|empty), power (mains|battery|solar|empty), notes (at most 500 characters)}. 200 the repeater info with canEdit and claimedByMe. Allowed for an admin, for any active user when the repeater has no active claimer, otherwise only for its claimers. Writes a repeater.edit audit row with the changed fields (none when nothing changed). 400 malformed pubkey, invalid value, or a node that is not a repeater; 401 not logged in; 403 not a maintainer or CSRF failure; 404 unknown node; 429 above 120 repeater requests per hour per user and per IP.", Tag: "users", Session: true}, - "POST /api/repeaters/{pubkey}/claim": {Summary: "Claim a repeater", Description: "No body. 200 the repeater info with canEdit and claimedByMe. Idempotent: a repeat answers 200 and writes no second repeater.claim audit row. 400 malformed pubkey or not a repeater; 401 not logged in; 403 CSRF failure; 404 unknown node; 429 rate limited.", Tag: "users", Session: true}, - "DELETE /api/repeaters/{pubkey}/claim": {Summary: "Remove own claim on a repeater", Description: "200 the repeater info with canEdit and claimedByMe. Writes a repeater.unclaim audit row. 400 malformed pubkey; 401 not logged in; 403 CSRF failure; 404 the caller has no claim on it; 429 rate limited.", Tag: "users", Session: true}, + "PUT /api/repeaters/{pubkey}/info": {Summary: "Edit a repeater's community details", Description: "A browser session (with the CSRF header) or a device token with repeater:edit. Body is a full replace, omitted fields are cleared, and an unchanged body is a no-op: {heightM (null = unknown, 0 to 300), gainDbi (omitted = 0, -10 to 30), status (active|maintenance|decommissioned|empty), power (mains|battery|solar|empty), notes (at most 500 characters), baseRevision (optional)}. With baseRevision the save is conditional: it must be the stored revision (0 when no details are saved yet), checked in the same statement as the write; otherwise 409 with the stored repeater info (canEdit and claimedByMe included) and nothing is written, also for a body that would change nothing. Merge and retry from the 409's revision. Without baseRevision the save is unconditional. 200 the repeater info with canEdit and claimedByMe. Allowed for an admin, for any active user when the repeater has no active claimer, otherwise only for its claimers. Writes a repeater.edit audit row with the changed fields (none when nothing changed), with via=device when sent with a device token. 400 malformed pubkey, invalid value, negative baseRevision, or a node that is not a repeater; 401 not logged in or the token is gone; 403 not a maintainer, CSRF failure or a token without repeater:edit; 404 unknown node; 429 above 120 repeater requests per hour per user and per IP.", Tag: "users", Session: true}, + "POST /api/repeaters/{pubkey}/claim": {Summary: "Claim a repeater", Description: "A browser session (with the CSRF header) or a device token with repeater:claim. No body. 200 the repeater info with canEdit and claimedByMe. A repeater may have several claimers. Idempotent: a repeat answers 200 and writes no second repeater.claim audit row (via=device when sent with a device token). 400 malformed pubkey or not a repeater; 401 not logged in or the token is gone; 403 CSRF failure or a token without repeater:claim; 404 unknown node; 429 rate limited.", Tag: "users", Session: true}, + "DELETE /api/repeaters/{pubkey}/claim": {Summary: "Remove own claim on a repeater", Description: "A browser session (with the CSRF header) or a device token with repeater:claim. Removes only the caller's claim; other claimers keep theirs. 200 the repeater info with canEdit and claimedByMe. Writes a repeater.unclaim audit row (via=device when sent with a device token). 400 malformed pubkey; 401 not logged in or the token is gone; 403 CSRF failure or a token without repeater:claim; 404 the caller has no claim on it; 429 rate limited.", Tag: "users", Session: true}, "GET /api/repeaters/info": {Summary: "Community details of all repeaters with details or claimers", Description: "{repeaters: [...]} ordered by pubkey; each entry has the shape of GET /api/repeaters/{pubkey}/info without canEdit and claimedByMe. Contains every pubkey with a saved info row or at least one active claimer. Only display names are public, never email. 404 when user management is off.", Tag: "users", Session: false}, - "GET /api/repeaters/{pubkey}/info": {Summary: "Community details of one repeater", Description: "{pubkey, heightM, gainDbi, status, power, notes, claimers: [{displayName, claimedAt}], updatedAt, updatedBy}. A repeater without a saved row answers 200 with defaults: heightM null, gainDbi 0, status null, power null, notes \"\", claimers [], updatedAt null, updatedBy null. heightM 0 is a real value, null is unknown. canEdit and claimedByMe appear only with a browser session (a bearer token is treated as anonymous). The pubkey is case-insensitive; 400 when it is not 64 hex characters. No analyzer lookup: any well-formed pubkey answers. 404 when user management is off.", Tag: "users", Session: false}, + "GET /api/repeaters/{pubkey}/info": {Summary: "Community details of one repeater", Description: "{pubkey, revision, heightM, gainDbi, status, power, notes, claimers: [{displayName, claimedAt}], updatedAt, updatedBy}. revision counts saves of the details from 1 (claims do not change it); send it as baseRevision with PUT. A repeater without a saved row answers 200 with defaults: revision 0, heightM null, gainDbi 0, status null, power null, notes \"\", claimers [], updatedAt null, updatedBy null. heightM 0 is a real value, null is unknown. canEdit and claimedByMe appear with a browser session, or with a device token holding repeater:claim or repeater:edit; a device token without either scope, or a bearer that is no live device token (unknown, expired, or an auth proxy's own Authorization header), reads the public view. The pubkey is case-insensitive; 400 when it is not 64 hex characters. No analyzer lookup: any well-formed pubkey answers. 404 when user management is off.", Tag: "users", Session: false}, "GET /api/account/export": {Summary: "Download own account data", Description: "One JSON file (Content-Disposition attachment corescope-account-.json): {formatVersion: 1, exportedAt, instance, profile, sessions (with kind web|device and the device label), companions (linked companions: pubkey, name, linkedAt), settings, proposals, notifications: {prefs, watches}, audit, mail, observerLogin: {username, createdAt, revoked} or null, observerBindings: [{pubkey, boundAt, boundBy}], repeaterClaims: [{pubkey, claimedAt}], newest first, all own claims}. Every row, no caps. Leaves out the password hash, every session, link and unsubscribe token, and companion link challenges. Audit rows name other accounts by id only. Includes activatedAt, activatedBy (id) and each mail row's to-address. Records a user.export audit row after the file is built.", Tag: "users", Session: true}, "GET /api/admin/users": {Summary: "List users (admin)", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | active | disabled", Type: "string"}, {Name: "role", Description: "user | admin", Type: "string"}, {Name: "q", Description: "Substring of email or display name", Type: "string"}, {Name: "bouncing", Description: "1 = only addresses whose mail bounces", Type: "string"}}}, - "DELETE /api/admin/repeaters/{pubkey}/claims/{userId}": {Summary: "Remove a user's claim on a repeater (admin)", Description: "204. Writes a repeater.unclaim audit row with actor = the admin, target = the user and detail {pubkey, by: admin}. 400 malformed pubkey or user id; 401 not logged in; 403 not an admin or CSRF failure; 404 no such claim.", Tag: "users", Session: true}, - "GET /api/admin/users/{id}": {Summary: "User detail with sessions, companions, repeater claims, mail log and audit (admin)", Description: "{user, sessions, companions, repeaterClaims, mail, audit}. companions is [{pubkey, name, linkedAt, lastSeenAt}] like GET /api/account/companions. repeaterClaims is [{pubkey, claimedAt}], newest first, every claim of the user whatever the user's status.", Tag: "users", Session: true}, + "DELETE /api/admin/repeaters/{pubkey}/claims/{userId}": {Summary: "Remove a user's claim on a repeater (admin)", Description: "Browser session only; device tokens answer 403. 204. Writes a repeater.unclaim audit row with actor = the admin, target = the user and detail {pubkey, by: admin}. 400 malformed pubkey or user id; 401 not logged in; 403 not an admin or CSRF failure; 404 no such claim.", Tag: "users", Session: true}, + "GET /api/admin/users/{id}": {Summary: "User detail with sessions, companions, repeater claims, mail log and audit (admin)", Description: "{user, sessions, companions, repeaterClaims, mail, audit}. companions is [{pubkey, name, linkedAt, lastSeenAt}] like GET /api/account/companions. repeaterClaims is [{pubkey, claimedAt}], newest first, every claim of the user whatever the user's status. mailDeliveryStatus is false when the provider (smtp) cannot report delivery events: mail shows as sent and there is nothing to refresh.", Tag: "users", Session: true}, "DELETE /api/admin/users/{id}": {Summary: "Delete a user (admin)", Tag: "users", Session: true}, "POST /api/admin/users/{id}/disable": {Summary: "Disable a user (admin)", Tag: "users", Session: true}, "POST /api/admin/users/{id}/enable": {Summary: "Enable a user (admin)", Tag: "users", Session: true}, @@ -124,7 +125,8 @@ func routeDescriptions() map[string]routeMeta { "POST /api/admin/users/{id}/activate": {Summary: "Activate a pending user manually (admin)", Description: "For when mail keeps failing. The address stays unverified; recorded as activatedBy + audit row.", Tag: "users", Session: true}, "POST /api/admin/users/{id}/mail/{mailId}/refresh": {Summary: "Pull delivery events for one mail from the provider (admin)", Tag: "users", Session: true}, "GET /api/admin/audit": {Summary: "Global audit log (admin)", Description: "Newest first, keyset-paginated: {entries, next}. Pass next as before for the following page; next is null on the last page. Entry: {id, at, action, actor, target, detail}; actor and target are {id, displayName, email}, {id, deleted: true} for a removed account, or null for the system. Login rows (user.login, user.login.failed) are kept 90 days. 400 on an invalid parameter.", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "action", Description: "One action, or a group ending in .* (user.login.* matches user.login and user.login.failed)", Type: "string"}, {Name: "user", Description: "User id, as actor or target", Type: "integer"}, {Name: "from", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "to", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "before", Description: "Only entries with a smaller id (next of the previous page)", Type: "integer"}, {Name: "limit", Description: "Page size, default 100, capped at 500", Type: "integer"}}}, - "GET /api/admin/stats": {Summary: "User figures for the admin overview (admin)", Description: "Accounts by status, active admins, pending accounts older than 24 hours (stuckPending), bouncing addresses, registrations in 7 and 30 days and per UTC day for 30 days (newPerDay, oldest first), users active in 7 and 30 days, logins and failed logins in 24 hours, mail sent in 7 days by latest delivery status (mail7d), and accounts with 5 or more failed logins in 24 hours (guessing: [{userId, displayName, failed}]).", Tag: "users", Session: true}, + "GET /api/admin/stats": {Summary: "User figures for the admin overview (admin)", Description: "Accounts by status, active admins, pending accounts older than 24 hours (stuckPending), bouncing addresses, registrations in 7 and 30 days and per UTC day for 30 days (newPerDay, oldest first), users active in 7 and 30 days, logins and failed logins in 24 hours, mail sent in 7 days by latest delivery status (mail7d), accounts with 5 or more failed logins in 24 hours (guessing: [{userId, displayName, failed}]), and mailDeliveryStatus: false when the provider (smtp) cannot report delivery events, so mail counts only as sent.", Tag: "users", Session: true}, + "POST /api/admin/mail/test": {Summary: "Send a test mail to your own address (admin)", Description: "Sends a fixed test mail to the calling admin's own address through the configured provider; the address is never a parameter and any body is ignored. 200 {ok: true, provider, messageId}; 502 {ok: false, provider, error} with the provider's error text, addresses redacted. Recorded in the mail log with purpose test and as a mail.test audit row with detail {provider, result: ok|failed}. 401 not logged in, 403 not an admin or CSRF failure, 429 above 3 test mails per admin and per IP address per 10 minutes (Retry-After in seconds).", Tag: "users", Session: true}, "GET /api/admin/observer-logins": {Summary: "List observer MQTT logins and bindings (admin)", Description: "{logins: [{userId, email, displayName, username, createdAt, revoked, lastAuthAt, observers: [pubkey]}], bindings: [{pubkey, userId|null, boundAt, boundBy, confirmedAt|null}]}. confirmedAt is when the owner's own login first published under the pubkey. Never contains passwords, hashes or ciphertext. Routes exist only when userManagement.observerLogins is enabled.", Tag: "users", Session: true}, "POST /api/admin/observer-logins/{id}/revoke": {Summary: "Revoke a user's observer MQTT login (admin)", Description: "Takes effect at once for the broker hooks. 404 when the user has no login. Records an observer.login.revoke audit row.", Tag: "users", Session: true}, "POST /api/admin/observer-logins/{id}/reissue": {Summary: "Issue new observer MQTT credentials (admin)", Description: "New username and password, revocation cleared, credentials mailed to the account address. 200 {sent: true}; 404 without a login; 503 when the mail fails (the new login is already active). Records an observer.login.reissue audit row without the password.", Tag: "users", Session: true}, diff --git a/cmd/server/packets_exclude_tx_test.go b/cmd/server/packets_exclude_tx_test.go index d2b7bb5a1..60815f882 100644 --- a/cmd/server/packets_exclude_tx_test.go +++ b/cmd/server/packets_exclude_tx_test.go @@ -41,7 +41,7 @@ func TestPacketsExcludeTx(t *testing.T) { t.Helper() if db.isV3 { mustExec(`INSERT INTO observations (transmission_id, observer_idx, direction, path_json, timestamp) - VALUES (?, (SELECT rowid FROM observers WHERE id = ?), ?, ?, ?)`, tx, observer, direction, path, seen.Unix()) + VALUES (?, (SELECT idx FROM observers WHERE id = ?), ?, ?, ?)`, tx, observer, direction, path, seen.Unix()) } else { mustExec(`INSERT INTO observations (transmission_id, observer_id, direction, path_json, timestamp) VALUES (?, ?, ?, ?, ?)`, tx, observer, direction, path, seen.Unix()) diff --git a/cmd/server/pathhop_dedupe_2108_test.go b/cmd/server/pathhop_dedupe_2108_test.go index b77b2fe5c..1f0750726 100644 --- a/cmd/server/pathhop_dedupe_2108_test.go +++ b/cmd/server/pathhop_dedupe_2108_test.go @@ -66,7 +66,7 @@ func phdSeed(t testing.TB, db *DB, observers int) { pk, fmt.Sprintf("phdRelay-%d", i), ts) } for i := 1; i <= observers; i++ { - phdExec(t, db, `INSERT INTO observers (rowid, id, name, iata) VALUES (?, ?, ?, 'TST')`, + phdExec(t, db, `INSERT INTO observers (idx, id, name, iata) VALUES (?, ?, ?, 'TST')`, i, fmt.Sprintf("phdObs-%02d", i), fmt.Sprintf("Observer %d", i)) } } diff --git a/cmd/server/preparable_schema_test.go b/cmd/server/preparable_schema_test.go index 0540091d7..c21e50658 100644 --- a/cmd/server/preparable_schema_test.go +++ b/cmd/server/preparable_schema_test.go @@ -22,7 +22,7 @@ var preparableTables = []string{ `CREATE TABLE IF NOT EXISTS transmissions (id INTEGER PRIMARY KEY, hash TEXT)`, `CREATE TABLE IF NOT EXISTS observations (id INTEGER PRIMARY KEY, timestamp TEXT)`, `CREATE TABLE IF NOT EXISTS nodes (public_key TEXT PRIMARY KEY)`, - `CREATE TABLE IF NOT EXISTS observers (id TEXT)`, + `CREATE TABLE IF NOT EXISTS observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE)`, } // preparableColumns are added when absent. A fixture that already declared the diff --git a/cmd/server/proposal_channels_test.go b/cmd/server/proposal_channels_test.go index aff426647..558e28c73 100644 --- a/cmd/server/proposal_channels_test.go +++ b/cmd/server/proposal_channels_test.go @@ -113,7 +113,7 @@ func TestClientConfigAdvertisesChannelProposals(t *testing.T) { a, _ := newTestAuthService(t) a.set.proposals = defaultProposalSettings() srv.auth = a - if body := getBody(router, "/api/config/client"); !strings.Contains(body, `"userManagement":{"enabled":true,"channelProposals":true,"companionLinking":true}`) { + if body := getBody(router, "/api/config/client"); !strings.Contains(body, `"userManagement":{"enabled":true,"channelProposals":true,"companionLinking":true,"repeaterTokens":true}`) { t.Fatalf("client config = %s", body) } } diff --git a/cmd/server/repeater_device_token_test.go b/cmd/server/repeater_device_token_test.go new file mode 100644 index 000000000..57cd199db --- /dev/null +++ b/cmd/server/repeater_device_token_test.go @@ -0,0 +1,348 @@ +package main + +import ( + "net/http" + "slices" + "strings" + "testing" + + "github.com/meshcore-analyzer/users" +) + +// scopedToken logs in like a mobile client asking for scopes. +func (f *authFixture) scopedToken(t *testing.T, email, name string, scopes ...string) string { + t.Helper() + w := f.do("POST", "/api/auth/device-token", + deviceTokenRequest{Email: email, Password: pw, DeviceName: name, Scopes: scopes}) + expectStatus(t, w, http.StatusOK) + got := decode[deviceTokenResponse](t, w) + if !slices.Equal(got.Scopes, scopes) { + t.Fatalf("granted scopes = %v, want %v", got.Scopes, scopes) + } + return got.Token +} + +func TestDeviceTokenScopesDefaultToRX(t *testing.T) { + f := newAuthFixture(t) + f.registerAndActivate(t, "alice@example.org", "Alice", pw) + got := f.deviceToken(t, "alice@example.org", pw, "Pixel") + if !slices.Equal(got.Scopes, []string{deviceScopeRX}) { + t.Fatalf("scopes = %v, want [rx]", got.Scopes) + } + sess, err := f.st.LookupSession(got.Token) + if err != nil || sess.HasScope(deviceScopeRepeaterClaim) || sess.HasScope(deviceScopeRepeaterEdit) { + t.Fatalf("an RX token holds repeater scopes: %+v, %v", sess, err) + } +} + +func TestDeviceTokenScopesRequested(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + // Repeats collapse and the order is fixed. + w := f.do("POST", "/api/auth/device-token", deviceTokenRequest{Email: "alice@example.org", Password: pw, + DeviceName: "iPhone", Scopes: []string{deviceScopeRepeaterEdit, deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}}) + expectStatus(t, w, http.StatusOK) + got := decode[deviceTokenResponse](t, w) + want := []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} + if !slices.Equal(got.Scopes, want) { + t.Fatalf("scopes = %v, want %v", got.Scopes, want) + } + sess, err := f.st.LookupSession(got.Token) + if err != nil || !slices.Equal(sess.Scopes, want) || sess.HasScope(deviceScopeRX) { + t.Fatalf("stored session = %+v, %v", sess, err) + } + rows := auditOf(t, f, alice.me.ID, "user.login") + if len(rows) == 0 || rows[0].Detail["scopes"] != "repeater:claim,repeater:edit" { + t.Fatalf("login audit = %+v", rows) + } +} + +func TestDeviceTokenScopesRejected(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + for _, scopes := range [][]string{{}, {"admin"}, {deviceScopeRX, "repeater:delete"}, {""}} { + w := f.do("POST", "/api/auth/device-token", deviceTokenRequest{Email: "alice@example.org", Password: pw, + DeviceName: "x", Scopes: scopes}) + if w.Code != http.StatusBadRequest { + t.Errorf("scopes %q = %d, want 400", scopes, w.Code) + } + } + list, err := f.st.ListSessions(alice.me.ID) + if err != nil { + t.Fatal(err) + } + for _, s := range list { + if s.Kind == users.SessionKindDevice { + t.Fatalf("a rejected request created a device session: %+v", s) + } + } +} + +func TestBearerScopesForRoutes(t *testing.T) { + both := []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} + for _, c := range []struct { + method, path string + want []string + }{ + {"GET", "/api/auth/me", deviceScopes}, + {"POST", "/api/auth/logout", deviceScopes}, + {"PUT", "/api/account/settings", []string{deviceScopeRX}}, + {"DELETE", "/api/account/companions/" + rpkA, []string{deviceScopeRX}}, + {"POST", repPath(rpkA, "claim"), []string{deviceScopeRepeaterClaim}}, + {"DELETE", repPath(rpkA, "claim"), []string{deviceScopeRepeaterClaim}}, + {"PUT", repPath(rpkA, "info"), []string{deviceScopeRepeaterEdit}}, + {"GET", repPath(rpkA, "info"), both}, + {"GET", "/api/account/repeaters", both}, + {"HEAD", "/api/account/repeaters", both}, + {"POST", "/api/account/repeaters", nil}, + {"DELETE", "/api/account/repeaters", nil}, + {"GET", repPath(rpkA, "claim"), nil}, + {"POST", repPath(rpkA, "info"), nil}, + {"GET", "/api/repeaters/info", nil}, + {"PUT", "/api/repeaters//info", nil}, + {"PUT", repPath(rpkA, "info/x"), nil}, + {"DELETE", "/api/admin/repeaters/" + rpkA + "/claims/1", nil}, + {"GET", "/api/account/sessions", nil}, + } { + if got := bearerScopesFor(c.method, c.path); !slices.Equal(got, c.want) { + t.Errorf("bearerScopesFor(%s %s) = %v, want %v", c.method, c.path, got, c.want) + } + } + for path, want := range map[string]bool{ + repPath(rpkA, "info"): true, repPath(rpkA, "claim"): true, "/api/auth/device-token": true, + "/api/account/companions": true, "/api/account/repeaters": true, "/api/repeaters/info": false, "/api/account/sessions": false, + } { + if got := bearerCORSPath(path); got != want { + t.Errorf("bearerCORSPath(%s) = %v, want %v", path, got, want) + } + } +} + +// Each scope opens only its own routes; RX and repeater tokens stay apart. +func TestRepeaterTokenScopesPerRoute(t *testing.T) { + f := repeaterFixture(t) + f.registerAndActivate(t, "alice@example.org", "Alice", pw) + tokens := map[string]string{ + "rx": f.deviceToken(t, "alice@example.org", pw, "RX").Token, + "claim": f.scopedToken(t, "alice@example.org", "claim", deviceScopeRepeaterClaim), + "edit": f.scopedToken(t, "alice@example.org", "edit", deviceScopeRepeaterEdit), + } + for _, c := range []struct { + token, method, path string + body any + want int + }{ + {"rx", "POST", repPath(rpkA, "claim"), nil, 403}, + {"rx", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 403}, + {"edit", "POST", repPath(rpkA, "claim"), nil, 403}, + {"claim", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 403}, + {"claim", "GET", "/api/account/settings", nil, 403}, + {"edit", "GET", "/api/account/companions", nil, 403}, + {"claim", "GET", "/api/auth/me", nil, 200}, + {"edit", "GET", "/api/auth/me", nil, 200}, + {"edit", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 200}, + {"claim", "POST", repPath(rpkA, "claim"), nil, 200}, + {"claim", "DELETE", repPath(rpkA, "claim"), nil, 200}, + } { + if w := f.do(c.method, c.path, c.body, bearer(tokens[c.token])); w.Code != c.want { + t.Errorf("%s token: %s %s = %d (%s), want %d", c.token, c.method, c.path, w.Code, w.Body.String(), c.want) + } + } + // A repeater-only token can still end its own login. + expectStatus(t, f.do("POST", "/api/auth/logout", nil, bearer(tokens["claim"])), 200) + if _, err := f.st.LookupSession(tokens["claim"]); err == nil { + t.Fatal("logout left the claim token valid") + } +} + +// A claim token manages the caller's own claim only, beside other claimers. +func TestRepeaterTokenClaimsOwnClaimOnly(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + bob := f.scopedToken(t, "bob@example.org", "Bob's phone", deviceScopeRepeaterClaim) + + // Bob has no claim yet: his DELETE must not touch Alice's. + expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(bob)), 404) + w := f.do("POST", repPath(rpkA, "claim"), nil, bearer(bob)) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if len(got.Claimers) != 2 || got.ClaimedByMe == nil || !*got.ClaimedByMe { + t.Fatalf("after Bob's claim: %+v", got) + } + // Repeating the claim stays a 200 without a second claim. + got = decode[repeaterInfoJSON](t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(bob))) + if len(got.Claimers) != 2 { + t.Fatalf("a repeated claim changed the claimers: %+v", got.Claimers) + } + w = f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(bob)) + expectStatus(t, w, 200) + got = decode[repeaterInfoJSON](t, w) + if len(got.Claimers) != 1 || got.Claimers[0].DisplayName != "Alice" || *got.ClaimedByMe { + t.Fatalf("after Bob's unclaim: %+v", got) + } + expectStatus(t, f.do("POST", repPath(rpkComp, "claim"), nil, bearer(bob)), 400) + if rows := auditOf(t, f, alice.me.ID, "repeater.unclaim"); len(rows) != 0 { + t.Fatalf("Alice's claim was audited as removed: %+v", rows) + } +} + +// An edit token follows the browser's rule: anyone on an unclaimed repeater, +// then only its active claimers, and admins always. +func TestRepeaterTokenEditFollowsCanEdit(t *testing.T) { + f := repeaterFixture(t, "boss@example.org") + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + f.registerAndActivate(t, "boss@example.org", "Boss", pw) + bobEdit := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit) + bobBoth := f.scopedToken(t, "bob@example.org", "Bob 2", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit) + boss := f.scopedToken(t, "boss@example.org", "Boss", deviceScopeRepeaterEdit) + + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 10}, bearer(bobEdit)), 200) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 11}, bearer(bobEdit)) + expectStatus(t, w, 403) + if info, _ := f.st.GetRepeaterInfo(rpkA); info == nil || info.HeightM == nil || *info.HeightM != 10 { + t.Fatalf("a refused edit changed the row: %+v", info) + } + // Claiming makes Bob a maintainer again. + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(bobBoth)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 12}, bearer(bobBoth)), 200) + // The admin edits a claimed repeater through a token too. + w = f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 13}, bearer(boss)) + expectStatus(t, w, 200) + if got := decode[repeaterInfoJSON](t, w); got.CanEdit == nil || !*got.CanEdit || *got.ClaimedByMe { + t.Fatalf("admin response = %+v", got) + } + // A disabled account's token stops working. + bobMe := decode[meResponse](t, f.do("GET", "/api/auth/me", nil, bearer(bobBoth))) + bobID := bobMe.ID + // A token reads its own scopes back (review on #2429), with no CSRF token. + if !slices.Equal(bobMe.Scopes, []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}) || bobMe.CSRFToken != "" { + t.Fatalf("/api/auth/me for a device token = %+v", bobMe) + } + if err := f.st.SetStatus(bobID, users.StatusDisabled); err != nil { + t.Fatal(err) + } + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 14}, bearer(bobBoth)), 401) +} + +// Admin claim removal stays a browser-only admin action. +func TestRepeaterTokenCannotUseAdminRoute(t *testing.T) { + f := repeaterFixture(t, "boss@example.org") + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "boss@example.org", "Boss", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + boss := f.scopedToken(t, "boss@example.org", "Boss", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit) + expectStatus(t, f.do("DELETE", adminClaimPath(rpkA, alice.me.ID), nil, bearer(boss)), 403) + if c, _ := f.st.RepeaterClaims(rpkA); len(c) != 1 { + t.Fatalf("claims = %+v", c) + } +} + +func TestRepeaterInfoGetWithToken(t *testing.T) { + f := newAuthFixture(t) + alice := seedAliceRepeater(t, f) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + aliceClaim := f.scopedToken(t, "alice@example.org", "Alice", deviceScopeRepeaterClaim) + bobEdit := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit) + rx := f.deviceToken(t, "bob@example.org", pw, "RX").Token + + got := decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, bearer(aliceClaim))) + if got.CanEdit == nil || !*got.CanEdit || got.ClaimedByMe == nil || !*got.ClaimedByMe { + t.Fatalf("Alice's token: %+v", got) + } + got = decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, bearer(bobEdit))) + if got.CanEdit == nil || *got.CanEdit || got.ClaimedByMe == nil || *got.ClaimedByMe { + t.Fatalf("Bob's token: %+v", got) + } + // An RX token reads the public view, like an anonymous visitor. + w := f.do("GET", repPath(rpkA, "info"), nil, bearer(rx)) + expectStatus(t, w, 200) + if strings.Contains(w.Body.String(), "canEdit") { + t.Fatalf("RX token got caller fields: %s", w.Body.String()) + } + // A bearer that is no live device token reads the public view: a token + // that is gone, a web session token, and an auth proxy's own header + // (review on #2429: a 401 here hid the Repeater info section). + for _, tok := range []string{"nonsense", alice.cookie.Value, "eyJhbGciOiJSUzI1NiJ9.proxy.jwt"} { + w := f.do("GET", repPath(rpkA, "info"), nil, bearer(tok)) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "canEdit") { + t.Errorf("bearer %.8s… = %d %s, want 200 with the public view", tok, w.Code, w.Body.String()) + } + } + // The same foreign header still gets 401 on a write, which needs a login. + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "x"}, bearer("eyJhbGciOiJSUzI1NiJ9.proxy.jwt")), http.StatusUnauthorized) + // The cookie still decides when both are sent, and anonymous reads stay public. + got = decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, as(alice), bearer("nonsense"))) + if got.ClaimedByMe == nil || !*got.ClaimedByMe { + t.Fatalf("cookie with a stray bearer: %+v", got) + } + if w := f.do("GET", repPath(rpkA, "info"), nil); strings.Contains(w.Body.String(), "claimedByMe") || w.Code != 200 { + t.Fatalf("anonymous read = %d %s", w.Code, w.Body.String()) + } +} + +func TestRepeaterTokenWritesAuditVia(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + tok := f.scopedToken(t, "alice@example.org", "iPhone", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(tok)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "roof"}, bearer(tok)), 200) + expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(tok)), 200) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + for action, want := range map[string][]string{ + "repeater.claim": {"", "device"}, "repeater.edit": {"device"}, "repeater.unclaim": {"device"}, + } { + rows := auditOf(t, f, alice.me.ID, action) + var via []string + for _, r := range rows { + via = append(via, r.Detail["via"]) + } + if !slices.Equal(via, want) { + t.Errorf("%s via = %q, want %q (newest first)", action, via, want) + } + } +} + +// The browser path is unchanged: a cookie write still needs the CSRF token. +func TestRepeaterCookieWriteStillNeedsCSRF(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + noCSRF := &client{cookie: alice.cookie} + for _, c := range []struct{ method, what string }{{"POST", "claim"}, {"PUT", "info"}, {"DELETE", "claim"}} { + if w := f.do(c.method, repPath(rpkA, c.what), map[string]any{}, as(noCSRF)); w.Code != http.StatusForbidden { + t.Errorf("%s %s without CSRF = %d, want 403", c.method, c.what, w.Code) + } + } + if c, _ := f.st.RepeaterClaims(rpkA); len(c) != 0 { + t.Fatalf("claims = %+v", c) + } +} + +// My account, Devices tells an app token's scopes apart from CoreDrive RX. +func TestAccountSessionsListScopes(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.deviceToken(t, "alice@example.org", pw, "RX") + f.scopedToken(t, "alice@example.org", "iPhone", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit) + w := f.do("GET", "/api/account/sessions", nil, as(alice)) + expectStatus(t, w, http.StatusOK) + got := map[string][]string{} + for _, s := range decode[[]sessionJSON](t, w) { + got[s.Kind+":"+s.Label] = s.Scopes + } + if s, ok := got["web:"]; !ok || s != nil { + t.Errorf("web session scopes = %v (present %v), want none", s, ok) + } + if s := got["device:RX"]; !slices.Equal(s, []string{deviceScopeRX}) { + t.Errorf("RX scopes = %v", s) + } + if s := got["device:iPhone"]; !slices.Equal(s, []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}) { + t.Errorf("app scopes = %v", s) + } + if strings.Contains(w.Body.String(), `"scopes":null`) { + t.Errorf("web session has a null scopes field: %s", w.Body.String()) + } +} diff --git a/cmd/server/repeater_handlers.go b/cmd/server/repeater_handlers.go index ad7f68896..b68843147 100644 --- a/cmd/server/repeater_handlers.go +++ b/cmd/server/repeater_handlers.go @@ -33,6 +33,7 @@ func claimRefsJSON(claims []users.RepeaterClaim) []repeaterClaimRefJSON { type repeaterInfoJSON struct { Pubkey string `json:"pubkey"` + Revision int64 `json:"revision"` HeightM *float64 `json:"heightM"` GainDBi float64 `json:"gainDbi"` Status *string `json:"status"` @@ -55,6 +56,7 @@ func (s *Server) registerRepeaterRoutes(r *mux.Router) { r.HandleFunc("/api/repeaters/{pubkey}/info", s.withUser(s.handleRepeaterInfoPut)).Methods("PUT") r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterClaim)).Methods("POST") r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterUnclaim)).Methods("DELETE") + r.HandleFunc("/api/account/repeaters", s.withUser(s.handleMyRepeaters)).Methods("GET") r.HandleFunc("/api/admin/repeaters/{pubkey}/claims/{userId}", s.withAdmin(s.handleAdminRepeaterUnclaim)).Methods("DELETE") } @@ -79,6 +81,7 @@ func repeaterInfoBase(pk string, info *users.RepeaterInfo, claims []users.Repeat if info == nil { return out } + out.Revision = info.Revision out.HeightM = info.HeightM out.GainDBi = info.GainDBi out.Status = stringPtrOrNil(info.Status) @@ -129,7 +132,7 @@ func (s *Server) handleRepeaterInfoGet(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "pubkey must be 64 hex characters") return } - u, _ := s.auth.currentUser(w, r) + u, _ := s.optionalUser(w, r) out, err := s.repeaterInfoFor(pk, u) if err != nil { log.Printf("[users] repeater info %s: %v", pk, err) @@ -173,6 +176,10 @@ type repeaterEditRequest struct { Status string `json:"status"` Power string `json:"power"` Notes string `json:"notes"` + // BaseRevision makes the save conditional: it must be the stored + // revision (0: no details saved yet). nil saves unconditionally, as the + // browser editor does. + BaseRevision *int64 `json:"baseRevision"` } func fmtFloat(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) } @@ -205,6 +212,15 @@ func repeaterEditDiff(prev *users.RepeaterInfo, next users.RepeaterEdit) map[str return out } +// withVia marks an audit detail written through a device token, so admins can +// tell app writes from browser ones. +func withVia(detail map[string]string, sess *users.Session) map[string]string { + if sess != nil && sess.Kind == users.SessionKindDevice { + detail["via"] = "device" + } + return detail +} + // repeaterTarget applies the per-user rate limit and normalises the pubkey; // with needKnown it also requires a known repeater in the analyzer DB. ok // false means the error answer is already written. @@ -245,7 +261,7 @@ func (s *Server) writeRepeaterInfo(w http.ResponseWriter, pk string, u *users.Us writeJSON(w, out) } -func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { +func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) { pk, ok := s.repeaterTarget(w, r, u, true) if !ok { return @@ -254,6 +270,10 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u if !decodeJSON(w, r, &req) { return } + if req.BaseRevision != nil && *req.BaseRevision < 0 { + writeError(w, http.StatusBadRequest, "baseRevision must not be negative") + return + } can, err := s.auth.st.CanEditRepeater(u, pk) if err != nil { log.Printf("[users] repeater permission %s: %v", pk, err) @@ -286,11 +306,31 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u writeError(w, http.StatusInternalServerError, "internal error") return } - // An unchanged body writes nothing: updated_at and updated_by stay. The - // early read only decides that; the audit diff comes from the row the - // save replaced. + var curRev int64 + if cur != nil { + curRev = cur.Revision + } + // A conditional save from a stale base is refused even when it would + // change nothing: the client's copy is out of date either way. + if req.BaseRevision != nil && *req.BaseRevision != curRev { + s.writeRepeaterConflict(w, pk, u) + return + } + // An unchanged body writes nothing: updated_at, updated_by and the + // revision stay. The early read only decides that; the audit diff comes + // from the row the save replaced. if len(repeaterEditDiff(cur, edit)) > 0 { - prev, err := s.auth.st.SaveRepeaterInfo(u.ID, pk, edit) + var prev *users.RepeaterInfo + if req.BaseRevision != nil { + prev, err = s.auth.st.SaveRepeaterInfoAt(u.ID, pk, edit, *req.BaseRevision) + } else { + prev, err = s.auth.st.SaveRepeaterInfo(u.ID, pk, edit) + } + if errors.Is(err, users.ErrRepeaterConflict) { + // Another save landed between the read above and this one. + s.writeRepeaterConflict(w, pk, u) + return + } if err != nil { if writeValidation(w, err) { return @@ -301,12 +341,24 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u } diff := repeaterEditDiff(prev, edit) diff["pubkey"] = pk - s.auth.auditAsync(idPtr(u.ID), "repeater.edit", nil, diff) + s.auth.auditAsync(idPtr(u.ID), "repeater.edit", nil, withVia(diff, sess)) } s.writeRepeaterInfo(w, pk, u) } -func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { +// writeRepeaterConflict answers 409 with the stored details, so the client +// can merge and retry from their revision without another read. +func (s *Server) writeRepeaterConflict(w http.ResponseWriter, pk string, u *users.User) { + out, err := s.repeaterInfoFor(pk, u) + if err != nil { + log.Printf("[users] repeater info %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + writeJSONStatus(w, http.StatusConflict, out) +} + +func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) { pk, ok := s.repeaterTarget(w, r, u, true) if !ok { return @@ -318,12 +370,12 @@ func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u * return } if added { - s.auth.auditAsync(idPtr(u.ID), "repeater.claim", idPtr(u.ID), map[string]string{"pubkey": pk}) + s.auth.auditAsync(idPtr(u.ID), "repeater.claim", idPtr(u.ID), withVia(map[string]string{"pubkey": pk}, sess)) } s.writeRepeaterInfo(w, pk, u) } -func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { +func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) { pk, ok := s.repeaterTarget(w, r, u, false) if !ok { return @@ -338,7 +390,7 @@ func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u writeError(w, http.StatusInternalServerError, "internal error") return } - s.auth.auditAsync(idPtr(u.ID), "repeater.unclaim", idPtr(u.ID), map[string]string{"pubkey": pk}) + s.auth.auditAsync(idPtr(u.ID), "repeater.unclaim", idPtr(u.ID), withVia(map[string]string{"pubkey": pk}, sess)) s.writeRepeaterInfo(w, pk, u) } diff --git a/cmd/server/repeater_lookup.go b/cmd/server/repeater_lookup.go index fb850dff2..569ca7dac 100644 --- a/cmd/server/repeater_lookup.go +++ b/cmd/server/repeater_lookup.go @@ -3,6 +3,7 @@ package main import ( "database/sql" "errors" + "strings" ) // RepeaterKnown reports whether pubkey (lowercase) is a known node, and @@ -31,3 +32,40 @@ func (db *DB) RepeaterKnown(pubkey string) (found bool, isRepeater bool, err err } return false, false, nil } + +// InactiveNodeBasics reads name, role and last_seen of the given pubkeys +// from inactive_nodes (nodes retention moved there), keyed by lowercase +// pubkey. Empty when the table does not exist. Read-only. +func (db *DB) InactiveNodeBasics(pubkeys []string) (map[string]notifyNode, error) { + out := make(map[string]notifyNode, len(pubkeys)) + if !db.inactiveNodesPresent() { + return out, nil + } + for i := 0; i < len(pubkeys); i += notifyNodeChunk { + chunk := pubkeys[i:min(i+notifyNodeChunk, len(pubkeys))] + args := make([]any, len(chunk)) + for j, pk := range chunk { + args[j] = pk + } + rows, err := db.conn.Query(`SELECT public_key, COALESCE(name, ''), COALESCE(role, ''), COALESCE(last_seen, '') + FROM inactive_nodes WHERE public_key IN (`+sqlPlaceholders(len(chunk))+`)`, args...) + if err != nil { + return nil, err + } + for rows.Next() { + var n notifyNode + if err := rows.Scan(&n.Pubkey, &n.Name, &n.Role, &n.LastSeen); err != nil { + rows.Close() + return nil, err + } + n.Pubkey = strings.ToLower(n.Pubkey) + out[n.Pubkey] = n + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + } + return out, nil +} diff --git a/cmd/server/repeater_revision_test.go b/cmd/server/repeater_revision_test.go new file mode 100644 index 000000000..93cd6c4a6 --- /dev/null +++ b/cmd/server/repeater_revision_test.go @@ -0,0 +1,164 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +func editAt(base int64, fields map[string]any) map[string]any { + out := map[string]any{"baseRevision": base} + for k, v := range fields { + out[k] = v + } + return out +} + +func TestRepeaterRevisionOnReads(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if got := decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil)); got.Revision != 0 { + t.Fatalf("revision without details = %d, want 0", got.Revision) + } + got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "a"}, as(alice))) + if got.Revision != 1 { + t.Fatalf("revision after the first save = %d", got.Revision) + } + // Claims are not details: they leave the revision alone. + got = decode[repeaterInfoJSON](t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice))) + if got.Revision != 1 { + t.Fatalf("revision after a claim = %d", got.Revision) + } + list := decode[repeaterInfoListJSON](t, f.do("GET", "/api/repeaters/info", nil)) + if len(list.Repeaters) != 1 || list.Repeaters[0].Revision != 1 { + t.Fatalf("list = %+v", list) + } +} + +// Two clients start from the same copy: the first save wins, the second gets +// 409 with what is stored now and changes nothing. +func TestRepeaterEditBaseRevisionConflict(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + bob := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit) + + // First edit of a repeater with no details yet. + w := f.do("PUT", repPath(rpkA, "info"), editAt(0, map[string]any{"notes": "from Alice"}), as(alice)) + expectStatus(t, w, 200) + if got := decode[repeaterInfoJSON](t, w); got.Revision != 1 || got.Notes != "from Alice" { + t.Fatalf("Alice's save = %+v", got) + } + w = f.do("PUT", repPath(rpkA, "info"), editAt(0, map[string]any{"notes": "from Bob"}), bearer(bob)) + expectStatus(t, w, http.StatusConflict) + got := decode[repeaterInfoJSON](t, w) + if got.Revision != 1 || got.Notes != "from Alice" || got.CanEdit == nil || !*got.CanEdit { + t.Fatalf("409 body = %+v, want the stored details with caller fields", got) + } + // Bob merges and retries from the revision the 409 gave him. + w = f.do("PUT", repPath(rpkA, "info"), editAt(got.Revision, map[string]any{"notes": "from Alice\nand Bob"}), bearer(bob)) + expectStatus(t, w, 200) + if got := decode[repeaterInfoJSON](t, w); got.Revision != 2 || got.UpdatedBy == nil || *got.UpdatedBy != "Bob" { + t.Fatalf("Bob's retry = %+v", got) + } + // Alice's copy is now stale, even for a body that would change nothing. + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), editAt(1, map[string]any{"notes": "from Alice\nand Bob"}), as(alice)), http.StatusConflict) + // One audit row per accepted save; the refused ones wrote none. + if rows := auditOf(t, f, alice.me.ID, "repeater.edit"); len(rows) != 1 { + t.Fatalf("Alice's edit audit rows = %d, want 1", len(rows)) + } +} + +// Without baseRevision a save is unconditional, as the browser editor sends it. +func TestRepeaterEditWithoutBaseRevision(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + for i, notes := range []string{"one", "two"} { + w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": notes}, as(alice)) + expectStatus(t, w, 200) + if got := decode[repeaterInfoJSON](t, w); got.Revision != int64(i+1) { + t.Fatalf("save %d revision = %d", i+1, got.Revision) + } + } + // An unchanged save writes nothing, so the revision stays. + if got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "two"}, as(alice))); got.Revision != 2 { + t.Fatalf("revision after an unchanged save = %d", got.Revision) + } + if got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), editAt(2, map[string]any{"notes": "two"}), as(alice))); got.Revision != 2 { + t.Fatalf("revision after an unchanged conditional save = %d", got.Revision) + } +} + +func TestRepeaterEditBaseRevisionValidation(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + w := f.do("PUT", repPath(rpkA, "info"), editAt(-1, map[string]any{"notes": "x"}), as(alice)) + expectStatus(t, w, 400) + if !strings.Contains(w.Body.String(), "baseRevision") { + t.Fatalf("body = %s", w.Body.String()) + } + // Permission is checked before the revision: no 409 leaks the details. + alicePK := rpkA + expectStatus(t, f.do("POST", repPath(alicePK, "claim"), nil, as(alice)), 200) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), editAt(7, map[string]any{"notes": "y"}), as(bob)), 403) +} + +// Two requests from the same revision at the same time: one 200, one 409. +func TestRepeaterEditConcurrentSaves(t *testing.T) { + f := repeaterFixture(t) + f.registerAndActivate(t, "alice@example.org", "Alice", pw) + f.registerAndActivate(t, "bob@example.org", "Bob", pw) + tokens := []string{ + f.scopedToken(t, "alice@example.org", "Alice", deviceScopeRepeaterEdit), + f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit), + } + for _, base := range []int64{0, 1} { + codes := make([]int, len(tokens)) + var wg sync.WaitGroup + for i, tok := range tokens { + wg.Add(1) + go func(i int, tok string) { + defer wg.Done() + body := editAt(base, map[string]any{"notes": "client " + string(rune('A'+i)) + " at " + string(rune('0'+base))}) + codes[i] = f.serve("PUT", repPath(rpkA, "info"), body, bearer(tok)).Code + }(i, tok) + } + wg.Wait() + f.srv.auth.waitAudits() + ok, conflict := 0, 0 + for _, c := range codes { + switch c { + case 200: + ok++ + case http.StatusConflict: + conflict++ + } + } + if ok != 1 || conflict != 1 { + t.Fatalf("base %d: codes %v, want one 200 and one 409", base, codes) + } + } + if info, err := f.st.GetRepeaterInfo(rpkA); err != nil || info.Revision != 2 { + t.Fatalf("stored = %+v, %v", info, err) + } +} + +func TestClientConfigAnnouncesRepeaterTokens(t *testing.T) { + srv, router := setupTestServer(t) + get := func() string { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil)) + return w.Body.String() + } + if strings.Contains(get(), "repeaterTokens") { + t.Fatal("repeaterTokens present with user management off") + } + a, _ := newTestAuthService(t) + srv.auth = a + if !strings.Contains(get(), `"repeaterTokens":true`) { + t.Fatalf("repeaterTokens missing with user management on: %s", get()) + } +} diff --git a/cmd/server/routes.go b/cmd/server/routes.go index b89044762..3646396a7 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -590,7 +590,7 @@ func (s *Server) clientUserManagement() *ClientUserManagement { if s.auth == nil { return nil } - return &ClientUserManagement{Enabled: true, ChannelProposals: s.auth.set.proposals.enabled, Notifications: s.auth.notify != nil, CompanionLinking: true, ObserverLogins: s.auth.set.observerLogins.enabled} + return &ClientUserManagement{Enabled: true, ChannelProposals: s.auth.set.proposals.enabled, Notifications: s.auth.notify != nil, CompanionLinking: true, ObserverLogins: s.auth.set.observerLogins.enabled, RepeaterTokens: true} } func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) { @@ -2441,6 +2441,12 @@ func (s *Server) handleNodeAnalytics(w http.ResponseWriter, r *http.Request) { writeError(w, 404, "Not found") return } + if s.cfg.ClientRxCoverageEnabled() { + // SQL, after GetNodeAnalytics has released s.mu (#2146). + _, pm := s.store.getCachedNodesAndPM() + lat, lon := nodePosition(result.Node) + result.MobileReceptions = s.mobileReceptionsSummary(pubkey, result.TimeRange.From, lat, lon, pm) + } writeJSON(w, result) return } @@ -2580,7 +2586,6 @@ func (s *Server) handleAnalyticsTopology(w http.ResponseWriter, r *http.Request) HopDistribution: []TopologyHopDist{}, TopRepeaters: []TopRepeater{}, TopPairs: []TopPair{}, - HopsVsSnr: []HopsVsSnr{}, Observers: []ObserverRef{}, PerObserverReach: map[string]*ObserverReach{}, MultiObsNodes: []MultiObsNode{}, diff --git a/cmd/server/routes_test.go b/cmd/server/routes_test.go index 970041050..2c300d18e 100644 --- a/cmd/server/routes_test.go +++ b/cmd/server/routes_test.go @@ -1244,6 +1244,11 @@ func TestAnalyticsTopology(t *testing.T) { if body["uniqueNodes"] == nil { t.Error("expected uniqueNodes") } + // The SNR on a transmission is the observer's reception of the last + // hop, unrelated to the path length, so "Hops vs SNR" measured nothing. + if _, ok := body["hopsVsSnr"]; ok { + t.Error("topology still reports hopsVsSnr") + } } func TestAnalyticsChannels(t *testing.T) { diff --git a/cmd/server/rx_coverage.go b/cmd/server/rx_coverage.go index c5b98bf04..3da886719 100644 --- a/cmd/server/rx_coverage.go +++ b/cmd/server/rx_coverage.go @@ -1,7 +1,9 @@ package main import ( + "database/sql" "encoding/json" + "math" "net/http" "sort" "strconv" @@ -380,3 +382,103 @@ func (s *Server) handleNodeRxCoverage(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(fc) } + +// MobileReceptionsSummary sums up the mobile client receptions of one node +// for the node analytics page. MedianSNR is nil when no row carried an SNR, +// MaxDistanceKm when the node has no position. +type MobileReceptionsSummary struct { + Receptions int `json:"receptions"` + Receivers int `json:"receivers"` + MedianSNR *float64 `json:"medianSnr"` + MaxDistanceKm *float64 `json:"maxDistanceKm"` +} + +// uniqueHeardKeyCandidates is coverageHeardKeyCandidates for the analytics +// summary: the 2- and 3-byte prefixes count only when this node is the one +// known node holding them and no retired repeater shares them, the same +// rule the direct-heard pass applies to path hops. The full key and the +// 8-byte discover prefix always count. +func uniqueHeardKeyCandidates(pubkey string, pm *prefixMap) []string { + pk := strings.ToLower(pubkey) + out := make([]string, 0, 4) + for _, c := range coverageHeardKeyCandidates(pk) { + if len(c) == 4 || len(c) == 6 { + if pm == nil { + continue + } + if _, retired := pm.retired[c]; retired { + continue + } + if cands := pm.m[c]; len(cands) != 1 || !strings.EqualFold(cands[0].PublicKey, pk) { + continue + } + } + out = append(out, c) + } + return out +} + +// mobileReceptionsSummary reads this node's mobile receptions since fromISO. +// SQL on the read-only connection, so callers run it outside s.mu (#2146). +// nil when there are none or the query fails. +func (s *Server) mobileReceptionsSummary(pubkey, fromISO string, nodeLat, nodeLon *float64, pm *prefixMap) *MobileReceptionsSummary { + if s.db == nil || s.db.conn == nil { + return nil + } + cands := uniqueHeardKeyCandidates(pubkey, pm) + args := make([]interface{}, 0, len(cands)+1) + for _, c := range cands { + args = append(args, c) + } + args = append(args, fromISO) + rows, err := s.db.conn.Query(` + SELECT snr, lat, lon, rx_pubkey FROM client_receptions + WHERE heard_key IN (`+sqlPlaceholders(len(cands))+`) AND rx_at >= ?`, args...) + if err != nil { + return nil + } + defer rows.Close() + var sum MobileReceptionsSummary + var snrs []float64 + receivers := map[string]struct{}{} + maxKm := -1.0 + for rows.Next() { + var snr, lat, lon sql.NullFloat64 + var rx sql.NullString + if rows.Scan(&snr, &lat, &lon, &rx) != nil { + return nil + } + sum.Receptions++ + receivers[rx.String] = struct{}{} + if snr.Valid { + snrs = append(snrs, snr.Float64) + } + if nodeLat != nil && nodeLon != nil && lat.Valid && lon.Valid { + maxKm = math.Max(maxKm, haversineKm(*nodeLat, *nodeLon, lat.Float64, lon.Float64)) + } + } + if rows.Err() != nil || sum.Receptions == 0 { + return nil + } + sum.Receivers = len(receivers) + if len(snrs) > 0 { + sort.Float64s(snrs) + m := snrs[(len(snrs)-1)/2] + sum.MedianSNR = &m + } + if maxKm >= 0 { + sum.MaxDistanceKm = &maxKm + } + return &sum +} + +// nodePosition reads lat/lon from a node row; nil when absent or 0,0 +// (a node that never sent a position). +func nodePosition(node map[string]interface{}) (lat, lon *float64) { + la, okLa := node["lat"].(float64) + lo, okLo := node["lon"].(float64) + if !okLa || !okLo || (la == 0 && lo == 0) { + return nil, nil + } + return &la, &lo +} diff --git a/cmd/server/rx_coverage_analytics_test.go b/cmd/server/rx_coverage_analytics_test.go new file mode 100644 index 000000000..1c76eb89e --- /dev/null +++ b/cmd/server/rx_coverage_analytics_test.go @@ -0,0 +1,106 @@ +package main + +import ( + "math" + "net/http/httptest" + "strings" + "testing" +) + +const ( + rxSumPK = "bb11220000000000000000000000000000000000000000000000000000000001" + rxSumTwin = "bb11ff0000000000000000000000000000000000000000000000000000000002" + rxSumOther = "5a5a5a0000000000000000000000000000000000000000000000000000000003" +) + +func rxSumPM() *prefixMap { + return buildPrefixMap([]nodeInfo{ + {PublicKey: rxSumPK, Role: "repeater"}, + {PublicKey: rxSumTwin, Role: "repeater"}, + {PublicKey: rxSumOther, Role: "repeater"}, + }) +} + +func TestUniqueHeardKeyCandidates(t *testing.T) { + got := uniqueHeardKeyCandidates(rxSumPK, rxSumPM()) + want := []string{rxSumPK, rxSumPK[:16], "bb1122"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("got %v, want %v (the shared bb11 must be left out)", got, want) + } + + pm := rxSumPM() + pm.retired = map[string]struct{}{"5a5a": {}} + got = uniqueHeardKeyCandidates(rxSumOther, pm) + want = []string{rxSumOther, rxSumOther[:16], "5a5a5a"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("retired prefix: got %v, want %v", got, want) + } + + // A companion is no path candidate, so a prefix whose only candidate is + // another node must not be taken as the companion's. + comp := "5a5a5a1100000000000000000000000000000000000000000000000000000009" + got = uniqueHeardKeyCandidates(comp, rxSumPM()) + want = []string{comp, comp[:16]} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("companion: got %v, want %v", got, want) + } +} + +func TestMobileReceptionsSummary(t *testing.T) { + db := seedCoverageDB(t) + mustExecDB(t, db, `INSERT INTO client_receptions (rx_pubkey,heard_key,heard_keylen,snr,lat,lon,rx_at,ingested_at,src) VALUES + ('rx1','bb1122',3,-3,51.00,4.00,'2026-11-10T10:00:00Z','x','rxlog'), + ('rx1','`+rxSumPK[:16]+`',8,1,51.10,4.00,'2026-11-10T11:00:00Z','x','discover'), + ('rx2','bb1122',3,4,51.00,4.00,'2026-11-11T10:00:00Z','x','rxlog'), + ('rx3','bb11',2,9,52.00,4.00,'2026-11-11T10:00:00Z','x','rxlog'), + ('rx4','bb1122',3,9,52.00,4.00,'2026-11-01T10:00:00Z','x','rxlog')`) + srv := &Server{db: db, cfg: &Config{ClientRxCoverage: &ClientRxCoverageConfig{Enabled: true}}} + lat, lon := 51.0, 4.0 + + got := srv.mobileReceptionsSummary(rxSumPK, "2026-11-05T00:00:00Z", &lat, &lon, rxSumPM()) + if got == nil || got.Receptions != 3 || got.Receivers != 2 || got.MedianSNR == nil || *got.MedianSNR != 1 { + t.Fatalf("summary = %+v, want 3 receptions, 2 receivers, median 1", got) + } + if got.MaxDistanceKm == nil || math.Abs(*got.MaxDistanceKm-11.12) > 0.05 { + t.Fatalf("max distance = %v, want about 11.12 km", got.MaxDistanceKm) + } + + got = srv.mobileReceptionsSummary(rxSumPK, "2026-11-05T00:00:00Z", nil, nil, rxSumPM()) + if got == nil || got.MaxDistanceKm != nil { + t.Fatalf("no node position: summary = %+v, want no distance", got) + } + + if got = srv.mobileReceptionsSummary(rxSumTwin, "2026-11-05T00:00:00Z", nil, nil, rxSumPM()); got != nil { + t.Fatalf("node without receptions: summary = %+v, want nil", got) + } +} + +func TestNodeAnalytics_MobileOmittedWhenFeatureOff(t *testing.T) { + _, router := setupTestServer(t) + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/nodes/aabbccdd11223344/analytics?days=7", nil)) + if w.Code != 200 { + t.Fatalf("status %d", w.Code) + } + if strings.Contains(w.Body.String(), "mobileReceptions") { + t.Fatal("mobileReceptions present while clientRxCoverage is off") + } +} + +func TestNodeAnalytics_MobileReceptionsWhenFeatureOn(t *testing.T) { + srv, router := setupTestServer(t) + srv.cfg.ClientRxCoverage = &ClientRxCoverageConfig{Enabled: true} + mustExecDB(t, srv.db, `CREATE TABLE client_receptions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, rx_pubkey TEXT, heard_key TEXT, heard_keylen INTEGER, + rssi INTEGER, snr REAL, lat REAL, lon REAL, pos_acc_m REAL, rx_at TEXT, ingested_at TEXT, src TEXT)`) + mustExecDB(t, srv.db, `INSERT INTO client_receptions (rx_pubkey,heard_key,heard_keylen,snr,lat,lon,rx_at,ingested_at,src) + VALUES ('rx1','aabbccdd11223344',32,-2,51.0,4.0,'2099-01-01T00:00:00Z','x','rxlog')`) + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/nodes/aabbccdd11223344/analytics?days=7", nil)) + if w.Code != 200 { + t.Fatalf("status %d", w.Code) + } + if !strings.Contains(w.Body.String(), `"mobileReceptions":{"receptions":1,"receivers":1,"medianSnr":-2`) { + t.Fatalf("mobileReceptions missing or wrong: %s", w.Body.String()) + } +} diff --git a/cmd/server/scope_audit.go b/cmd/server/scope_audit.go index a76b8805d..8120f3623 100644 --- a/cmd/server/scope_audit.go +++ b/cmd/server/scope_audit.go @@ -405,7 +405,7 @@ func (db *DB) observerRegionClause(q interface { } col, obsCol := "o.observer_id", "id" if db.isV3 { - col, obsCol = "o.observer_idx", "rowid" + col, obsCol = "o.observer_idx", "idx" } placeholders := strings.TrimSuffix(strings.Repeat("?,", len(codes)), ",") args := make([]interface{}, len(codes)) diff --git a/cmd/server/scope_audit_region_test.go b/cmd/server/scope_audit_region_test.go index 80bc09d92..39a6944c3 100644 --- a/cmd/server/scope_audit_region_test.go +++ b/cmd/server/scope_audit_region_test.go @@ -22,9 +22,9 @@ func setupScopeRegionServer(t *testing.T) (*Server, *mux.Router) { t.Helper() srv, router := setupScopeAuditServer(t) for _, ddl := range []string{ - `CREATE TABLE observers (id TEXT, name TEXT, iata TEXT)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT)`, `ALTER TABLE observations ADD COLUMN observer_idx INTEGER`, - `INSERT INTO observers (rowid, id, name, iata) VALUES (1, 'obs-sfo', 'San Francisco', 'SFO'), (2, 'obs-bru', 'Brussels', 'BRU')`, + `INSERT INTO observers (idx, id, name, iata) VALUES (1, 'obs-sfo', 'San Francisco', 'SFO'), (2, 'obs-bru', 'Brussels', 'BRU')`, } { if _, err := srv.db.conn.Exec(ddl); err != nil { t.Fatal(err) @@ -154,7 +154,7 @@ func TestScopeAudit_RegionWithNoObserversMatchesNothing(t *testing.T) { func TestScopeTransport_RegionOnV2Schema(t *testing.T) { srv, router := setupScopeAuditServer(t) for _, ddl := range []string{ - `CREATE TABLE observers (id TEXT, name TEXT, iata TEXT)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT)`, `ALTER TABLE observations ADD COLUMN observer_id TEXT`, `INSERT INTO observers (id, name, iata) VALUES ('obs-sfo', 'San Francisco', 'SFO'), ('obs-bru', 'Brussels', 'BRU')`, } { diff --git a/cmd/server/scope_stats_region_index_test.go b/cmd/server/scope_stats_region_index_test.go index 57a96e080..42b71a621 100644 --- a/cmd/server/scope_stats_region_index_test.go +++ b/cmd/server/scope_stats_region_index_test.go @@ -46,7 +46,7 @@ func scopeStatsFixtureDB(tb testing.TB, numTx int) *DB { `CREATE INDEX idx_tx_scope_name ON transmissions(scope_name) WHERE scope_name IS NOT NULL`, `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_id TEXT, observer_name TEXT, direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT)`, - `CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`, + `CREATE TABLE observers (idx INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, name TEXT, iata TEXT, inactive INTEGER)`, `CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, last_seen TEXT, first_seen TEXT, frequency REAL)`, } { diff --git a/cmd/server/site_url.go b/cmd/server/site_url.go new file mode 100644 index 000000000..759157135 --- /dev/null +++ b/cmd/server/site_url.go @@ -0,0 +1,92 @@ +package main + +import ( + "bytes" + "html" + "log" + "net/http" + "regexp" + "strings" +) + +// siteURLPlaceholder marks where a top-level page needs the instance's public +// URL: index.html's og:url (configured URL only, see withoutOGURL), og:image +// and twitter:image, which link previews (Discord, Slack, Facebook) require to +// be absolute. +const siteURLPlaceholder = "__CORESCOPE_URL__" + +// siteURLEnv is the environment variable that sets the public URL. The docker +// compose files pass it through; unset, og:url is left out and the image +// links are filled in with the origin the request reached. +const siteURLEnv = "CORESCOPE_URL" + +var ( + // An origin with an optional base path, nothing that could leave an HTML + // attribute value. + configuredSiteURLRe = regexp.MustCompile(`^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~/-]*)?$`) + // A Host header: a DNS name or IPv4 address, or a bracketed IPv6 one, + // with an optional port. + requestHostRe = regexp.MustCompile(`^([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$`) + // The og:url line of index.html, as scripts/static/build.sh drops it. + ogURLTagRe = regexp.MustCompile(`[ \t]*(\r?\n)?`) +) + +// resolveConfiguredSiteURL validates CORESCOPE_URL. It returns the URL with +// any trailing slash trimmed, or "" when it is unset or invalid; an invalid +// value is logged and the request's own origin is used instead. +func resolveConfiguredSiteURL(raw string) string { + v := strings.TrimRight(strings.TrimSpace(raw), "/") + if v == "" { + return "" + } + if !configuredSiteURLRe.MatchString(v) { + log.Printf("[static] warning: %s=%q is not an http(s)://host[:port][/path] URL; using each request's own origin", siteURLEnv, raw) + return "" + } + return v +} + +// withoutOGURL drops the og:url tag, which a page keeps only with a configured +// URL: the fragment of a deep link never reaches the server, so og:url can +// only name the site root, and some platforms open it from a preview (#1890). +func withoutOGURL(page []byte) []byte { + return ogURLTagRe.ReplaceAll(page, nil) +} + +// requestOrigin is scheme://host of the URL the client asked for. The host is +// the Host header only (the bundled Caddy passes it through): a CDN caches by +// Host but not by X-Forwarded-Host, so believing the latter would let one +// request choose the host for later visitors. The scheme is TLS, else +// X-Forwarded-Proto, which can only say http or https. A Host that fails +// requestHostRe gives "" and the page's URLs become root-relative. +func requestOrigin(r *http.Request) string { + scheme := "http" + if r.TLS != nil { + scheme = "https" + } else if p := strings.ToLower(firstHeaderValue(r.Header.Get("X-Forwarded-Proto"))); p == "https" || p == "http" { + scheme = p + } + host := r.Host + if !requestHostRe.MatchString(host) { + return "" + } + return scheme + "://" + strings.ToLower(host) +} + +// firstHeaderValue is the first entry of a comma-separated header: the one the +// outermost proxy, nearest the client, wrote. +func firstHeaderValue(v string) string { + if i := strings.IndexByte(v, ','); i >= 0 { + v = v[:i] + } + return strings.TrimSpace(v) +} + +// withSiteURL fills the placeholder in body with the request's origin, when +// no URL is configured. A page without one comes back as it is, without a copy. +func withSiteURL(body []byte, r *http.Request) []byte { + if !bytes.Contains(body, []byte(siteURLPlaceholder)) { + return body + } + return bytes.ReplaceAll(body, []byte(siteURLPlaceholder), []byte(html.EscapeString(requestOrigin(r)))) +} diff --git a/cmd/server/site_url_test.go b/cmd/server/site_url_test.go new file mode 100644 index 000000000..f1cc7dc87 --- /dev/null +++ b/cmd/server/site_url_test.go @@ -0,0 +1,225 @@ +package main + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +const siteURLTestPage = `` + "\n" + + ` ` + "\n" + + `` + + `` + +func newSiteURLHandler(t *testing.T, siteURL string) http.Handler { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte(siteURLTestPage), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "area-map.html"), []byte(`x`), 0644); err != nil { + t.Fatal(err) + } + return spaHandler(dir, http.FileServer(http.Dir(dir)), siteURL) +} + +func serveSiteURL(h http.Handler, path string, mod func(*http.Request)) string { + req := httptest.NewRequest("GET", path, nil) + if mod != nil { + mod(req) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + return w.Body.String() +} + +func TestSiteURLConfigured(t *testing.T) { + h := newSiteURLHandler(t, "https://analyzer.example.org/") + for _, path := range []string{"/", "/index.html", "/some/spa/route", "/area-map.html"} { + body := serveSiteURL(h, path, func(r *http.Request) { + // A configured URL wins over whatever the request says. + r.Host = "other.example.net" + r.Header.Set("X-Forwarded-Host", "evil.example.com") + }) + if strings.Contains(body, siteURLPlaceholder) { + t.Errorf("%s: placeholder left: %s", path, body) + } + if strings.Contains(body, "other.example.net") || strings.Contains(body, "evil.example.com") { + t.Errorf("%s: request host used despite CORESCOPE_URL: %s", path, body) + } + if !strings.Contains(body, `"https://analyzer.example.org/`) { + t.Errorf("%s: configured URL missing (trailing slash trimmed): %s", path, body) + } + } + body := serveSiteURL(h, "/", nil) + if !strings.Contains(body, ``) { + t.Errorf("og:url missing with CORESCOPE_URL set: %s", body) + } + if !strings.Contains(body, `content="https://analyzer.example.org/og-image.png"`) { + t.Errorf("og:image not absolute on the configured URL: %s", body) + } + if strings.Contains(body, "__BUST__") { + t.Errorf("__BUST__ no longer replaced: %s", body) + } +} + +func TestSiteURLFromRequest(t *testing.T) { + h := newSiteURLHandler(t, "") + cases := []struct { + name string + mod func(*http.Request) + want string + }{ + {"plain host", func(r *http.Request) { r.Host = "mesh.example.org:8080" }, "http://mesh.example.org:8080"}, + {"host lowercased", func(r *http.Request) { r.Host = "Mesh.Example.ORG" }, "http://mesh.example.org"}, + {"direct TLS", func(r *http.Request) { r.Host = "mesh.example.org"; r.TLS = &tls.ConnectionState{} }, "https://mesh.example.org"}, + {"proxy scheme", func(r *http.Request) { + r.Host = "mesh.example.org" + r.Header.Set("X-Forwarded-Proto", "https") + }, "https://mesh.example.org"}, + {"proxy chain: first scheme", func(r *http.Request) { + r.Host = "mesh.example.org" + r.Header.Set("X-Forwarded-Proto", "HTTPS, http") + }, "https://mesh.example.org"}, + // Not part of a cache key, so one request could set it for the next. + {"X-Forwarded-Host ignored", func(r *http.Request) { + r.Host = "mesh.example.org" + r.Header.Set("X-Forwarded-Host", "evil.example.com") + }, "http://mesh.example.org"}, + {"unknown proto ignored", func(r *http.Request) { + r.Host = "mesh.example.org" + r.Header.Set("X-Forwarded-Proto", "javascript") + }, "http://mesh.example.org"}, + {"IPv6 host", func(r *http.Request) { r.Host = "[::1]:3000" }, "http://[::1]:3000"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + body := serveSiteURL(h, "/", c.mod) + if !strings.Contains(body, `content="`+c.want+`/og-image.png"`) { + t.Errorf("want %s, got %s", c.want, body) + } + }) + } + // Tool pages are filled in the same way, and the page served to one + // request is not left holding the previous request's origin. + if body := serveSiteURL(h, "/area-map.html", func(r *http.Request) { r.Host = "a.example.org" }); !strings.Contains(body, `href="http://a.example.org/"`) { + t.Errorf("area-map.html: %s", body) + } + if body := serveSiteURL(h, "/", func(r *http.Request) { r.Host = "b.example.org" }); !strings.Contains(body, "http://b.example.org/og-image.png") || strings.Contains(body, "a.example.org") { + t.Errorf("origin leaked between requests: %s", body) + } +} + +func TestSiteURLForgedHostCannotInjectMarkup(t *testing.T) { + h := newSiteURLHandler(t, "") + body := serveSiteURL(h, "/", func(r *http.Request) { + r.Host = "mesh.example.org" + r.Header.Set("X-Forwarded-Host", `x">`) + }) + if strings.Contains(body, " + + diff --git a/public/live.js b/public/live.js index ba49ac0b4..7806f4b96 100644 --- a/public/live.js +++ b/public/live.js @@ -18,6 +18,13 @@ function statusGreen() { return cssVar('--status-green') || '#22c55e'; } let map, wsHandler, nodesLayer, pathsLayer, animLayer, heatLayer, geoFilterLayer, clickablePathsLayer; + let _liveAutoTiles = null; // MC_attachAutoTiles handle for the basemap + // Bumped by init() and destroy(). Every await in init() (and loadNodes()) + // re-checks it: navigating away mid-await used to resume on a destroyed page + // and call map.on() on the nulled map, or build a map in the next page's DOM. + let pageGen = 0; + // AreaFilter subscription, removed in destroy() so visits don't accumulate listeners. + let _areaChangeHandler = null; // New animation canvas let animCanvas, animCtx; let _dprMedia = null; @@ -1267,6 +1274,7 @@ } async function init(app) { + const gen = ++pageGen; app.innerHTML = `
@@ -1425,6 +1433,7 @@ if (Array.isArray(mapCfg.center) && mapCfg.center.length === 2) mapCenter = mapCfg.center; if (typeof mapCfg.zoom === 'number') mapZoom = mapCfg.zoom; } catch { } + if (gen !== pageGen) return; // #1709: URL hash lat/lon/zoom is the highest-precedence viewport source. // Applied here so the very first setView() lands at the requested viewport @@ -1570,51 +1579,12 @@ } _rebindDPRListener(); - const isDark = window.MC_isDarkTheme(); - // #1420 — multi-provider dark-tile picker. Light mode unchanged (live page). - let _liveDarkRefLayer = null; - // Single shared registry resolver (map-tile-providers.js loads before this - // file; there is deliberately no second fallback body here — AGENTS.md DRY). - function _liveResolveTile(dark) { - const r = window.MC_resolveTile(!!dark); - return { url: r.url, attribution: r.attribution, refUrl: r.refUrl, maxZoom: r.maxZoom }; - } - const liveAutoLayerGroup = L.layerGroup().addTo(map); - - function _liveSyncDarkTiles(dark) { - const r = _liveResolveTile(dark); - window.MC_updateTileLayer(tileLayer, liveAutoLayerGroup, r); - if (dark && r.refUrl) { - if (!_liveDarkRefLayer) { - _liveDarkRefLayer = L.tileLayer(r.refUrl, { maxZoom: r.maxZoom || 19, attribution: r.attribution }).addTo(liveAutoLayerGroup); - } else { - window.MC_updateTileLayer(_liveDarkRefLayer, liveAutoLayerGroup, { url: r.refUrl, maxZoom: r.maxZoom, attribution: r.attribution }); - } - } else if (_liveDarkRefLayer) { - liveAutoLayerGroup.removeLayer(_liveDarkRefLayer); - _liveDarkRefLayer = null; - } - if (typeof window.MC_applyTileFilter === 'function') window.MC_applyTileFilter(); - // #1420 parity with map.js — refresh visible attribution credit after provider swap. - // Make sure the map is loaded before trying to update the ui - if (map && map.attributionControl) { - try { map.attributionControl._update && map.attributionControl._update(); } catch (_) {} - } - } - const _liveInitTile = _liveResolveTile(isDark); - let tileLayer = L.tileLayer(_liveInitTile.url, { maxZoom: _liveInitTile.maxZoom || 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); - if (isDark && _liveInitTile.refUrl) { - _liveDarkRefLayer = L.tileLayer(_liveInitTile.refUrl, { maxZoom: _liveInitTile.maxZoom || 19, attribution: _liveInitTile.attribution }).addTo(liveAutoLayerGroup); - } - if (typeof window.MC_applyTileFilter === 'function') window.MC_applyTileFilter(); - // Add Zoom Control L.control.zoom({ position: 'topright' }).addTo(map); - // Add Layer Control, passing 'topright' to put it on the right - if (typeof window.MC_createLayerControl === 'function') { - window.MC_createLayerControl(map, liveAutoLayerGroup, 'topright'); - } + // Shared theme-synced basemap; the provider picker goes on the right, + // after the zoom control. + _liveAutoTiles = window.MC_attachAutoTiles(map, { controlPosition: 'topright' }); // Add custom Leaflet Control for Fullscreen const LiveFullscreenControl = L.Control.extend({ @@ -1658,18 +1628,6 @@ - // Swap tiles when theme changes - const _themeObs = new MutationObserver(function () { - _liveSyncDarkTiles(window.MC_isDarkTheme()); - }); - _themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); - // #1420 — re-render on customizer change. - window.addEventListener('mc-tile-provider-changed', function (e) { - const dark = window.MC_isDarkTheme(); - if (e && e.detail && e.detail.type && e.detail.type !== (dark ? 'dark' : 'light')) return; - _liveSyncDarkTiles(dark); - }); - // #1485 — animations + trails need their own pane above markerPane. // PR #1334 moved node markers from L.circleMarker (overlayPane @ 400) // to L.marker+divIcon (markerPane @ 600); animations stayed in the @@ -1689,8 +1647,10 @@ injectSVGFilters(); AreaFilter.init(document.getElementById('liveAreaFilter')); - AreaFilter.onChange(function () { loadNodes(); }); + if (_areaChangeHandler) AreaFilter.offChange(_areaChangeHandler); + _areaChangeHandler = AreaFilter.onChange(function () { loadNodes(); }); await loadNodes(); + if (gen !== pageGen) return; // Build the heat layer only when the user wants it. It used to be built // unconditionally and torn down ~270 lines later, which was invisible // (no await in between, so no frame composited) but meant that any throw @@ -1925,6 +1885,7 @@ (async function () { try { const gf = await api('/config/geo-filter', { ttl: 3600 }); + if (gen !== pageGen) return; if (!gf || !gf.polygon || gf.polygon.length < 3) return; const geoColor = cssVar('--geo-filter-color') || '#3b82f6'; const latlngs = gf.polygon.map(function (p) { return [p[0], p[1]]; }); @@ -2642,7 +2603,7 @@ : `${escapeHtml(n.default_scope)}` }` : ''} ${hasLoc ? `Location${n.lat.toFixed(5)}, ${n.lon.toFixed(5)}` : ''} - ${stats.avgSnr != null ? `Avg SNR${stats.avgSnr.toFixed(1)} dB` : ''} + ${stats.avgSnr != null ? `Direct SNR${stats.avgSnr.toFixed(1)} dB` : ''} ${stats.avgHops != null ? `Avg Hops${stats.avgHops.toFixed(1)}` : ''} ${stats.totalTransmissions || stats.totalPackets ? `Total Packets${stats.totalTransmissions || stats.totalPackets}` : ''} `; @@ -2745,6 +2706,8 @@ } async function loadNodes(beforeTs) { + const gen = pageGen; + if (!map) return; try { const aqs = AreaFilter.areaQueryString(); // #1108 — honor region selector for visible map nodes unless @@ -2771,6 +2734,7 @@ }), loadLiveObservers(), ]); + if (gen !== pageGen) return; var now = Date.now(); // Time-scoped reload (VCR scrub/replay): reconcile against the existing // markers instead of tearing the layer down. addNodeMarker() already @@ -4628,6 +4592,9 @@ } function destroy() { + pageGen++; + if (_areaChangeHandler) { AreaFilter.offChange(_areaChangeHandler); _areaChangeHandler = null; } + if (AreaFilter.destroy) AreaFilter.destroy(); // #1514 S3 — drain onComplete callbacks BEFORE clearing the array. Audio // `onHop` hooks rely on these firing exactly once per queued animation; // previously destroy() dropped them silently when navigating away with @@ -4673,7 +4640,9 @@ RegionFilter.offChange(regionFilterChangeHandler); regionFilterChangeHandler = null; } - if (map) { map.remove(); map = null; } + if (window.RegionFilter && typeof RegionFilter.destroy === 'function') RegionFilter.destroy(); + if (_liveAutoTiles) { _liveAutoTiles.destroy(); _liveAutoTiles = null; } + if (map) { window.MC_safeRemoveMap(map); map = null; } if (_onResize) { window.removeEventListener('resize', _onResize); window.removeEventListener('orientationchange', _onResize); diff --git a/public/map-hillshade.js b/public/map-hillshade.js new file mode 100644 index 000000000..b24114c52 --- /dev/null +++ b/public/map-hillshade.js @@ -0,0 +1,215 @@ +/* map-hillshade.js — client-side hillshade overlay (#2428 map providers). + * + * Fetches Terrarium-encoded elevation PNG tiles (elevation m = + * R*256 + G + B/256 - 32768) and shades them on a canvas into + * semi-transparent relief that works over light, dark and satellite basemaps. + * + * window.MC_hillshadeShade(elev, w, h, zoom, lat, out) + * Pure kernel. elev: Float32Array (w*h metres), out: Uint8ClampedArray + * (w*h*4 RGBA). Horn gradient, light from the NW (azimuth 315°, altitude + * 45°). Each pixel is black (shadow) or white (highlight) with alpha equal + * to how far it is from the flat-terrain brightness, so flat ground is + * fully transparent. No-data (<= -500 m, incl. the Terrarium zero value + * -32768) is transparent. + * + * window.MC_createHillshadeLayer(opts) -> L.GridLayer + * opts { url, opacity = 0.35, maxZoom = 19, maxNativeZoom = 15, + * attribution, zIndex = 250, pane? } + * + * Edges: gradients use the tile's own pixels only (border rows/columns fall + * back to a one-sided difference). No neighbour tiles are fetched, so a faint + * 1px seam can show where two tiles meet on very rough terrain. + * + * Security (S6): crossOrigin is set before src; a host without CORS taints the + * canvas, getImageData throws, and the layer goes blank for good with a single + * console warning. Images that are not 256x256 or 512x512 are refused. + */ +(function () { + 'use strict'; + + var NODATA = -500; // at or below: ocean floor / no-data + var DEG = Math.PI / 180; + // Local refs keep global lookups out of the per-pixel loop. + var sqrt = Math.sqrt, exp = Math.exp; + // Light vector, azimuth 315° (NW), altitude 45°; x east, y north, z up. + var ALT = 45 * DEG, AZ = 315 * DEG; + var LX = Math.cos(ALT) * Math.sin(AZ); + var LY = Math.cos(ALT) * Math.cos(AZ); + var LZ = Math.sin(ALT); + // |brightness delta| -> alpha via 1 - e^(-GAIN*d): linear for gentle + // slopes, a soft knee instead of a hard clip so steep faces keep detail. + var GAIN = 2.4; + + // Vertical exaggeration: strong at low zoom, where a pixel spans hundreds of + // metres and real slopes average out, easing to 1 by zoom 14. It falls by + // well under 2x per zoom, so on-screen relief still grows with zoom. + function exaggeration(zoom) { + var e = Math.pow(2, (14 - zoom) * 0.35); + return e < 1 ? 1 : (e > 10 ? 10 : e); + } + + function hillshadeShade(elev, w, h, zoom, lat, out) { + var cosLat = Math.cos((Number(lat) || 0) * DEG); + if (!(cosLat > 0.01)) cosLat = 0.01; + var mpp = 156543.03392 * cosLat / Math.pow(2, zoom) * (256 / w); + var k = exaggeration(zoom) / (4 * mpp); + var x, y, i, o, c, xm, xp, ym, yp, rm, r0, rp, sx, sy; + var a, b, cc, d, f, g, hh, ii, dzdx, dzdy, dot, v, alpha, len; + for (y = 0; y < h; y++) { + ym = y > 0 ? y - 1 : 0; + yp = y < h - 1 ? y + 1 : h - 1; + sy = k / (yp - ym || 1); + rm = ym * w; r0 = y * w; rp = yp * w; + for (x = 0; x < w; x++) { + i = r0 + x; + o = i * 4; + c = elev[i]; + if (!(c > NODATA)) { out[o] = out[o + 1] = out[o + 2] = out[o + 3] = 0; continue; } + xm = x > 0 ? x - 1 : 0; + xp = x < w - 1 ? x + 1 : w - 1; + sx = k / (xp - xm || 1); + // 3x3 window, no-data neighbours replaced by the centre so coasts + // don't read as cliffs. + a = elev[rm + xm]; if (!(a > NODATA)) a = c; + b = elev[rm + x]; if (!(b > NODATA)) b = c; + cc = elev[rm + xp]; if (!(cc > NODATA)) cc = c; + d = elev[r0 + xm]; if (!(d > NODATA)) d = c; + f = elev[r0 + xp]; if (!(f > NODATA)) f = c; + g = elev[rp + xm]; if (!(g > NODATA)) g = c; + hh = elev[rp + x]; if (!(hh > NODATA)) hh = c; + ii = elev[rp + xp]; if (!(ii > NODATA)) ii = c; + dzdx = ((cc + 2 * f + ii) - (a + 2 * d + g)) * sx; // rise to the east + dzdy = ((a + 2 * b + cc) - (g + 2 * hh + ii)) * sy; // rise to the north + // Surface normal (-dzdx, -dzdy, 1) against the light, minus flat. + len = sqrt(dzdx * dzdx + dzdy * dzdy + 1); + dot = (LZ - LX * dzdx - LY * dzdy) / len - LZ; + v = dot < 0 ? -dot : dot; + alpha = 255 - 255 * exp(-GAIN * v); + v = dot < 0 ? 0 : 255; + out[o] = out[o + 1] = out[o + 2] = v; + out[o + 3] = alpha; + } + } + return out; + } + + window.MC_hillshadeShade = hillshadeShade; + + if (typeof L === 'undefined') return; + + var VALID_SIZES = { 256: true, 512: true }; + + function tileCentreLat(coords) { + var n = Math.PI * (1 - 2 * (coords.y + 0.5) / Math.pow(2, coords.z)); + return Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))) / DEG; + } + + var HillshadeLayer = L.GridLayer.extend({ + options: { + opacity: 0.35, + maxZoom: 19, + maxNativeZoom: 15, + zIndex: 250, + }, + + initialize: function (url, options) { + this._url = String(url || ''); + L.setOptions(this, options); + this._failed = false; + this._scratch = null; // { size, canvas, ctx, elev, out } reused per layer + this.on('tileunload', this._onTileUnload, this); + }, + + getTileUrl: function (coords) { + return this._url.replace(/\{([zxy])\}/g, function (_, key) { return String(coords[key]); }); + }, + + createTile: function (coords, done) { + var tile = document.createElement('canvas'); + var size = this.getTileSize(); + tile.width = size.x; + tile.height = size.y; + if (this._failed) { + // Leaflet registers the tile only after createTile returns. + setTimeout(function () { done(null, tile); }, 0); + return tile; + } + var self = this; + var img = new Image(); + img.crossOrigin = 'anonymous'; // S6: before src + tile._mcImg = img; + img.onload = function () { + img.onload = img.onerror = null; + tile._mcImg = null; + self._shadeInto(tile, img, coords); + done(null, tile); + }; + img.onerror = function () { + img.onload = img.onerror = null; + tile._mcImg = null; + done(null, tile); // blank tile, no console noise + }; + img.src = this.getTileUrl(coords); + return tile; + }, + + _scratchFor: function (n) { + var s = this._scratch; + if (s && s.size === n) return s; + var canvas = document.createElement('canvas'); + canvas.width = canvas.height = n; + var ctx = canvas.getContext('2d', { willReadFrequently: true }); + s = this._scratch = { + size: n, canvas: canvas, ctx: ctx, + elev: new Float32Array(n * n), + out: ctx.createImageData(n, n), + }; + return s; + }, + + _shadeInto: function (tile, img, coords) { + if (this._failed) return; + var n = img.naturalWidth; + if (!VALID_SIZES[n] || img.naturalHeight !== n) return; + var s = this._scratchFor(n); + var px; + s.ctx.clearRect(0, 0, n, n); + s.ctx.drawImage(img, 0, 0); + try { + px = s.ctx.getImageData(0, 0, n, n).data; + } catch (e) { + // Tainted canvas: the tile host sent no CORS header. Nothing will decode. + this._failed = true; + console.warn('[hillshade] elevation tiles cannot be read (no CORS on the tile host); hillshade disabled.'); + return; + } + var elev = s.elev; + for (var i = 0, j = 0, len = n * n; i < len; i++, j += 4) { + elev[i] = px[j] * 256 + px[j + 1] + px[j + 2] / 256 - 32768; + } + hillshadeShade(elev, n, n, coords.z, tileCentreLat(coords), s.out.data); + tile.width = tile.height = n; // CSS size stays the tile size + tile.getContext('2d').putImageData(s.out, 0, 0); + }, + + _onTileUnload: function (e) { + var tile = e && e.tile; + var img = tile && tile._mcImg; + if (!img) return; + tile._mcImg = null; + img.onload = img.onerror = null; // never draw into a removed canvas + img.src = ''; // cancel the download + }, + }); + + window.MC_createHillshadeLayer = function (opts) { + opts = opts || {}; + var options = {}; + for (var key in opts) { + if (Object.prototype.hasOwnProperty.call(opts, key) && key !== 'url' && opts[key] !== undefined) { + options[key] = opts[key]; + } + } + return new HillshadeLayer(opts.url, options); + }; +})(); diff --git a/public/map-tile-providers.js b/public/map-tile-providers.js index ee5115a6a..2c5fa5295 100644 --- a/public/map-tile-providers.js +++ b/public/map-tile-providers.js @@ -7,11 +7,159 @@ * - MC_setDarkTileProvider(id) / MC_setLightTileProvider(id) persist per-browser * to localStorage and dispatch `mc-tile-provider-changed`. * - Resolves localStorage → server default → 'carto-dark' / 'carto-light'. - * - MC_applyTileFilter() applies/clears the CSS filter on - * `.leaflet-tile-pane` based on current theme + selected provider. + * - MC_applyTileFilter(pane?) applies/clears the CSS filter on the given + * tile pane (default: the first `.leaflet-tile-pane`) based on current + * theme + selected provider. * - MC_createLayerControl() builds a Leaflet control mapping providers. + * - MC_buildTileLayer() / MC_attachAutoTiles(): the shared basemap layer + * builder and theme-synced "Auto" group (raster, vector via map-vector.js; + * overlays incl. hillshade via map-hillshade.js; see CONTRACT). * - * No new deps — URL-only providers. + * ── CONTRACT (#2428 map providers) ────────────────────────────────────────── + * Additive only: every existing id, config key, default and public function + * keeps its current behaviour. Carto stays the shipped default. + * + * Provider entry (BASE_STYLES, custom entries, window.MC_TILE_PROVIDERS[id]): + * provider string config group under map.tiles.providers (enable switch) + * label string picker text (plain text; escaped before display) + * type 'light' | 'dark' | 'any' which theme picker lists it. + * 'any' (new) = listed under both, never colour-inverted + * (satellite). getActiveId/getActiveLightId/setActive/ + * MC_resolveTile accept an 'any' entry for either theme. + * category 'street' | 'topo' | 'satellite' (new, optional; default + * 'street') groups the picker. + * format 'raster' | 'vector' (new, optional; default 'raster') + * url string | () => string raster: XYZ template; vector: style + * JSON URL (MapLibre style spec) + * refUrl string? raster labels tileset stacked on the base (Esri) + * invertFilter string? CSS filter applied in dark mode (unchanged) + * attribution string plain text for new/custom entries (escaped) + * maxZoom number (default 19) + * maxNativeZoom number? (new) highest zoom the server has; Leaflet + * upsamples above it up to maxZoom + * subdomains string? (new) for {s}; default 'abc' + * optIn boolean (new) true = off unless the group's config says + * enabled:true. Every provider added for #2428 is optIn, so + * an upgrade changes nothing until the operator turns a group + * on (licences and volunteer servers are the operator's call); + * existing groups keep their current opt-in/opt-out rules. + * + * Overlay entry (new; window.MC_TILE_OVERLAYS[id]), stacked above any base: + * provider, label, attribution, maxZoom, maxNativeZoom, subdomains, optIn + * kind 'raster' | 'hillshade' + * url raster: XYZ template; hillshade: Terrarium-encoded elevation PNG + * template (elevation m = R*256 + G + B/256 - 32768) + * opacity number 0-1 (default 1; hillshade default 0.35) + * zIndex number (default 250, above tiles 200, below overlayPane 400) + * Overlays are off until the viewer ticks them; the ticked set persists in + * localStorage 'mc-tile-overlays' (JSON array of ids). + * + * MC_resolveTile(isDark) descriptor gains: format, category, maxNativeZoom, + * subdomains (existing fields unchanged). + * + * New public functions (all synchronous unless noted): + * MC_buildTileLayer(desc, opts?) -> L.Layer + * desc: a provider entry or an MC_resolveTile descriptor. Raster -> + * L.tileLayer (grouped with refUrl when present). Vector -> an + * L.LayerGroup that mounts L.maplibreGL once MC_loadMapLibre() + * resolves; on load failure or no WebGL it mounts the raster entry + * opts.fallbackId (default: the theme's shipped Carto id) instead. + * MC_buildOverlayLayer(overlay) -> L.Layer raster or hillshade overlay. + * MC_createHillshadeLayer({url, opacity, maxNativeZoom, ...}) -> L.GridLayer + * canvas tiles shaded client-side from Terrarium elevation tiles. + * MC_loadMapLibre() -> Promise injects the vendored maplibre-gl scripts and + * CSS once; resolves with window.maplibregl. Only vector layers call it. + * MC_attachAutoTiles(map, {controlPosition?}) -> { group, sync, destroy } + * The one theme-synced basemap helper every map surface uses: owns the + * "Auto" layer group, resolves via MC_resolveTile(MC_isDarkTheme()), + * re-syncs on 'mc-tile-provider-changed' and data-theme changes, and + * adds MC_createLayerControl when controlPosition is given. + * + * Operator config, map.tiles: + * providers..enabled unchanged; new groups: eox, osmfr, + * openfreemap, versatiles, hillshade (all + * optIn: on only with enabled:true) + * providers.hillshade.url elevation tiles; default AWS Open Data + * terrarium (the planner's terrain bucket) + * custom: [ { id, label, type, category, format, url, attribution, + * maxZoom, maxNativeZoom, subdomains, overlay } ] + * id /^[a-z0-9][a-z0-9-]{0,31}$/; registered as 'custom-' + * url 'https://' or 'http://' absolute, or a same-site path starting + * with a single '/'. Anything else rejects the entry. + * overlay true registers a raster overlay instead of a base provider. + * At most 20 entries; invalid entries are skipped with one console.warn. + * darkDefault / lightDefault may name any registered id, incl. custom-*. + * + * Security requirements (threat model, #2428): + * S1 attribution of custom/overlay entries is plain text, HTML-escaped ONCE + * at registration (MC_initTileRegistry) and stored escaped, so every + * consumer handing it to Leaflet stays safe unchanged. + * S2 picker labels are set with textContent, never innerHTML; overlays are + * handed to L.control.layers keyed by id and relabelled the same way. + * S3 one _validTileUrl(s): ^https?:// with an authority free of '@', '\', + * whitespace and control chars, OR a path matching ^/(?![/\\]). Only the + * placeholders {z} {x} {y} {s} {r} {-y} are allowed. Custom fields are + * copied from a whitelist with type/range checks (label string <= 64 + * chars; maxZoom/maxNativeZoom finite, clamped 0-24; subdomains + * ^[a-z0-9]{1,8}$; enums checked); never Object.assign the config. + * Rejections console.warn once quoting the entry id only (URLs may + * carry keys). + * S4 MapLibre: build maplibregl.Map options explicitly (style, + * transformRequest, attributionControl:false); never setRTLTextPlugin; + * transformRequest refuses non-http(s)/relative URLs and http: on an + * https page. Attribution shows only through Leaflet (S1). + * S5 MapLibre 5.24.0 (CSP build) + @maplibre/maplibre-gl-leaflet 0.1.4, + * byte-identical npm copies in public/vendor/-/. + * MC_loadMapLibre uses constant paths, sets integrity (sha384) on the + * injected tags, calls maplibregl.setWorkerUrl on the CSP worker, caches + * its promise, and rejects after 15 s -> raster fallback. + * S6 hillshade: img.crossOrigin='anonymous' before src; getImageData in + * try/catch (SecurityError -> blank tile, warn once, layer marked + * failed); refuse images that are not 256x256 or 512x512. + * S7 localStorage 'mc-tile-overlays' and provider picks are untrusted: + * parse in try/catch, keep only registered ids. WebGL missing or + * context lost -> fallbackId raster. + * Everything under map.tiles is public (served to anonymous visitors). + * + * Sprint 3 additions (gray basemaps, overlays, vector): + * Entry field `filter` (string, built-ins only, never from config): a CSS + * filter applied to the tile pane in BOTH themes whenever this entry is + * shown (e.g. 'grayscale(1)'). It replaces invertFilter for that entry: + * MC_resolveTile returns it as desc.invertFilter (so every consumer that + * applies desc.invertFilter keeps working), MC_applyTileFilter and the + * picker's explicit-layer handler apply it regardless of theme. + * Entry field `style: 'gray'` (optional tag) marks gray basemaps; the + * picker shows them inside their category after the plain entries of + * the same type. No new `type` value. + * New groups, all optIn: openfreemap (vector), versatiles (vector), + * and the raster gray pair lives in osmfr. + * Split across files (each sets window globals; loaded after this file): + * map-hillshade.js MC_createHillshadeLayer(opts) -> L.GridLayer + * opts: { url, opacity=0.35, maxZoom=19, maxNativeZoom=15, + * attribution, zIndex=250 } + * also window.MC_hillshadeShade(elev: Float32Array, w, h, zoom, lat, + * out: Uint8ClampedArray) — the pure shading kernel (testable). + * map-vector.js MC_loadMapLibre() -> Promise + * MC_buildVectorLayer(desc, { fallback: () => L.Layer }) -> + * L.LayerGroup. Mounts L.maplibreGL({style: desc.url, ...S4}) into + * the group when the library loads; on load failure, 15 s timeout, + * no WebGL or context loss it adds fallback() to the group instead + * (and removes the GL layer). desc.attribution is shown by Leaflet. + * This file: MC_buildTileLayer calls MC_buildVectorLayer for format + * 'vector' when it exists (else the raster fallback, as today); + * MC_buildOverlayLayer calls MC_createHillshadeLayer for kind + * 'hillshade' when it exists (else returns null and the overlay is not + * listed). + * + * Fix-up additions (review findings, #2428): + * MC_buildTileLayer(desc, { raster: true }) never loads MapLibre: a vector + * desc builds its raster fallback directly. Every static/secondary map + * (node detail/reach/RX coverage via _applyTilesToNodeMap, analytics, + * home mini-map, customizer previews) passes { raster: true }; only the + * full map pages (map, live, planner via MC_attachAutoTiles) render + * vector maps. + * Static maps that are re-created on re-render keep a reference and + * remove() the previous Leaflet map first (no orphaned maps). */ (function () { 'use strict'; @@ -22,6 +170,11 @@ var DEFAULT_ID = 'carto-dark'; var DEFAULT_ID_LIGHT = 'carto-light'; var EVENT_NAME = 'mc-tile-provider-changed'; + // A map pinned in a layer picker (any theme), or absent for Auto. Untrusted: + // honoured only while it names a registered entry. + var PIN_KEY = 'mc-tile-pinned'; + var _pinMemo = null; // last value written, for when localStorage throws + var _pinUnsaved = false; // the last write failed: localStorage holds an older pin var _serverDefault = null; var _serverDefaultLight = null; @@ -29,6 +182,7 @@ var INVERT_CSS = 'invert(1) hue-rotate(180deg) brightness(0.9) contrast(1.05)'; var _cfg = null; + var _DEFAULT_MAX_ZOOM = 19; // contract default maxZoom (also used by MC_resolveTile) var _getCartoBase = function() { return (_cfg && _cfg.providers && _cfg.providers.carto && _cfg.providers.carto.domain) ? 'https://{s}.' + _cfg.providers.carto.domain + '.cartocdn.com' : 'https://{s}.basemaps.cartocdn.com'; }; // Carto started requiring an API key in 2026-08: unauthenticated tiles come back @@ -49,28 +203,340 @@ return 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; }; + // Keyless vector built-ins (optIn). Attribution is plain text (S1). + var _VECTOR_ATTRIBUTION = { + openfreemap: 'OpenFreeMap © OpenMapTiles Data from OpenStreetMap', + versatiles: '© OpenStreetMap contributors, VersaTiles' + }; + function _vector(group, label, type, style, url) { + var e = { provider: group, optIn: true, label: label, category: 'street', type: type, format: 'vector', + invertFilter: null, url: url, attribution: _VECTOR_ATTRIBUTION[group], maxZoom: 19 }; + if (style) e.style = style; + return e; + } + function _versatiles(name) { return 'https://tiles.versatiles.org/assets/styles/' + name + '/style.json'; } + var BASE_STYLES = { - 'carto-dark': { provider: 'carto', label: 'Carto Dark', url: function() { return _getCartoBase() + '/dark_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: null, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, - 'carto-light': { provider: 'carto', label: 'Carto Positron', url: function() { return _getCartoBase() + '/light_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: null, type: 'light', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, + 'carto-dark': { provider: 'carto', style: 'gray', label: 'Carto Dark', url: function() { return _getCartoBase() + '/dark_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: null, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, + 'carto-light': { provider: 'carto', style: 'gray', label: 'Carto Positron', url: function() { return _getCartoBase() + '/light_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: null, type: 'light', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, 'carto-voyager': { provider: 'carto', label: 'Carto Voyager', url: function() { return _getCartoBase() + '/rastertiles/voyager/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: null, type: 'light', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, - 'carto-voyager-dark': { provider: 'carto', label: 'Carto Voyager', url: function() { return _getCartoBase() + '/rastertiles/voyager/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, - 'positron-dark': { provider: 'carto', label: 'Carto Positron', url: function() { return _getCartoBase() + '/light_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, + 'carto-voyager-dark': { provider: 'carto', label: 'Carto Voyager (inverted)', url: function() { return _getCartoBase() + '/rastertiles/voyager/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, + 'positron-dark': { provider: 'carto', style: 'gray', label: 'Carto Positron (inverted)', url: function() { return _getCartoBase() + '/light_all/{z}/{x}/{y}{r}.png' + _getCartoKey(); }, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap © CartoDB', maxZoom: 19 }, 'osm-standard': { provider: 'osm', label: 'OSM Standard', url: _getOsmUrl, invertFilter: null, type: 'light', attribution: '© OpenStreetMap contributors, Maps © Mapbox/Thunderforest/MapTiler', maxZoom: 18 }, - 'osm-dark': { provider: 'osm', label: 'OSM Standard', url: _getOsmUrl, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap contributors, Maps © Mapbox/Thunderforest/MapTiler', maxZoom: 18 }, - 'opentopomap': { provider: 'opentopomap', label: 'OpenTopoMap', url: function() { return 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png'; }, invertFilter: null, type: 'light', attribution: '© OpenStreetMap contributors, SRTM, © OpenTopoMap (CC-BY-SA)', maxZoom: 17 }, + 'osm-dark': { provider: 'osm', label: 'OSM Standard (inverted)', url: _getOsmUrl, invertFilter: INVERT_CSS, type: 'dark', attribution: '© OpenStreetMap contributors, Maps © Mapbox/Thunderforest/MapTiler', maxZoom: 18 }, + 'opentopomap': { provider: 'opentopomap', label: 'OpenTopoMap', url: function() { return 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png'; }, invertFilter: null, type: 'light', category: 'topo', attribution: '© OpenStreetMap contributors, SRTM, © OpenTopoMap (CC-BY-SA)', maxZoom: 17 }, 'stamen-toner-lite': { provider: 'stamen', label: 'Stamen Toner Lite', url: _getStamenUrl, invertFilter: null, type: 'light', attribution: '© Stadia Maps © Stamen Design © OpenStreetMap', maxZoom: 20 }, - 'stamen-toner-dark': { provider: 'stamen', label: 'Stamen Toner Lite', url: _getStamenUrl, invertFilter: INVERT_CSS, type: 'dark', attribution: '© Stadia Maps © Stamen Design © OpenStreetMap', maxZoom: 20 }, - 'usgs-topo': { provider: 'usgs', label: 'USGS Topographic', url: function() { return 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}'; }, invertFilter: null, type: 'light', attribution: 'U.S. Geological Survey, National Geospatial Program', maxZoom: 16 }, - 'usgs-imagery': { provider: 'usgs', label: 'USGS Imagery', url: function() { return 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryTopo/MapServer/tile/{z}/{y}/{x}'; }, invertFilter: null, type: 'light', attribution: 'U.S. Geological Survey, National Geospatial Program', maxZoom: 16 }, - 'esri-darkgray-labels': { provider: 'esri', label: 'Esri Dark Gray Canvas', url: function() { return 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}'; }, refUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Reference/MapServer/tile/{z}/{y}/{x}', invertFilter: null, type: 'dark', attribution: 'Tiles © Esri', maxZoom: 19 } + 'stamen-toner-dark': { provider: 'stamen', label: 'Stamen Toner Lite (inverted)', url: _getStamenUrl, invertFilter: INVERT_CSS, type: 'dark', attribution: '© Stadia Maps © Stamen Design © OpenStreetMap', maxZoom: 20 }, + 'usgs-topo': { provider: 'usgs', label: 'USGS Topographic', url: function() { return 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}'; }, invertFilter: null, type: 'light', category: 'topo', attribution: 'U.S. Geological Survey, National Geospatial Program', maxZoom: 16 }, + 'usgs-imagery': { provider: 'usgs', label: 'USGS Imagery', url: function() { return 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryTopo/MapServer/tile/{z}/{y}/{x}'; }, invertFilter: null, type: 'light', category: 'satellite', attribution: 'U.S. Geological Survey, National Geospatial Program', maxZoom: 16 }, + 'esri-darkgray-labels': { provider: 'esri', style: 'gray', label: 'Esri Dark Gray Canvas', url: function() { return 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}'; }, refUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Reference/MapServer/tile/{z}/{y}/{x}', invertFilter: null, type: 'dark', attribution: 'Tiles © Esri', maxZoom: 19 }, + + // ── #2428 keyless built-ins: optIn (off unless the group says enabled:true) ── + // Their attribution is plain text stored HTML-escaped (S1), hence '&'. + // maxNativeZoom is the deepest level with real detail, measured against EOX + // (z+1 tiles compared with their upsampled parent): Sentinel-2 is 10 m + // imagery, so deeper EOX levels are resampled and Leaflet upsamples instead. + 'eox-s2-2025': { provider: 'eox', optIn: true, label: 'Satellite 2025 (EOX Sentinel-2)', category: 'satellite', type: 'any', invertFilter: null, + url: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg', + attribution: 'Sentinel-2 cloudless 2025 - s2maps.eu by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025), CC BY-NC-SA 4.0', + maxZoom: 19, maxNativeZoom: 15 }, + 'eox-s2-2016': { provider: 'eox', optIn: true, label: 'Satellite 2016 (EOX Sentinel-2)', category: 'satellite', type: 'any', invertFilter: null, + url: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless_3857/default/g/{z}/{y}/{x}.jpg', + attribution: 'Sentinel-2 cloudless - s2maps.eu by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2016 & 2017), CC BY 4.0', + maxZoom: 19, maxNativeZoom: 14 }, + 'eox-terrain-light': { provider: 'eox', optIn: true, label: 'Terrain Light (EOX)', category: 'topo', type: 'light', invertFilter: null, + url: 'https://tiles.maps.eox.at/wmts/1.0.0/terrain-light_3857/default/g/{z}/{y}/{x}.jpg', + attribution: 'Terrain Light: Data © OpenStreetMap contributors and others, Rendering © EOX', + maxZoom: 19, maxNativeZoom: 15 }, + 'osmfr-hot': { provider: 'osmfr', optIn: true, label: 'Humanitarian (OSM France)', category: 'street', type: 'light', invertFilter: null, + url: 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', subdomains: 'abc', + attribution: '© OpenStreetMap contributors, style by Humanitarian OpenStreetMap Team, hosted by OpenStreetMap France', + maxZoom: 19 }, + 'osmfr-cyclosm': { provider: 'osmfr', optIn: true, label: 'CyclOSM (topographic)', category: 'topo', type: 'light', invertFilter: null, + url: 'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png', subdomains: 'abc', + attribution: 'CyclOSM, map data © OpenStreetMap contributors', + maxZoom: 19 }, + + // ── Sprint 3: gray rasters (OSM France tiles + a CSS `filter`, both themes) ── + 'osmfr-gray': { provider: 'osmfr', optIn: true, label: 'OSM Gray', category: 'street', type: 'light', style: 'gray', invertFilter: null, + filter: 'grayscale(1) contrast(0.92) brightness(1.04)', + url: 'https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', subdomains: 'abc', + attribution: '© OpenStreetMap contributors, tiles by OpenStreetMap France', + maxZoom: 19 }, + 'osmfr-gray-dark': { provider: 'osmfr', optIn: true, label: 'OSM Gray Dark', category: 'street', type: 'dark', style: 'gray', invertFilter: null, + filter: 'grayscale(1) invert(1) contrast(0.9) brightness(0.95)', + url: 'https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', subdomains: 'abc', + attribution: '© OpenStreetMap contributors, tiles by OpenStreetMap France', + maxZoom: 19 }, + + // ── Sprint 3: vector basemaps (url = MapLibre style JSON; see map-vector.js) ── + 'openfreemap-liberty': _vector('openfreemap', 'OpenFreeMap Liberty', 'light', null, 'https://tiles.openfreemap.org/styles/liberty'), + 'openfreemap-bright': _vector('openfreemap', 'OpenFreeMap Bright', 'light', null, 'https://tiles.openfreemap.org/styles/bright'), + 'openfreemap-positron': _vector('openfreemap', 'OpenFreeMap Positron', 'light', 'gray', 'https://tiles.openfreemap.org/styles/positron'), + 'openfreemap-dark': _vector('openfreemap', 'OpenFreeMap Dark', 'dark', 'gray', 'https://tiles.openfreemap.org/styles/dark'), + 'openfreemap-fiord': _vector('openfreemap', 'OpenFreeMap Fiord', 'dark', null, 'https://tiles.openfreemap.org/styles/fiord'), + 'versatiles-colorful': _vector('versatiles', 'VersaTiles Colorful', 'light', null, _versatiles('colorful')), + 'versatiles-muted': _vector('versatiles', 'VersaTiles Muted', 'light', null, _versatiles('muted')), + 'versatiles-gray': _vector('versatiles', 'VersaTiles Gray', 'light', 'gray', _versatiles('gray')), + 'versatiles-colorful-dark': _vector('versatiles', 'VersaTiles Colorful Dark', 'dark', null, _versatiles('colorful-dark')), + 'versatiles-gray-dark': _vector('versatiles', 'VersaTiles Gray Dark', 'dark', 'gray', _versatiles('gray-dark')) }; var REGISTRY = {}; + // ── Overlays (CONTRACT "Overlay entry"), stacked above whichever base ── + var OVERLAY_Z = 250; // pane z-index: above tiles (200), below overlayPane (400) + var OVERLAY_PANE = 'mcOverlayPane'; // own pane, so the tile pane's invert/gray filter never reaches it + var OVERLAYS_KEY = 'mc-tile-overlays'; + var OVERLAYS_EVENT = 'mc-tile-overlays-changed'; + var OVERLAYS_RAW_MAX = 4096; // S7: a longer stored value is ignored unparsed + var HILLSHADE_URL = 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png'; + function _eoxOverlay(layer) { return 'https://tiles.maps.eox.at/wmts/1.0.0/' + layer + '/default/g/{z}/{y}/{x}.png'; } + // EOX label overlays: transparent PNGs, served up to z14 (z15 is a 404). + // overlay_bright draws light text with a dark halo (for imagery); + // overlay draws dark text with a light halo (for light basemaps). + var OVERLAY_STYLES = { + 'eox-labels': { provider: 'eox', optIn: true, kind: 'raster', label: 'Place labels (EOX)', + url: _eoxOverlay('overlay_bright_3857'), + attribution: 'Overlay: Data © OpenStreetMap contributors, Rendering © EOX', + maxZoom: 19, maxNativeZoom: 14, opacity: 1, zIndex: OVERLAY_Z }, + 'eox-labels-dark': { provider: 'eox', optIn: true, kind: 'raster', label: 'Place labels, dark text (EOX)', + url: _eoxOverlay('overlay_3857'), + attribution: 'Overlay: Data © OpenStreetMap contributors, Rendering © EOX', + maxZoom: 19, maxNativeZoom: 14, opacity: 1, zIndex: OVERLAY_Z } + }; + var OVERLAYS = {}; + var _customOverlays = {}; // the last registration's custom overlay entries + var _hillshade = null; // the last hillshade entry built + function _hasId(id) { return typeof id === 'string' && Object.prototype.hasOwnProperty.call(REGISTRY, id); } + // ── Operator custom entries (map.tiles.custom; contract + S1/S3) ────────── + // map.tiles is served to anonymous visitors, so every value is validated + // here and nothing reaches the registry unchecked. + + var CUSTOM_MAX = 20; + var CUSTOM_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/; + var SUBDOMAINS_RE = /^[a-z0-9]{1,8}$/; + var URL_MAX_LEN = 2048; + var LABEL_MAX = 64; + var ATTRIBUTION_MAX = 200; + var ZOOM_MAX = 24; + var PLACEHOLDERS = { '{z}': 1, '{x}': 1, '{y}': 1, '{s}': 1, '{r}': 1, '{-y}': 1 }; + var TYPES = { light: 1, dark: 1, any: 1 }; + var CATEGORIES = { street: 1, topo: 1, satellite: 1 }; + var FORMATS = { raster: 1, vector: 1 }; + + // S3: the one URL gate. Absolute http(s) with a clean authority (no '@' + // userinfo, no '\', no whitespace/control chars), or a same-site path that + // cannot become protocol-relative ('//host', '/\host'). Whitespace and + // control chars are refused anywhere in the URL, and every {...} must be a + // Leaflet placeholder we support. Only {s} may appear in the authority: + // Leaflet fills {r} with '@2x' (a{r}b.example -> userinfo 'a' at host + // '2xb.example'), and {z}/{x}/{y}/{-y} would put tile numbers in the host. + function _validTileUrl(s) { + if (typeof s !== 'string' || !s || s.length > URL_MAX_LEN) return false; + if (/[\s\u0000-\u001f\u007f-\u009f]/.test(s)) return false; + var abs = /^https?:\/\/([^\/?#]*)/.exec(s); + if (abs) { + if (!abs[1] || /[@\\]/.test(abs[1])) return false; + if (/[{}]/.test(abs[1].replace(/\{s\}/g, ''))) return false; + } else if (!/^\/(?![\/\\])/.test(s)) { + return false; + } + var rest = s.replace(/\{[^{}]*\}/g, function (m) { return _inSet(PLACEHOLDERS, m) ? '' : '\u0000'; }); + return !/[{}\u0000]/.test(rest); + } + + function _hasXYZ(v) { + return v.indexOf('{z}') >= 0 && v.indexOf('{x}') >= 0 && (v.indexOf('{y}') >= 0 || v.indexOf('{-y}') >= 0); + } + + function _escapeHtml(s) { + return String(s).replace(/&/g, '&').replace(//g, '>') + .replace(/"/g, '"').replace(/'/g, '''); + } + + // Own properties only: a config entry never lends us inherited values. + function _own(o, k) { + return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : undefined; + } + + // Set membership that 'constructor' or '__proto__' can't satisfy. + function _inSet(set, v) { + return typeof v === 'string' && Object.prototype.hasOwnProperty.call(set, v); + } + + // Bounded: one entry per distinct message, and messages come from at most + // CUSTOM_MAX entries per config. Re-registration (config arriving async) + // does not repeat a warning. + var _warned = {}; + var _warnedCount = 0; + function _warnOnce(msg) { + if (_warned[msg] || _warnedCount >= 64) return; + _warned[msg] = true; + _warnedCount++; + try { console.warn('[tiles] ' + msg); } catch (_) {} + } + + function _zoom(v) { + if (typeof v !== 'number' || !isFinite(v)) return null; + return Math.min(ZOOM_MAX, Math.max(0, v)); + } + + // One config entry -> a registry entry, or a string saying why it was + // rejected. Fields are copied from a whitelist; absent (undefined/null) + // optional fields take their defaults, present-but-invalid ones reject. + function _customEntry(c, id) { + var v; + var e = { provider: 'custom', label: id, type: 'light', category: 'street', format: 'raster', + url: null, attribution: '', maxZoom: _DEFAULT_MAX_ZOOM, invertFilter: null }; + + v = _own(c, 'label'); + if (v != null) { + if (typeof v !== 'string' || v.length > LABEL_MAX) return 'label must be text of at most ' + LABEL_MAX + ' characters'; + if (v.trim()) e.label = v; + } + v = _own(c, 'type'); + if (v != null) { if (!_inSet(TYPES, v)) return "type must be 'light', 'dark' or 'any'"; e.type = v; } + v = _own(c, 'category'); + if (v != null) { if (!_inSet(CATEGORIES, v)) return "category must be 'street', 'topo' or 'satellite'"; e.category = v; } + v = _own(c, 'format'); + if (v != null) { if (!_inSet(FORMATS, v)) return "format must be 'raster' or 'vector'"; e.format = v; } + + v = _own(c, 'url'); + if (!_validTileUrl(v)) return "url must be an https://, http:// or '/' URL using only {z} {x} {y} {s} {r} {-y}"; + if (e.format === 'raster' && !_hasXYZ(v)) return 'a raster url needs {z}, {x} and {y}'; + e.url = v; + + v = _own(c, 'attribution'); + if (v != null) { + if (typeof v !== 'string' || v.length > ATTRIBUTION_MAX) return 'attribution must be text of at most ' + ATTRIBUTION_MAX + ' characters'; + e.attribution = _escapeHtml(v); // S1: escaped once, stored escaped + } + v = _own(c, 'maxZoom'); + if (v != null) { if (_zoom(v) === null) return 'maxZoom must be a number'; e.maxZoom = _zoom(v); } + v = _own(c, 'maxNativeZoom'); + if (v != null) { + if (_zoom(v) === null) return 'maxNativeZoom must be a number'; + e.maxNativeZoom = Math.floor(_zoom(v)); // Leaflet builds tile URLs from it: keep it whole + } + v = _own(c, 'subdomains'); + if (v != null) { + if (typeof v !== 'string' || !SUBDOMAINS_RE.test(v)) return 'subdomains must be 1-8 characters of a-z and 0-9'; + e.subdomains = v; + } + return e; + } + + // A validated custom entry -> a raster overlay entry (fields already checked). + function _customOverlay(e) { + var o = { provider: 'custom', kind: 'raster', label: e.label, url: e.url, attribution: e.attribution, + maxZoom: e.maxZoom, opacity: 1, zIndex: OVERLAY_Z }; + if (e.maxNativeZoom != null) o.maxNativeZoom = e.maxNativeZoom; + if (e.subdomains) o.subdomains = e.subdomains; + return o; + } + + // Adds the valid map.tiles.custom entries as 'custom-': base providers + // to `reg`, overlay:true entries to `overlays`. + function _registerCustom(list, reg, overlays) { + if (list == null) return; + if (!Array.isArray(list)) { _warnOnce('map.tiles.custom is not a list; ignored'); return; } + if (list.length > CUSTOM_MAX) { + _warnOnce('map.tiles.custom has ' + list.length + ' entries; only the first ' + CUSTOM_MAX + ' are used'); + } + var n = Math.min(list.length, CUSTOM_MAX); + for (var i = 0; i < n; i++) { + var c = list[i]; + var where = 'map.tiles.custom[' + i + ']'; + if (!c || typeof c !== 'object' || Array.isArray(c)) { _warnOnce(where + ' skipped: not an object'); continue; } + var id = _own(c, 'id'); + // An invalid id is never quoted: it is not known to be harmless text. + if (typeof id !== 'string' || !CUSTOM_ID_RE.test(id)) { + _warnOnce(where + ' skipped: id must be 1-32 characters of a-z, 0-9 and -, starting with a letter or digit'); + continue; + } + var key = 'custom-' + id; + var overlay = _own(c, 'overlay'); + if (overlay != null && typeof overlay !== 'boolean') { _warnOnce('custom tile "' + id + '" skipped: overlay must be true or false'); continue; } + // One 'custom-' namespace across base providers and overlays. + if (Object.prototype.hasOwnProperty.call(reg, key) || Object.prototype.hasOwnProperty.call(overlays, key)) { + _warnOnce('custom tile "' + id + '" skipped: duplicate id'); continue; + } + var e = _customEntry(c, id); + if (typeof e === 'string') { _warnOnce('custom tile "' + id + '" skipped: ' + e); continue; } + if (overlay === true) { + if (e.format !== 'raster') { _warnOnce('custom tile "' + id + '" skipped: an overlay must be a raster url'); continue; } + e = _customOverlay(e); + overlays[key] = Object.freeze ? Object.freeze(e) : e; + continue; + } + reg[key] = Object.freeze ? Object.freeze(e) : e; + } + } + + // An optIn group is on only when map.tiles.providers..enabled === true. + function _groupOn(group) { + var p = _cfg && _cfg.providers; + var g = (p && typeof p === 'object') ? _own(p, group) : null; + return !!(g && typeof g === 'object' && g.enabled === true); + } + + // map-hillshade.js fills in only {z}, {x} and {y}: a hillshade url must use + // exactly those, each once ({s}, {r}, {-y} would fetch a literal and draw + // a silently blank layer). + function _hillshadeUrlOk(u) { + if (!_validTileUrl(u)) return false; + var ph = u.match(/\{[^{}]*\}/g) || []; + return ph.length === 3 && ph.slice().sort().join('') === '{x}{y}{z}'; + } + + // The hillshade overlay: providers.hillshade.url when it passes the S3 gate + // and _hillshadeUrlOk, else the AWS Open Data Terrarium tiles. + function _hillshadeEntry() { + var p = _cfg && _cfg.providers; + var g = (p && typeof p === 'object') ? _own(p, 'hillshade') : null; + var u = (g && typeof g === 'object') ? _own(g, 'url') : null; + var url = HILLSHADE_URL; + if (u != null) { + if (_hillshadeUrlOk(u)) url = u; + else _warnOnce('map.tiles.providers.hillshade.url rejected; using the default elevation tiles'); + } + // Same url -> same entry object, so maps keep their hillshade layer when + // the registry is rebuilt (config arriving async) instead of redrawing it. + if (_hillshade && _hillshade.url === url) return _hillshade; + _hillshade = { provider: 'hillshade', optIn: true, kind: 'hillshade', label: 'Hillshade (terrain)', url: url, + attribution: 'Terrain: Mapzen/AWS Open Data (SRTM, USGS and others)', + maxZoom: _DEFAULT_MAX_ZOOM, maxNativeZoom: 15, opacity: 0.35, zIndex: OVERLAY_Z }; + return _hillshade; + } + + // Rebuilds window.MC_TILE_OVERLAYS: hillshade (only while map-hillshade.js + // has defined MC_createHillshadeLayer), the EOX labels, then custom ones. + function _buildOverlays() { + var o = {}; + if (typeof window.MC_createHillshadeLayer === 'function' && _groupOn('hillshade')) o.hillshade = _hillshadeEntry(); + for (var k in OVERLAY_STYLES) { + if (_groupOn(OVERLAY_STYLES[k].provider)) o[k] = OVERLAY_STYLES[k]; + } + for (k in _customOverlays) o[k] = _customOverlays[k]; + OVERLAYS = o; + window.MC_TILE_OVERLAYS = o; + } + + // map-hillshade.js loads after this file, so the registry built at parse + // time has no hillshade; every picker build / overlay sync re-checks. + function _ensureHillshade() { + if (!_hasOverlay('hillshade') && typeof window.MC_createHillshadeLayer === 'function' && _groupOn('hillshade')) _buildOverlays(); + } + + function _hasOverlay(id) { + return typeof id === 'string' && Object.prototype.hasOwnProperty.call(OVERLAYS, id); + } + window.MC_initTileRegistry = function(fromAsync) { _cfg = (typeof window !== 'undefined' && window.MC_MAP_CFG && window.MC_MAP_CFG.tiles) ? window.MC_MAP_CFG.tiles : null; @@ -84,6 +550,7 @@ REGISTRY = {}; for (var key in BASE_STYLES) { var style = BASE_STYLES[key]; + if (style.optIn) { if (_groupOn(style.provider)) REGISTRY[key] = style; continue; } if (style.provider === 'carto' && HAS_CARTO) REGISTRY[key] = style; if (style.provider === 'osm' && HAS_OSM) REGISTRY[key] = style; if (style.provider === 'opentopomap' && HAS_OPENTOPOMAP) REGISTRY[key] = style; @@ -91,6 +558,11 @@ if (style.provider === 'usgs' && HAS_USGS) REGISTRY[key] = style; if (style.provider === 'esri' && HAS_ESRI) REGISTRY[key] = style; } + // Custom entries are always enabled when valid; registered before the + // defaults below so darkDefault/lightDefault may name a custom-* id. + _customOverlays = {}; + if (_cfg) _registerCustom(_own(_cfg, 'custom'), REGISTRY, _customOverlays); + _buildOverlays(); // Keep the public reference in sync with the newly rebuilt REGISTRY window.MC_TILE_PROVIDERS = REGISTRY; @@ -109,6 +581,9 @@ } }; + // Exposed for unit tests of the S3 URL gate. + window.MC__validTileUrl = _validTileUrl; + // Run once immediately with whatever config is available at parse time window.MC_initTileRegistry(); @@ -121,11 +596,16 @@ } catch (_) { return false; } } - + // An entry fits a theme when it was made for that theme or for both ('any', + // e.g. satellite imagery, which is never colour-inverted). + function _fitsTheme(p, theme) { + return !!p && (p.type === theme || p.type === 'any'); + } + function getActiveId() { try { var stored = window.localStorage && window.localStorage.getItem(STORAGE_KEY); - if (_hasId(stored) && REGISTRY[stored].type === 'dark') return stored; + if (_hasId(stored) && _fitsTheme(REGISTRY[stored], 'dark')) return stored; } catch (_) {} if (_cfg && _cfg.darkDefault && _hasId(_cfg.darkDefault)) return _cfg.darkDefault; if (_hasId(_serverDefault)) return _serverDefault; @@ -135,7 +615,7 @@ function getActiveLightId() { try { var stored = window.localStorage && window.localStorage.getItem(STORAGE_KEY_LIGHT); - if (_hasId(stored) && REGISTRY[stored].type === 'light') return stored; + if (_hasId(stored) && _fitsTheme(REGISTRY[stored], 'light')) return stored; } catch (_) {} if (_cfg && _cfg.lightDefault && _hasId(_cfg.lightDefault)) return _cfg.lightDefault; if (_hasId(_serverDefaultLight)) return _serverDefaultLight; @@ -144,7 +624,8 @@ function setActive(id, type) { if (!_hasId(id)) return false; - if (REGISTRY[id].type !== type) return false; + if (type !== 'light' && type !== 'dark') return false; + if (!_fitsTheme(REGISTRY[id], type)) return false; var skey = type === 'light' ? STORAGE_KEY_LIGHT : STORAGE_KEY; try { if (window.localStorage) window.localStorage.setItem(skey, id); @@ -161,6 +642,47 @@ } + // The pinned map: the stored id while it is registered, else null (Auto). + function getPinnedId() { + var v = _pinMemo; + if (!_pinUnsaved) { + try { if (window.localStorage) v = window.localStorage.getItem(PIN_KEY); } catch (_) {} + } + return _hasId(v) ? v : null; + } + + // Pin `id` (a registered entry, any theme), or clear the pin with null. + // Every map follows: the event makes MC_attachAutoTiles re-sync. + function setPinned(id) { + if (id !== null && !_hasId(id)) return false; + _pinMemo = id; + _pinUnsaved = false; + try { + if (window.localStorage) { + if (id === null) window.localStorage.removeItem(PIN_KEY); + else window.localStorage.setItem(PIN_KEY, id); + } + } catch (_) { _pinUnsaved = true; } // e.g. quota full: never fall back to the stored, older pin + var detail = { pinned: id }; + try { + var ev = (typeof CustomEvent === 'function') + ? new CustomEvent(EVENT_NAME, { detail: detail }) + : { type: EVENT_NAME, detail: detail }; + window.dispatchEvent(ev); + } catch (_) { } + return true; + } + + // The entry a map without an explicit layer shows for a theme: the pin + // when it suits the theme (an 'any' entry, e.g. satellite, always does), + // else that theme's choice. A map with a picker ignores the pin: there + // the pin is the explicit layer, and Auto always means the theme's map. + function _themeId(isDark, ignorePin) { + var pin = ignorePin ? null : getPinnedId(); + if (pin && _fitsTheme(REGISTRY[pin], isDark ? 'dark' : 'light')) return pin; + return isDark ? getActiveId() : getActiveLightId(); + } + function setServerDefault(id) { if (_hasId(id)) _serverDefault = id; } function setServerDefaultLight(id) { if (_hasId(id)) _serverDefaultLight = id; } @@ -169,9 +691,14 @@ return _isDark(); } - function applyTileFilter() { - var pane; - try { pane = document.querySelector('.leaflet-tile-pane'); } catch (_) { pane = null; } + // `pane` (optional): a specific map's tile pane. Without it the first + // `.leaflet-tile-pane` in the document is used (the original behaviour); + // MC_attachAutoTiles passes its own map's pane so several maps on one page + // each get their filter. + function applyTileFilter(pane) { + if (!pane || !pane.style || typeof pane.getAttribute !== 'function') { + try { pane = document.querySelector('.leaflet-tile-pane'); } catch (_) { pane = null; } + } if (!pane || !pane.style) return; // Contract: if an explicit layer was selected via the map control, it locks // the CSS filter state. We bypass our auto-theme logic here so we don't accidentally @@ -181,9 +708,16 @@ } var isDark = _isDarkEffective(); - var id = isDark ? getActiveId() : getActiveLightId(); - var p = REGISTRY[id]; - pane.style.filter = (isDark && p && p.invertFilter) ? p.invertFilter : ''; + var picker = typeof pane.getAttribute === 'function' && pane.getAttribute('data-mc-picker') === 'true'; + pane.style.filter = _paneFilter(REGISTRY[_themeId(isDark, picker)], isDark); + } + + // The tile-pane CSS filter for an entry: its `filter` in both themes, else + // its invertFilter in dark mode (never for 'any'), else none. + function _paneFilter(p, isDark) { + if (!p) return ''; + if (p.filter) return p.filter; + return (isDark && p.type !== 'any' && p.invertFilter) ? p.invertFilter : ''; } @@ -195,6 +729,8 @@ window.MC_setLightTileProvider = function(id) { return setActive(id, 'light'); }; window.MC_getDarkTileProvider = getActiveId; window.MC_getLightTileProvider = getActiveLightId; + window.MC_getPinnedTileProvider = getPinnedId; + window.MC_setPinnedTileProvider = setPinned; window.MC_setServerDefaultTileProvider = setServerDefault; window.MC_setServerDefaultLightTileProvider = setServerDefaultLight; window.MC_applyTileFilter = applyTileFilter; @@ -216,17 +752,6 @@ return (typeof u === 'function') ? u() : u; }; - // Re-register a changed layer with Leaflet so its map zoom limits and - // attribution follow the provider, not just its URL. This also works while - // the Auto group is inactive: the layer takes effect when selected again. - window.MC_updateTileLayer = function (layer, group, descriptor) { - group.removeLayer(layer); - layer.options.maxZoom = descriptor.maxZoom || 19; - layer.options.attribution = descriptor.attribution || ''; - layer.setUrl(descriptor.url); - layer.addTo(group); - }; - // ── Shared tile resolution (single source of truth) ────────────────────── // // Before this block every surface resolved its own basemap: map.js/_resolveTileUrl @@ -244,7 +769,6 @@ var _FALLBACK_TILE_LIGHT = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'; var _ATTR_CARTO = '© OpenStreetMap © CartoDB'; var _ATTR_OSM = '© OpenStreetMap contributors'; - var _DEFAULT_MAX_ZOOM = 19; function _constantTileUrl(dark) { // Prefer the roles.js-scalar when present (it carries explicit legacy @@ -258,7 +782,11 @@ /** * Resolve the effective tile provider for a theme into a plain descriptor: - * { type, id, url, attribution, maxZoom, refUrl, invertFilter } + * { type, id, url, attribution, maxZoom, refUrl, invertFilter, override, + * format, category, maxNativeZoom, subdomains } + * `type` is always the theme asked for ('dark' | 'light'), also when the + * entry is an 'any' one. format defaults to 'raster', category to 'street', + * maxNativeZoom and subdomains to null. * `url` is always a resolved string — provider `url`/`baseUrl` builders are * invoked here so callers never hand L.tileLayer a function (#1614). * Resolution happens at call time (never cached): MC_initTileRegistry(true) @@ -275,8 +803,11 @@ * 3. The TILE_DARK/TILE_LIGHT constants (pre-config load or a registry * the config has emptied out). */ - window.MC_resolveTile = function (isDark) { + // opts.ignorePin: resolve the theme's map even when a map is pinned (the + // Auto layer of a map with a picker). + window.MC_resolveTile = function (isDark, opts) { isDark = !!isDark; + var ignorePin = !!(opts && opts.ignorePin); var desc = { type: isDark ? 'dark' : 'light', id: null, @@ -285,7 +816,11 @@ maxZoom: _DEFAULT_MAX_ZOOM, refUrl: null, invertFilter: null, - override: false + override: false, + format: 'raster', + category: 'street', + maxNativeZoom: null, + subdomains: null }; // 1. Explicit operator override beats user picks try { @@ -303,7 +838,14 @@ // MC_initTileRegistry after every rebuild) and they let test sandboxes // inject mocks the same way the #1614 harness does. var id = null; - try { + var reg0 = null; + try { reg0 = window.MC_TILE_PROVIDERS || REGISTRY; } catch (_e) { reg0 = REGISTRY; } + // 2a. A map pinned in a picker, when it suits this theme. + if (!ignorePin) try { + var pin = (typeof window.MC_getPinnedTileProvider === 'function') ? window.MC_getPinnedTileProvider() : null; + if (pin && Object.prototype.hasOwnProperty.call(reg0, pin) && _fitsTheme(reg0[pin], desc.type)) id = pin; + } catch (_e) { id = null; } + if (!id) try { if (isDark && typeof window.MC_getDarkTileProvider === 'function') id = window.MC_getDarkTileProvider(); else if (!isDark && typeof window.MC_getLightTileProvider === 'function') id = window.MC_getLightTileProvider(); } catch (_e) { id = null; } @@ -320,7 +862,8 @@ // shipped default entry before giving up on the registry. var defId = isDark ? DEFAULT_ID : DEFAULT_ID_LIGHT; if (!p) { p = _pick(defId); pickedId = p ? defId : null; } - if (p && p.type && p.type !== desc.type) { p = null; pickedId = null; } // registry is authoritative on types + // Registry is authoritative on types; an 'any' entry fits both themes. + if (p && p.type && p.type !== desc.type && p.type !== 'any') { p = null; pickedId = null; } if (!p) { // 3. Bare constants (roles.js scalars or shipped literals) desc.url = _constantTileUrl(isDark); return desc; @@ -331,11 +874,290 @@ desc.attribution = p.attribution || _ATTR_CARTO; desc.maxZoom = p.maxZoom || _DEFAULT_MAX_ZOOM; desc.refUrl = p.refUrl || null; - desc.invertFilter = p.invertFilter || null; + // A `filter` entry is filtered in both themes; 'any' is never inverted. + desc.invertFilter = p.filter || ((p.type === 'any') ? null : (p.invertFilter || null)); + desc.format = p.format || 'raster'; + desc.category = p.category || 'street'; + desc.maxNativeZoom = (p.maxNativeZoom != null) ? p.maxNativeZoom : null; + desc.subdomains = p.subdomains || null; return desc; }; + // ── Shared basemap layer builder ───────────────────────────────────────── + + var _vectorWarned = false; + + // Leaflet options for one raster entry/descriptor. maxNativeZoom and + // subdomains are only passed when set, so Leaflet keeps its own defaults. + function _rasterOpts(desc) { + var o = { attribution: desc.attribution || '', maxZoom: desc.maxZoom || _DEFAULT_MAX_ZOOM }; + if (typeof desc.maxNativeZoom === 'number' && isFinite(desc.maxNativeZoom)) o.maxNativeZoom = desc.maxNativeZoom; + if (desc.subdomains) o.subdomains = desc.subdomains; + return o; + } + + /** + * Build the Leaflet layer for a provider entry or an MC_resolveTile + * descriptor. Raster: an L.tileLayer, grouped with its refUrl labels layer + * in an L.layerGroup when the entry has one (Esri). Function-typed url + * builders are invoked here (#1614). + * + * Vector entries go to MC_buildVectorLayer (map-vector.js), handing it a + * factory for the raster entry opts.fallbackId (default: the theme's + * shipped Carto id) that it mounts when MapLibre can't run. Without + * map-vector.js they warn once and build that raster entry directly. + * opts.raster (static/secondary maps) builds that raster entry directly + * and never loads MapLibre. + * + * @param {Object} desc - registry entry or resolved descriptor + * @param {{fallbackId?: string, raster?: boolean}} [opts] + * @returns {L.Layer} + */ + window.MC_buildTileLayer = function (desc, opts) { + opts = opts || {}; + if (desc && desc.format === 'vector') { + var fallback = function () { return _buildRaster(_withMapZoom(_vectorFallback(desc, opts.fallbackId), desc)); }; + if (opts.raster) return fallback(); + if (typeof window.MC_buildVectorLayer === 'function') { + try { return window.MC_buildVectorLayer(desc, { fallback: fallback }); } catch (_) { /* raster below */ } + } else if (!_vectorWarned) { + _vectorWarned = true; + try { console.warn('[tiles] vector basemap support is not loaded; using a raster fallback'); } catch (_) {} + } + return fallback(); + } + return _buildRaster(desc); + }; + + // The raster entry a vector one falls back to. A descriptor's type is the + // theme it was resolved for; an 'any' entry follows the current theme. + function _vectorFallback(desc, fallbackId) { + var dark = desc.type === 'dark' || (desc.type === 'any' && _isDark()); + var defFallback = dark ? DEFAULT_ID : DEFAULT_ID_LIGHT; + var fid = fallbackId || defFallback; + var fb = (_hasId(fid) && REGISTRY[fid]) || BASE_STYLES[fid]; + // Never recurse into another vector entry: the shipped Carto raster is the floor. + if (!fb || fb.format === 'vector') fb = (_hasId(defFallback) && REGISTRY[defFallback]) || BASE_STYLES[defFallback]; + return fb; + } + + // A raster XYZ url for a descriptor: its own url, or, for a vector entry + // (a MapLibre style JSON, which L.tileLayer can't use), the raster it falls + // back to. For callers that only want a tile template (getTileUrl). + window.MC_rasterTileUrl = function (desc) { + if (!desc) return null; + if (desc.format !== 'vector') return desc.url; + var fb = _vectorFallback(desc); + var u = fb && (fb.url || fb.baseUrl); + return (typeof u === 'function') ? u() : (u || null); + }; + + // The raster standing in for a vector entry keeps that entry's maxZoom, so + // the map's zoom limit doesn't change when the fallback appears; past the + // raster's own last zoom it upsamples instead of requesting missing tiles. + function _withMapZoom(fb, desc) { + var max = desc && desc.maxZoom; + if (typeof max !== 'number' || !isFinite(max)) return fb; + var own = (typeof fb.maxNativeZoom === 'number') ? fb.maxNativeZoom : (fb.maxZoom || _DEFAULT_MAX_ZOOM); + var out = {}; + Object.keys(fb).forEach(function (k) { out[k] = fb[k]; }); + out.maxZoom = max; + out.maxNativeZoom = Math.min(own, max); + return out; + } + + // A vector layer that fell back for a transient reason while MapLibre has + // loaded since (map-vector.js decides): rebuilding it now mounts GL. + function _vectorStale(layer) { + if (typeof window.MC_vectorLayerStale !== 'function') return false; + try { return !!window.MC_vectorLayerStale(layer); } catch (_) { return false; } + } + + function _buildRaster(desc) { + var u = desc.url || desc.baseUrl; + var url = (typeof u === 'function') ? u() : u; + var lopts = _rasterOpts(desc); + var layer = L.tileLayer(url, lopts); + if (desc.refUrl && typeof L.layerGroup === 'function') { + layer = L.layerGroup([layer, L.tileLayer(desc.refUrl, _rasterOpts(desc))]); + } + return layer; + } + + /** + * Build the Leaflet layer for an overlay entry (window.MC_TILE_OVERLAYS[id]). + * Raster -> L.tileLayer; hillshade -> MC_createHillshadeLayer (map-hillshade.js). + * opts.pane puts the layer in that map pane (MC_attachAutoTiles passes its + * map's overlay pane, which the tile pane's CSS filter does not reach). + * + * @param {Object} overlay + * @param {{pane?: string}} [opts] + * @returns {L.Layer|null} null when the overlay can't be built here + */ + window.MC_buildOverlayLayer = function (overlay, opts) { + opts = opts || {}; + if (!overlay || typeof overlay.url !== 'string') return null; + var o = { + attribution: overlay.attribution || '', + maxZoom: overlay.maxZoom || _DEFAULT_MAX_ZOOM, + opacity: (typeof overlay.opacity === 'number') ? overlay.opacity : 1, + zIndex: (typeof overlay.zIndex === 'number') ? overlay.zIndex : OVERLAY_Z + }; + if (typeof overlay.maxNativeZoom === 'number' && isFinite(overlay.maxNativeZoom)) o.maxNativeZoom = overlay.maxNativeZoom; + var layer = null; + try { + if (overlay.kind === 'hillshade') { + if (typeof window.MC_createHillshadeLayer !== 'function') return null; + o.url = overlay.url; + layer = window.MC_createHillshadeLayer(o); + } else if (overlay.kind === 'raster') { + if (overlay.subdomains) o.subdomains = overlay.subdomains; + if (opts.pane) o.pane = opts.pane; + layer = L.tileLayer(overlay.url, o); + } + } catch (_) { layer = null; } + // The hillshade factory's options don't name a pane; Leaflet reads + // options.pane when the layer is added, so set it on the instance. + if (layer && opts.pane && layer.options) layer.options.pane = opts.pane; + return layer || null; + }; + + + // ── Picker grouping ───────────────────────────────────────────────────── + + var PICKER_GROUPS = [ + { category: 'street', heading: 'Street' }, + { category: 'topo', heading: 'Topographic' }, + { category: 'satellite', heading: 'Satellite' } + ]; + var PICKER_TYPES = ['light', 'dark', 'any']; + var PICKER_AUTO_KEY = '__auto__'; + var PICKER_AUTO_TITLE = 'Follows the app\'s current light/dark theme'; + + // Entries of an unknown category list under Street (the contract default). + function _categoryOf(p) { + return (p && _inSet(CATEGORIES, p.category)) ? p.category : 'street'; + } + + // Registry ids in picker order: group, then type, then plain entries before + // style:'gray' ones, then registry order. Entries of any other type are not + // listed (as before). + function _pickerOrder() { + var ids = Object.keys(REGISTRY); + var out = []; + PICKER_GROUPS.forEach(function (g) { + PICKER_TYPES.forEach(function (t) { + [false, true].forEach(function (gray) { + ids.forEach(function (id) { + var p = REGISTRY[id]; + if (p && p.type === t && _categoryOf(p) === g.category && (p.style === 'gray') === gray) out.push(id); + }); + }); + }); + }); + return out; + } + + function _headingOf(category) { + for (var i = 0; i < PICKER_GROUPS.length; i++) { + if (PICKER_GROUPS[i].category === category) return PICKER_GROUPS[i].heading; + } + return category; + } + + // DOM surgery on a freshly rendered L.control.layers base list. Leaflet is + // handed raw ids as names (so e.name is the exact id); here each label gets + // data-tile-id and its plain-text label (S2: textContent, never innerHTML), + // and each category's labels move into a
whose names + // the group, so screen readers announce it before the group's radios. A + // separator splits a group's light entries from its dark ones. Auto stays + // first, outside any group. + function _decorateControl(control) { + try { + var labels = control.getContainer().querySelectorAll('.leaflet-control-layers-base label'); + var group = null, groupCat = null, sawLight = false, sepDone = false; + for (var i = 0; i < labels.length; i++) { + var labelEl = labels[i]; + var spans = labelEl.querySelectorAll('span'); + if (spans.length === 0) continue; + + // Target the last span to avoid nuking Leaflet's radio + var span = spans[spans.length - 1]; + var id = span.textContent.trim(); + labelEl.setAttribute('data-tile-id', id); + + if (id === PICKER_AUTO_KEY) { + span.textContent = ' '; + var auto = document.createElement('span'); + auto.title = PICKER_AUTO_TITLE; + auto.textContent = 'Auto'; + span.appendChild(auto); + continue; + } + var p = REGISTRY[id]; + if (!p) continue; + span.textContent = ' ' + (p.label || id); + + var cat = _categoryOf(p); + if (cat !== groupCat) { + group = document.createElement('fieldset'); + group.className = 'mc-tile-group'; + var legend = document.createElement('legend'); + legend.className = 'mc-tile-group-heading'; + legend.textContent = _headingOf(cat); + group.appendChild(legend); + labelEl.parentNode.insertBefore(group, labelEl); + groupCat = cat; + sawLight = false; + sepDone = false; + } + if (p.type === 'dark' && sawLight && !sepDone) { + var sep = document.createElement('div'); + sep.className = 'leaflet-control-layers-separator'; + group.appendChild(sep); + sepDone = true; + } + group.appendChild(labelEl); + if (p.type === 'light') sawLight = true; + } + } catch (_) {} + _decorateOverlays(control); + } + + // The overlay checkboxes get the same treatment: data-tile-overlay-id, + // plain-text label (S2), and one 'Overlays' fieldset styled like the + // category groups. Leaflet names them by id (control._mcOverlayIds). + function _decorateOverlays(control) { + var ids = control._mcOverlayIds; + if (!ids) return; + try { + var labels = control.getContainer().querySelectorAll('.leaflet-control-layers-overlays label'); + var group = null; + for (var i = 0; i < labels.length; i++) { + var labelEl = labels[i]; + var spans = labelEl.querySelectorAll('span'); + if (spans.length === 0) continue; + var span = spans[spans.length - 1]; + var id = span.textContent.trim(); + if (!_inSet(ids, id) || !_hasOverlay(id)) continue; + labelEl.setAttribute('data-tile-overlay-id', id); + span.textContent = ' ' + (OVERLAYS[id].label || id); + if (!group) { + group = document.createElement('fieldset'); + group.className = 'mc-tile-group mc-tile-overlays'; + var legend = document.createElement('legend'); + legend.className = 'mc-tile-group-heading'; + legend.textContent = 'Overlays'; + group.appendChild(legend); + labelEl.parentNode.insertBefore(group, labelEl); + } + group.appendChild(labelEl); + } + } catch (_) {} + } + + /** * Build and attach a Leaflet layer control listing "Auto (follows theme)" * at the top, then every enabled provider as an individual selectable base @@ -343,25 +1165,34 @@ * selecting a specific provider overrides it. * * @param {L.Map} map - The Leaflet map instance - * @param {L.LayerGroup} autoLayerGroup - Existing group managed by _syncDarkTiles + * @param {L.LayerGroup} autoLayerGroup - the theme-synced group MC_attachAutoTiles owns */ + // Overlays are listed only on pickers MC_attachAutoTiles builds (they need + // its per-map overlay set); this public form lists base layers only. window.MC_createLayerControl = function(map, autoLayerGroup, position) { + var lc = _createLayerControl(map, autoLayerGroup, position, null); + return lc ? lc.control() : null; + }; + + // Implementation of MC_createLayerControl. Returns { control(), detach() } so + // MC_attachAutoTiles can tear the control down with its map; the public + // function keeps returning just the L.control.layers instance. + function _createLayerControl(map, autoLayerGroup, position, overlaySet) { if (typeof L === 'undefined') return null; // Set a default position just in case it isn't provided var controlPosition = position || 'topleft'; - var AUTO_KEY = '__auto__'; - var AUTO_LABEL = ' Auto'; + var AUTO_KEY = PICKER_AUTO_KEY; var _control = null; // current L.control.layers instance var _layerMap = {}; // provider-id → L.tileLayer var _isAuto = true; // true when "Auto" is the active selection - var _overrideLightId = null; - var _overrideDarkId = null; + var _explicitId = null; // the entry the user picked while not Auto - // Restore the auto tile group and kick _syncDarkTiles + // Restore the auto tile group; the event makes MC_attachAutoTiles re-sync it function _activateAuto() { _isAuto = true; + _explicitId = null; try { var pane = map.getPane('tilePane'); if (pane) pane.removeAttribute('data-explicit-layer'); @@ -380,7 +1211,7 @@ function _buildControl() { // Tear down existing control + explicit tile layers - if (_control) { try { _control.remove(); } catch (_) {} _control = null; } + if (_control) { try { _control.remove(); } catch (_) {} _control = null; map._mcLayerControl = null; } Object.keys(_layerMap).forEach(function (id) { try { map.removeLayer(_layerMap[id]); } catch (_) {} }); @@ -389,36 +1220,40 @@ if (map._mcBaselayerchangeHandler) { try { map.off('baselayerchange', map._mcBaselayerchangeHandler); } catch (_) {} } + _offOverlayHandler(); - var isDark = _isDarkEffective(); - var activeDarkId = _overrideDarkId || getActiveId(); - var activeLightId = _overrideLightId || getActiveLightId(); - - // Light providers first, then dark — natural grouping in the UI - var lightIds = Object.keys(REGISTRY).filter(function (id) { return REGISTRY[id].type === 'light'; }); - var darkIds = Object.keys(REGISTRY).filter(function (id) { return REGISTRY[id].type === 'dark'; }); + // Grouped by category (Street, Topographic, Satellite); within a group + // light entries first, then dark, then theme-neutral ('any') ones. + var orderedIds = _pickerOrder(); function _makeLayer(id) { var p = REGISTRY[id]; - var url = typeof p.url === 'function' ? p.url() : p.url; - var opts = { attribution: p.attribution || '', maxZoom: p.maxZoom || 19 }; - var layer = L.tileLayer(url, opts); - - // Two-layer providers (Esri Dark Gray Canvas) ship their place labels as - // a separate transparent reference tileset that has to be stacked on the - // base. The theme-synced path in map.js/live.js already does this; the - // layer control did not, so picking such a provider explicitly produced - // a map with no place names at all. - if (p.refUrl && typeof L.layerGroup === 'function') { - layer = L.layerGroup([layer, L.tileLayer(p.refUrl, opts)]); - } - + // Shared builder: also stacks a two-layer provider's (Esri) labels + // reference tileset on its base, so an explicit pick keeps place names. + // A vector entry is an empty group until first picked: building it + // starts the MapLibre download, which only a vector pick should cost. + var isVector = p.format === 'vector'; + var layer = isVector ? L.layerGroup() : window.MC_buildTileLayer(p); + var inner = null; + // Every explicit layer enforces its own filter and locks the pane layer.on('add', function () { + // Re-picked after a transient fallback (MapLibre timed out, then + // arrived): build it again instead of keeping the raster. + if (isVector && inner && _vectorStale(inner)) { + layer.removeLayer(inner); + inner = null; + } + if (isVector && !inner) { + inner = window.MC_buildTileLayer(p); + layer.addLayer(inner); + } var pane = map.getPane('tilePane'); if (pane) { pane.setAttribute('data-explicit-layer', 'true'); - pane.style.filter = p.invertFilter || ''; // Clears it if null! + // Clears it if null; an 'any' entry is never inverted; a `filter` + // entry gets its filter whatever the theme. + pane.style.filter = p.filter || ((p.type === 'any') ? '' : (p.invertFilter || '')); } }); @@ -430,50 +1265,47 @@ var baseMaps = {}; baseMaps[AUTO_KEY] = autoLayerGroup; - lightIds.forEach(function (id) { baseMaps[id] = _makeLayer(id); }); - darkIds.forEach(function (id) { baseMaps[id] = _makeLayer(id); }); + orderedIds.forEach(function (id) { baseMaps[id] = _makeLayer(id); }); // Use the dynamic controlPosition variable instead of a hardcoded string - _control = L.control.layers(baseMaps, null, { position: controlPosition }).addTo(map); + // Overlay checkboxes, keyed by id (S2: relabelled as text below). + var overlayMaps = overlaySet ? overlaySet.layers() : null; + var overlayIds = overlayMaps ? Object.keys(overlayMaps) : []; + if (!overlayIds.length) overlayMaps = null; - // DOM surgery: map IDs to human-readable labels, inject separator, set data attributes. - // We pass raw IDs to Leaflet as keys so e.name is the exact ID without label parsing. - try { - var firstDarkId = darkIds.length > 0 ? darkIds[0] : null; - var labels = _control.getContainer().querySelectorAll('.leaflet-control-layers-base label'); - for (var i = 0; i < labels.length; i++) { - var labelEl = labels[i]; - var spans = labelEl.querySelectorAll('span'); - if (spans.length === 0) continue; - - // Target the last span to avoid nuking Leaflet's radio - var span = spans[spans.length - 1]; - - var id = span.textContent.trim(); - labelEl.setAttribute('data-tile-id', id); - - if (id === AUTO_KEY) { - span.innerHTML = AUTO_LABEL; - } else if (REGISTRY[id]) { - span.innerHTML = ' ' + (REGISTRY[id].label || id); - } - - if (id === firstDarkId && lightIds.length > 0) { - var sep = document.createElement('div'); - sep.className = 'leaflet-control-layers-separator'; - labelEl.parentNode.insertBefore(sep, labelEl); - } - } - } catch (_) {} + _control = L.control.layers(baseMaps, overlayMaps, { position: controlPosition }).addTo(map); + // The overlay set defers its sync while this control handles a click. + map._mcLayerControl = _control; + if (overlayMaps) { + _control._mcOverlayIds = {}; + overlayIds.forEach(function (id) { _control._mcOverlayIds[id] = true; }); + } + + _decorateControl(_control); + // Leaflet re-renders the list from raw ids whenever a listed layer is + // added or removed other than by a click; re-apply the labels and groups. + if (typeof _control._update === 'function') { + var leafletUpdate = _control._update; + _control._update = function () { + var r = leafletUpdate.apply(this, arguments); + _decorateControl(this); + return r; + }; + } + + // The pinned map, saved by a pick here or on another page, wins; a + // pin that is gone (or none) means Auto. + var pinned = getPinnedId(); + _isAuto = !pinned; + _explicitId = pinned; // Decide initial active layer if (_isAuto) { // Ensure autoLayerGroup is on the map; explicit layers are off _activateAuto(); } else { - // Re-select whichever explicit provider was active before rebuild - var prevId = isDark ? activeDarkId : activeLightId; - var prevLayer = _layerMap[prevId]; + // Re-select the explicit pick (whatever its type), if still registered + var prevLayer = _explicitId ? _layerMap[_explicitId] : null; if (prevLayer) { map.addLayer(prevLayer); try { if (autoLayerGroup && map.hasLayer(autoLayerGroup)) map.removeLayer(autoLayerGroup); } catch (_) {} @@ -484,6 +1316,7 @@ map._mcBaselayerchangeHandler = function (e) { if (e.name === AUTO_KEY) { + setPinned(null); // before _activateAuto, whose sync resolves the theme map _activateAuto(); return; } @@ -493,6 +1326,8 @@ if (!REGISTRY[selectedId]) return; _isAuto = false; + _explicitId = selectedId; + setPinned(selectedId); // saved: this and every other map follow it try { var pane = map.getPane('tilePane'); // Contract: mark the pane as explicit so applyTileFilter skips auto-theme CSS filters @@ -502,31 +1337,378 @@ // Hide autoLayerGroup while an explicit layer is active try { if (autoLayerGroup && map.hasLayer(autoLayerGroup)) map.removeLayer(autoLayerGroup); } catch (_) {} - var p = REGISTRY[selectedId]; - if (p.type === 'light') _overrideLightId = selectedId; - else _overrideDarkId = selectedId; - // CSS invert filter is handled by the layer's own add/remove events above }; // Now attach the correctly assigned handler map.on('baselayerchange', map._mcBaselayerchangeHandler); + // A ticked/unticked overlay becomes the shared preference; every map's + // overlay set mirrors it through OVERLAYS_EVENT. The set's own adds and + // removes (restore, mirror, destroy) are not user choices: skipped. + if (overlayMaps) { + map._mcOverlayHandler = function (e) { + var ids = _control && _control._mcOverlayIds; + if (!e || !ids || overlaySet.busy() || !_inSet(ids, e.name)) return; + window.MC_setTileOverlay(e.name, e.type === 'overlayadd'); + }; + map.on('overlayadd', map._mcOverlayHandler); + map.on('overlayremove', map._mcOverlayHandler); + } + return _control; } _buildControl(); // Re-build when server config arrives async so newly-enabled providers appear - window.addEventListener('mc-tile-provider-changed', function (e) { + function _onConfig(e) { if (e && e.detail && e.detail.fromConfig) _buildControl(); - }); + } + window.addEventListener(EVENT_NAME, _onConfig); - // When the site theme flips, update the Auto tile via the existing _syncDarkTiles - // path (map.js/live.js listen for mc-tile-provider-changed and call _syncDarkTiles). + // When the site theme flips, MC_attachAutoTiles (which owns autoLayerGroup) + // re-syncs the Auto tile on its own data-theme observer and on + // mc-tile-provider-changed. // Nothing extra needed here — autoLayerGroup is managed externally. - return _control; + function _offOverlayHandler() { + if (!map._mcOverlayHandler) return; + try { map.off('overlayadd', map._mcOverlayHandler); } catch (_) {} + try { map.off('overlayremove', map._mcOverlayHandler); } catch (_) {} + map._mcOverlayHandler = null; + } + + function _detach() { + try { window.removeEventListener(EVENT_NAME, _onConfig); } catch (_) {} + if (map._mcBaselayerchangeHandler) { + try { map.off('baselayerchange', map._mcBaselayerchangeHandler); } catch (_) {} + map._mcBaselayerchangeHandler = null; + } + _offOverlayHandler(); + if (_control) { try { _control.remove(); } catch (_) {} _control = null; map._mcLayerControl = null; } + Object.keys(_layerMap).forEach(function (id) { + try { map.removeLayer(_layerMap[id]); } catch (_) {} + }); + _layerMap = {}; + try { + var pane = map.getPane('tilePane'); + if (pane) pane.removeAttribute('data-explicit-layer'); + } catch (_) {} + } + + return { control: function () { return _control; }, detach: _detach }; + } + + + // ── Overlay preference + per-map overlay set ──────────────────────────── + // The ticked overlays are a per-browser preference shared by every map + // (like the provider pick), so they are not put in the URL hash. + + var _overlaysMemo = null; // last value written, for when localStorage throws + var _overlaysUnsaved = false; // the last write failed: _overlaysMemo is newer than storage + + function _rawOverlays() { + // A failed write (quota) leaves an older value in storage that getItem + // still returns; the page's own copy wins until a write succeeds. + if (_overlaysUnsaved) return _overlaysMemo; + try { + if (window.localStorage) return window.localStorage.getItem(OVERLAYS_KEY); + } catch (_) { /* storage blocked: use the in-page copy */ } + return _overlaysMemo; + } + + // S7: the stored value is untrusted. Parsed in try/catch; only registered + // ids are kept, each once, at most one per registered overlay. + function _readOverlays() { + var raw = _rawOverlays(); + if (typeof raw !== 'string' || !raw || raw.length > OVERLAYS_RAW_MAX) return []; + var arr; + try { arr = JSON.parse(raw); } catch (_) { return []; } + if (!Array.isArray(arr)) return []; + var max = Object.keys(OVERLAYS).length; + var out = []; + for (var i = 0; i < arr.length && out.length < max; i++) { + if (_hasOverlay(arr[i]) && out.indexOf(arr[i]) < 0) out.push(arr[i]); + } + return out; + } + + function _dispatch(name, detail) { + try { + var ev = (typeof CustomEvent === 'function') + ? new CustomEvent(name, { detail: detail }) + : { type: name, detail: detail }; + window.dispatchEvent(ev); + } catch (_) { /* dispatch optional */ } + } + + /** @returns {string[]} ids of the ticked overlays that are registered now */ + window.MC_getTileOverlays = function () { + _ensureHillshade(); + return _readOverlays(); + }; + + /** + * Tick or untick an overlay for every map in this browser. Persists to + * localStorage 'mc-tile-overlays' and dispatches 'mc-tile-overlays-changed' + * when the set changes. + * @returns {boolean} false when id is not a registered overlay + */ + window.MC_setTileOverlay = function (id, on) { + _ensureHillshade(); + if (!_hasOverlay(id)) return false; + on = !!on; + var cur = _readOverlays(); + var at = cur.indexOf(id); + if (on === (at >= 0)) return true; + if (on) cur.push(id); else cur.splice(at, 1); + _overlaysMemo = JSON.stringify(cur); + try { + if (window.localStorage) window.localStorage.setItem(OVERLAYS_KEY, _overlaysMemo); + _overlaysUnsaved = false; + } catch (_) { _overlaysUnsaved = true; } + _dispatch(OVERLAYS_EVENT, { id: id, on: on }); + return true; + }; + + // The map pane overlays live in: a sibling of the tile pane (so its CSS + // filter doesn't reach them), above it and below vector/marker panes. + // Created once per map; null when the map can't make panes. + function _overlayPane(map) { + try { + if (typeof map.getPane === 'function' && map.getPane(OVERLAY_PANE)) return OVERLAY_PANE; + if (typeof map.createPane !== 'function') return null; + var el = map.createPane(OVERLAY_PANE); + if (el && el.style) { + el.style.zIndex = String(OVERLAY_Z); + el.style.pointerEvents = 'none'; + } + return OVERLAY_PANE; + } catch (_) { return null; } + } + + // One map's overlay layers, kept in line with the shared preference. + // Layers are built once per registry entry and reused by the picker. + function _overlaySet(map) { + var built = {}; // id -> { entry, layer } + var busy = false; // true while this set adds/removes layers itself + var pane = _overlayPane(map); + + function drop(id) { + try { map.removeLayer(built[id].layer); } catch (_) {} + delete built[id]; + } + + function layerOf(id) { + var e = OVERLAYS[id]; + if (built[id] && built[id].entry !== e) drop(id); // registry rebuilt (config arrived) + if (!built[id]) { + var l = window.MC_buildOverlayLayer(e, { pane: pane }); + if (!l) return null; + built[id] = { entry: e, layer: l }; + } + return built[id].layer; + } + + // { id: layer } for every overlay that can be built, in registry order. + function layers() { + _ensureHillshade(); + var out = {}; + Object.keys(OVERLAYS).forEach(function (id) { + var l = layerOf(id); + if (l) out[id] = l; + }); + return out; + } + + // A sync while this map's layer control handles a click is deferred to + // the next tick. Leaflet applies a click by walking every checkbox, and + // skips redrawing the list for layer changes it sees while doing so: a + // layer added mid-click (say, another tab's pick that is already in + // localStorage before its 'storage' event arrives) would be removed + // again by a later unchecked box, or leave a stale box that the next + // click removes, writing the removal back to every tab. + var deferred = null; + function sync() { + var c = map._mcLayerControl; + if (c && c._handlingClick) { + if (!deferred) deferred = setTimeout(function () { deferred = null; sync(); }, 0); + return; + } + _ensureHillshade(); + var want = {}; + _readOverlays().forEach(function (id) { want[id] = true; }); + busy = true; + try { + Object.keys(built).forEach(function (id) { + if (!_hasOverlay(id) || built[id].entry !== OVERLAYS[id]) { drop(id); return; } + if (!want[id] && map.hasLayer(built[id].layer)) map.removeLayer(built[id].layer); + }); + Object.keys(want).forEach(function (id) { + var l = layerOf(id); + if (l && !map.hasLayer(l)) map.addLayer(l); + }); + } catch (_) { /* map torn down */ } + busy = false; + } + + function onStorage(e) { if (e && e.key === OVERLAYS_KEY) sync(); } + + try { + window.addEventListener(OVERLAYS_EVENT, sync); + window.addEventListener('storage', onStorage); + } catch (_) {} + + function destroy() { + if (deferred) { clearTimeout(deferred); deferred = null; } + try { + window.removeEventListener(OVERLAYS_EVENT, sync); + window.removeEventListener('storage', onStorage); + } catch (_) {} + busy = true; + Object.keys(built).forEach(drop); + busy = false; + } + + return { layers: layers, sync: sync, destroy: destroy, busy: function () { return busy; } }; + } + + + // ── Theme-synced basemap for one map ──────────────────────────────────── + + // Fields of a descriptor that need a new Leaflet layer when they change. + // Anything else (url, attribution, id) is updated in place, which keeps the + // old tiles on screen until the new ones load (no flash). maxZoom rebuilds: + // Leaflet reads it into the map's zoom limits only on layeradd/layerremove, + // so an in-place edit leaves the map capped at (or past) the old value. + function _needsRebuild(a, b) { + return a.format !== b.format || a.refUrl !== b.refUrl || a.maxZoom !== b.maxZoom || + a.maxNativeZoom !== b.maxNativeZoom || String(a.subdomains) !== String(b.subdomains); + } + + function _sameTile(a, b) { + return !_needsRebuild(a, b) && a.id === b.id && a.url === b.url && a.attribution === b.attribution; + } + + // Swap a tile layer's attribution text. Leaflet's attribution control counts + // the text it saw on layeradd, so a layer already on the map has its old text + // removed and the new one added; otherwise layeradd picks the new one up. + function _setAttribution(map, layer, text) { + if (!layer.options || layer.options.attribution === text) return; + var ac = map.attributionControl; + var shown = false; + try { shown = !!(ac && map.hasLayer(layer)); } catch (_) { shown = false; } + if (shown && ac.removeAttribution) { try { ac.removeAttribution(layer.options.attribution); } catch (_) {} } + layer.options.attribution = text; + if (shown && ac.addAttribution) { try { ac.addAttribution(text); } catch (_) {} } + } + + /** + * The theme-synced "Auto" basemap for one Leaflet map. Owns an L.layerGroup + * on the map holding the layer MC_buildTileLayer made from + * MC_resolveTile(MC_isDarkTheme()), and re-syncs it on + * 'mc-tile-provider-changed' and on documentElement data-theme changes. + * Every call keeps its own state, so several maps on one page are + * independent; the config arriving async re-syncs through the same event. + * + * @param {L.Map} map + * @param {{controlPosition?: string}} [opts] - controlPosition adds the + * MC_createLayerControl provider picker at that corner. + * @returns {{group: L.LayerGroup, sync: function(), destroy: function()}} + */ + window.MC_attachAutoTiles = function (map, opts) { + opts = opts || {}; + var group = L.layerGroup().addTo(map); + var cur = null; // descriptor the current layer was built from + var layer = null; // the layer inside group + var destroyed = false; + var observer = null; + var lc = null; + // Overlays come with the picker: surfaces without one (node maps, + // analytics, home, customizer) show none. + var overlays = opts.controlPosition ? _overlaySet(map) : null; + // Marks this map's tile pane as having a picker: its Auto filter (like + // its Auto layer) ignores the pin. + if (opts.controlPosition) { + try { var tp = map.getPane && map.getPane('tilePane'); if (tp && tp.setAttribute) tp.setAttribute('data-mc-picker', 'true'); } catch (_) {} + } + + function themeIsDark() { + return typeof window.MC_isDarkTheme === 'function' ? !!window.MC_isDarkTheme() : _isDark(); + } + + function tilesOf(l) { + return (l && typeof l.getLayers === 'function') ? l.getLayers() : [l]; + } + + function sync() { + if (destroyed) return; + var r; + // On a map with a picker the Auto group is always the theme's map: the + // pin is shown as the explicit layer, never loaded into the hidden group. + try { r = window.MC_resolveTile(themeIsDark(), opts.controlPosition ? { ignorePin: true } : undefined); } catch (_) { return; } + if (!r || !r.url) return; + // A vector entry is built as a raster fallback, so its url can't be + // swapped in place. A vector layer stuck on a transient fallback is + // rebuilt on the next sync once MapLibre is ready. + if (!layer || _needsRebuild(cur, r) || (r.format !== 'raster' && !_sameTile(cur, r)) || _vectorStale(layer)) { + var next = window.MC_buildTileLayer(r); + if (layer) { try { group.removeLayer(layer); } catch (_) {} } + layer = next; + group.addLayer(layer); + } else if (!_sameTile(cur, r)) { + var tiles = tilesOf(layer); + // refUrl is unchanged here, so only the base layer's url can differ. + if (tiles[0] && typeof tiles[0].setUrl === 'function') tiles[0].setUrl(r.url); + tiles.forEach(function (t) { + if (t && t.options) _setAttribution(map, t, r.attribution); + }); + } + cur = r; + // Applied on every sync: the filter can change while the tiles don't + // (an 'any' entry kept across a theme flip). + var pane = null; + try { pane = map.getPane && map.getPane('tilePane'); } catch (_) { pane = null; } + if (typeof window.MC_applyTileFilter === 'function') window.MC_applyTileFilter(pane || undefined); + if (map.attributionControl && map.attributionControl._update) { + try { map.attributionControl._update(); } catch (_) { /* map not ready */ } + } + } + + function onProviderChanged(e) { + // Async config can add/remove/replace overlays (the picker rebuilds too). + if (overlays && e && e.detail && e.detail.fromConfig) overlays.sync(); + // A pick for the other theme doesn't change these tiles. + var type = e && e.detail && e.detail.type; + if (type && type !== (themeIsDark() ? 'dark' : 'light')) return; + sync(); + } + + sync(); + try { window.addEventListener(EVENT_NAME, onProviderChanged); } catch (_) {} + if (typeof MutationObserver === 'function') { + try { + observer = new MutationObserver(function () { sync(); }); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + } catch (_) { observer = null; } + } + if (overlays) overlays.sync(); // restore the ticked overlays + if (opts.controlPosition) lc = _createLayerControl(map, group, opts.controlPosition, overlays); + + function destroy() { + if (destroyed) return; + destroyed = true; + try { window.removeEventListener(EVENT_NAME, onProviderChanged); } catch (_) {} + if (observer) { try { observer.disconnect(); } catch (_) {} observer = null; } + if (lc) { lc.detach(); lc = null; } + if (overlays) { overlays.destroy(); overlays = null; } + try { map.removeLayer(group); } catch (_) {} + layer = null; + cur = null; + } + + return { group: group, sync: sync, destroy: destroy }; }; diff --git a/public/map-vector.js b/public/map-vector.js new file mode 100644 index 000000000..934dd35ca --- /dev/null +++ b/public/map-vector.js @@ -0,0 +1,424 @@ +/* map-vector.js — vector (MapLibre GL) basemaps inside Leaflet (#2428). + * + * Uses Leaflet internals (map._addZoomLimit/_removeZoomLimit, _loaded, + * _transitionEnd, layer._map) and the binding's _glMap: recheck them on any + * Leaflet or maplibre-gl-leaflet upgrade. + * + * MC_loadMapLibre() -> Promise + * Injects, once, MapLibre's stylesheet, its CSP build and the Leaflet + * binding from vendor/ (constant paths + SRI), and points MapLibre at its + * vendored worker (once). Never runs at page load: only when a vector map + * is picked. The promise is cached and rejects only on a script error + * event, never on time; after a failure one later call retries, replacing + * only the tags that errored. Pending tags are never removed or doubled. + * + * MC_buildVectorLayer(desc, opts) -> L.LayerGroup + * desc = { url, attribution, maxZoom, type } (url: MapLibre style JSON) + * opts.fallback() -> raster L.Layer + * Returns a group at once; the GL layer is mounted into it once the + * library is loaded and the group is on a map. No WebGL, a failed load, + * no library within LOAD_TIMEOUT_MS of this layer's build (a per-layer + * timer; the load goes on for later layers), a style that errors before + * its first load/idle, or a lost GL context swap the GL layer for + * opts.fallback(), once. group.mcFallbackReason names why (else null). + * The group registers its maxZoom/minZoom with the map on add and + * unregisters on remove (as a GridLayer does), so the map has a zoom + * limit before, while and after GL is shown. + * + * MC_vectorLayerStale(layer) -> boolean + * True when layer fell back for a transient reason (load-timeout, + * load-failed) and MapLibre has loaded since; callers rebuild it then. + * + * Security: MapLibre's RTL text plugin is never loaded; its attribution control + * stays off (it renders HTML from remote style sources); every URL MapLibre + * requests passes transformRequest, which refuses anything but https (or http + * on an http page), and refuses this page's origin (cookie-bearing) unless the + * style itself is served from it. No config value reaches a script or link URL. + */ +(function () { + 'use strict'; + + // ── VENDOR INTEGRITY TABLE ────────────────────────────────────────────── + // Paths are relative to the page. tests/unit/test-vendored-libs.js parses + // the path/integrity pairs between these markers and checks each against + // the file on disk. The worker cannot carry SRI in the browser (new Worker + // has no integrity option); it is listed so the test still pins its bytes. + // VENDOR-INTEGRITY-BEGIN + var VENDOR = { + css: { path: 'vendor/maplibre-gl-5.24.0/maplibre-gl.css', integrity: 'sha384-uTttxo/aOKbdE5RlD/SPzSDoDmNvGlUYPjONi2MN/b7c9HPSvW07OIuyP7uL6jxK' }, + maplibre: { path: 'vendor/maplibre-gl-5.24.0/maplibre-gl-csp.js', integrity: 'sha384-+lDFpEYaS5ofD0qW/5dA+duOMWMSGs+utCY+wx9H/lS1i0WZ0bQH31giSmqYsxqR' }, + worker: { path: 'vendor/maplibre-gl-5.24.0/maplibre-gl-csp-worker.js', integrity: 'sha384-wBzwLUk46fiEnNOOlHXeylfQrL/SzyNqSD0gYdQJskF9cbBaNcRDYn6ZmSBW4l0z' }, + binding: { path: 'vendor/maplibre-gl-leaflet-0.1.4/leaflet-maplibre-gl.js', integrity: 'sha384-tXYNKOHx4T02jMP7YYCtBxPIv1B5gaA5mcVPBzqMp6d7VzWzxJgI2aWF/nJLrQdS' }, + }; + // VENDOR-INTEGRITY-END + + var LOAD_TIMEOUT_MS = 15000; + var TAG_ATTR = 'data-mc-maplibre'; + + // ── Loader ────────────────────────────────────────────────────────────── + // A script tag cannot be cancelled: once inserted it downloads and runs + // even if removed. So each script is inserted at most once per page and + // left alone while pending; only a tag whose error event fired (it never + // ran) is replaced, on the one retry. The shared promise rejects only on + // such an error; a slow load is a per-layer timeout (buildVectorLayer), + // so a library that arrives late still serves later layers. + // + // The binding captures window.maplibregl when it executes. It is only + // usable if it ran after MapLibre: boundLib records what it captured. + var loadPromise = null; + var loadFailures = 0; + var libTag = null; // the MapLibre