Files
meshcore-analyzer/docs/api-spec.md
T
4ebb5ccc11 feat: radio line-of-sight on packet routes + repeater planner (#2391)
Both features are OPT-IN ("los" and "planner" config blocks, default
off); with them off nothing is fetched and payloads are unchanged.

Route view
- Multi-path picker discoverability: on-map "N hops shown · tap to see
all" badge, picker pulse (reduced-motion safe), one-time tip, row hover
arrow; "no GPS" hops counted apart from "unresolved".
- Line of sight for every leg of a packet route: clear / marginal /
blocked chips (first-Fresnel clearance, k=4/3), obstruction markers on
the map, docked terrain-profile panel with antenna/frequency inputs and
a &los= deep link. Backed by GET /api/elevation/profile, an Open-Meteo
proxy that only accepts known node positions, with weighted budgets,
back-off and a per-IP limit.

Repeater planner (#/tools/planner)
- Chain: LOS on every leg between any number of points or nodes.
- Relay: best single relay for A→B among known repeaters and open
terrain.
- Area: suggested new repeater sites that best join the existing
repeater backbone in a box up to 100×100 km, picked greedily to merge
clusters, then remove single points of failure, then reach unlinked
repeaters.
- Terrain: SRTM 1° tiles from AWS Open Data, in memory only (~90 m,
bounded LRU); the server stays read-only. Exact-length gunzip, fetch
budget with back-off, missing terrain reported rather than read as sea
level, fuzzed pixel maths.
- GET /api/planner/{profile,relay,coverage}: quantised cache keys, 202 +
progress then cached 200, separate compute slots, per-IP and global
limits, failed jobs remembered, unpolled jobs cancelled. Nodes pass the
same blacklist / hidden-name / geo_filter rules as /api/nodes. The Go
LOS maths matches public/los.js on shared test vectors.

Also: the per-IP client limiter is extracted from elevation.go into
client_limit.go (behaviour-preserving) so both features share it.

Perf (real SRTM): coverage cold 1.5-5.6 s (tile download), warm 10 ms;
worst real compute 545 ms; peak RSS 91 MiB; live /api/nodes and
/api/packets p95 at most 1.6x while a job computes (GOMAXPROCS=2).

Tests: Go suites for elevation, terrain (fuzz), LOS vectors, graph
(brute-force property test), search and planner API; frontend unit
suites in test-all.sh; Playwright e2e for route LOS and the planner.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: efiten <erwin.fiten@gmail.com>
2026-11-16 16:15:36 +01:00

135 KiB
Raw Blame History

CoreScope — API Contract Specification

Authoritative contract. Both the Node.js and Go backends MUST conform to this spec. The frontend relies on these exact shapes. Breaking changes require a spec update first.

Version: 1.1.0 Last updated: 2026-04-22


Table of Contents


Conventions

Types

Notation Meaning
string JSON string
number JSON number (integer or float)
boolean true / false
string (ISO) ISO 8601 timestamp, e.g. "2025-07-17T04:23:01.000Z"
string (hex) Hex-encoded bytes, uppercase, e.g. "4F01A3..."
number | null May be null when data is unavailable
[T] JSON array of type T; always [] when empty, never null
object Nested JSON object (shape defined inline)

Null Rules

  • Fields marked | null may be absent or null.
  • Array fields MUST be [] when empty, NEVER null.
  • String fields that are "unknown" SHOULD be null, not "".

Pagination

Paginated endpoints accept limit (default 50) and offset (default 0) as query params. They return total (the unfiltered/filtered count before pagination).

Error Responses

{ "error": "string" }
  • 400 — Bad request (missing/invalid params)
  • 404 — Resource not found

User management (optional)

These routes are registered only when userManagement.enabled is true. When it is off they do not exist, and requests to them fall through to the SPA page (HTTP 200, HTML). The webhook route exists only when mail.webhookSecret is also set, and only for the configured mail.provider. Sessions use the cs_session cookie (HttpOnly, SameSite=Lax). Every state-changing request that authenticates with the cookie needs an Origin (or Referer) equal to publicBaseUrl and the header X-CS-CSRF: <csrfToken from GET /api/auth/me>. Errors are {"error": "<message>"}. Rate-limited calls answer 429 with Retry-After. Request bodies are JSON. On every route except the webhook and PUT /api/account/settings they are limited to 16 KiB and unknown fields are rejected with 400; the webhooks take up to 256 KiB of the provider's payload as is.

Method and path Auth Body and response
POST /api/auth/register origin {email, displayName, password} -> {ok, message}, identical for known addresses. Registering a pending address again replaces its password and name and mails a new link
POST /api/auth/activate origin {token, password} -> me + session cookie. 410 expired, used or already activated; 401 "wrong password for this account" (the link stays usable); 409 "account changed, try again" when the account changed between the password check and the activation (for example a re-register)
POST /api/auth/login origin {email, password} -> me + cookie. 401 "incorrect email or password" for every failure, including pending and disabled accounts
POST /api/auth/logout origin -> {ok}
GET /api/auth/me session -> {id, email, displayName, role, csrfToken}. 401 when not logged in
POST /api/auth/forgot origin {email} -> {ok, message}
POST /api/auth/reset origin {token, password} -> {ok, message}. Ends all sessions and any pending email-change link. 410 expired or used
PATCH /api/account session {displayName} -> me
POST /api/account/password session {currentPassword, newPassword} -> {ok, message}. Ends the other sessions and outstanding reset and email-change links
POST /api/account/email session {newEmail, currentPassword} -> {ok, message}. Rate-limited. A confirmation goes to the new address and a notice to the old one; the answer is the same when the new address is already in use
POST /api/account/confirm-email origin {token} -> {ok, message}. 410 expired or used; 409 address now in use
GET /api/account/sessions session -> [{id, createdAt, lastSeenAt, expiresAt, userAgent, current}]
DELETE /api/account/sessions/{id} session -> {ok}. 404 not your session
GET /api/account/settings session -> {revision, generation, doc, allowlist}. doc is {v: 1, keys: {<localStorage key>: <raw string>}}, or null at revision 0. generation is a random id of the stored document ("" at revision 0): revisions restart at 1 after a DELETE, the generation does not repeat. allowlist is [{key, kind, id?}]: kind is set (JSON array merged per item; id names the field that identifies an item, absent means the item itself) or scalar
PUT /api/account/settings session {baseRevision, baseGeneration, doc} -> {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 for another shape, a key that is never synced (corescope_channel_*, live-channel-colors, meshcore-api-key) or a key not in the allowlist; 413 when doc is over 256 KiB (body cap 264 KiB); 429 above 60 PUT requests per hour per user
DELETE /api/account/settings session -> {ok}. The next PUT with baseRevision 0 starts a new document in a new generation
GET /api/account/export session -> attachment corescope-account-<YYYY-MM-DD>.json: {formatVersion: 1, exportedAt, instance, profile, sessions, companions, settings, proposals, notifications, audit, mail}. profile is {id, email, displayName, role, status, createdAt, lastLoginAt, emailBouncing, activatedAt, activatedBy} (activatedBy is the admin id, null for a link activation); sessions [{kind, label?, createdAt, lastSeenAt, userAgent?}] (kind is web or device, label the device name); companions [{pubkey, name, linkedAt}]; settings {revision, updatedAt, doc} or null; proposals [{kind, subject, status, note, createdAt, decidedAt}]; notifications {prefs: {enabled, events} or null, watches: [{pubkey, createdAt}]}; audit [{at, action, actorUserId, targetUserId, detail}] (other accounts by id only); mail [{to, purpose, sentAt, status, statusAt, reason?, events}]. No row caps. No password hash, no session, link or unsubscribe token and no companion link challenge. Writes a user.export audit row afterwards
DELETE /api/account session {currentPassword} -> {ok, message}. 409 you are the last admin
GET /api/admin/users?status=&role=&q=&bouncing= admin -> [adminUser], at most 1000, newest first. status is pending, active or disabled; role is user or admin; bouncing=1 keeps only addresses whose mail bounces (any other value is 400)
GET /api/admin/users/{id} admin -> {user, sessions, mail, audit}
POST /api/admin/users/{id}/disable admin -> adminUser. Active accounts only; ends the user's sessions and links
POST /api/admin/users/{id}/enable admin -> adminUser. Disabled accounts only
DELETE /api/admin/users/{id} admin -> {ok}
POST /api/admin/users/{id}/role admin {role} (user or admin) -> adminUser
POST /api/admin/users/{id}/resend-activation admin -> adminUser. Pending accounts only
POST /api/admin/users/{id}/activate admin -> adminUser. Pending accounts only; the address stays unverified
POST /api/admin/users/{id}/mail/{mailId}/refresh admin -> mail record with events, pulled from the provider. 502 provider unavailable
GET /api/admin/audit?action=&user=&from=&to=&before=&limit= admin -> {entries, next}, newest first. action is one action or a group ending in .* (user.login.*); user matches actor or target; from/to are RFC 3339 and inclusive; pass next as before for the next page (null on the last page); limit defaults to 100, capped at 500. Entry: {id, at, action, actor, target, detail}, with actor and target {id, displayName, email}, {id, deleted: true} or null (system). Login rows are kept 90 days. 400 on an invalid parameter
GET /api/admin/stats admin -> {total, active, pending, disabled, admins, stuckPending, bouncing, new7d, new30d, newPerDay, active7d, active30d, logins24h, failedLogins24h, mail7d, guessing}. newPerDay is [{day, count}] for 30 UTC days, oldest first; registrations count user.register audit rows. stuckPending counts pending accounts older than 24 hours. mail7d is {delivered, bounced, blocked, spam, pending, other} by latest delivery event. guessing is [{userId, displayName, failed}]: accounts with 5 or more failed logins in 24 hours
GET /api/admin/users-backup admin -> application/octet-stream, attachment corescope-users-<YYYYMMDD-HHMMSS>.db (UTC): a fresh consistent copy of users.db. It holds every password hash and address, so store it encrypted. Writes a user.backup audit row. Restore: docs/user-guide/accounts.md, Backups
POST /api/mail/brevo/webhook Authorization: Bearer <webhookSecret> Brevo transactional event payload -> {ok}. 401 on a wrong secret
POST /api/mail/postal/webhook HTTP Basic auth, password <webhookSecret> (any user name) Postal webhook payload {event, timestamp, payload, uuid} -> {ok}, also for events that are not about a message. 401 on a wrong secret

adminUser = {id, email, displayName, role, status, createdAt, activatedAt, activatedManually, activatedBy, lastLoginAt, emailBouncing, configAdmin, lastMail}. status is pending, active or disabled.

Error codes you can get on the routes above:

Code Meaning
400 Validation failed (email, display name, password, role, filter, id)
401 Not logged in, or wrong password on activate or login
403 "CSRF check failed", "request origin not allowed", "admin role required", or "current password is incorrect" (password change, email change, account delete)
404 "user not found" (admin {id} routes), "mail not found" (mail refresh), "session not found" (DELETE /api/account/sessions/{id})
409 A state guard: "only active accounts can be disabled; ...", role change on a pending account, disable or delete of yourself, disable, delete or demotion of a config admin or the last admin, enable of a non-disabled account, "this mail has no provider message id" (mail refresh), "account changed, try again" (activate)
410 Link expired, invalid or already used
429 Rate limit; see Retry-After
502 "mail provider unavailable" (mail refresh)
503 "mail could not be sent, try again later"

With user management on, every endpoint that needs X-API-Key also accepts an admin session (plus the CSRF header for unsafe methods). A request that sends X-API-Key is judged on the key alone. GET /api/config/client gains "userManagement": {"enabled": true} only when the feature is on; that block also carries "companionLinking": true on servers with the device-token and companion routes, which CoreDrive RX checks before it shows its login (an older server answers those paths with the SPA page).


GET /api/stats

Server-wide statistics. Lightweight, cached 10s.

Response 200

{
  "totalPackets":        number,       // observation count (legacy name)
  "totalTransmissions":  number | null, // unique transmission count
  "totalObservations":   number,       // total observation records
  "totalNodes":          number,       // active nodes (last 7 days)
  "totalNodesAllTime":   number,       // all nodes ever seen
  "totalObservers":      number,       // observer device count
  "packetsLastHour":     number,       // observations in last hour
  "engine":              "node",       // backend engine identifier
  "version":             string,       // package.json version, e.g. "2.6.0"
  "commit":              string,       // git short SHA or "unknown"
  "counts": {
    "repeaters":         number,       // active repeaters (last 7 days)
    "rooms":             number,
    "companions":        number,
    "sensors":           number
  }
}

GET /api/health

Server health and telemetry. Used by monitoring.

Response 200

{
  "status":    "ok",
  "engine":    "node",
  "version":   string,
  "commit":    string,
  "uptime":    number,          // seconds
  "uptimeHuman": string,       // e.g. "4h 32m"
  "memory": {
    "rss":       number,       // MB
    "heapUsed":  number,       // MB
    "heapTotal": number,       // MB
    "external":  number        // MB
  },
  "eventLoop": {
    "currentLagMs": number,
    "maxLagMs":     number,
    "p50Ms":        number,
    "p95Ms":        number,
    "p99Ms":        number
  },
  "cache": {
    "entries":    number,
    "hits":       number,
    "misses":     number,
    "staleHits":  number,
    "recomputes": number,
    "hitRate":    number        // percentage (0–100)
  },
  "websocket": {
    "clients":   number        // connected WS clients
  },
  "packetStore": {
    "packets":      number,    // loaded transmissions
    "estimatedMB":  number
  },
  "perf": {
    "totalRequests": number,
    "avgMs":         number,
    "slowQueries":   number,
    "recentSlow": [            // last 5
      {
        "path":   string,
        "ms":     number,
        "time":   string,      // ISO timestamp
        "status": number       // HTTP status
      }
    ]
  }
}

GET /api/perf

Detailed performance metrics per endpoint.

Response 200

{
  "uptime":        number,          // seconds since perf stats reset
  "totalRequests": number,
  "avgMs":         number,
  "endpoints": {
    "/api/packets": {               // keyed by route path
      "count":  number,
      "avgMs":  number,
      "p50Ms":  number,
      "p95Ms":  number,
      "maxMs":  number
    }
    // ... more endpoints
  },
  "slowQueries": [                  // last 20 queries > 100ms
    {
      "path":   string,
      "ms":     number,
      "time":   string,             // ISO timestamp
      "status": number
    }
  ],
  "cache": {
    "size":       number,
    "hits":       number,
    "misses":     number,
    "staleHits":  number,
    "recomputes": number,
    "hitRate":    number             // percentage (0–100)
  },
  "packetStore": {                  // from PacketStore.getStats()
    "totalLoaded":       number,
    "totalObservations": number,
    "evicted":           number,
    "inserts":           number,
    "queries":           number,
    "inMemory":          number,
    "sqliteOnly":        boolean,
    "maxPackets":        number,
    "estimatedMB":       number,
    "maxMB":             number,
    "indexes": {
      "byHash":            number,
      "byObserver":        number,
      "byNode":            number,
      "advertByObserver":  number
    }
  },
  "sqlite": {
    "dbSizeMB":    number,
    "walSizeMB":   number,
    "freelistMB":  number,
    "walPages":    { "total": number, "checkpointed": number, "busy": number } | null,
    "rows": {
      "transmissions": number,
      "observations":  number,
      "nodes":         number,
      "observers":     number
    }
  },
  "goRuntime": {                    // Go server only
    "heapMB":       number,         // heap allocation in MB
    "sysMB":        number,         // total system memory in MB
    "numGoroutine": number,         // active goroutines
    "numGC":        number,         // completed GC cycles
    "gcPauseMs":    number          // last GC pause in ms
  }
}

POST /api/perf/reset

Resets performance counters. Requires API key.

Headers

  • X-API-Key: <key> (required if config.apiKey is set)

Response 200

{ "ok": true }

GET /api/nodes

Paginated node list with filtering.

Query Parameters

Param Type Default Description
limit number 50 Page size
offset number 0 Pagination offset
role string — Filter by role: repeater, room, companion, sensor
region string — Comma-separated IATA codes for regional filtering
area string — Area key from config.json — filters to nodes whose GPS falls inside the area polygon (see Area Filter)
lastHeard string — Recency filter: 1h, 6h, 24h, 7d, 30d
sortBy string lastSeen Sort key: name, lastSeen, packetCount
search string — Substring match on name
before string — ISO timestamp; only nodes with first_seen <= before

Response 200

{
  "nodes": [
    {
      "public_key":    string,           // 64-char hex public key
      "name":          string | null,
      "role":          string,           // "repeater" | "room" | "companion" | "sensor"
      "lat":           number | null,
      "lon":           number | null,
      "last_seen":     string (ISO),
      "first_seen":    string (ISO),
      "advert_count":  number,
      "hash_size":     number | null,    // latest hash size (1–3 bytes)
      "hash_size_inconsistent": boolean, // true if flip-flopping
      "hash_sizes_seen": [number] | undefined, // present only if >1 unique size seen
      "last_heard":    string (ISO) | undefined, // from in-memory packets or path relay
      "default_scope": string | null | undefined, // Most recently observed transport scope for this node. null = never observed transport-scoped, "" = observed scoped but no configured region matched, "#name" = matched region. Only present when ingestor has applied the nodes_default_scope_v1 migration.
      "scope_config_state": string | undefined, // Repeater/room only. How this node's region config reads: "full" | "no-unscoped" | "no-scopes" | "no-flood" from its own declared-regions answer, "observed" when it never answered but has been seen forwarding scoped traffic, "none" when it never answered and nothing scoped was observed. Absent for other roles and when the declared-regions lookup failed.
      "declared_regions": [string] | undefined, // Repeater/room only. Named regions from this node's newest declared-regions answer, spelled like GET /api/scope-audit `declaredRegions` (leading "#" stripped, "*" excluded). [] = answered with no named region. Absent = never answered, other roles, no declared-regions source, or the declared-regions lookup failed.
      "declared_regions_truncated": true | undefined // Repeater/room only. Present, and true, only when the answer behind declared_regions was flagged as truncated: the list is partial. Same flag as GET /api/scope-audit `truncated`.
    }
  ],
  "total":  number,                      // total matching count (before pagination)
  "counts": {
    "repeaters":  number,                // global counts (not filtered by current query)
    "rooms":      number,
    "companions": number,
    "sensors":    number
  }
}

Notes:

  • hash_sizes_seen is only present when more than one hash size has been observed.
  • last_heard is only present when in-memory data provides a more recent timestamp than last_seen.
  • declared_regions is what the map's region-scope filter reads (#1862), together with transported_scopes. It is the same list the Scope Audit shows as declaredRegions, split and normalised by the same function, so the audit's region search and the map list a repeater under the same names. Its presence follows scope_config_state: set whenever that field is one of the four declared states. An absent field or a region missing from the list is not evidence that the repeater lacks that region.
  • declared_regions_truncated is set only when the newest declared answer was flagged as cut off (node_declared_regions.truncated), and the map popup then marks the declared list as truncated, as the Scope Audit does. It is never false: the nodes.configured_scope source does not record whether its size cap fired, so an absent field does not mean the list is complete.
  • scope_config_state carries the same four declared states as GET /api/scope-audit and is computed the same way, from the newest declared-regions answer merged across collectors. The audit lists only repeaters that have answered; this field also classifies the ones that have not, which is what the map colours by. "none" means the answer is missing, not that the node is misconfigured: firmware drops scoped floods for regions it holds no key for, so a repeater with no region config and one nobody sends scoped traffic past are indistinguishable here. The four declared states are computed from stored data and do not depend on a window; "observed" and "none" are separated by transported_scopes, which the in-memory packet store accumulates over its retention window, so a node can move between them after a restart. The field is absent entirely when this database carries no declared-regions source at all, since "nobody has answered" is then a claim the schema cannot support.

GET /api/nodes/search

Quick node search for autocomplete/typeahead.

Query Parameters

Param Type Required Description
q string yes Search term (name substring or pubkey prefix)

Response 200

{
  "nodes": [
    {
      "public_key":   string,
      "name":         string | null,
      "role":         string,
      "lat":          number | null,
      "lon":          number | null,
      "last_seen":    string (ISO),
      "first_seen":   string (ISO),
      "advert_count": number
    }
  ]
}

Returns { "nodes": [] } when q is empty.


GET /api/nodes/bulk-health

Bulk health summary for all nodes. Used by analytics dashboard.

Query Parameters

Param Type Default Description
limit number 50 Max nodes (capped at 200)
region string — Comma-separated IATA codes for regional filtering

Response 200

Returns a JSON array (not wrapped in an object):

[
  {
    "public_key": string,
    "name":       string | null,
    "role":       string,
    "lat":        number | null,
    "lon":        number | null,
    "stats": {
      "totalTransmissions": number,
      "totalObservations":  number,
      "totalPackets":       number,   // same as totalTransmissions (backward compat)
      "packetsToday":       number,
      "avgSnr":             number | null,
      "lastHeard":          string (ISO) | null
    },
    // Direct-RF only, same shape and rule as GET /api/nodes/:pubkey/health.
    "observers": [
      {
        "observer_id":   string,
        "observer_name": string | null,
        "avgSnr":        number | null,
        "avgRssi":       number | null,
        "packetCount":   number,
        "can_relay":     boolean | null
      }
    ],
    "relayObserverCount": number
  }
]

Note: This is a bare array, not { nodes: [...] }.


GET /api/nodes/network-status

Aggregate network health status counts.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes

Response 200

{
  "total":      number,
  "active":     number,    // within degradedMs threshold
  "degraded":   number,    // between degradedMs and silentMs
  "silent":     number,    // beyond silentMs
  "roleCounts": {
    "repeater":  number,
    "room":      number,
    "companion": number,
    "sensor":    number
    // may include "unknown" if role is missing
  }
}

GET /api/nodes/:pubkey

Node detail page data.

Path Parameters

Param Type Description
pubkey string Node public key (hex)

Response 200

{
  "node": {
    "public_key":    string,
    "name":          string | null,
    "role":          string,
    "lat":           number | null,
    "lon":           number | null,
    "last_seen":     string (ISO),
    "first_seen":    string (ISO),
    "advert_count":  number,
    "hash_size":     number | null,
    "hash_size_inconsistent": boolean,
    "hash_sizes_seen": [number] | undefined
  },
  "recentAdverts": [Packet]   // last 20 packets for this node, newest first
}

Where Packet is a transmission object (see Packet Object).

Response 404

{ "error": "Not found" }

GET /api/nodes/:pubkey/health

Detailed health information for a single node.

Response 200

{
  "node": {                          // full node row
    "public_key":   string,
    "name":         string | null,
    "role":         string,
    "lat":          number | null,
    "lon":          number | null,
    "last_seen":    string (ISO),
    "first_seen":   string (ISO),
    "advert_count": number
  },
  // Observers that received this node's OWN transmission off the air:
  // a flood packet whose last path hop resolves unambiguously to this
  // node, or a flood ADVERT it originated that arrived with an empty
  // path. Only here do avgSnr/avgRssi describe this node's signal.
  // Direct routes never qualify: their path is the remaining route,
  // not the travelled one.
  "observers": [
    {
      "observer_id":   string,
      "observer_name": string | null,
      "packetCount":   number,
      "avgSnr":        number | null,
      "avgRssi":       number | null,
      "can_relay":     boolean | null  // null = observer never reported a repeat field
    }
  ],
  // Observers that saw traffic through this node without hearing it.
  // The stats below count that relayed traffic, so this keeps the two
  // consistent. Most nodes have no observer in radio range at all.
  "relayObserverCount": number,
  "stats": {
    "totalTransmissions": number,
    "totalObservations":  number,
    "totalPackets":       number,    // same as totalTransmissions (backward compat)
    "packetsToday":       number,
    "avgSnr":             number | null,
    "avgHops":            number,    // rounded integer
    "lastHeard":          string (ISO) | null
  },
  "recentPackets": [                 // last 20 packets, observations stripped
    {
      // Packet fields (see Packet Object) minus `observations`
      "observation_count": number    // added for display
    }
  ]
}

Response 404

{ "error": "Not found" }

GET /api/nodes/:pubkey/paths

Path analysis for a node — all paths containing this node's prefix.

Response 200

{
  "node": {
    "public_key": string,
    "name":       string | null,
    "lat":        number | null,
    "lon":        number | null
  },
  "paths": [
    {
      "hops": [
        {
          "prefix": string,        // raw hex hop prefix
          "name":   string,        // resolved node name
          "pubkey": string | null,
          "lat":    number | null,
          "lon":    number | null
        }
      ],
      "count":      number,        // times this path was seen
      "lastSeen":   string (ISO) | null,
      "sampleHash": string         // hash of a sample packet using this path
    }
  ],
  "totalPaths":         number,    // unique path signatures
  "totalTransmissions": number     // total transmissions with this node in path
}

Response 404

{ "error": "Not found" }

GET /api/nodes/:pubkey/analytics

Per-node analytics over a time range.

Query Parameters

Param Type Default Description
days number 7 Lookback window (1–365)

Response 200

{
  "node": {                          // full node row (same shape as nodes table)
    "public_key": string, "name": string | null, "role": string,
    "lat": number | null, "lon": number | null,
    "last_seen": string (ISO), "first_seen": string (ISO), "advert_count": number
  },
  "timeRange": {
    "from": string (ISO),
    "to":   string (ISO),
    "days": number
  },
  "activityTimeline": [
    { "bucket": string (ISO),  "count": number }   // hourly buckets
  ],
  "snrTrend": [
    {
      "timestamp":     string (ISO),
      "snr":           number,
      "rssi":          number | null,
      "observer_id":   string | null,
      "observer_name": string | null
    }
  ],
  "packetTypeBreakdown": [
    { "payload_type": number, "count": number }
  ],
  "observerCoverage": [
    {
      "observer_id":   string,
      "observer_name": string | null,
      "packetCount":   number,
      "avgSnr":        number | null,
      "avgRssi":       number | null,
      "firstSeen":     string (ISO),
      "lastSeen":      string (ISO)
    }
  ],
  "hopDistribution": [
    { "hops": string, "count": number }    // "0", "1", "2", "3", "4+"
  ],
  "peerInteractions": [
    {
      "peer_key":    string,
      "peer_name":   string,
      "messageCount": number,
      "lastContact": string (ISO)
    }
  ],
  "uptimeHeatmap": [
    { "dayOfWeek": number, "hour": number, "count": number }  // 0=Sun, 0–23
  ],
  "computedStats": {
    "availabilityPct":    number,     // 0–100
    "longestSilenceMs":   number,
    "longestSilenceStart": string (ISO) | null,
    "signalGrade":        string,     // "A", "A-", "B+", "B", "C", "D"
    "snrMean":            number,
    "snrStdDev":          number,
    "relayPct":           number,     // % of packets with >1 hop
    "totalPackets":       number,
    "uniqueObservers":    number,
    "uniquePeers":        number,
    "avgPacketsPerDay":   number
  }
}

Response 404

{ "error": "Not found" }

GET /api/nodes/:pubkey/hop_analytics

Hop count at this node for every flood packet it forwarded, to help choose flood.max, flood.max.unscoped and flood.max.advert. A repeater checks those limits against the number of hashes already in the path, then appends its own hash, so the hop count is the node's zero-based index in the observed path (firmware src/helpers/RoutingPolicy.h, src/Mesh.cpp routeRecvPacket). This is not the hopDistribution of /analytics, which is the path length at the observer.

  • One entry per packet hash. Values are raw so the client can filter and bin.
  • Only floods (route types 0 and 1). DIRECT packets carry the remaining route, not a hop count, and are left out. Packets the node originated are left out.
  • Every observation of every flood packet in the window is read, not only the packet's longest path, so a relay on a shorter branch of the flood counts too.
  • A packet is attributed when the node's path prefix sits at exactly one index across its observations, and either no other relay-capable node shares that prefix, or the hop resolves to the node under the ingestor's strict rule (every earlier hop identified without a tiebreak, and exactly one candidate is a neighbor_edges neighbor of the previous hop, or of the originator for an advert) in at least one observation and to another node in none. The server's resolved-path pick (affinity, GPS distance, advert count) is not used, so the result is the same before and after a restart. Everything else with the node's prefix is counted in ambiguous and left out; in practice that is most packets with a colliding 1-byte path hash.
  • Size: for a busy repeater on a 1,669-node mesh over 7 days (2026-09-13) the response held 23,068 entries, 2.3 MB of JSON, 375 KB gzipped. hash and timestamp are 61% of the raw and 91% of the gzipped bytes; they stay so a client can join entries to packets and bin by time (issue #1812).

Query Parameters

Param Type Default Description
days number 7 Lookback window (1-365)

Response 200

{
  "timeRange": { "from": string (ISO), "to": string (ISO), "days": number },
  "packets": [
    {
      "hash":      string,
      "timestamp": string (ISO),      // first seen
      "hops":      number,            // 0 = heard straight from the originator
      "tags":      [string]           // "flood", then "scoped" or "unscoped", then "advert" if an ADVERT
    }
  ],
  "ambiguous": number                 // prefix matched, hop position not attributable to this node
}

Filters that match the firmware limits: flood.max uses all entries, flood.max.unscoped the entries tagged unscoped, flood.max.advert the entries tagged advert.

Response 404

{ "error": "Not found" }

GET /api/nodes/:pubkey/reach

Per-node RF reach report (two-way link quality). Computes directional link counts from raw path adjacency (a flood path is recorded origin→observer, so in [A,B] B received A directly). A link is bidirectional when both directions have observations; the bottleneck (weaker direction) rates two-way stability. Read-only; bounded to a recent window. Identifies nodes only by unique 2–3 byte path prefixes (1-byte prefixes collide and are excluded).

Query Parameters

Param Type Default Description
days number 7 Lookback window, clamped 1–30

Response 200

{
  "node": { "pubkey": string, "name": string, "role": string,
            "lat": number | null, "lon": number | null, "first_seen": string (ISO) },
  "window": { "days": number, "since": string (ISO) },
  "reliable_tokens": [string],          // uppercase hex prefixes unique to this node ([] if unidentifiable)
  "importance": {
    "neighbor_degree":    number,        // all-time, from neighbor_edges
    "degree_rank":        number,        // 1-based rank among nodes with edges
    "nodes_with_edges":   number,
    "relay_observations": number,        // windowed obs with this node anywhere in path
    "bidirectional_links":number,
    "direct_observers":   number
  },
  "direct_observers": [
    { "pubkey": string, "name": string, "count": number,
      "avg_snr": number | null, "lat": number | null, "lon": number | null,
      "distance_km": number | null }
  ],
  "links": [
    { "pubkey": string, "name": string, "role": string,
      "lat": number | null, "lon": number | null,
      "we_hear": number, "they_hear": number,
      "bottleneck": number, "bidir": boolean,
      "distance_km": number | null }
  ]
}

reliable_tokens: [] means the node has no unique 1–3 byte prefix and cannot be reliably identified in paths; links/direct_observers will be empty.

Caching & limits

  • Response cache: computed responses are cached for 5 minutes per pubkey|days. Polling faster than that returns an identical body — clients should not expect sub-5-minute freshness.
  • Scan cap: the windowed path scan is hard-capped at 200,000 rows. A node with more matching observations in the window is truncated (counts become a representative sample rather than exhaustive).

Response 400

Returned when :pubkey is not a 64-char hex string.

{ "error": "invalid pubkey: expected 64 hex chars" }

Response 404

Returned when the node is unknown or blacklisted.

{ "error": "Not found" }

Response 429

At most 2 uncached reports compute at once, with up to 8 distinct cold build leaders waiting for a slot for up to 3 s. A further distinct cold leader gets 429 immediately when the queue is full; an admitted leader gets 429 if no slot frees before its wait expires. Waiting holds no database connection. These are fixed internal defaults, with no operator or customizer setting.

Cached answers never wait. Concurrent requests for the same node and days share one computation and one queue admission, so the eight-leader cap does not bound all existing singleflight followers. When the request that started a shared computation disconnects first, the others sharing it also get 429. Nothing is cached for a 429; retry after Retry-After seconds.

Retry-After: 2
{ "error": "reach is busy computing other reports", "retryAfter": 2 }

GET /api/packets

Paginated packet (transmission) list with filtering.

Query Parameters

Param Type Default Description
limit number 50 Page size
offset number 0 Pagination offset
type string — Filter by payload type (number or name)
route string — Filter by route type
region string — Filter by region (IATA code substring)
observer string — Filter by observer ID
excludeTx boolean false Set exactly true to exclude TX-only evidence for the selected observer(s)
hash string — Filter by packet hash
since string — ISO timestamp lower bound
until string — ISO timestamp upper bound
node string — Filter by node pubkey
nodes string — Comma-separated pubkeys (multi-node filter)
order string DESC Sort direction: asc or desc
groupByHash string — Set to "true" for grouped response
expand string — Set to "observations" to include observation arrays

With excludeTx=true, a transmission must have at least one observation whose direction is not tx. When observer is set, that same observation must belong to one of its comma-separated IDs; without it, any observer can qualify. Missing/empty directions remain eligible for legacy data. This filters membership, including totals and grouped results; displayed direction and signal values still come from the transmission's representative observation. Multi-node mode (nodes) ignores this option, as it does the other ordinary packet filters.

Response 200 (default)

{
  "packets": [Packet],    // see Packet Object below (observations stripped unless expand=observations)
  "total":   number,
  "limit":   number,
  "offset":  number
}

Response 200 (groupByHash=true)

{
  "packets": [
    {
      "hash":              string,
      "first_seen":        string (ISO),
      "count":             number,       // observation count
      "observer_count":    number,       // unique observers
      "latest":            string (ISO),
      "observer_id":       string | null,
      "observer_name":     string | null,
      "path_json":         string | null,
      "payload_type":      number,
      "route_type":        number,
      "raw_hex":           string (hex),
      "decoded_json":      string | null,
      "observation_count": number,
      "snr":               number | null,
      "rssi":              number | null
    }
  ],
  "total": number
}

Response 200 (nodes=... multi-node)

{
  "packets": [Packet],
  "total":   number,
  "limit":   number,
  "offset":  number
}

GET /api/packets/timestamps

Lightweight endpoint returning only timestamps for timeline sparklines.

Query Parameters

Param Type Required Description
since string yes ISO timestamp lower bound

Response 200

Returns a JSON array of timestamps (strings or numbers):

["2025-07-17T00:00:01.000Z", "2025-07-17T00:00:02.000Z", ...]

Response 400

{ "error": "since required" }

GET /api/packets/:id

Single packet detail with byte breakdown and observations.

Path Parameters

Param Type Description
id string Packet ID (numeric) or 16-char hex hash

Response 200

{
  "packet": Packet,                  // full packet/transmission object
  "path":   [string],                // parsed path hops (from packet.paths or [])
  "breakdown": {                     // byte-level packet structure
    "ranges": [
      {
        "start":  number,            // byte offset
        "end":    number,
        "label":  string,
        "hex":    string,
        "value":  string | number | null
      }
    ]
  } | null,
  "observation_count": number,
  "observations": [
    {
      "id":              number,
      "transmission_id": number,
      "hash":            string,
      "observer_id":     string | null,
      "observer_name":   string | null,
      "direction":       string | null,
      "snr":             number | null,
      "rssi":            number | null,
      "score":           number | null,
      "path_json":       string | null,
      "timestamp":       string (ISO),
      "raw_hex":         string (hex),
      "payload_type":    number,
      "decoded_json":    string | null,
      "route_type":      number
    }
  ]
}

Response 404

{ "error": "Not found" }

POST /api/decode

Decode a raw packet without storing it.

Request Body

{
  "hex": string              // required — raw hex-encoded packet
}

Response 200

{
  "decoded": {
    "header":  DecodedHeader,
    "path":    DecodedPath,
    "payload": object
  }
}

Response 400

{ "error": "hex is required" }

GET /api/observers

List all observers with packet counts.

Response 200

{
  "observers": [
    {
      "id":              string,
      "name":            string | null,
      "iata":            string | null,      // region code
      "last_seen":       string (ISO),
      "first_seen":      string (ISO),
      "packet_count":    number,
      "model":           string | null,      // hardware model
      "firmware":        string | null,
      "client_version":  string | null,
      "radio":           string | null,
      "battery_mv":      number | null,      // millivolts
      "uptime_secs":     number | null,
      "noise_floor":     number | null,      // dBm
      "packetsLastHour": number,             // computed, not from DB
      "lat":             number | null,      // from matched node
      "lon":             number | null,      // from matched node
      "nodeRole":        string | null       // from matched node
    }
  ],
  "server_time": string (ISO)                // server's current time
}

GET /api/observers/:id

Single observer detail.

Response 200

{
  "id":              string,
  "name":            string | null,
  "iata":            string | null,
  "last_seen":       string (ISO),
  "first_seen":      string (ISO),
  "packet_count":    number,
  "model":           string | null,
  "firmware":        string | null,
  "client_version":  string | null,
  "radio":           string | null,
  "battery_mv":      number | null,
  "uptime_secs":     number | null,
  "noise_floor":     number | null,
  "packetsLastHour": number
}

Response 404

{ "error": "Observer not found" }

GET /api/observers/:id/analytics

Per-observer analytics.

Query Parameters

Param Type Default Description
days number 7 Lookback window

Response 200

{
  "timeline": [
    { "label": string, "count": number }    // bucketed by hours/days
  ],
  "packetTypes": {
    "4": number,                             // keyed by payload_type number
    "5": number
  },
  "nodesTimeline": [
    { "label": string, "count": number }    // unique nodes per time bucket
  ],
  "snrDistribution": [
    { "range": string, "count": number }    // e.g. "6 to 8"
  ],
  "recentPackets": [Packet]                 // last 20 enriched observations
}

GET /api/channels

List decoded channels with message counts.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes

Response 200

{
  "channels": [
    {
      "hash":         string,        // channel name (used as key)
      "name":         string,        // decoded channel name
      "lastMessage":  string | null, // text of most recent message
      "lastSender":   string | null, // sender of most recent message
      "messageCount": number,
      "lastActivity": string (ISO)
    }
  ]
}

GET /api/channels/:hash/messages

Messages for a specific channel.

Path Parameters

Param Type Description
hash string Channel name (from /api/channels)

Query Parameters

Param Type Default Description
limit number 100 Page size
offset number 0 Pagination offset (from end)

Response 200

{
  "messages": [
    {
      "sender":           string,
      "text":             string,
      "timestamp":        string (ISO),
      "sender_timestamp": number | null,    // device timestamp (unreliable)
      "packetId":         number,
      "packetHash":       string,
      "repeats":          number,           // dedup count
      "observers":        [string],         // observer names
      "hops":             number,
      "snr":              number | null,
      "scope_name":       string | null     // region scope, see below
    }
  ],
  "total": number                           // total deduplicated messages
}

scope_name is the transmission's region scope (transmissions.scope_name), the same field /api/packets returns:

Value Meaning
null No transport code: the message was not region-scoped. Also null when the database has no scope_name column yet (ingestor migration not run).
"" Transport-scoped, but the ingestor could not match it to a single region: no region key matched, or several matched with no single operator-configured key among them.
"#name" The matched region name.

The same field is on the WebSocket packet broadcast, both top-level and inside packet.


GET /api/analytics/rf

RF signal analytics.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — restricts to packets whose transmitter GPS falls in the area (ADVERT packets only; see Area Filter)

Response 200

{
  "totalPackets":       number,      // observations with SNR data
  "totalAllPackets":    number,      // all regional observations
  "totalTransmissions": number,      // unique transmission hashes
  "snr": {
    "min":    number,
    "max":    number,
    "avg":    number,
    "median": number,
    "stddev": number
  },
  "rssi": {
    "min":    number,
    "max":    number,
    "avg":    number,
    "median": number,
    "stddev": number
  },
  "snrValues":  Histogram,           // pre-computed histogram (20 bins)
  "rssiValues": Histogram,           // pre-computed histogram (20 bins)
  "packetSizes": Histogram,          // pre-computed histogram (25 bins)
  "minPacketSize": number,           // bytes
  "maxPacketSize": number,
  "avgPacketSize": number,
  "packetsPerHour": [
    { "hour": string, "count": number }   // "2025-07-17T04"
  ],
  "payloadTypes": [
    { "type": number, "name": string, "count": number }
  ],
  "snrByType": [
    { "name": string, "count": number, "avg": number, "min": number, "max": number }
  ],
  "signalOverTime": [
    { "hour": string, "count": number, "avgSnr": number }
  ],
  "scatterData": [
    { "snr": number, "rssi": number }    // max 500 points
  ],
  "timeSpanHours": number
}

Histogram Shape

{
  "bins": [
    { "x": number, "w": number, "count": number }
  ],
  "min": number,
  "max": number
}

GET /api/rf-noise

RF noise-floor map layer: where the LoRa band is quiet vs. busy, as measured by mobile companions' own radio counters along a driver's track. Opt-in, gated by config.json's clientRfSamples.enabled (the same flag cmd/ingestor uses to decide whether to record the underlying client_rf_samples rows); the endpoint 404s when disabled. The response shape mirrors the /api/rx-coverage hex-grid GeoJSON, but reports noise floor (dBm, negative; lower is quieter, the opposite direction from the SNR rx-coverage colours) instead of signal.

Stationary samples (a parked companion) are excluded from the aggregate entirely: a single parked driver can log hundreds of samples at one GPS point, which would otherwise dominate a cell's reported noise floor and misrepresent what the band looks like from the road.

Deployment note: this endpoint is gated only by clientRfSamples.enabled and has no dependency on clientRxCoverage.enabled. Enabling clientRfSamples without also enabling clientRxCoverage leaves /api/rf-noise live and returning data with no UI to reach it: the Coverage page (which hosts the Noise layer toggle) stops at "Coverage is not enabled" before the toggle is rendered.

Query Parameters

Param Type Default Description
bbox string - Required. minLat,minLon,maxLat,maxLon
z number - Leaflet zoom level; selects the hex display resolution
days number 7 Lookback window by sampled_at, clamped to [1,30]

Response 200

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": { "type": "Polygon", "coordinates": [ [ [lon, lat], ... ] ] },
      "properties": {
        "cell":                  string,   // hex cell id
        "count":                 number,   // mobile (non-stationary) samples in this cell
        "median_noise_floor":    number,   // dBm; median of the cell's samples
        "quietest_noise_floor":  number,   // dBm; the cell's minimum (best) sample
        "noisiest_noise_floor":  number    // dBm; the cell's maximum (worst) sample
      }
    }
  ],
  "truncated": boolean  // true when more cells existed than the response cap; densest cells are kept
}

Response 404

Returned when clientRfSamples.enabled is not true in config.json.

Response 400

Returned when bbox is missing or malformed.


GET /api/elevation/profile

Terrain elevation along consecutive legs of a route, for the map's line-of-sight view. Only available when los.enabled is true in config.json; otherwise the endpoint returns 404.

The terrain is the repeater planner's: the same SRTM tiles (the shared terrain block) sampled the same way as /api/planner/profile, so a leg gets the same heights, and the same verdict, in both views.

Query Parameters

Param Type Default Description
pts string - Required. Flat comma list lat1,lon1,lat2,lon2,.... 2 to 16 points. Lat in [-90,90], lon in [-180,180]

Response 200

{"source":"SRTM (AWS Open Data)","legs":[{"distance_km":12.345,"elev_m":[201.4,203.0,207.8,"... N values ..."]},{"distance_km":412.1,"error":"too_long"}]}
Field Description
source Terrain attribution: "SRTM (AWS Open Data)" for the default tiles, otherwise "SRTM (<host of terrain.tileUrl>)". The planner reports the same string
legs[i] The leg from pts[i] to pts[i+1]
distance_km Great-circle distance of the leg
elev_m Terrain height in metres (0.1 m steps), evenly spaced along the great circle from the first point to the second, both ends included. The count varies with the leg: about one sample per 90 m, at least 64 and at most 600. Omitted on error
error See below

Per-leg failures do not fail the request: a leg with an error has no elev_m. The codes, checked in this order:

Code Meaning
too_long The leg is longer than 300 km. No terrain is loaded for it
unknown_point An endpoint is not a known node (see below). No terrain is loaded for it
too_many_tiles The leg's tiles would take the request past 16 distinct 1° terrain tiles. It loads nothing; later legs over tiles already in the request still fit. Split the route to check it
upstream A tile the leg needs could not be loaded: tile downloads are paused after a tile-server failure, over their budget, or the download failed. Worth retrying later
no_terrain A sample lies in a tile without data (open sea, or a tile the server lacks)

Response 202

Some tiles the request needs are still downloading after the server waited about 1.5 s for them. The downloads carry on; re-poll the same URL after retry_after_s. Sent with Retry-After and Cache-Control: no-store.

{"state":"loading_terrain","progress":0.5,"retry_after_s":2}

progress is the share of the request's tiles already in memory, from 0 to 1.

Known-node rule

Every point must be the position of a known node that /api/nodes shows (GPS set, not 0,0), matched at 5 decimals. A leg with any other endpoint answers unknown_point and loads no terrain. This bounds the tiles a client can make the server download to those under real node pairs. The node set is refreshed at most every 60 s, and at once when the node-hiding rules change.

Terrain tiles

Route line of sight and the repeater planner read one shared terrain source, configured by the top-level terrain block in config.json. It is built only while los.enabled or planner.enabled is true.

Key Default Valid Meaning
terrain.tileUrl https://s3.amazonaws.com/elevation-tiles-prod/skadi (AWS Open Data) https URL without a query Base of an SRTM skadi tile tree: <tileUrl>/N30/N30W098.hgt.gz
terrain.tileCacheTiles 24 4 to 200 Tiles kept in memory, about 2.9 MB each

A value of 0 or a missing key means the default; an invalid value falls back to the default and logs a warning at startup. The cache never holds fewer tiles than the largest single load of an enabled feature (16 for route line of sight, 12 for the planner at its default sizes), so a request never evicts its own tiles; a smaller tileCacheTiles is raised at startup and the log says so.

Tiles are 1 arc-second SRTM, downsampled to 3 arc-seconds (about 90 m) and held in server memory only. Downsampling keeps every third sample, not the highest of each cell, and a leg is sampled at most 600 times, so the spacing grows past 90 m on legs over about 54 km. Both can step over a ridge narrower than the spacing, which leans a verdict towards clear. Nothing is written to disk or the database. Downloads are shared by both features: at most 2 at a time, 20 per minute and 200 per hour. When the planner's size limits let one load span more than 20 tiles (up to 40 at the largest sizes), the per-minute limit is that many and the hourly one five times that, if more than 200, so the largest load can still download in one go. After a 429, 5xx or transport error from the tile server, every download pauses for 60 s, then 5 min, 30 min and 1 h for each further consecutive failure; a successful download resets this. A tile the server does not have (404, 403), or one whose body is unusable or all void, has no terrain for a while instead.

Each client IP also has one download budget for both features, so using both buys no more downloads. A route line-of-sight request, or a new planner job, takes one token for each tile download it starts, all or nothing, before any starts. Tiles already in memory or already downloading (for any client, or for either feature) cost nothing, and neither do downloads the server-wide limits above would refuse. The budget holds the largest single load of an enabled feature (16 tiles for route line of sight, 12 to 40 for the planner depending on its size limits), so any one request fits it, and refills at 10 tokens a minute. A second bucket caps it at 40 tokens an hour, or twice the largest load when that is more, refilled at the same number an hour. The startup log prints the numbers in effect.

The per-client budgets (this one and the planner's jobs per minute) need clients the server can tell apart. Behind a reverse proxy on a loopback or private address that is not in webSocket.trustedProxies, every visitor arrives from the proxy's address, so no client is charged and only the server-wide limits apply; one warning is logged.

Caching & limits

  • Terrain comes from SRTM 1° tiles held in server memory (see Terrain tiles). Only the tiles the legs' samples fall in are loaded, not each leg's bounding box. A request loads at most 16 distinct tiles.
  • Cache-Control: public, max-age=86400 when every leg is OK or too_long; otherwise no-store.
  • Per client IP, a request takes one token from the client's download budget, shared with the planner, for each tile download it starts, all or nothing, before any starts. A request that would start more downloads than its tokens allow answers 429 with Retry-After and starts none. Tiles already in memory or already downloading (for any client, or for the planner) cost nothing. So do tiles the server-wide download limits have no room for: they are not downloaded, and their legs answer upstream. A request whose tiles are all in memory is never limited, and a poll after 202 costs nothing unless the server-wide limits have since made room for a tile they refused.
  • The request query may not exceed 2048 bytes.
  • Data: SRTM terrain only; trees and buildings are not modelled. The grid is about 90 m and a leg has at most 600 samples, so a narrow ridge can be missed (see Terrain tiles): read clear as a best case.

Response 400

Returned when pts is missing, has an odd number of values, holds fewer than 2 or more than 16 points, contains a non-numeric value, or has a lat or lon out of range.

Response 404

Returned when los.enabled is not true in config.json.

{ "error": "los disabled" }

Response 429

Returned when the request would start more tile downloads than the client's download budget allows. The budget is shared with the planner. The Retry-After header gives whole seconds to wait.

{ "error": "rate limited" }

GET /api/planner/profile

Line-of-sight profile along a chain of points, for the repeater planner at #/tools/planner. The server returns the terrain height along each consecutive leg. Only available when planner.enabled is true in config.json; otherwise the endpoint returns 404.

Common rules

These rules apply to all three planner endpoints: this one, /api/planner/relay and /api/planner/coverage.

  • Opt-in. Only available when planner.enabled is true. Otherwise the endpoints return 404, and /api/config/client omits the planner block.

  • Quantised input. Points are rounded to 0.001°, antenna heights to 1 m, and range must be one of a fixed set. Coverage boxes are snapped outward to a 0.05° grid. Requests that round to the same values share one cache entry and one job.

  • Unknown or repeated parameters. A parameter the endpoint does not take, a repeated parameter, or a query longer than 512 bytes returns 400.

  • Terrain. SRTM 1° tiles, shared with route line of sight (see Terrain tiles). A tile that is missing upstream (open sea or no data), unusable or all void has no terrain: relay and area searches skip every site and link that touches it, a profile leg across it is no_terrain, and a relay direct link across it carries error: "no_terrain" with no verdict.

  • Size limits. Three config.json keys set how large a request may be. A value of 0 or a missing key means the default. A value outside the valid range falls back to the default and logs a warning at startup.

    Key Default Valid Limits
    planner.maxAreaKm 100 20 to 250 Each side of a snapped coverage box
    planner.nodeMarginKm 30 10 to 60 How far outside the coverage box repeaters and rooms are still read
    planner.maxLegKm 100 10 to 200 The A to B leg of a profile or relay. Only range values up to it are accepted

    The server derives from these how many 1° terrain tiles one request may load, as the worst case anywhere within latitudes -56 to 60. At the defaults that is 12 tiles for each endpoint. Each resident tile takes about 2.9 MB, so larger limits cost memory, and the terrain cache never holds fewer tiles than one full view. The startup log prints the tile counts, the memory one view and the cache take, and how many tiles the cache has dropped that views still in use may briefly keep in memory (about a minute of downloads). /api/config/client reports the sizes in effect.

  • Caveat. Results are line of sight against bare terrain on a grid of about 90 m, which can miss a narrow ridge (see Terrain tiles). Trees, buildings and other clutter are not modelled. The output is not a link budget: it has no transmit power, gain or receiver sensitivity.

Job protocol

The planner runs each request as a background job, one per cache key. A request waits up to about 1.5 s for its job. If the job is still running, the response is 202 and the client re-polls the same URL.

Status Body Meaning
200 The endpoint's result Finished. Cached on the server for about 10 minutes. Sent with Cache-Control: public, max-age=300.
202 {"state":"computing","progress":0.42,"retry_after_s":1} Job still running. The Retry-After header carries the same wait. Re-poll the same URL after retry_after_s seconds.
400 {"error":"..."} Bad input. See the endpoint's error codes.
404 {"error":"planner disabled"} planner.enabled is not true.
429 {"error":"rate limited"} Per-IP limit of 6 new jobs per minute. A new job also takes one token from the client's download budget, shared with route line of sight, for each tile download its terrain view starts, all or nothing; tiles in memory or already downloading cost nothing. The Retry-After header gives whole seconds to wait. Cache hits and polls of a live job are never limited.
503 {"error":"planner busy"} Too many jobs are live or queued (planner busy). The server is shutting down (planner unavailable). The terrain fetch for this key failed and is cooling down (terrain busy). The Retry-After header gives whole seconds to wait.

state is one of queued, loading_terrain or computing. progress runs from 0 to 1. A job that no client has polled for 15 s is cancelled.

Query Parameters

Param Type Default Description
pts string - Required. Flat comma list lat1,lon1,lat2,lon2,.... 2 to 16 points. Lat in [-90,90], lon in [-180,180].

Response 200

{"source":"SRTM (AWS Open Data)","legs":[{"distance_km":12.345,"elev_m":[201.4,203.0,207.8,"... N values ..."]},{"distance_km":118.9,"error":"too_long"}]}
Field Description
source Terrain attribution: "SRTM (AWS Open Data)" for the default tiles, otherwise "SRTM (<host of terrain.tileUrl>)". Route line of sight reports the same string
legs[i] The leg from pts[i] to pts[i+1]. One entry per leg, in order
distance_km Great-circle distance of the leg, rounded to 3 decimals
elev_m Terrain height in metres at evenly spaced points along the great circle, both endpoints included, rounded to 0.1 m. The count depends on the leg length (about one sample per 90 m, between 64 and 600). Omitted on error
error Omitted on success. Per-leg code, see below

Per-leg failures do not fail the request. A leg with an error has no elev_m.

Error codes

Whole-request 400 messages:

Message Cause
pts required pts is missing
pts must hold 2 to 16 lat,lon points Odd number of values, fewer than 2 points or more than 16
pts contains an invalid or out-of-range number A value is not a number, or lat or lon is out of range
too_many_tiles The chain needs more 1° terrain tiles than the server loads for one request. Any single leg up to the maximum length within latitudes -56 to 60 fits. Long multi-leg chains may not

Per-leg error codes (the request still returns 200):

Code Cause
too_long The leg is longer than planner.maxLegKm (100 km by default). No terrain is loaded for it
out_of_area An endpoint is not within 50 km of a known node. Legs touching that point are marked
no_terrain Terrain for the leg could not be read

Response 400

{ "error": "pts must hold 2 to 16 lat,lon points" }

Response 404

{ "error": "planner disabled" }

GET /api/planner/relay

Best relay for a link from point A to point B. The server analyses the direct path, then ranks candidate relay sites in two lists:

  • existing: known repeaters and rooms from the node store, with an assumed mast height (planner.existingAntennaM).
  • open: sites picked from the terrain, with the new-relay height hr.

Each candidate is checked as two legs, A to relay and relay to B. Common rules and the job protocol are described under /api/planner/profile.

Query Parameters

Param Type Default Description
a string - Required. Point A as lat,lon. Must be within 50 km of a known node
b string - Required. Point B as lat,lon. Same rule as a
ha number planner.newAntennaM (10) Antenna height at A, metres. Rounded to 1 m and clamped to 1 to 100
hb number planner.newAntennaM (10) Antenna height at B, metres. Same limits as ha
hr number planner.newAntennaM (10) Height of a new relay at an open site, metres. Same limits as ha
range number planner.defaultRangeKm (30) Largest distance in km from the relay to each end. One of 10,15,20,30,40,50,60, up to planner.maxLegKm (the client config's rangesKm)

The A to B distance is limited to planner.maxLegKm (100 km by default). The existing-relay height comes from planner.existingAntennaM and is echoed in params.he. It is not a query parameter.

Response 200

{
  "source": "SRTM (AWS Open Data)",
  "direct": {
    "distance_km": 24.812,
    "clearance_pct": -35.2,
    "verdict": "blocked",
    "worst_km": 9.4,
    "obstruction_m": 38.6,
    "elev_m": [212.0, 240.5, "... up to 200 values ..."]
  },
  "existing": [
    {
      "kind": "existing",
      "pubkey": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
      "name": "Example Hilltop",
      "lat": 30.1,
      "lon": -97.7,
      "elev_m": 312,
      "antenna_m": 5,
      "leg_a": {"distance_km": 12.1, "clearance_pct": 74.0, "verdict": "clear60", "worst_km": 6.0, "obstruction_m": -8.2},
      "leg_b": {"distance_km": 12.7, "clearance_pct": 61.5, "verdict": "clear60", "worst_km": 5.1, "obstruction_m": -4.0},
      "bottleneck_pct": 61.5
    }
  ],
  "open": [
    {
      "kind": "open",
      "lat": 30.2,
      "lon": -97.6,
      "elev_m": 298,
      "antenna_m": 10,
      "leg_a": {"distance_km": 11.8, "clearance_pct": 88.0, "verdict": "clear", "worst_km": 4.2, "obstruction_m": -20.1},
      "leg_b": {"distance_km": 12.9, "clearance_pct": 66.3, "verdict": "clear60", "worst_km": 6.7, "obstruction_m": -6.5},
      "bottleneck_pct": 66.3
    }
  ],
  "params": {
    "a": {"lat": 30.1, "lon": -97.7},
    "b": {"lat": 30.2, "lon": -97.5},
    "ha": 10,
    "hb": 10,
    "hr": 10,
    "he": 5,
    "range_km": 30,
    "frequency_mhz": 910.525,
    "k_factor": 1.333
  },
  "warnings": []
}

Abbreviated: the elev_m arrays in direct, leg_a and leg_b are truncated for readability. A real response includes them in full, and leg_a/leg_b carry an elev_m array as well.

Field Description
source Terrain attribution
direct The A to B link, see Link object below
existing Up to 5 known repeaters and rooms, ranked by bottleneck_pct, then by total distance
open Up to 5 terrain sites, ranked the same way
params The quantised inputs the result was computed with, and the mast heights used
warnings Human-readable notes, for example No relay gives a clear first Fresnel zone. Always an array

Option object (existing[] and open[]):

Field Description
kind existing or open
pubkey Node public key. Present only for existing
name Node name. Present only for existing, when the node has one
lat, lon Site position
elev_m Terrain height at the site, metres
antenna_m Mast height used at the site: he for existing, hr for open
leg_a, leg_b Link objects for A to site and site to B. Each carries its own elev_m profile
bottleneck_pct The weaker of leg_a.clearance_pct and leg_b.clearance_pct

Link object (direct, leg_a, leg_b):

Field Description
distance_km Great-circle distance of the link
clearance_pct 100 × the worst first-Fresnel clearance along the path. Negative means terrain crosses the line
verdict clear (100% or more), clear60 (60% or more), marginal (0% or more) or blocked (below 0%). Empty when error is set
worst_km Distance along the link to the point with the worst clearance
obstruction_m Height of the highest terrain point above the line of sight, metres. Negative means it clears the line
elev_m Terrain profile, decimated to at most 200 samples. Present on direct and on the option legs, absent when error is set
error Present only when the link could not be measured: no_terrain (part of it has no terrain data). verdict is then empty, clearance_pct, worst_km and obstruction_m are 0, and warnings says so. Only direct can carry it: an option whose leg would is not offered

Error codes

Message or code Cause
a required, b required Point missing
a must be lat,lon within range, b must be lat,lon within range Point malformed or out of range
ha must be a number of metres, hb ..., hr ... Height is not a number
range must be one of 10,15,20,30,40,50,60 Range not in the allowed set. The message lists the values allowed up to planner.maxLegKm
too_long A to B is longer than planner.maxLegKm (100 km by default)
out_of_area A or B is not within 50 km of a known node
too_many_tiles The corridor around A and B needs more 1° terrain tiles than the server loads for one request. Any leg up to the maximum length with both ends within latitudes -56 to 60 fits

Response 400

{ "error": "too_long" }

Response 404

{ "error": "planner disabled" }

GET /api/planner/coverage

Repeater backbone plan for an area. The server reads the repeaters and rooms in a bounding box, builds the backbone graph between them, and suggests up to sites new sites that would strengthen it. The result is a suggestion, not an optimum. Common rules and the job protocol are described under /api/planner/profile.

Objective

Sites are picked greedily, one at a time, against a fixed order of goals:

  1. Fewer separate clusters. Reduce the number of backbone components. An isolated repeater counts as a component of its own. Ties go to a larger largest component.
  2. Fewer single points of failure. Reduce cut vertices, the repeaters whose loss would split the backbone. Each is weighted by the size of the smaller side it separates.
  3. Reach. Add repeaters that have no solid link to the rest, so more of the area is covered at solid quality.

Each pick is the candidate that gives the best gain under this order, comparing the goals in turn. Candidates are local high points on a 1 km grid, and no two picks sit closer than 2 km. Each pick links to nearby repeaters and earlier picks within range.

Query Parameters

Param Type Default Description
bbox string - Required. s,w,n,e in degrees. Snapped outward to a 0.05° grid. South below north, west below west-east (no antimeridian crossing). Latitude must be within -56 to 60 (SRTM coverage). The snapped box may be at most planner.maxAreaKm (100 km by default) on either side
sites int 3 Number of suggested sites, 1 to 10
range number planner.defaultRangeKm (30) Largest link distance in km considered. One of 10,15,20,30,40,50,60, up to planner.maxLegKm
hr number planner.newAntennaM (10) Height of a new site, metres. Rounded to 1 m and clamped to 1 to 100
he number planner.existingAntennaM (5) Assumed mast height of existing repeaters and rooms, metres. Same limits as hr
baseline string predicted predicted: the backbone is every pair in range that terrain says is clear enough, plus observed links. observed: only links seen in real neighbour data (score × confidence of at least 0.1)
stale string 0 1 includes repeaters the node store marks as stale. 0 leaves them out and counts them in stale_excluded

The area must hold at least one repeater or room within 10 km of the box. Nodes are read from up to planner.nodeMarginKm (30 km by default) outside the box, at most 300 of them.

Response 200

{
  "area": {"s": 30.10, "w": -97.80, "n": 30.35, "e": -97.55},
  "params": {
    "sites": 3,
    "range_km": 30,
    "hr": 10,
    "he": 5,
    "baseline": "predicted",
    "stale": false,
    "frequency_mhz": 910.525,
    "k_factor": 1.333,
    "min_clearance": 0.6
  },
  "source": "SRTM (AWS Open Data)",
  "status": "improved",
  "baseline": {"repeaters": 9, "components": 3, "largest_component": 5, "isolated": 1, "cut_vertices": 2, "stale_excluded": 0},
  "final": {"repeaters": 9, "components": 1, "largest_component": 9, "isolated": 0, "cut_vertices": 0, "stale_excluded": 0},
  "nodes": [
    {"pubkey": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "name": "Example Hilltop", "role": "repeater", "lat": 30.12, "lon": -97.74, "stale": false, "in_area": true, "component": 0}
  ],
  "edges": [
    {"a": 0, "b": 1, "class": "observed", "distance_km": 8.4, "clearance_pct": 112.0}
  ],
  "sites": [
    {
      "step": 1,
      "lat": 30.24,
      "lon": -97.66,
      "elev_m": 301,
      "antenna_m": 10,
      "reason": "joins",
      "gain": {"components_joined": 2, "cut_vertices_removed": 0, "repeaters_reached": 1},
      "after": {"repeaters": 9, "components": 2, "largest_component": 6, "isolated": 0, "cut_vertices": 2, "stale_excluded": 0},
      "links": [
        {"node": 4, "distance_km": 9.7, "clearance_pct": 64.2, "class": "solid"},
        {"node": -1, "peer_step": 0, "distance_km": 6.1, "clearance_pct": 71.0, "class": "solid"}
      ],
      "joins_components": [1, 2]
    }
  ],
  "warnings": [],
  "truncated": false,
  "computed_at": "2026-11-11T12:00:00Z"
}
Field Description
area The snapped bounding box actually analysed
params The quantised inputs. hr, he, baseline and stale are echoed here
source Terrain attribution
status improved: at least one site was picked and the backbone changed. connected: the baseline backbone was already a single component, so the sites added redundancy. no_gain: no candidate improved anything
baseline Backbone summary before any site is added
final Backbone summary after the last site
nodes[] Repeaters and rooms considered. Fields come from the same data /api/nodes shows. component is the baseline component id, 0 being the largest
edges[] Backbone links. a and b are indexes into nodes. Capped at 2000 edges
sites[] Greedy picks in order. See the site object below
warnings Human-readable notes, for example Area has no candidate high ground with a usable link. Always an array
truncated true when the node or candidate set was capped (300 nodes, 500 candidates)
computed_at When the plan was computed (UTC)

Summary object (baseline, final, sites[].after):

Field Description
repeaters In-area repeaters and rooms counted
components Number of backbone components. An isolated repeater counts as one
largest_component Size of the largest component
isolated Repeaters with no backbone link
cut_vertices Single points of failure
stale_excluded Stale repeaters left out of the plan

Edge class (edges[].class):

Class Meaning
observed A link seen in real neighbour data, with a score × confidence of at least 0.1
solid A terrain-predicted link with at least 60% first-Fresnel clearance (min_clearance)
marginal A terrain-predicted link with clearance from 0% up to 60%. The line clears the terrain but not by much

Site object (sites[]):

Field Description
step 1-based greedy order
lat, lon Suggested position
elev_m Terrain height at the site, metres
antenna_m Mast height used, hr
reason Why this site was picked (see below)
gain What the pick improved: components_joined, cut_vertices_removed, repeaters_reached
after Backbone summary after this pick
links[] Links from the site. node is an index into nodes, or -1 when the peer is an earlier site, in which case peer_step gives its step. class is solid or marginal
joins_components Baseline component ids this site connects

Site reason (sites[].reason):

Reason Meaning
joins The site connects two or more separate backbone components
redundancy No components joined, but the site removes a single point of failure or otherwise reduces fragility
reach Neither of the above. The site brings in repeaters that had no solid link

Error codes

Message or code Cause
bbox required bbox missing
bbox must be s,w,n,e in degrees Wrong number of values, not a number, or out of range
bbox needs south below north and west below east (no antimeridian crossing) Degenerate or reversed box
bbox must lie within latitudes -56 to 60 (terrain coverage) Outside SRTM coverage
area_too_large The snapped box is over planner.maxAreaKm (100 km by default) on a side
too_many_tiles The box plus the node margin needs more 1° terrain tiles than the server loads for one request. Never returned for a box the size check accepts; kept as a safeguard
no_nodes_in_area No repeater or room within 10 km of the box
sites must be an integer 1-10 sites not an integer in range
range must be one of 10,15,20,30,40,50,60 range not in the allowed set. The message lists the values allowed up to planner.maxLegKm
hr and he must be numbers of metres A height is not a number
baseline must be predicted or observed Unknown baseline value
stale must be 0 or 1 Unknown stale value

Response 400

{ "error": "no_nodes_in_area" }

Response 404

{ "error": "planner disabled" }

GET /api/analytics/topology

Network topology analytics.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — only hops that resolve to nodes inside the area are counted in repeater/pair frequency tables

Response 200

{
  "uniqueNodes": number,
  "avgHops":     number,
  "medianHops":  number,
  "maxHops":     number,
  "hopDistribution": [
    { "hops": number, "count": number }      // capped at 25
  ],
  "topRepeaters": [
    {
      "hop":    string,         // raw hex prefix
      "count":  number,
      "name":   string | null,  // resolved name
      "pubkey": string | null
    }
  ],
  "topPairs": [
    {
      "hopA":    string,
      "hopB":    string,
      "count":   number,
      "nameA":   string | null,
      "nameB":   string | null,
      "pubkeyA": string | null,
      "pubkeyB": string | null
    }
  ],
  "hopsVsSnr": [
    { "hops": number, "count": number, "avgSnr": number }
  ],
  "observers": [
    { "id": string, "name": string }
  ],
  "perObserverReach": {
    "<observer_id>": {
      "observer_name": string,
      "rings": [
        {
          "hops": number,
          "nodes": [
            {
              "hop":       string,
              "name":      string | null,
              "pubkey":    string | null,
              "count":     number,
              "distRange": string | null   // e.g. "1-3" or null if constant
            }
          ]
        }
      ]
    }
  },
  "multiObsNodes": [
    {
      "hop":    string,
      "name":   string | null,
      "pubkey": string | null,
      "observers": [
        {
          "observer_id":   string,
          "observer_name": string,
          "minDist":       number,
          "count":         number
        }
      ]
    }
  ],
  "bestPathList": [
    {
      "hop":           string,
      "name":          string | null,
      "pubkey":        string | null,
      "minDist":       number,
      "observer_id":   string,
      "observer_name": string
    }
  ]
}

GET /api/analytics/retransmissions

Retransmission pressure over time (#1699): a collision-pressure proxy, not a measured collision rate.

For each flood event of a flood-routed packet (route_type 0 or 1, TRACE excluded) the server takes the union of the paths of all its observations and counts the distinct repeaters in it: paths [A], [A,B,C] and [A,D] give 4. Direct routes are excluded because their path is the route still to travel, not the forwarders; zero-hop sends are direct routes. A flood event heard only with an empty path counts as 0 repeaters.

A transmission is one packet hash, and the same bytes can flood again later: those observations are stored on the same transmission. Its observations are therefore sorted by time and split into flood events wherever two consecutive observations are more than 5 minutes apart. Each event is counted on its own and bucketed by its first observation. A firmware node holds a flood for at most 32 s before forwarding it, plus a random retransmit delay, so a flood that is still spreading is not split. Every count in the response (packets, one_byte_packets, no_repeater_packets) counts flood events. Observations are stored once per observer and path per transmission, so a later event holds only the observer and path pairs not already stored for that hash, and its count is a lower bound.

Events that start before the store's retention floor (now minus retentionHours) are left out for every request shape, including explicit window, from and to: the store keeps observations older than that only for hashes heard again recently, so they do not represent that period.

Hop prefixes are not resolved to nodes. A prefix counts once per flood event, whether it repeats across observations or inside one path. A 2- or 3-byte prefix that repeats inside one path is one node forwarding the flood again after its duplicate filter (a cyclic buffer of 160 hashes) dropped the hash. A repeated 1-byte prefix can also be two nodes; counting it once keeps the value a lower bound, as does merging repeaters that share a prefix across observations. Only repeaters that some observer heard are counted, so the value also follows observer coverage.

The default shape (no region, no window, bucket=1h) is served from the analytics recomputer; other shapes use the TTL cache, and concurrent requests for the same uncached shape share one computation. During startup the default shape returns 503 with Retry-After until the recomputer completes a pass after the hot startup window has loaded, or for at most 60 s after the recomputer started, whichever comes first. The history beyond the hot window keeps loading in the background after that, so until the first recompute pass after that load finishes the default shape can cover less than the retention window. ?area= is not supported: the area filter works on resolved node public keys and this metric does not resolve prefixes.

Query Parameters

Param Type Default Description
region string none Comma-separated IATA codes; only observations from the region's observers feed the union, events none of them heard are skipped. Events are split before this filter. A region with no known observers is not filtered and returns network-wide data, as /api/analytics/rf does
window string none 1h, 24h, 3d, 7d or 30d (relative to now)
from, to string (ISO) none Absolute window bounds, take precedence over window
bucket string 1h 5m, 15m, 1h, 6h or 1d; other values fall back to 1h

Response 200

{
  "bucket_seconds": number,
  "window":         string,          // window label, "" for all data
  "region":         string,
  "summary": {
    "packets":             number,   // flood events that started in the window
    "avg_repeaters":       number,   // mean distinct repeaters per event
    "observers":           number,   // distinct observers that heard them
    "one_byte_packets":    number,   // events on 1-byte hop hashes (most ambiguous)
    "no_repeater_packets": number    // events heard with an empty path only
  },
  "buckets": [                       // ascending, empty buckets omitted
    {
      "start":         string (ISO), // bucket start, UTC
      "packets":       number,       // flood events that started in the bucket
      "repeater_sum":  number,
      "avg_repeaters": number,
      "observers":     number
    }
  ]
}

GET /api/analytics/channels

Channel analytics.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — area filtering is supported but not exposed in the dashboard (channel stats are observer-based)

Response 200

{
  "activeChannels": number,
  "decryptable":    number,
  "channels": [
    {
      "hash":       string,
      "name":       string,
      "messages":   number,
      "senders":    number,        // unique sender count
      "lastActivity": string (ISO),
      "encrypted":  boolean
    }
  ],
  "topSenders": [
    { "name": string, "count": number }
  ],
  "channelTimeline": [
    { "hour": string, "channel": string, "count": number }
  ],
  "msgLengths": [number]            // raw array of message character lengths
}

GET /api/analytics/distance

Hop distance analytics.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — restricts distance calculations to paths where the transmitter GPS falls in the area

Response 200

{
  "summary": {
    "totalHops":  number,
    "totalPaths": number,
    "avgDist":    number,      // km, 2 decimal places
    "maxDist":    number       // km
  },
  "topHops": [
    {
      "fromName": string,
      "fromPk":   string,
      "toName":   string,
      "toPk":     string,
      "dist":     number,      // km
      "type":     string,      // "R↔R" | "C↔R" | "C↔C"
      "snr":      number | null,
      "hash":     string,
      "timestamp": string (ISO)
    }
  ],
  "topPaths": [
    {
      "hash":      string,
      "totalDist": number,     // km
      "hopCount":  number,
      "timestamp": string (ISO),
      "hops": [
        {
          "fromName": string,
          "fromPk":   string,
          "toName":   string,
          "toPk":     string,
          "dist":     number
        }
      ]
    }
  ],
  "catStats": {
    "R↔R": { "count": number, "avg": number, "median": number, "min": number, "max": number },
    "C↔R": { "count": number, "avg": number, "median": number, "min": number, "max": number },
    "C↔C": { "count": number, "avg": number, "median": number, "min": number, "max": number }
  },
  "distHistogram": Histogram | [],   // empty array if no data
  "distOverTime": [
    { "hour": string, "avg": number, "count": number }
  ]
}

GET /api/analytics/hash-sizes

Hash size analysis across the network.

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — restricts to packets from nodes in the area

Response 200

{
  "total": number,              // packets analyzed
  "distribution": {
    "1": number,                // 1-byte hash count
    "2": number,                // 2-byte hash count
    "3": number                 // 3-byte hash count
  },
  "hourly": [
    { "hour": string, "1": number, "2": number, "3": number }
  ],
  "topHops": [
    {
      "hex":    string,         // raw hop hex
      "size":   number,         // bytes (ceil(hex.length/2))
      "count":  number,
      "name":   string | null,
      "pubkey": string | null
    }
  ],
  "multiByteNodes": [
    {
      "name":     string,
      "hashSize": number,
      "packets":  number,
      "lastSeen": string (ISO),
      "pubkey":   string | null
    }
  ]
}

GET /api/analytics/hash-collisions

Hash collision analysis — packets where the same hash was used by multiple different nodes (ambiguous routing).

Query Parameters

Param Type Default Description
region string — Comma-separated IATA codes
area string — Area key — restricts to packets from nodes in the area

Response 200

{
  "collisions": [
    {
      "hash":     string,           // hop hex prefix that collides
      "count":    number,           // number of distinct nodes sharing this prefix
      "nodes": [
        {
          "pubkey": string,
          "name":   string | null,
          "count":  number          // observation count for this node
        }
      ]
    }
  ],
  "totalCollisions": number,
  "affectedPackets": number
}

GET /api/nodes/clock-skew

Fleet-wide clock skew data. Returns all nodes for which clock skew has been calculated from ADVERT timestamp pairs.

Query Parameters

Param Type Default Description
area string — Area key — restricts to nodes whose GPS falls in the area

Response 200

Returns a JSON array (not wrapped in an object):

[
  {
    "pubkey":         string,
    "nodeName":       string | null,
    "nodeRole":       string | null,
    "skewMs":         number | null,          // current estimated clock offset (ms)
    "driftPerDaySec": number | null,          // drift rate (seconds/day)
    "severity":       string,                 // "good" | "warning" | "critical"
    "samples":        null                    // always null in fleet response (too large)
  }
]

Note: This is a bare array, not { nodes: [...] }.


GET /api/analytics/subpaths

Subpath frequency analysis.

Query Parameters

Param Type Default Description
minLen number 2 Minimum subpath length (≥2)
maxLen number 8 Maximum subpath length
limit number 100 Max results
region string — Comma-separated IATA codes

Response 200

{
  "subpaths": [
    {
      "path":    string,        // "Node A → Node B → Node C"
      "rawHops": [string],      // ["aa", "bb", "cc"]
      "count":   number,
      "hops":    number,        // length of subpath
      "pct":     number         // percentage of totalPaths (0–100)
    }
  ],
  "totalPaths": number
}

GET /api/analytics/subpath-detail

Detailed stats for a specific subpath.

Query Parameters

Param Type Required Description
hops string yes Comma-separated raw hex hop prefixes

Response 200

{
  "hops":  [string],                     // input hops echoed back
  "nodes": [
    {
      "hop":    string,
      "name":   string,
      "lat":    number | null,
      "lon":    number | null,
      "pubkey": string | null
    }
  ],
  "totalMatches": number,
  "firstSeen":    string (ISO) | null,
  "lastSeen":     string (ISO) | null,
  "signal": {
    "avgSnr":  number | null,
    "avgRssi": number | null,
    "samples": number
  },
  "hourDistribution": [number],         // 24-element array (index = UTC hour)
  "parentPaths": [
    { "path": string, "count": number }
  ],
  "observers": [
    { "name": string, "count": number }
  ]
}

GET /api/scope-audit

Network-wide declared-vs-observed region-scope comparison: for every repeater that has ever successfully answered a declared-regions request, which of its declared regions have no observed forwarding in the window, which scopes it forwards without declaring, and whether it contradicts its own '*' wildcard. This is the whole-network answer to the question GET /api/nodes/:pubkey/scopes answers one repeater at a time — see that endpoint's notes for the full explanation of the three traps this comparison has to get right (the #-prefix spelling difference, '*' not being a scope, and "never asked" not being the same as "declared nothing"), which apply here identically.

Query Parameters

Param Type Default Description
window string 24h Time window: 1h, 24h, 7d
mode string declared declared (this section) or transport (see Transport view)
scope string — mode=transport only: region scope to split the fleet by (be, be-van), with or without #, any case
region string — Observer IATA filter, comma-separated (SFO,SJC), both views: count only forwarding heard by observers in those regions. As on every other endpoint this means heard by, not located in; All means no filter, and codes with no observer match nothing. Each region set is cached separately

Response 200

{
  "window": string,                    // echoed window ("1h", "24h", or "7d")
  "since":  string (ISO),              // start of the observed-forwarding window
  "region": string | undefined,        // normalised ?region= codes ("sfo,sjc" -> "SFO,SJC"); present only when given
  "repeaters": [
    {
      "publicKey":        string,
      "name":             string,      // "" if the node row is gone (pruned/deleted)
      "role":             string,      // "" if unknown
      "declaredRegions":  [string],    // '*' excluded — see declaredWildcard
      "declaredWildcard": boolean,     // '*' present in the raw declared list
      "configState":      string,      // "full" | "no-scopes" | "no-unscoped" | "no-flood" — see note below
      "declaredAt":       string (ISO),// age of the DECLARED answer, not bounded by window
      "truncated":        boolean,     // declared list may have had entries silently dropped

      "notObserved":            [string],            // declared regions with zero matched-forwarding observed this window
      "undeclaredObserved":     [
        { "scope": string, "packets": number, "firstSeen": string (ISO), "lastSeen": string (ISO) }
      ],
      "observedUnscopedPackets": number,               // plain-FLOOD packets forwarded this window
      "wildcardContradiction":   boolean,               // observed unscoped forwarding but '*' not declared
      "ambiguousHops":            number,                // forwarder hops this window that could not be attributed — see note below
      "observedUnmatchedPackets": number,                // forwarded packets whose scope this instance holds no key for — see note below
      "observedUnmatchedSampled": number,                // how many of those verification could examine — see note below
      "regionEvidence":           { "<region>": number } // declared regions corroborated by this repeater's own unnameable traffic — see note below
    }
  ]
}

Response 400

{ "error": "window must be 1h, 24h, or 7d" }

or, for an unknown mode:

{ "error": "mode must be declared or transport" }

Notes:

  • Only repeaters with at least one declared-regions answer appear in repeaters. A repeater that was never successfully asked is absent, not shown as a row that declares nothing — those are different facts (see GET /api/nodes/:pubkey/scopes's "never asked" note).

  • window bounds notObserved / undeclaredObserved / observedUnscopedPackets only — declaredAt is always the latest declared reading regardless of age, exactly like declared.observedAt on the per-node endpoint. A "declared but not observed" result is weak evidence at window=1h (a quiet region can simply have had no traffic) and much stronger at window=7d; a client MUST show which window a result belongs to and must not present a 1h result as if it were 7d. Because declaredAt is not bounded by window, the declared answer and the forwarding evidence are not guaranteed to be temporally aligned — a repeater could have declared its regions well before, or even after, the window that produced notObserved — and the server makes no attempt to align them; the declaredAt column in the UI is the mitigation (so a stale declared answer is visible to the reader), not a guarantee that the two sides describe the same period.

  • ambiguousHops counts forwarder-hop observations in this window whose truncated hash prefix matched more than one declared target's pubkey — i.e. two or more repeaters that declared a region list happen to share that prefix. Such a hop is attributed to none of the matching targets (crediting all of them risks papering over a real gap in a colliding neighbour's row; crediting none of them invents no failure) and this counter is incremented on every matching target instead. A row with a non-zero ambiguousHops carries weaker evidence than one with zero: any entry in that row's notObserved could be explained by a prefix collision rather than a genuine absence of forwarding, and a client should present it as a caveat rather than a confirmed finding.

  • observedUnmatchedPackets counts packets this repeater was observed forwarding whose transport scope matched no region key this instance has configured (hashRegions), so the ingestor stored them with an empty scope_name. Those packets name no region and therefore cannot satisfy a declared one, which means a repeater forwarding a region this instance cannot name is reported exactly like one forwarding nothing. A non-zero value is a caveat on this row's notObserved, in the same spirit as ambiguousHops but with a different cause and a different fix: ambiguousHops is a pubkey-prefix collision between two repeaters and nobody's fault, observedUnmatchedPackets is a missing entry in this instance's own configuration and the operator can act on it. It is not evidence for or against declaredWildcard — unmatched traffic is scoped, so it never affects wildcardContradiction, which counts only plain unscoped floods. Part of this count is explained: packets counted in regionEvidence are attributable to a declared region after all. A client showing this as a caveat should subtract them and report only the remainder, which carries a sharper meaning — traffic this repeater forwards for a region it does not declare and this instance cannot name. Two rules on that subtraction: count only evidence for regions absent from notObserved (a region with a single hit was deliberately not accepted as evidence, so its packet is not explained either), and compare against observedUnmatchedSampled first.

  • observedUnmatchedSampled is how many of those packets verification could actually examine. Two caps sit between the count and the evidence: the per-repeater working set (512 packets) and the per-window sample (the 4096 most recent unnameable packets, which a deployment with few hashRegions entries will reach). regionEvidence can only ever count packets inside that sample, so when this field is smaller than observedUnmatchedPackets the difference between the count and the evidence is an upper bound on the unexplained traffic rather than a figure, and a client should say so. Equal values mean the subtraction is exact.

  • regionEvidence maps a declared region to how many of this repeater's own unmatched forwarded packets derive to it. The server tests each declared region this repeater has no named evidence for by deriving SHA256("#region")[:16] and HMAC-ing that repeater's own unmatched packets with it — the same computation the ingestor performs at ingest, with the candidate set narrowed to this repeater's declarations. A region reaching 2 corroborating packets is removed from notObserved: code1 is two bytes, so one match happens by chance with probability 1/65536, while two on the same region is (1/65536)². A region with exactly one hit therefore stays in notObserved and appears here with the value 1, so a client can explain why it is still shown as not observed. notObserved remains the single source of truth for whether a region was observed; this field says only how that was established. The object is always present and may be empty.

  • All scope names in declaredRegions / notObserved / undeclaredObserved[].scope are already normalised (no leading #) — the server does the #/no-# reconciliation described on the per-node endpoint so this response is directly comparable without a client-side normalisation step.

  • '*' is never present in declaredRegions, notObserved, or undeclaredObserved — see declaredWildcard and wildcardContradiction for its dedicated (non-scope) treatment, same rule as the per-node endpoint.

  • configState is a derived reading of declaredRegions/declaredWildcard together — the repeater's overall configuration shape, rather than a per-region detail:

    • "full" — named regions and '*' declared: fully configured, forwards both its declared regions and plain unscoped floods.
    • "no-scopes" — '*' only, no named regions.
    • "no-unscoped" — named regions declared, '*' absent: this repeater does not forward plain unscoped floods. This reading is exact — '*' absent from the export always means the wildcard denies flooding.
    • "no-flood" — neither named regions nor '*': the repeater answered, but nothing at all is flood-allowed, not even plain unscoped traffic. The "no unscoped forwarding" half of this is exact for the same reason as "no-unscoped"; the "no named regions" half carries the same caveat as "no-scopes" below.

    Caveat on "no-scopes" and "no-flood": the firmware exports the FLOOD-allowed set (region_map.exportNamesTo(..., REGION_DENY_FLOOD) in examples/simple_repeater/MyMesh.cpp), not "every region this repeater has configured". A repeater with regions defined but every one of them marked deny-flood exports exactly the same list as a repeater with no region tree at all — the two are indistinguishable from this data alone. In practice "no-scopes" is almost always "no scopes configured", but a client MUST NOT present it as proven absence of configuration; word it as "no region is flood-allowed" rather than "no regions exist".

  • wildcardContradiction is true when the repeater was observed forwarding unscoped (plain-FLOOD) traffic this window but its declared list omits '*' — it declares it will NOT forward those packets, and the traffic says otherwise.

  • Rows are sorted with the interesting cases first: most notObserved entries first, then wildcardContradiction, then most undeclaredObserved entries, then alphabetically by name. A repeater in full agreement (no notObserved, no wildcardContradiction, no undeclaredObserved) sorts to the bottom.

  • Cached 30 seconds per window, mirroring /api/scope-stats.

  • Blacklisted nodes and nodes matching an operator-configured hidden-name prefix are excluded, same as other multi-node endpoints.


Transport view (mode=transport)

Issue #2142. One row per repeater seen forwarding in the window, whether or not it has ever answered a declared-regions request. Built from the same single forwarding scan as the declared view, with the same attribution rules (FLOOD-family route types only, no 1-byte hops, a hop whose prefix matches several repeaters is credited to none of them), but with every repeater and room this instance knows as a target instead of only the declared ones. "Transported" means seen carrying, not configured for; the declared side is reported separately where it exists. Cached per window with the same TTLs as the declared view; the scope filter is applied to the cached result.

{
  "mode": "transport",
  "window": string,
  "since": string (ISO),
  "region": string | undefined,        // normalised ?region= codes; present only when given
  "scope": string | undefined,         // normalised ?scope= filter ("#FR" -> "fr"); present only when given
  "carrying": number | undefined,      // rows with carriesScope: true; only with scope
  "notCarrying": number | undefined,   // rows with carriesScope: false; only with scope
  "repeaters": [
    {
      "publicKey":        string,
      "name":             string | null,  // null = no nodes row for this key
      "role":             string | null,
      "transported": [                    // named region scopes seen forwarded, most packets first
        { "scope": string, "packets": number, "firstSeen": string (ISO), "lastSeen": string (ISO) }
      ],
      "unscopedPackets":  number,         // plain floods forwarded
      "unmatchedPackets": number,         // scoped packets whose region this instance holds no key for
      "ambiguousHops":    number,         // hops shared with another repeater's prefix, credited to neither
      "asked":            boolean,        // a declared-regions answer exists
      "declaredRegions":  [string] | null,// null when not asked; [] when it answered with no named region
      "declaredWildcard": boolean,
      "configState":      string | undefined, // as in the declared view; only when asked
      "declaredAt":       string | undefined, // only when asked
      "notObserved":      [string] | null,    // declared regions not seen carried; null when not asked
      "carriesScope":     boolean | undefined // only with scope
    }
  ]
}

A repeater with no attributed forwarding in the window (only ambiguous hops, or no traffic) is not listed. Rows are sorted by name, then public key.

GET /api/scope-stats

Scope-based packet statistics over a time window. Requires ingestor scope_name_v1 migration to have run.

Query Parameters

Param Type Default Description
window string 24h Time window: 1h, 24h, 7d

Response 200

{
  "window":    string,               // echoed window ("1h", "24h", or "7d")
  "summary": {
    "total":             number,     // all observed transmissions, routes 0-3 (= scoped + unscoped)
    "transportTotal":    number,     // transport routes 0 and 3 (= scoped + unscopedTransport)
    "scoped":            number,     // Code1 ≠ 0000 (named + unknown regions)
    "unscoped":          number,     // all unscoped traffic (= unscopedTransport + unscopedFlood + unscopedDirect)
    "unscopedTransport": number,     // transport route (0, 3) with Code1 = 0000
    "unscopedFlood":     number,     // FLOOD (route 1): no transport code, unscoped by protocol
    "unscopedDirect":    number,     // DIRECT (route 2): no transport code, never floods
    "unknownScope":      number      // scoped but no configured region matched (subset of scoped)
  },
  "byRegion": [
    { "name": string, "count": number }  // region name and packet count
  ],
  "timeSeries": [
    { "t": string (ISO), "scoped": number, "unscoped": number }  // bucket timestamps and counts
  ],
  "advertsByRole": [
    {
      "role":         string,        // sender's nodes.role, or "unknown" (see notes below)
      "unscoped":     number,        // flood adverts with no scope (scope_name NULL)
      "unknownScope": number,        // scoped, but no region name could be assigned (scope_name "")
      "named":        number         // scoped with a named region
    }
  ]
}

Notes:

  • Route types per MeshCore docs/packet_format.md: 0 = TRANSPORT_FLOOD, 1 = FLOOD, 2 = DIRECT, 3 = TRANSPORT_DIRECT. Only routes 0 and 3 carry a transport code (Code1).
  • total = scoped + unscoped (all route types)
  • transportTotal = scoped + unscopedTransport (only route_type 0 or 3 packets)
  • scoped = packets with Code1 ≠ 0000
  • unscoped = unscopedTransport + unscopedFlood + unscopedDirect. Since #1838 it includes the non-transport routes 1 and 2, so it can exceed transportTotal; compute shares against total (#2364).
  • unscopedFlood is the figure to watch for region rollout: DIRECT traffic (unscopedDirect) is not subject to flood-region filtering, which repeaters apply to flood routes only.
  • timeSeries counts transport routes (0, 3) only; its unscoped corresponds to unscopedTransport.
  • unknownScope = scoped packets that did not match any configured region name
  • Time-series bucket size depends on window:
    • 1h window → 5-minute buckets
    • 24h window → 1-hour buckets
    • 7d window → 6-hour buckets
  • advertsByRole (#1979) counts ADVERT packets on flood routes only (TRANSPORT_FLOOD 0, FLOOD 1) in the window, grouped by the sender's current nodes.role. Zero-hop adverts (DIRECT/TRANSPORT_DIRECT) are excluded. Ordered by total adverts descending, then role. It reports what was sent per role, not why. role is "unknown" when the advert row has no from_pubkey (legacy rows the ingestor's #1143 from_pubkey backfill has not reached yet), when the sender has no row in nodes (including a sender the ingestor's node retention moved to inactive_nodes, which within the 7d window only happens with retention.nodeDays below 7), or when its nodes.role is empty.
  • Cached 30 seconds

Note: On deployments with pre-existing data, unscoped will be inflated until the async startup backfill completes, because transport-route rows inserted before the scope_name_v1 migration ran have scope_name = NULL and are indistinguishable from Code1=0000 rows. The backfill goroutine populates them at startup but may take several minutes on large databases.

Response 400

{ "error": "window must be 1h, 24h, or 7d" }

Response 500 Internal Server Error

scope_name column does not exist (ingestor has not run migrations yet):

{ "error": "scope_name column not present — run ingestor to apply migrations" }

GET /api/resolve-hops

Resolve path hop hex prefixes to node names with regional disambiguation.

Query Parameters

Param Type Required Description
hops string yes Comma-separated hex hop prefixes
observer string no Observer ID for regional context
originLat number no Origin latitude for distance-based disambiguation
originLon number no Origin longitude

Response 200

{
  "resolved": {
    "<hop>": {
      "name":         string | null,
      "pubkey":       string | null,
      "ambiguous":    boolean | undefined,   // true if multiple candidates
      "unreliable":   boolean | undefined,   // true if failed sanity check
      "candidates":   [Candidate],
      "conflicts":    [Candidate],
      "globalFallback": boolean | undefined,
      "filterMethod": string | undefined,    // "geo" | "observer"
      "hopBytes":     number | undefined,    // for ambiguous entries
      "totalGlobal":  number | undefined,
      "totalRegional": number | undefined,
      "filterMethods": [string] | undefined
    }
  },
  "region": string | null
}

Candidate shape:

{
  "name":         string,
  "pubkey":       string,
  "lat":          number | null,
  "lon":          number | null,
  "regional":     boolean,
  "filterMethod": string,
  "distKm":       number | null
}

GET /api/traces/:hash

All observations of a specific packet hash, sorted chronologically.

Path Parameters

Param Type Description
hash string Packet hash

Response 200

{
  "traces": [
    {
      "observer":      string | null,   // observer_id
      "observer_name": string | null,
      "time":          string (ISO),
      "snr":           number | null,
      "rssi":          number | null,
      "path_json":     string | null
    }
  ]
}

GET /api/config/theme

Theme and branding configuration (merged from config.json + theme.json).

Response 200

{
  "branding": {
    "siteName": string,          // default: "CoreScope"
    "tagline":  string           // default: "Real-time MeshCore LoRa mesh network analyzer"
    // ... additional branding keys from config/theme files
  },
  "theme": {
    "accent":      string,       // hex color, default "#4a9eff"
    "accentHover": string,
    "navBg":       string,
    "navBg2":      string
    // ... additional theme CSS values
  },
  "themeDark": {
    // dark mode overrides (may be empty object)
  },
  "nodeColors": {
    "repeater":  string,         // hex color
    "companion": string,
    "room":      string,
    "sensor":    string,
    "observer":  string
  },
  "typeColors": {
    // payload type → hex color overrides
  },
  "home": object | null          // home page customization
}

GET /api/config/regions

Available regions (IATA codes) merged from config + DB.

Response 200

{
  "<iata_code>": string          // code → display name
  // e.g. "SFO": "San Francisco", "LAX": "Los Angeles"
}

Returns a flat key-value object.


GET /api/config/region-quick-picks

Named groups of region codes from config.json regionQuickPicks, offered as one-tap choices by the region filter. Names and codes are trimmed, codes upper-cased and de-duplicated in their configured order, groups without a name or any code dropped; at most 20 groups of 200 codes.

Response 200

{
  "quickPicks": [
    {
      "name":        string,           // button label
      "description": string | undefined, // tooltip
      "regions":     [string]          // IATA codes, as configured (may include codes with no observer yet)
    }
  ]
}

quickPicks is [] when none are configured. The client offers a group only when at least one of its codes appears in GET /api/config/regions, and selects just those codes.


GET /api/config/areas

Available area filters defined in config.json under areas. Used by the frontend to populate the area pill bar. Entries with an empty label (e.g. comment keys) are excluded.

Response 200

[
  {
    "key":   string,   // area key as defined in config (e.g. "bayarea")
    "label": string    // display name (e.g. "Bay Area")
  }
]

Returns [] when no areas are configured.

Note: Polygon coordinates are not included. Use /api/config/areas/polygons for the full geometry.


GET /api/config/areas/polygons

Full area definitions including polygon/bounding-box coordinates. Intended for map rendering tools (e.g. the area-map debug tool).

Response 200

[
  {
    "key":   string,
    "label": string,
    "polygon": [[number, number]] | undefined,   // [lat, lon] pairs (if polygon-style)
    "latMin":  number | undefined,               // bounding-box style
    "latMax":  number | undefined,
    "lonMin":  number | undefined,
    "lonMax":  number | undefined
  }
]

Returns [] when no areas are configured.


GET /api/config/client

Client-side configuration values.

Response 200

{
  "roles":              object | null,
  "healthThresholds":   object | null,
  "tiles":              object | null,
  "snrThresholds":      object | null,
  "distThresholds":     object | null,
  "maxHopDist":         number | null,
  "limits":             object | null,
  "perfSlowMs":         number | null,
  "wsReconnectMs":      number | null,
  "cacheInvalidateMs":  number | null,
  "externalUrls":       object | null,
  "propagationBufferMs": number,         // default: 5000
  "clientRfSamples":    boolean,         // opt-in flag; gates /api/rf-noise
  "los":                object,          // omitted unless los.enabled is true: frequencyMhz, antennaHeightM, kFactor, maxPoints, maxLegKm. frequencyMhz 910.525 is the US default; use 869.618 for EU/UK meshes (set los.frequencyMhz to your mesh's frequency). The planner reads frequencyMhz and kFactor from the los block even when los.enabled is false.
  "planner":            object,          // omitted unless planner.enabled is true: defaultRangeKm, rangesKm (only those up to maxLegKm), newAntennaM, existingAntennaM, frequencyMhz, kFactor, maxPoints, maxLegKm, maxAreaKm, nodeMarginKm, maxSites, minClearance
  "clientRxAppUrl":     string           // omitted unless clientRxCoverage is on and clientRxCoverage.appUrl is an https URL
}

GET /api/config/cache

Cache TTL configuration (raw values in seconds).

Response 200

Returns the raw cacheTTL object from config.json, or {} if not set:

{
  "stats":                number | undefined,    // seconds
  "nodeDetail":           number | undefined,
  "nodeHealth":           number | undefined,
  "nodeList":             number | undefined,
  "bulkHealth":           number | undefined,
  "networkStatus":        number | undefined,
  "observers":            number | undefined,
  "channels":             number | undefined,
  "channelMessages":      number | undefined,
  "analyticsRF":          number | undefined,
  "analyticsTopology":    number | undefined,
  "analyticsChannels":    number | undefined,
  "analyticsHashSizes":   number | undefined,
  "analyticsSubpaths":    number | undefined,
  "analyticsSubpathDetail": number | undefined,
  "nodeAnalytics":        number | undefined,
  "nodeSearch":           number | undefined,
  "invalidationDebounce": number | undefined
}

GET /api/config/map

Map default center and zoom.

Response 200

{
  "center": [number, number],      // [lat, lon], default [37.45, -122.0]
  "zoom":   number                 // default 9
}

GET /api/iata-coords

IATA airport/region coordinates for client-side regional filtering.

Response 200

{
  "coords": {
    "<iata_code>": {
      "lat": number,
      "lon": number,
      "radiusKm": number
    }
  }
}

GET /api/audio-lab/buckets

Representative packets bucketed by payload type for audio lab.

Response 200

{
  "buckets": {
    "<type_name>": [
      {
        "hash":              string,
        "raw_hex":           string (hex),
        "decoded_json":      string | null,
        "observation_count": number,
        "payload_type":      number,
        "path_json":         string | null,
        "observer_id":       string | null,
        "timestamp":         string (ISO)
      }
    ]
  }
}

WebSocket Messages

Connection

Connect to ws://<host> (or wss://<host> for HTTPS). No authentication. The server broadcasts messages to all connected clients.

Message Wrapper

All WebSocket messages use this envelope:

{
  "type": string,     // "packet" or "message"
  "data": object      // payload (shape depends on type)
}

Message Type: "packet"

Broadcast on every new packet ingestion.

{
  "type": "packet",
  "data": {
    "id":                number,           // observation or transmission ID
    "raw":               string (hex) | null,
    "decoded": {
      "header": {
        "routeType":       number,
        "payloadType":     number,
        "payloadVersion":  number,
        "payloadTypeName": string          // "ADVERT", "GRP_TXT", "TXT_MSG", etc.
      },
      "path": {
        "hops":            [string]        // hex hop prefixes
      },
      "payload":           object          // decoded payload (varies by type)
    },
    "snr":               number | null,
    "rssi":              number | null,
    "hash":              string | null,
    "observer":          string | null,    // observer_id
    "observer_name":     string | null,
    "path_json":         string | null,    // JSON-stringified hops array
    "packet":            Packet | undefined, // full packet object (when available)
    "observation_count": number | undefined
  }
}

Notes:

  • data.decoded is always present with at least header.payloadTypeName.
  • data.packet is included for raw packet ingestion (Format 1 / MQTT), may be absent for companion bridge messages.
  • data.path_json is the JSON-stringified version of data.decoded.path.hops.

Fields consumed by frontend pages:

Field live.js packets.js app.js channels.js
data.id ✓ ✓
data.hash ✓ ✓
data.raw ✓
data.decoded.header.payloadTypeName ✓ ✓
data.decoded.payload ✓ ✓
data.decoded.path.hops ✓
data.snr ✓
data.rssi ✓
data.observer ✓
data.observer_name ✓
data.packet ✓
data.observation_count ✓
data.path_json ✓
(any) ✓ (*)

(*) app.js passes all messages to registered wsListeners and uses them only for cache invalidation.

Message Type: "message"

Broadcast for GRP_TXT (channel message) packets only. Same data shape as "packet" type. channels.js listens for this type to update the channel message feed in real time.

{
  "type": "message",
  "data": {
    // identical shape to "packet" data
  }
}

Shared Object Shapes

Packet Object

A transmission/packet as stored in memory and returned by most endpoints:

{
  "id":                number,              // transmission ID
  "raw_hex":           string (hex) | null,
  "hash":              string,              // content hash (dedup key)
  "first_seen":        string (ISO),        // when first observed
  "timestamp":         string (ISO),        // display timestamp (= first_seen)
  "route_type":        number,              // 0=TRANSPORT_FLOOD, 1=FLOOD, 2=DIRECT, 3=TRANSPORT_DIRECT
  "payload_type":      number,              // 0=REQ, 1=RESPONSE, 2=TXT_MSG, 3=ACK, 4=ADVERT, 5=GRP_TXT, 7=ANON_REQ, 8=PATH, 9=TRACE, 11=CONTROL
  "payload_version":   number | null,
  "decoded_json":      string | null,       // JSON-stringified decoded payload
  "observation_count": number,
  "observer_id":       string | null,       // from "best" observation
  "observer_name":     string | null,
  "snr":               number | null,
  "rssi":              number | null,
  "path_json":         string | null,       // JSON-stringified hop array
  "direction":         string | null,
  "score":             number | null,
  "observations":      [Observation] | undefined  // stripped by default on list endpoints
}

Observation Object

A single observation of a transmission by an observer:

{
  "id":              number,
  "transmission_id": number,
  "hash":            string,
  "observer_id":     string | null,
  "observer_name":   string | null,
  "direction":       string | null,
  "snr":             number | null,
  "rssi":            number | null,
  "score":           number | null,
  "path_json":       string | null,
  "timestamp":       string (ISO) | number,  // ISO string or unix epoch
  // Enriched fields (from parent transmission):
  "raw_hex":         string (hex) | null,
  "payload_type":    number,
  "decoded_json":    string | null,
  "route_type":      number
}

DecodedHeader

{
  "routeType":       number,
  "payloadType":     number,
  "payloadVersion":  number,
  "payloadTypeName": string    // human-readable name
}

DecodedPath

{
  "hops":      [string],       // hex hop prefixes, e.g. ["a1b2", "c3d4"]
  "hashSize":  number,         // bytes per hop hash (1–3)
  "hashCount": number          // number of hops in path field
}

Payload Type Reference

Value Name Description
0 REQ Request
1 RESPONSE Response
2 TXT_MSG Direct text message
3 ACK Acknowledgement
4 ADVERT Node advertisement
5 GRP_TXT Group/channel text message
7 ANON_REQ Anonymous request
8 PATH Path / traceroute
9 TRACE Trace response
11 CONTROL Control message

Route Type Reference

Value Name Description
0 DIRECT Direct (with transport codes)
1 FLOOD Flood/broadcast
2 (reserved)
3 TRANSPORT Transport (with transport codes)

Area Filter

The ?area=<key> query parameter is a display-side geographic filter that attributes data to a region based on the transmitting node's own GPS coordinates, as broadcast in its ADVERT packets. It is distinct from the observer-based ?region= filter.

Configuration

Areas are defined in config.json under the areas key:

{
  "areas": {
    "bayarea": {
      "label": "Bay Area",
      "polygon": [[37.9, -122.5], [37.9, -121.9], [37.3, -121.9], [37.3, -122.5]]
    },
    "sanjose": {
      "label": "San Jose",
      "latMin": 37.25, "latMax": 37.45,
      "lonMin": -122.05, "lonMax": -121.75
    }
  }
}

Each entry may use either a polygon (array of [lat, lon] pairs, minimum 3 points) or a bounding box (latMin/latMax/lonMin/lonMax). The polygon check uses standard ray-casting point-in-polygon.

Attribution rules

Packet type Area-attributable? Reason
ADVERT (4) Yes Carries public_key + transmitter GPS in payload
GRP_TXT (5), TXT_MSG (2), REQ (0), others No Sender is encrypted; origin cannot be determined

When ?area= is active, only ADVERT packets (and nodes derived from them) are included in filtered results. All other packet types are excluded. This is by design — non-ADVERT packets have encrypted senders and cannot be attributed to a geographic origin.

GPS staleness

Node GPS coordinates are read from the nodes table, which is updated on ADVERT ingest. A node that moves between areas will not be re-attributed until its next ADVERT (typically 12–24 hours for repeaters). The area node set is cached for 30 seconds server-side.

Endpoints supporting ?area=

Endpoint Area support
GET /api/nodes Filters node list by GPS in area
GET /api/analytics/rf Restricts RF stats to ADVERT packets from area nodes
GET /api/analytics/topology Counts only hops that resolve to nodes in the area
GET /api/analytics/channels Supported (not used by dashboard UI)
GET /api/analytics/distance Restricts distance paths to area-node transmitters
GET /api/analytics/hash-sizes Restricts hash analysis to area-node packets
GET /api/analytics/hash-collisions Restricts collision analysis to area-node packets
GET /api/nodes/clock-skew Restricts fleet clock skew list to nodes in area

Cross-antimeridian polygons

Polygons that span the 180° meridian (antimeridian) are not supported — ray-casting point-in-polygon breaks at the date line. Split such areas into two separate entries.