Files
ukmesh/docs/spam-detection.md

20 KiB
Raw Permalink Blame History

Message-Spam Detection (Spam Watch)

Detects people spamming the MeshCore mesh by finding repeated, near-duplicate messages sent in short time windows, groups them into incidents, and estimates a coarse origin area. Powers the public ukmesh.com/spam dashboard.

This is distinct from the older advert/identity-spoof detector (backend/src/mqtt/spamDetector.ts), which scores repeater/device adverts. This system is about chat-message abuse.

How it works

packets (type 5, decoded channel msgs)
        │  loadRecentMessages()       backend/src/spam/repository.ts
        ▼
MessageRecord[]  (one per packet_hash, with observers)
        │  clusterMessages()          backend/src/spam/cluster.ts
        ▼
Incident[]       (near-duplicate text, close in time)
        │  estimateOrigin()           backend/src/spam/origin.ts
        │  sanitizeIncident()         backend/src/spam/sanitize.ts
        ▼
spam_message_incidents / spam_message_members   (public_json is pre-sanitized)
        │  getPublic*()               backend/src/spam/repository.ts
        ▼
/api/spam/messages/*  →  Spam Watch dashboard (frontend SpamPage)

The overview map groups similar coarse origin estimates into suspected source areas, with one circle and an incident-count label per area. Centres must be on the same network, within 15 km of every other centre in the group, and within each other's original uncertainty radius. Broad uncertainty circles therefore cannot join distant centres or form chains across a region. The strongest origin estimate anchors each circle; its radius expands to retain every member's uncertainty. A group is red if any member is active. This is a display of similar origin estimates, not confirmed sender attribution: incident records, counts, details, and individual origin maps remain independent. Redacted sender prefixes and sanitized message placeholders are not evidence of a shared source.

Only decoded channel messages are used (MeshCore public/known-key channels where payload.decrypted.message exists). Direct messages and unknown-key channels stay encrypted and are never inspected.

Pipeline stages

  1. Normalize (normalize.ts) — lowercase, trim, collapse whitespace, normalize punctuation, collapse stretched repeats (heyyyy→heyy), and strip/canonicalize URLs (drop scheme/www./query so tracking variants collapse). ukmesh.com/spam is recognised as a marker — supporting evidence, never sufficient on its own.

  2. Fuzzy match (similarity.ts) — message similarity blends trigram Dice, token-set Jaccard and Levenshtein ratio; a shared canonical URL is a strong signal. Username similarity adds prefix/substring affinity so John, John2, John_UK read as related.

  3. Cluster (cluster.ts) — time-ordered greedy clustering inside a join window. Similar usernames lower the text-similarity bar but never create a cluster alone. A qualification gate then separates abuse from normal chatter (see below).

  4. Estimate origin — two methods, path-based preferred:

    a. Relay-path adjacency chain-walk (spamResolver.ts, used first for public incidents). Every reception carries its ordered relay path; the first repeater is the source of truth (the spammer transmitted into it). We take the closest receivers (lowest hop count) and walk each path backward from the observer, hop by hop: at each step we pick the candidate node that has a confirmed RF link (node_links) to the previously-resolved node, else the nearest candidate within range. Because a consecutive (AA,BB) hash pair is only realisable where two such repeaters sit within range, the adjacency chain disambiguates the otherwise-ambiguous 1-byte hashes — and the random deviations in the middle of the paths give many independent chains that converge on the same source. The chain's first repeaters are then combined into a geographic consensus. Confidence is tempered by the closest observer's hop count: a 2-hop reception is trusted (short chain); a source only heard 5–7 hops out is honestly less certain (long chain, compounding per-hop error) even when the chains agree. (spamResolver.ts is an independent copy of the lazy path resolver so the production resolver is never touched.)

    b. Observer-signal fallback (origin.ts) — when paths can't be resolved (no path hashes, or no confident consensus), fall back to the observer estimate below. A flood radiates outward from its source, so an observer that heard it at a low hop count sits close to the source while distant relays only heard it after it crossed the network. The estimate is therefore anchored on the closest-receiver cohort (the lowest hop counts available — min-hop + originNearHopSlack, at least everyone within originNearHopMax hops); their location gives the centroid, and the radius is their spread plus a per-hop allowance. Confidence comes from how close the nearest reception was — both absolutely and relative to how far the flood otherwise travelled (a 2-hop reception of something that otherwise relayed 14 hops is strong localisation). This works UK-wide: dense areas yield tight, high-confidence pins; sparse areas (where the closest reception is several hops out) honestly produce a broad radius and lower confidence rather than a false-precise point. Snaps to a coarse named UK region.

    Coverage note: localisation quality tracks observer density — strong across England, broader/lower-confidence in the far north of Scotland and the islands. With fewer than originMinObservers geolocated receivers the origin is reported as insufficient (no map zone) rather than guessed.

  5. Sanitize (sanitize.ts) — the single gate to public output (see Privacy).

  6. Persist (repository.ts) — merge qualifying bursts sharing a campaign key before origin estimation and sanitization, then upsert once per key. The campaign retains the union of transmissions, newest activity and strongest qualifying burst's confidence. Preserve historical first_seen in both the row and public JSON. An older snapshot cannot replace newer activity or its member evidence. A bounded pass never deletes campaigns it did not see.

What counts as spam (and what doesn't)

A cluster only becomes an incident when it is genuine abuse, not normal traffic:

  • Requires minTransmissions near-duplicates with minBurst inside one burst window. Only the full rotating-ID profile below gets the lower rotatingMinTransmissions floor (six by default); ordinary repeats still require eight transmissions.
  • Requires substantive content — at least minContentChars, or a URL, or the spam marker. Trivial/connectivity messages (test, ack, morning, gm, …) never qualify on their own.
  • Requires a suspicious sender pattern — a single repeating sender, one dominant sender, rotating similar usernames, or a rotating-ID botnet (see below). Many dissimilar people sending the same thing is treated as broad legitimate chatter, not one abuser — but "many senders" made of single-shot machine-named identities is a botnet, not people.
  • The test channel is excluded by default (it carries repeated test traffic by design). Configurable via SPAM_MESSAGE_EXCLUDE_CHANNELS. A flood that also hits another channel (e.g. Public) is still caught via those copies.
  • Content is dampened only when it is dominated by connectivity/test tokens — i.e. once benign words, bare numbers and 1–2-char fragments are removed, nothing substantive is left (test, rx ack 73, test 123). A templated message that merely contains the word test (e.g. an automated ANDY KIRBY MESHCORE(TM) 00:16:4: !test flood) keeps real words and is not treated as testing — so this camouflage no longer hides spam.
  • A sustained high-volume flood (≥ floodMinMessages near-duplicates) is a strong automated-abuse signal on its own and is scored up — but a benign test/connectivity flood is never rewarded, so it stays below the public floor no matter how large it grows.

Rotating-ID botnets

A distinct abuse class: the same canned line blasted from many fresh sender IDs — one message per ID, in timed bursts (a handful of IDs within minutes), then quiet. Per-sender rate logic sees nothing; the tell is one text arriving from many one-shot identities. A cluster is flagged rotatingIdentities when ALL of:

  • ≥ SPAM_MESSAGE_ROTATING_MIN_SENDERS distinct senders,
  • ≥ SPAM_MESSAGE_ROTATING_SINGLE_SHOT_SHARE of them appear exactly once in the analysis window (one-shot identities, not established members),
  • ≥ SPAM_MESSAGE_ROTATING_MACHINE_NAME_SHARE (30% by default) of the names look machine-generated (looksMachineGeneratedName in normalize.ts: separator-free base32-ish tokens, ≥1 digit, vowel-poor, mostly uppercase — amateur-callsign shapes and human composites are excluded), and
  • ≥ SPAM_MESSAGE_ROTATING_MIN_BURST_SENDERS distinct senders inside one burst window.

Flagged clusters are exempted from the broad-chatter rejection, scored +0.3, and carry the reason "N single-shot identities (X% machine-style names, N within 10 min) posted near-identical text". First production catch: the Oct-2026 anti-Kirby campaign — 9 incidents, 8–15 sender IDs each, confidence 0.54–0.81.

The lower transmission floor applies only when all four profile conditions hold. The volume component uses that same floor when scoring rotating bursts. The 30% name share accommodates bursts mixing vowel-poor and vowel-rich random IDs without weakening the individual name heuristic or classifying every uppercase human handle as machine-generated. Human chatter, established senders, trivial messages and excluded test-channel traffic retain their existing guards.

Bounded analysis and truncation

The default message budget is 5,000 logical transmissions per pass, with an operator-configurable hard ceiling of 10,000. This gives headroom above the reported approximately 2,900-message day; it is still a bounded sample on busier days. Candidate materialization is independently bounded (10,000 by default), as are observer evidence, work time and published campaigns.

The candidate query reads one extra row to distinguish an exactly full page from truncation. Exceeding a candidate, message or incident limit emits an aggregate warning and increments meshcore_spam_analysis_truncations_total{phase="candidates|messages|incidents"} (one of those three phase values per event). Warning counts are lower bounds when the candidate query was itself capped. They contain no sender names or message text. These limits do not constitute evidence that unseen traffic is clean, and existing incidents are not deleted because of an incomplete pass.

Incident lifecycle

  • active / ongoing while the last matching message is within SPAM_MESSAGE_ONGOING_WINDOW_MIN.
  • closed after that cooldown elapses with no new matching messages.

The periodic analyzer recomputes recent incidents every SPAM_MESSAGE_INTERVAL_MS and re-evaluates active→closed transitions each run. Separate qualifying bursts with the same network/text signature share one row: activity follows the newest burst, message/observer counts cover their union in the analyzed window, and reasons identify the strongest burst used for confidence. Member evidence is sampled only after merging, under its existing evidence cap. The cap is strict even at one or two records: keep the newest observation first, then the earliest endpoint, then the representative message as space permits. Campaign message counts still describe every qualifying transmission in the window. When an older burst leaves the rolling window, historical first-seen time remains while current-window counts/confidence may change.

Configuration

All knobs live in backend/src/spam/config.ts and read from the environment.

Env var Default Meaning
SPAM_MESSAGE_ANALYZER_ENABLED true Run the in-process periodic analyzer
SPAM_MESSAGE_INTERVAL_MS 300000 Analyzer interval (5 min)
SPAM_MESSAGE_WINDOW_HOURS 24 Rolling window the analyzer (re)clusters
SPAM_MESSAGE_MAX_MESSAGES 5000 Per-pass message budget, clamped to 100–10000; truncation is reported
SPAM_MESSAGE_MAX_CANDIDATE_ROWS 10000 Candidate materialization budget, plus one lookahead row
SPAM_MESSAGE_TEXT_SIM 0.82 Min text similarity to join a cluster
SPAM_MESSAGE_TEXT_SIM_NAME 0.6 Lower text bar when usernames are similar
SPAM_MESSAGE_NAME_SIM 0.7 Min username similarity (evidence)
SPAM_MESSAGE_JOIN_WINDOW_MIN 30 Max gap to join the same incident
SPAM_MESSAGE_MIN_TRANSMISSIONS 8 Min distinct messages for an incident
SPAM_MESSAGE_BURST_WINDOW_MIN 10 Burst window
SPAM_MESSAGE_MIN_BURST 3 Min messages inside one burst window
SPAM_MESSAGE_MIN_CONTENT_CHARS 12 Min canonical length (unless URL/marker)
SPAM_MESSAGE_MAX_INDEPENDENT_SENDERS 4 Above this (dissimilar) → broad chatter
SPAM_MESSAGE_DOMINANT_SENDER_SHARE 0.6 One sender at this share qualifies
SPAM_MESSAGE_FLOOD_MIN_MESSAGES 25 ≥ this many near-duplicates → sustained-flood boost
SPAM_MESSAGE_ROTATING_MIN_SENDERS 5 Min distinct senders for rotating-ID detection
SPAM_MESSAGE_ROTATING_MIN_TRANSMISSIONS 6 Lower floor only for the full rotating-ID profile; never raises the ordinary floor
SPAM_MESSAGE_ROTATING_SINGLE_SHOT_SHARE 0.8 Share of senders seen exactly once in the window
SPAM_MESSAGE_ROTATING_MACHINE_NAME_SHARE 0.3 Share of names that must look machine-generated
SPAM_MESSAGE_ROTATING_MIN_BURST_SENDERS 3 Min distinct senders inside one burst window
SPAM_MESSAGE_EXCLUDE_CHANNELS test Channel labels skipped (comma list)
SPAM_MESSAGE_PUBLIC_MIN_SCORE 0.5 Confidence floor for public list / status
SPAM_MESSAGE_ONGOING_WINDOW_MIN 30 How long an incident stays "ongoing"
SPAM_MESSAGE_ORIGIN_USE_PATHS true Anchor origin on the relay-path first repeater
SPAM_MESSAGE_ORIGIN_PATH_MAX_PACKETS 40 Max closest-receiver transmissions resolved
SPAM_MESSAGE_ORIGIN_PATH_MIN_VOTES 3 Min resolved paths before a path anchor is trusted
SPAM_MESSAGE_ORIGIN_PATH_CLUSTER_KM 45 Consensus cluster radius (outliers beyond it dropped)
SPAM_MESSAGE_ORIGIN_PATH_AMBIGUOUS_WEIGHT 0.4 Weight of an ambiguous vs certain repeater resolution
SPAM_MESSAGE_ORIGIN_MIN_OBSERVERS 2 Min observers before estimating origin (fallback)
SPAM_MESSAGE_ORIGIN_NEAR_HOP_MAX 2 Receivers within this many hops count as "near source"
SPAM_MESSAGE_ORIGIN_NEAR_HOP_SLACK 1 Width (hops) of the closest-receiver cohort that anchors it
SPAM_MESSAGE_ORIGIN_PER_HOP_KM 12 Radius allowance per hop (≈ LoRa link range)
SPAM_MESSAGE_ORIGIN_MIN_RADIUS_KM 8 Floor on reported radius (privacy)
SPAM_MESSAGE_COARSEN_STEP_DEG 0.1 Public coordinate coarsening (~11 km)
SPAM_MESSAGE_REGION_SNAP_KM 70 Max distance to snap to a named region

Tuning sensitivity: lower SPAM_MESSAGE_PUBLIC_MIN_SCORE to surface more (noisier) clusters; raise SPAM_MESSAGE_MIN_TRANSMISSIONS / MIN_CONTENT_CHARS to be stricter.

Confidence scores

Two separate confidences are shown:

  • Detection confidence (incident confidence, 0–1) — how strongly the pattern resembles spam. Built from volume, burst density, sustained-flood size, repeated links, the spam marker, rotating sender names, and rotating-identity evidence; content dominated by connectivity/test tokens is dampened. High ≥ 0.66, Medium ≥ 0.4, else Low. Only incidents at/above SPAM_MESSAGE_PUBLIC_MIN_SCORE appear publicly by default.
  • Origin confidence (origin confidence + level) — how trustworthy the reported zone is (region + radius), driven mainly by how close the nearest reception was (low hop count) and how much it stands out from the flood's overall reach, plus corroboration from other near-source receivers. insufficient means too few geolocated observers to triangulate; the map zone is then omitted. Note that confidence is confidence in the zone — a larger radius absorbs the uncertainty, so "high confidence" means the source is very likely inside that (coarse) area, not that it is pinpointed.

A single low-hop receiver gives a confident region but a coarse radius; more near-source receivers tighten the radius and raise confidence further. On the dashboard, click Estimated origin (or "View area on map") to see the coarse confidence circle on a map.

Privacy model

Abuse mitigation only. The public API serves the pre-computed public_json column, which is produced solely by sanitizeIncident(). Delivery also requires its migration-136 visibility certificate to match the current ready privacy generation; uncertified or old geometry is withheld. Fresh checks fence both publication and public response delivery:

  • Sender names are redacted to a short non-identifying hint (John_UK→Jo…) that still conveys variant similarity. Raw names stay in local-only columns.
  • Message samples strip URLs ([link], marker → [spam-link]), @mentions ([mention]) and long hex/number runs ([id]), and are length-bounded.
  • Locations are coarse only: a region label, a confidence level, and an optional broad heat zone (centre coarsened to a ~0.1° grid, radius floored at ORIGIN_MIN_RADIUS_KM and bucketed to 5 km). Exact coordinates, observer ids and node metadata are never published.
  • Clusters are labelled "suspected spam cluster" — neutral, not an accusation of any named individual.
  • No IPs, credentials, public keys or channel keys are exposed.

API

Endpoint Description
GET /api/spam/messages/status Current status: ongoing?, counts, last activity
GET /api/spam/messages/incidents?status=&minConfidence=&limit=&offset= Sanitized incident list
GET /api/spam/messages/incidents/:id One incident + sanitized timeline

minConfidence defaults to SPAM_MESSAGE_PUBLIC_MIN_SCORE; pass 0 to include lower-confidence clusters (the dashboard's "show lower-confidence" toggle).

Deployment

The derived tables are created by migration backend/src/db/migrations/005_spam_message_incidents.sql (additive, no destructive changes). The one-shot db-migrate service applies unrecorded migrations before the backend starts. Do not apply the SQL file or insert its migration-ledger row manually.

Production uses the approved immutable backend digest and the release procedure. Complete pending migrations before starting the analyzer; do not build over a deployed release. After selecting the reviewed image, the explicit migration command is:

docker compose run --rm db-migrate

The in-process analyzer starts automatically. To backfill historical incidents or run a one-off pass:

# dry run over 30 days (no writes)
docker compose exec backend node dist/tools/recomputeSpamMessages.js --hours 720
# apply
docker compose exec backend node dist/tools/recomputeSpamMessages.js --hours 720 --apply

If the analyzer log shows status=timed_out, the run's work exceeded SPAM_MESSAGE_ANALYSIS_BUDGET_MS — the 5 s default is tuned for quiet days; busy spam days need ~30–60 s (each public incident resolves relay paths for origin). Raise it in .env (e.g. SPAM_MESSAGE_ANALYSIS_BUDGET_MS=60000) and recreate the backend. The recompute tool first counts the selected logical transmissions and refuses an over-budget window. Reduce --hours, or qualify a higher SPAM_MESSAGE_MAX_MESSAGES within its 10,000-message ceiling; it does not silently publish a truncated historical recomputation.

Tests

Pure logic (normalization, fuzzy matching, username similarity, clustering, ongoing/closed status, origin scoring, sanitization) is covered by unit tests:

cd backend && npm ci && npm test