network-monitor/app/hub/devices.py
neil 54a765510a Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI):
- Network health: live probe/target matrix, status strips, incidents
- Probes: add (with install command), rename, remove, latency and throughput charts
- Clients merged from AdGuard, DHCP, query log and probe ARP tables; names,
  categories, suspicious flag, notes, per-client DNS requests
- Query log, domain detail (clients, related subdomains), blocked domains via
  the AdGuard Home /control API

Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS,
internet URLs and an optional VPS; buffers results while the hub is down.
Gateway and ARP from /proc/net on Linux, route/arp on macOS.

Install: install.sh (hub) and install-probe.sh (generated from it), each in
docker mode (compose; default on Linux hosts) or native mode (venv + systemd
or launchd; default on macOS and in LXC). Both modes deploy with an update
command that checks the new commit and rolls back on failure.

CLAUDE.md carries shared context for Claude Code sessions on each machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 18:10:29 -08:00

96 lines
4.6 KiB
Python

"""Client devices: merged from AdGuard (clients, DHCP leases, query log) and probe ARP tables.
A device is keyed by MAC address when one is known, else by IP (ip:<address>)."""
import re
import time
MAC_RE = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
USER_FIELDS = ("name", "category", "suspicious", "notes")
def norm_mac(mac: str | None) -> str | None:
if not mac:
return None
m = mac.strip().lower().replace("-", ":")
if not MAC_RE.match(m) or m == "00:00:00:00:00:00":
return None
return m
def _merge_into(con, src_key: str, dst_key: str) -> None:
"""Fold the IP-keyed device into the MAC-keyed one, keeping the user's labels."""
src = con.execute("SELECT * FROM devices WHERE key = ?", (src_key,)).fetchone()
dst = con.execute("SELECT * FROM devices WHERE key = ?", (dst_key,)).fetchone()
if not src or not dst:
return
updates = {f: src[f] for f in USER_FIELDS if src[f] and not dst[f]}
sources = ",".join(sorted(set(filter(None, (dst["sources"] + "," + src["sources"]).split(",")))))
updates["sources"] = sources
updates["first_seen"] = min(src["first_seen"], dst["first_seen"])
if src["last_seen"] and (not dst["last_seen"] or src["last_seen"] > dst["last_seen"]):
updates["last_seen"] = src["last_seen"]
if not dst["hostname"] and src["hostname"]:
updates["hostname"] = src["hostname"]
sets = ", ".join(f"{k} = ?" for k in updates)
con.execute(f"UPDATE devices SET {sets} WHERE key = ?", (*updates.values(), dst_key))
con.execute("DELETE FROM devices WHERE key = ?", (src_key,))
def sighting(con, *, ip: str | None = None, mac: str | None = None, hostname: str | None = None,
source: str, seen: float | None = None, now: float | None = None) -> str | None:
"""Record that a device exists. `seen` is a time of real activity; None means it was only listed."""
now = now or time.time()
ip = (ip or "").strip() or None
mac = norm_mac(mac)
if not ip and not mac:
return None
if ip and mac:
prev = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
con.execute("INSERT INTO ip_mac(ip, mac, last_seen) VALUES (?, ?, ?) ON CONFLICT(ip) DO UPDATE SET mac = excluded.mac, last_seen = excluded.last_seen",
(ip, mac, now))
if not prev or prev["mac"] != mac:
# The address moved to this device: other devices no longer hold it.
con.execute("UPDATE devices SET ip = NULL WHERE ip = ? AND key != ?", (ip, mac))
elif ip:
row = con.execute("SELECT mac FROM ip_mac WHERE ip = ?", (ip,)).fetchone()
mac = row["mac"] if row else None
key = mac or f"ip:{ip}"
exists = con.execute("SELECT key FROM devices WHERE key = ?", (key,)).fetchone()
if not exists:
con.execute("INSERT INTO devices(key, mac, ip, hostname, sources, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?)",
(key, mac, ip, hostname or None, source, seen or now, seen))
else:
con.execute(
"""UPDATE devices SET
ip = COALESCE(?, ip),
hostname = COALESCE(NULLIF(?, ''), hostname),
sources = CASE WHEN (',' || sources || ',') LIKE ? THEN sources
WHEN sources = '' THEN ? ELSE sources || ',' || ? END,
last_seen = CASE WHEN ? IS NOT NULL AND (last_seen IS NULL OR ? > last_seen) THEN ? ELSE last_seen END
WHERE key = ?""",
(ip, hostname or "", f"%,{source},%", source, source, seen, seen, seen, key),
)
if mac and ip:
_merge_into(con, f"ip:{ip}", mac)
return key
def ip_index(con) -> dict[str, dict]:
"""ip -> {key, name, suspicious} for linking query log rows to devices."""
out = {}
for r in con.execute("SELECT key, ip, name, hostname, suspicious, category FROM devices WHERE ip IS NOT NULL"):
out[r["ip"]] = {"key": r["key"], "name": r["name"] or r["hostname"] or "", "suspicious": bool(r["suspicious"]), "category": r["category"] or ""}
return out
def ips_for(con, key: str) -> list[str]:
"""Addresses to search the query log for: the current one plus others recently tied to its MAC."""
row = con.execute("SELECT mac, ip FROM devices WHERE key = ?", (key,)).fetchone()
if not row:
return []
ips = [row["ip"]] if row["ip"] else []
if row["mac"]:
ips += [r["ip"] for r in con.execute("SELECT ip FROM ip_mac WHERE mac = ? ORDER BY last_seen DESC LIMIT 4", (row["mac"],)) if r["ip"] not in ips]
if not ips and key.startswith("ip:"):
ips = [key[3:]]
return ips