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>
This commit is contained in:
commit
54a765510a
63 changed files with 6464 additions and 0 deletions
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/hub/__init__.py
Normal file
0
app/hub/__init__.py
Normal file
149
app/hub/adguard.py
Normal file
149
app/hub/adguard.py
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
"""AdGuard Home API client (/control/*, HTTP basic auth) and query log helpers."""
|
||||
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
|
||||
from app.hub import settings
|
||||
|
||||
# Tests swap this for an httpx.MockTransport.
|
||||
TRANSPORT: httpx.AsyncBaseTransport | None = None
|
||||
|
||||
BLOCKED_REASONS = {"FilteredBlackList", "FilteredBlockedService", "FilteredParental", "FilteredSafeBrowsing", "FilteredInvalid"}
|
||||
PAGE = 500
|
||||
|
||||
|
||||
class NotConfigured(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AdGuardError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _client() -> httpx.AsyncClient:
|
||||
s = settings.get()
|
||||
if not s.adguard_configured:
|
||||
raise NotConfigured("Set ADGUARD_URL (and ADGUARD_USERNAME / ADGUARD_PASSWORD) in the hub's .env")
|
||||
auth = (s.adguard_username, s.adguard_password) if s.adguard_username else None
|
||||
return httpx.AsyncClient(base_url=s.adguard_url, auth=auth, timeout=15, transport=TRANSPORT)
|
||||
|
||||
|
||||
async def get(path: str, params: dict | None = None):
|
||||
try:
|
||||
async with _client() as c:
|
||||
r = await c.get(path, params=params)
|
||||
except httpx.HTTPError as e:
|
||||
raise AdGuardError(f"AdGuard Home unreachable: {e.__class__.__name__}: {e}") from e
|
||||
if r.status_code in (401, 403):
|
||||
raise AdGuardError("AdGuard Home rejected the login. Check ADGUARD_USERNAME and ADGUARD_PASSWORD.")
|
||||
if r.status_code >= 400:
|
||||
raise AdGuardError(f"AdGuard Home returned {r.status_code} for {path}")
|
||||
try:
|
||||
return r.json()
|
||||
except ValueError as e:
|
||||
raise AdGuardError(f"AdGuard Home sent a non-JSON reply for {path}. Is ADGUARD_URL the web UI address?") from e
|
||||
|
||||
|
||||
_FRAC = re.compile(r"(\.\d{6})\d+")
|
||||
|
||||
|
||||
def parse_time(value: str) -> float:
|
||||
try:
|
||||
return datetime.fromisoformat(_FRAC.sub(r"\1", value.replace("Z", "+00:00"))).timestamp()
|
||||
except (ValueError, AttributeError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def normalize(row: dict) -> dict:
|
||||
q = row.get("question") or {}
|
||||
info = row.get("client_info") or {}
|
||||
rules = row.get("rules") or []
|
||||
reason = row.get("reason", "")
|
||||
try:
|
||||
elapsed = round(float(row.get("elapsedMs") or 0), 2)
|
||||
except ValueError:
|
||||
elapsed = None
|
||||
return {
|
||||
"time": row.get("time", ""),
|
||||
"ts": parse_time(row.get("time", "")),
|
||||
"client": row.get("client", ""),
|
||||
"client_name": info.get("name") or "",
|
||||
"domain": (q.get("name") or q.get("host") or "").rstrip(".").lower(),
|
||||
"type": q.get("type", ""),
|
||||
"status": row.get("status", ""),
|
||||
"reason": reason,
|
||||
"blocked": reason in BLOCKED_REASONS,
|
||||
"rule": (rules[0].get("text") if rules else row.get("rule")) or "",
|
||||
"elapsed_ms": elapsed,
|
||||
"upstream": row.get("upstream", ""),
|
||||
"cached": bool(row.get("cached")),
|
||||
}
|
||||
|
||||
|
||||
async def collect(*, search: str = "", status: str = "all", older_than: str = "", want: int = 200,
|
||||
keep=None, max_rows: int = 5000) -> dict:
|
||||
"""Page through the query log, newest first, until `want` rows pass `keep` or `max_rows`
|
||||
have been read. Returns {rows, oldest, done}: pass `oldest` back as older_than for more."""
|
||||
rows, scanned, done = [], 0, False
|
||||
cursor = older_than
|
||||
while len(rows) < want and scanned < max_rows:
|
||||
params = {"limit": PAGE, "response_status": status}
|
||||
if search:
|
||||
params["search"] = search
|
||||
if cursor:
|
||||
params["older_than"] = cursor
|
||||
data = await get("/control/querylog", params)
|
||||
page = data.get("data") or []
|
||||
scanned += len(page)
|
||||
for raw in page:
|
||||
r = normalize(raw)
|
||||
if keep is None or keep(r):
|
||||
rows.append(r)
|
||||
if len(rows) >= want:
|
||||
cursor = raw.get("time", cursor)
|
||||
break
|
||||
else:
|
||||
cursor = data.get("oldest") or (page[-1].get("time") if page else "")
|
||||
if len(page) < PAGE or not cursor:
|
||||
done = True
|
||||
break
|
||||
return {"rows": rows, "oldest": "" if done else cursor, "done": done, "scanned": scanned}
|
||||
|
||||
|
||||
def top_list(items) -> list[tuple[str, int]]:
|
||||
"""AdGuard returns top lists as [{"name": count}, ...]."""
|
||||
out = []
|
||||
for it in items or []:
|
||||
if isinstance(it, dict):
|
||||
out.extend((str(k), int(v)) for k, v in it.items())
|
||||
return out
|
||||
|
||||
|
||||
_stats_cache: dict = {"at": 0.0, "data": None}
|
||||
|
||||
|
||||
async def stats(max_age: float = 60) -> dict:
|
||||
if _stats_cache["data"] is not None and time.time() - _stats_cache["at"] < max_age:
|
||||
return _stats_cache["data"]
|
||||
data = await get("/control/stats")
|
||||
_stats_cache.update(at=time.time(), data=data)
|
||||
return data
|
||||
|
||||
|
||||
MULTI_PART_SUFFIXES = {
|
||||
"co.uk", "org.uk", "ac.uk", "gov.uk", "me.uk", "com.au", "net.au", "org.au", "co.nz", "co.jp", "ne.jp",
|
||||
"com.br", "com.cn", "com.mx", "co.in", "co.za", "com.tr", "com.sg", "com.ph", "com.hk", "com.tw", "co.kr",
|
||||
"com.ar", "com.my", "co.id", "com.vn", "com.pk", "com.ng", "com.eg", "com.sa", "co.il", "com.ua",
|
||||
}
|
||||
|
||||
|
||||
def base_domain(name: str) -> str:
|
||||
"""Registrable domain, approximately (no full public suffix list): a.b.example.co.uk -> example.co.uk."""
|
||||
labels = name.lower().rstrip(".").split(".")
|
||||
if len(labels) <= 2 or all(x.isdigit() for x in labels):
|
||||
return ".".join(labels)
|
||||
n = 3 if ".".join(labels[-2:]) in MULTI_PART_SUFFIXES else 2
|
||||
return ".".join(labels[-n:])
|
||||
86
app/hub/db.py
Normal file
86
app/hub/db.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"""SQLite storage under $DATA_DIR. One short-lived connection per unit of work."""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS probes (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
address TEXT, -- set by the hub from the report, or ADVERTISE_ADDR, or by hand
|
||||
address_locked INTEGER NOT NULL DEFAULT 0,
|
||||
port INTEGER,
|
||||
hostname TEXT,
|
||||
version TEXT,
|
||||
icmp INTEGER, -- 1/0: whether ICMP works on that probe
|
||||
created REAL NOT NULL,
|
||||
last_seen REAL,
|
||||
last_error TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS measurements (
|
||||
ts REAL NOT NULL,
|
||||
probe_id INTEGER NOT NULL,
|
||||
target TEXT NOT NULL, -- probe:<id>, gateway, dns:<ip>, vps, web:<url>
|
||||
label TEXT,
|
||||
kind TEXT NOT NULL, -- lan | wan
|
||||
method TEXT NOT NULL, -- icmp | http | dns | throughput
|
||||
ok INTEGER NOT NULL,
|
||||
latency REAL, -- ms
|
||||
loss REAL, -- 0..1 (icmp)
|
||||
mbps REAL, -- throughput
|
||||
error TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS m_ts ON measurements(ts);
|
||||
CREATE INDEX IF NOT EXISTS m_series ON measurements(probe_id, target, method, ts);
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
key TEXT PRIMARY KEY, -- MAC when known, else ip:<address>
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
sources TEXT NOT NULL DEFAULT '',
|
||||
first_seen REAL NOT NULL,
|
||||
last_seen REAL, -- last activity (DNS query or ARP); NULL = only listed somewhere
|
||||
name TEXT,
|
||||
category TEXT,
|
||||
suspicious INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS d_ip ON devices(ip);
|
||||
CREATE TABLE IF NOT EXISTS ip_mac (
|
||||
ip TEXT PRIMARY KEY,
|
||||
mac TEXT NOT NULL,
|
||||
last_seen REAL NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def path() -> Path:
|
||||
return Path(os.environ.get("DATA_DIR", "data")) / "hub.sqlite3"
|
||||
|
||||
|
||||
def connect() -> sqlite3.Connection:
|
||||
con = sqlite3.connect(path(), timeout=15)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
con.execute("PRAGMA synchronous=NORMAL")
|
||||
return con
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db():
|
||||
"""A connection whose work commits on success and rolls back on error."""
|
||||
con = connect()
|
||||
try:
|
||||
with con:
|
||||
yield con
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def init() -> None:
|
||||
path().parent.mkdir(parents=True, exist_ok=True)
|
||||
with db() as con:
|
||||
con.executescript(SCHEMA)
|
||||
96
app/hub/devices.py
Normal file
96
app/hub/devices.py
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
"""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
|
||||
319
app/hub/dns.py
Normal file
319
app/hub/dns.py
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
"""Clients, DNS query log, domain detail and blocked domains, all backed by AdGuard Home."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.hub import adguard, devices, settings
|
||||
from app.hub.db import db
|
||||
|
||||
log = logging.getLogger("hub.dns")
|
||||
router = APIRouter()
|
||||
|
||||
CATEGORIES = ["Computer", "Mobile", "Tablet", "IoT", "Server", "Network", "Media", "Gaming", "Other"]
|
||||
ONLINE_SECONDS = 600
|
||||
|
||||
|
||||
def _decorate(rows: list[dict], index: dict) -> list[dict]:
|
||||
for r in rows:
|
||||
d = index.get(r["client"])
|
||||
r["device"] = d
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- status
|
||||
|
||||
@router.get("/dns/status")
|
||||
async def dns_status() -> dict:
|
||||
s = settings.get()
|
||||
if not s.adguard_configured:
|
||||
return {"configured": False, "ok": False, "message": "Set ADGUARD_URL in the hub's .env to see clients and DNS queries."}
|
||||
try:
|
||||
st = await adguard.get("/control/status")
|
||||
except adguard.AdGuardError as e:
|
||||
return {"configured": True, "ok": False, "url": s.adguard_url, "message": str(e)}
|
||||
return {"configured": True, "ok": True, "url": s.adguard_url, "version": st.get("version", ""),
|
||||
"protection_enabled": st.get("protection_enabled"), "running": st.get("running")}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- clients
|
||||
|
||||
class DeviceMeta(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=80)
|
||||
category: str | None = Field(default=None, max_length=40)
|
||||
suspicious: bool | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
|
||||
|
||||
def device_out(r, counts: dict | None = None, now: float | None = None, epoch: float | None = None) -> dict:
|
||||
"""epoch: when the hub first saw any device. Devices from that first day aren't "new"."""
|
||||
now = now or time.time()
|
||||
return {
|
||||
"key": r["key"], "mac": r["mac"], "ip": r["ip"], "hostname": r["hostname"] or "",
|
||||
"name": r["name"] or "", "display": r["name"] or r["hostname"] or r["ip"] or r["mac"],
|
||||
"category": r["category"] or "", "suspicious": bool(r["suspicious"]), "notes": r["notes"] or "",
|
||||
"sources": [x for x in r["sources"].split(",") if x], "first_seen": r["first_seen"], "last_seen": r["last_seen"],
|
||||
"online": bool(r["last_seen"]) and now - r["last_seen"] < ONLINE_SECONDS,
|
||||
"new": now - r["first_seen"] < 86400 and (epoch is None or r["first_seen"] - epoch > 86400),
|
||||
"queries": (counts or {}).get(r["ip"]) if r["ip"] else None,
|
||||
}
|
||||
|
||||
|
||||
async def _client_counts() -> dict:
|
||||
if not settings.get().adguard_configured:
|
||||
return {}
|
||||
try:
|
||||
return dict(adguard.top_list((await adguard.stats()).get("top_clients")))
|
||||
except adguard.AdGuardError:
|
||||
return {}
|
||||
|
||||
|
||||
@router.get("/clients")
|
||||
async def list_clients() -> dict:
|
||||
counts = await _client_counts()
|
||||
with db() as con:
|
||||
rows = con.execute("SELECT * FROM devices ORDER BY COALESCE(name, hostname, ip, mac) COLLATE NOCASE").fetchall()
|
||||
epoch = min((r["first_seen"] for r in rows), default=None)
|
||||
return {"clients": [device_out(r, counts, epoch=epoch) for r in rows], "categories": CATEGORIES,
|
||||
"adguard": settings.get().adguard_configured}
|
||||
|
||||
|
||||
def _device(con, key: str):
|
||||
row = con.execute("SELECT * FROM devices WHERE key = ?", (key,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "No client with that id")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/clients/{key}")
|
||||
async def get_client(key: str) -> dict:
|
||||
counts = await _client_counts()
|
||||
with db() as con:
|
||||
row = _device(con, key)
|
||||
ips = devices.ips_for(con, key)
|
||||
out = device_out(row, counts)
|
||||
out["ips"] = ips
|
||||
out["categories"] = CATEGORIES
|
||||
return out
|
||||
|
||||
|
||||
@router.put("/clients/{key}")
|
||||
def update_client(key: str, body: DeviceMeta) -> dict:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
if "suspicious" in fields:
|
||||
fields["suspicious"] = int(bool(fields["suspicious"]))
|
||||
for k in ("name", "category", "notes"):
|
||||
if k in fields:
|
||||
fields[k] = (fields[k] or "").strip() or None
|
||||
if fields:
|
||||
con.execute(f"UPDATE devices SET {', '.join(f'{k} = ?' for k in fields)} WHERE key = ?", (*fields.values(), key))
|
||||
return device_out(_device(con, key))
|
||||
|
||||
|
||||
@router.delete("/clients/{key}", status_code=204)
|
||||
def forget_client(key: str) -> None:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
con.execute("DELETE FROM devices WHERE key = ?", (key,))
|
||||
|
||||
|
||||
@router.get("/clients/{key}/summary")
|
||||
async def client_summary(key: str, sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||
with db() as con:
|
||||
_device(con, key)
|
||||
ips = devices.ips_for(con, key)
|
||||
if not ips:
|
||||
return {"ips": [], "sample": 0, "top": [], "blocked_top": [], "blocked": 0, "since": None}
|
||||
wanted = set(ips)
|
||||
res = await adguard.collect(search=ips[0] if len(ips) == 1 else "", want=sample, keep=lambda r: r["client"] in wanted, max_rows=sample * 5)
|
||||
rows = res["rows"]
|
||||
top = Counter(r["domain"] for r in rows)
|
||||
blocked = Counter(r["domain"] for r in rows if r["blocked"])
|
||||
return {
|
||||
"ips": ips, "sample": len(rows), "blocked": sum(blocked.values()),
|
||||
"since": min((r["ts"] for r in rows), default=None),
|
||||
"top": [{"domain": d, "count": c, "blocked": blocked.get(d, 0)} for d, c in top.most_common(25)],
|
||||
"blocked_top": [{"domain": d, "count": c} for d, c in blocked.most_common(10)],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- query log
|
||||
|
||||
@router.get("/dns/queries")
|
||||
async def queries(search: str = "", status: str = Query("all", pattern="^(all|blocked|allowed)$"),
|
||||
client: str = "", ip: str = "", domain: str = "", older_than: str = "",
|
||||
limit: int = Query(100, ge=1, le=500)) -> dict:
|
||||
"""The AdGuard query log, newest first. `client` is a client id, `ip` a comma list of exact addresses."""
|
||||
with db() as con:
|
||||
ips = {x.strip() for x in ip.split(",") if x.strip()}
|
||||
if client:
|
||||
ips.update(devices.ips_for(con, client) or ["-"])
|
||||
index = devices.ip_index(con)
|
||||
domain = domain.strip().lower()
|
||||
|
||||
def keep(r):
|
||||
if ips and r["client"] not in ips:
|
||||
return False
|
||||
if domain and r["domain"] != domain:
|
||||
return False
|
||||
if status == "allowed" and r["blocked"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
ag_search = search.strip() or domain or (next(iter(ips)) if len(ips) == 1 else "")
|
||||
res = await adguard.collect(search=ag_search, status="blocked" if status == "blocked" else "all",
|
||||
older_than=older_than, want=limit, keep=keep, max_rows=limit * 20)
|
||||
res["rows"] = _decorate(res["rows"], index)
|
||||
return res
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- domains
|
||||
|
||||
@router.get("/domains")
|
||||
async def top_domains() -> dict:
|
||||
st = await adguard.stats()
|
||||
return {
|
||||
"top_queried": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_queried_domains"))],
|
||||
"top_blocked": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||
"num_queries": st.get("num_dns_queries"), "num_blocked": st.get("num_blocked_filtering"),
|
||||
"time_units": st.get("time_units"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/domains/{name}")
|
||||
async def domain_detail(name: str, sample: int = Query(3000, ge=100, le=10000)) -> dict:
|
||||
name = name.strip().rstrip(".").lower()
|
||||
if not name or len(name) > 253:
|
||||
raise HTTPException(400, "Give a domain name, like example.com")
|
||||
base = adguard.base_domain(name)
|
||||
res = await adguard.collect(search=base, want=sample, max_rows=sample,
|
||||
keep=lambda r: r["domain"] == base or r["domain"].endswith("." + base))
|
||||
rows = res["rows"]
|
||||
exact = [r for r in rows if r["domain"] == name]
|
||||
with db() as con:
|
||||
index = devices.ip_index(con)
|
||||
|
||||
clients = defaultdict(lambda: {"count": 0, "blocked": 0, "last": 0.0, "name": ""})
|
||||
for r in exact:
|
||||
c = clients[r["client"]]
|
||||
c["count"] += 1
|
||||
c["blocked"] += r["blocked"]
|
||||
c["last"] = max(c["last"], r["ts"])
|
||||
c["name"] = c["name"] or r["client_name"]
|
||||
related = Counter(r["domain"] for r in rows if r["domain"] != name)
|
||||
related_blocked = Counter(r["domain"] for r in rows if r["domain"] != name and r["blocked"])
|
||||
|
||||
now = time.time()
|
||||
hours = [0] * 24
|
||||
blocked_hours = [0] * 24
|
||||
for r in exact:
|
||||
age = int((now - r["ts"]) // 3600)
|
||||
if 0 <= age < 24:
|
||||
hours[23 - age] += 1
|
||||
blocked_hours[23 - age] += r["blocked"]
|
||||
lat = [r["elapsed_ms"] for r in exact if r["elapsed_ms"] is not None]
|
||||
|
||||
st = {}
|
||||
try:
|
||||
st = await adguard.stats()
|
||||
except adguard.AdGuardError:
|
||||
pass
|
||||
stats_count = dict(adguard.top_list(st.get("top_queried_domains"))).get(name)
|
||||
stats_blocked = dict(adguard.top_list(st.get("top_blocked_domains"))).get(name)
|
||||
|
||||
return {
|
||||
"domain": name, "base": base, "sample_rows": len(rows), "scanned": res["scanned"], "complete": res["done"],
|
||||
"since": min((r["ts"] for r in rows), default=None),
|
||||
"count": len(exact), "blocked": sum(r["blocked"] for r in exact),
|
||||
"first": min((r["ts"] for r in exact), default=None), "last": max((r["ts"] for r in exact), default=None),
|
||||
"avg_ms": round(sum(lat) / len(lat), 2) if lat else None,
|
||||
"types": Counter(r["type"] for r in exact).most_common(),
|
||||
"reasons": Counter(r["reason"] for r in exact).most_common(),
|
||||
"rules": Counter(r["rule"] for r in exact if r["rule"]).most_common(5),
|
||||
"stats_count": stats_count, "stats_blocked": stats_blocked,
|
||||
"hours": hours, "blocked_hours": blocked_hours,
|
||||
"clients": sorted(({"ip": ip, **v, "device": index.get(ip)} for ip, v in clients.items()), key=lambda x: -x["count"]),
|
||||
"related": [{"domain": d, "count": c, "blocked": related_blocked.get(d, 0)} for d, c in related.most_common(50)],
|
||||
"recent": _decorate(exact[:50], index),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dns/blocked")
|
||||
async def blocked(sample: int = Query(1000, ge=50, le=5000)) -> dict:
|
||||
st = await adguard.stats()
|
||||
res = await adguard.collect(status="blocked", want=sample, max_rows=sample, keep=lambda r: r["blocked"])
|
||||
with db() as con:
|
||||
index = devices.ip_index(con)
|
||||
agg = defaultdict(lambda: {"count": 0, "clients": set(), "last": 0.0, "rule": "", "reason": ""})
|
||||
for r in res["rows"]:
|
||||
a = agg[r["domain"]]
|
||||
a["count"] += 1
|
||||
a["clients"].add(r["client"])
|
||||
a["last"] = max(a["last"], r["ts"])
|
||||
a["rule"] = a["rule"] or r["rule"]
|
||||
a["reason"] = a["reason"] or r["reason"]
|
||||
recent = [
|
||||
{"domain": d, "count": a["count"], "last": a["last"], "rule": a["rule"], "reason": a["reason"],
|
||||
"clients": [{"ip": ip, "device": index.get(ip)} for ip in sorted(a["clients"])]}
|
||||
for d, a in sorted(agg.items(), key=lambda kv: -kv[1]["count"])
|
||||
]
|
||||
return {
|
||||
"top": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))],
|
||||
"num_blocked": st.get("num_blocked_filtering"), "num_queries": st.get("num_dns_queries"),
|
||||
"recent": recent, "sample": len(res["rows"]), "since": min((r["ts"] for r in res["rows"]), default=None),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- discovery (background)
|
||||
|
||||
async def discover_once() -> int:
|
||||
"""Pull client lists, DHCP leases and recent queries from AdGuard into the device table."""
|
||||
if not settings.get().adguard_configured:
|
||||
return 0
|
||||
found: list[dict] = []
|
||||
clients = await adguard.get("/control/clients")
|
||||
for c in clients.get("clients") or []:
|
||||
ids = c.get("ids") or []
|
||||
macs = [i for i in ids if devices.norm_mac(i)]
|
||||
ips = [i for i in ids if i.replace(".", "").isdigit() or (":" in i and not devices.norm_mac(i) and "/" not in i)]
|
||||
for ip in ips or [None]:
|
||||
found.append({"ip": ip, "mac": macs[0] if macs else None, "hostname": c.get("name"), "source": "adguard"})
|
||||
for c in clients.get("auto_clients") or []:
|
||||
found.append({"ip": c.get("ip"), "hostname": c.get("name"), "source": f"adguard-{(c.get('source') or 'auto').lower()}"})
|
||||
try:
|
||||
dhcp = await adguard.get("/control/dhcp/status")
|
||||
for lease in (dhcp.get("leases") or []) + (dhcp.get("static_leases") or []):
|
||||
found.append({"ip": lease.get("ip"), "mac": lease.get("mac"), "hostname": lease.get("hostname"), "source": "dhcp"})
|
||||
except adguard.AdGuardError:
|
||||
pass # DHCP not in use
|
||||
recent = await adguard.collect(want=adguard.PAGE, max_rows=adguard.PAGE)
|
||||
last: dict[str, tuple[float, str]] = {}
|
||||
for r in recent["rows"]:
|
||||
if r["client"] and r["ts"] > last.get(r["client"], (0, ""))[0]:
|
||||
last[r["client"]] = (r["ts"], r["client_name"])
|
||||
|
||||
def write():
|
||||
with db() as con:
|
||||
for f in found:
|
||||
devices.sighting(con, ip=f["ip"], mac=f.get("mac"), hostname=f.get("hostname"), source=f["source"])
|
||||
for ip, (ts, name) in last.items():
|
||||
devices.sighting(con, ip=ip, hostname=name or None, source="dns", seen=ts)
|
||||
await asyncio.to_thread(write)
|
||||
return len(found) + len(last)
|
||||
|
||||
|
||||
async def discovery_loop(every: float = 60) -> None:
|
||||
while True:
|
||||
try:
|
||||
await discover_once()
|
||||
except (adguard.AdGuardError, adguard.NotConfigured) as e:
|
||||
log.warning("client discovery: %s", e)
|
||||
except Exception:
|
||||
log.exception("client discovery failed")
|
||||
await asyncio.sleep(every)
|
||||
215
app/hub/health.py
Normal file
215
app/hub/health.py
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
"""Network health from probe measurements: the live matrix, status strips, incidents, series."""
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from app.hub import settings
|
||||
from app.hub.db import db
|
||||
from app.hub.probes import is_online
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
RANGES = {"1h": (3600, 60), "6h": (6 * 3600, 72), "24h": (86400, 96), "7d": (7 * 86400, 84), "30d": (30 * 86400, 90)}
|
||||
|
||||
|
||||
def _sev_sql() -> tuple[str, dict]:
|
||||
"""Severity per measurement: 2 = failed, 1 = slow or lossy, 0 = fine."""
|
||||
s = settings.get()
|
||||
sql = """CASE WHEN ok = 0 THEN 2
|
||||
WHEN (loss IS NOT NULL AND loss >= 0.3)
|
||||
OR latency > (CASE WHEN method = 'dns' THEN :slow_dns WHEN kind = 'lan' THEN :slow_lan ELSE :slow_wan END) THEN 1
|
||||
ELSE 0 END"""
|
||||
return sql, {"slow_dns": s.slow_dns_ms, "slow_lan": s.slow_lan_ms, "slow_wan": s.slow_wan_ms}
|
||||
|
||||
|
||||
def bucket_status(n: int, down: int, slow: int) -> str:
|
||||
if not n:
|
||||
return "nodata"
|
||||
if down * 2 >= n:
|
||||
return "down"
|
||||
if (down + slow) * 5 >= n:
|
||||
return "degraded"
|
||||
return "ok"
|
||||
|
||||
|
||||
RANK = {"nodata": 0, "ok": 1, "degraded": 2, "down": 3}
|
||||
|
||||
|
||||
def _range(range_: str, until: float | None):
|
||||
if range_ not in RANGES:
|
||||
raise HTTPException(400, f"range must be one of {', '.join(RANGES)}")
|
||||
span, buckets = RANGES[range_]
|
||||
until = until or time.time()
|
||||
return until - span, until, span / buckets, buckets
|
||||
|
||||
|
||||
def _probe_names(con) -> dict[int, dict]:
|
||||
return {r["id"]: {"id": r["id"], "name": r["name"], "online": is_online(r), "last_seen": r["last_seen"], "icmp": r["icmp"]}
|
||||
for r in con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE")}
|
||||
|
||||
|
||||
def _target_order(target: str, kind: str) -> tuple:
|
||||
group = 0 if target.startswith("probe:") else 1 if target == "gateway" else 2 if kind == "lan" else 3
|
||||
return (group, target)
|
||||
|
||||
|
||||
@router.get("/health/matrix")
|
||||
def matrix(window: int = Query(300, ge=60, le=3600)) -> dict:
|
||||
"""Per probe and target, over the last `window` seconds."""
|
||||
sev, params = _sev_sql()
|
||||
since = time.time() - window
|
||||
with db() as con:
|
||||
probes = _probe_names(con)
|
||||
rows = con.execute(f"""
|
||||
SELECT probe_id, target, method, MAX(label) label, MAX(kind) kind, COUNT(*) n,
|
||||
SUM(sev = 2) down, SUM(sev = 1) slow,
|
||||
AVG(CASE WHEN ok THEN latency END) latency, AVG(loss) loss, MAX(ts) last,
|
||||
(SELECT error FROM measurements e WHERE e.probe_id = m.probe_id AND e.target = m.target
|
||||
AND e.method = m.method AND e.ok = 0 AND e.ts >= :since ORDER BY ts DESC LIMIT 1) error
|
||||
FROM (SELECT *, {sev} sev FROM measurements WHERE ts >= :since AND method != 'throughput') m
|
||||
GROUP BY probe_id, target, method""", {**params, "since": since}).fetchall()
|
||||
cells: dict = defaultdict(lambda: {"methods": {}, "status": "nodata"})
|
||||
targets: dict = {}
|
||||
for r in rows:
|
||||
if r["probe_id"] not in probes:
|
||||
continue
|
||||
key = (r["probe_id"], r["target"])
|
||||
st = bucket_status(r["n"], r["down"], r["slow"])
|
||||
c = cells[key]
|
||||
c["methods"][r["method"]] = {"status": st, "n": r["n"], "down": r["down"], "slow": r["slow"],
|
||||
"latency": r["latency"], "loss": r["loss"], "last": r["last"], "error": r["error"]}
|
||||
if RANK[st] > RANK[c["status"]]:
|
||||
c["status"] = st
|
||||
targets.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"]})
|
||||
for t in targets.values():
|
||||
if t["target"].startswith("probe:"):
|
||||
pid = int(t["target"].split(":", 1)[1])
|
||||
if pid in probes:
|
||||
t["label"] = probes[pid]["name"]
|
||||
return {
|
||||
"window": window, "probes": list(probes.values()),
|
||||
"targets": sorted(targets.values(), key=lambda t: _target_order(t["target"], t["kind"])),
|
||||
"cells": [{"probe_id": k[0], "target": k[1], **v} for k, v in cells.items()],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/strips")
|
||||
def strips(range: str = "24h", probe: int | None = None, until: float | None = None) -> dict:
|
||||
"""Status per time bucket for every probe → target pair."""
|
||||
since, until, width, n_buckets = _range(range, until)
|
||||
sev, params = _sev_sql()
|
||||
where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "")
|
||||
with db() as con:
|
||||
probes = _probe_names(con)
|
||||
rows = con.execute(f"""
|
||||
SELECT probe_id, target, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b,
|
||||
COUNT(*) n, SUM(sev = 2) down, SUM(sev = 1) slow, AVG(CASE WHEN ok THEN latency END) latency
|
||||
FROM (SELECT *, {sev} sev FROM measurements WHERE {where}) GROUP BY probe_id, target, b""",
|
||||
{**params, "since": since, "until": until, "width": width, "probe": probe}).fetchall()
|
||||
series: dict = {}
|
||||
for r in rows:
|
||||
if r["probe_id"] not in probes or not 0 <= r["b"] < n_buckets:
|
||||
continue
|
||||
key = (r["probe_id"], r["target"])
|
||||
if key not in series:
|
||||
label = r["label"]
|
||||
if r["target"].startswith("probe:"):
|
||||
label = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", label)
|
||||
series[key] = {"probe_id": r["probe_id"], "target": r["target"], "label": label, "kind": r["kind"],
|
||||
"buckets": [None] * n_buckets}
|
||||
series[key]["buckets"][r["b"]] = {"s": bucket_status(r["n"], r["down"], r["slow"]), "n": r["n"],
|
||||
"down": r["down"], "slow": r["slow"],
|
||||
"latency": round(r["latency"], 1) if r["latency"] is not None else None}
|
||||
out = sorted(series.values(), key=lambda x: (probes[x["probe_id"]]["name"].lower(), _target_order(x["target"], x["kind"])))
|
||||
for s in out:
|
||||
s["uptime"] = _uptime(s["buckets"])
|
||||
return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probes": list(probes.values()), "series": out}
|
||||
|
||||
|
||||
def _uptime(buckets) -> float | None:
|
||||
n = sum(b["n"] for b in buckets if b)
|
||||
down = sum(b["down"] for b in buckets if b)
|
||||
return round(100 * (n - down) / n, 2) if n else None
|
||||
|
||||
|
||||
@router.get("/health/incidents")
|
||||
def incidents(range: str = "24h", probe: int | None = None, until: float | None = None, limit: int = Query(200, ge=1, le=1000)) -> dict:
|
||||
"""Runs of failed or slow measurements, merged per probe → target when they are close together."""
|
||||
since, until, _, _ = _range(range, until)
|
||||
s = settings.get()
|
||||
gap = s.probe_interval * 2.5 + 5
|
||||
sev, params = _sev_sql()
|
||||
where = "ts >= :since AND ts < :until AND method != 'throughput'" + (" AND probe_id = :probe" if probe else "")
|
||||
with db() as con:
|
||||
probes = _probe_names(con)
|
||||
rows = con.execute(f"""SELECT * FROM (SELECT ts, probe_id, target, label, kind, method, ok, latency, loss, error, {sev} sev
|
||||
FROM measurements WHERE {where}) WHERE sev > 0 ORDER BY probe_id, target, ts""",
|
||||
{**params, "since": since, "until": until, "probe": probe}).fetchall()
|
||||
found, cur = [], None
|
||||
for r in rows:
|
||||
if r["probe_id"] not in probes:
|
||||
continue
|
||||
if cur and cur["probe_id"] == r["probe_id"] and cur["target"] == r["target"] and r["ts"] - cur["end"] <= gap:
|
||||
cur["end"] = r["ts"]
|
||||
else:
|
||||
cur = {"probe_id": r["probe_id"], "probe": probes[r["probe_id"]]["name"], "target": r["target"],
|
||||
"label": r["label"], "kind": r["kind"], "start": r["ts"], "end": r["ts"], "samples": 0,
|
||||
"failed": 0, "methods": set(), "max_latency": None, "error": None}
|
||||
found.append(cur)
|
||||
cur["samples"] += 1
|
||||
cur["failed"] += r["sev"] == 2
|
||||
cur["methods"].add(r["method"])
|
||||
if r["latency"] is not None and r["ok"]:
|
||||
cur["max_latency"] = max(cur["max_latency"] or 0, r["latency"])
|
||||
if r["error"]:
|
||||
cur["error"] = r["error"]
|
||||
now = time.time()
|
||||
out = []
|
||||
for i in found:
|
||||
if not i["failed"] and i["samples"] < 2:
|
||||
continue # one slow sample is noise
|
||||
if i["target"].startswith("probe:"):
|
||||
i["label"] = probes.get(int(i["target"].split(":", 1)[1]), {}).get("name", i["label"])
|
||||
i["type"] = "down" if i["failed"] else "degraded"
|
||||
i["methods"] = sorted(i["methods"])
|
||||
i["ongoing"] = now - i["end"] < gap
|
||||
i["duration"] = i["end"] - i["start"] + s.probe_interval
|
||||
out.append(i)
|
||||
out.sort(key=lambda i: -i["start"])
|
||||
return {"since": since, "until": until, "incidents": out[:limit], "total": len(out),
|
||||
"thresholds": {"lan_ms": s.slow_lan_ms, "wan_ms": s.slow_wan_ms, "dns_ms": s.slow_dns_ms, "loss": 0.3}}
|
||||
|
||||
|
||||
@router.get("/health/series")
|
||||
def series(probe: int, range: str = "24h", until: float | None = None) -> dict:
|
||||
"""Latency, loss and throughput per target and method for one probe, bucketed."""
|
||||
since, until, width, n_buckets = _range(range, until)
|
||||
with db() as con:
|
||||
probes = _probe_names(con)
|
||||
if probe not in probes:
|
||||
raise HTTPException(404, "No probe with that id")
|
||||
rows = con.execute("""
|
||||
SELECT target, method, MAX(label) label, MAX(kind) kind, CAST((ts - :since) / :width AS INTEGER) b,
|
||||
COUNT(*) n, SUM(ok = 0) failed, AVG(CASE WHEN ok THEN latency END) avg, MAX(CASE WHEN ok THEN latency END) max,
|
||||
AVG(loss) loss, AVG(mbps) mbps
|
||||
FROM measurements WHERE probe_id = :probe AND ts >= :since AND ts < :until
|
||||
GROUP BY target, method, b""", {"since": since, "until": until, "width": width, "probe": probe}).fetchall()
|
||||
out: dict = {}
|
||||
for r in rows:
|
||||
if not 0 <= r["b"] < n_buckets:
|
||||
continue
|
||||
t = out.setdefault(r["target"], {"target": r["target"], "label": r["label"], "kind": r["kind"], "methods": {}})
|
||||
if r["target"].startswith("probe:"):
|
||||
t["label"] = probes.get(int(r["target"].split(":", 1)[1]), {}).get("name", t["label"])
|
||||
m = t["methods"].setdefault(r["method"], [None] * n_buckets)
|
||||
rnd = lambda v, d=1: None if v is None else round(v, d)
|
||||
m[r["b"]] = {"n": r["n"], "failed": r["failed"], "avg": rnd(r["avg"]), "max": rnd(r["max"]),
|
||||
"loss": rnd(r["loss"], 3), "mbps": rnd(r["mbps"])}
|
||||
targets = sorted(out.values(), key=lambda t: _target_order(t["target"], t["kind"]))
|
||||
return {"since": since, "until": until, "width": width, "buckets": n_buckets, "probe": probes[probe], "targets": targets}
|
||||
|
||||
|
||||
def prune(con, retention_days: float) -> int:
|
||||
return con.execute("DELETE FROM measurements WHERE ts < ?", (time.time() - retention_days * 86400,)).rowcount
|
||||
174
app/hub/probes.py
Normal file
174
app/hub/probes.py
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
"""Probe management (UI) and the probe report endpoint (probes, token auth)."""
|
||||
|
||||
import ipaddress
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.hub import devices, settings
|
||||
from app.hub.db import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_BATCH = 5000
|
||||
|
||||
|
||||
class ProbeCreate(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
|
||||
|
||||
class ProbeUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=60)
|
||||
address: str | None = Field(default=None, max_length=255) # "" = detect again from reports
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
|
||||
|
||||
class Measurement(BaseModel):
|
||||
ts: float
|
||||
target: str = Field(max_length=300)
|
||||
label: str | None = Field(default=None, max_length=200)
|
||||
kind: str = Field(pattern="^(lan|wan)$")
|
||||
method: str = Field(pattern="^(icmp|http|dns|throughput)$")
|
||||
ok: bool
|
||||
latency: float | None = None
|
||||
loss: float | None = None
|
||||
mbps: float | None = None
|
||||
error: str | None = Field(default=None, max_length=300)
|
||||
|
||||
|
||||
class Neighbor(BaseModel):
|
||||
ip: str = Field(max_length=64)
|
||||
mac: str = Field(max_length=32)
|
||||
|
||||
|
||||
class Report(BaseModel):
|
||||
version: str | None = Field(default=None, max_length=40)
|
||||
hostname: str | None = Field(default=None, max_length=255)
|
||||
port: int = Field(default=8765, ge=1, le=65535)
|
||||
advertise_addr: str | None = Field(default=None, max_length=255)
|
||||
icmp: bool | None = None
|
||||
measurements: list[Measurement] = Field(default_factory=list, max_length=MAX_BATCH)
|
||||
neighbors: list[Neighbor] = Field(default_factory=list, max_length=4096)
|
||||
|
||||
|
||||
def is_online(row, now: float | None = None) -> bool:
|
||||
now = now or time.time()
|
||||
return bool(row["last_seen"]) and now - row["last_seen"] < settings.get().probe_interval * 3 + 10
|
||||
|
||||
|
||||
def probe_out(row, *, with_token: bool = False) -> dict:
|
||||
out = {k: row[k] for k in ("id", "name", "address", "port", "hostname", "version", "created", "last_seen", "last_error")}
|
||||
out["address_locked"] = bool(row["address_locked"])
|
||||
out["icmp"] = None if row["icmp"] is None else bool(row["icmp"])
|
||||
out["online"] = is_online(row)
|
||||
if with_token:
|
||||
out["token"] = row["token"]
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/probes")
|
||||
def list_probes() -> dict:
|
||||
with db() as con:
|
||||
rows = con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE").fetchall()
|
||||
s = settings.get()
|
||||
return {"probes": [probe_out(r) for r in rows], "interval": s.probe_interval,
|
||||
"install_url": s.probe_install_url, "hub_url": s.hub_public_url}
|
||||
|
||||
|
||||
@router.post("/probes", status_code=201)
|
||||
def create_probe(body: ProbeCreate) -> dict:
|
||||
token = secrets.token_urlsafe(24)
|
||||
with db() as con:
|
||||
cur = con.execute("INSERT INTO probes(name, token, created) VALUES (?, ?, ?)", (body.name.strip(), token, time.time()))
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return probe_out(row, with_token=True)
|
||||
|
||||
|
||||
def _get(con, probe_id: int):
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (probe_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "No probe with that id")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/probes/{probe_id}")
|
||||
def get_probe(probe_id: int) -> dict:
|
||||
with db() as con:
|
||||
return probe_out(_get(con, probe_id), with_token=True)
|
||||
|
||||
|
||||
@router.patch("/probes/{probe_id}")
|
||||
def update_probe(probe_id: int, body: ProbeUpdate) -> dict:
|
||||
with db() as con:
|
||||
_get(con, probe_id)
|
||||
if body.name is not None:
|
||||
con.execute("UPDATE probes SET name = ? WHERE id = ?", (body.name.strip(), probe_id))
|
||||
if body.address is not None:
|
||||
addr = body.address.strip()
|
||||
con.execute("UPDATE probes SET address = ?, address_locked = ? WHERE id = ?", (addr or None, int(bool(addr)), probe_id))
|
||||
if body.port is not None:
|
||||
con.execute("UPDATE probes SET port = ? WHERE id = ?", (body.port, probe_id))
|
||||
return probe_out(_get(con, probe_id), with_token=True)
|
||||
|
||||
|
||||
@router.delete("/probes/{probe_id}", status_code=204)
|
||||
def delete_probe(probe_id: int, keep_history: bool = False) -> None:
|
||||
with db() as con:
|
||||
_get(con, probe_id)
|
||||
con.execute("DELETE FROM probes WHERE id = ?", (probe_id,))
|
||||
if not keep_history:
|
||||
con.execute("DELETE FROM measurements WHERE probe_id = ?", (probe_id,))
|
||||
|
||||
|
||||
def probe_config(con, row) -> dict:
|
||||
"""What a probe should test, returned on every report."""
|
||||
s = settings.get()
|
||||
peers = [
|
||||
{"id": p["id"], "name": p["name"], "host": p["address"], "port": p["port"] or 8765}
|
||||
for p in con.execute("SELECT * FROM probes WHERE id != ? AND address IS NOT NULL ORDER BY id", (row["id"],))
|
||||
]
|
||||
dns = [{"server": d, "label": "LAN DNS" if len(s.lan_dns_servers) == 1 else f"LAN DNS {d}", "kind": "lan"} for d in s.lan_dns_servers]
|
||||
dns += [{"server": d, "label": f"DNS {d}", "kind": "wan"} for d in s.dns_servers]
|
||||
http = [{"url": u, "label": u.split("//", 1)[-1].split("/", 1)[0], "kind": "wan", "target": f"web:{u}"} for u in s.wan_http_urls]
|
||||
if s.vps_url:
|
||||
http.append({"url": f"{s.vps_url}/probe/ping", "label": "VPS", "kind": "wan", "target": "vps"})
|
||||
return {
|
||||
"probe_id": row["id"], "name": row["name"], "interval": s.probe_interval, "peers": peers,
|
||||
"dns": dns, "dns_name": s.dns_query_name, "http": http,
|
||||
"throughput_every": s.throughput_every, "throughput_bytes": s.throughput_bytes,
|
||||
}
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str | None:
|
||||
host = request.client.host if request.client else None
|
||||
try:
|
||||
return str(ipaddress.ip_address(host)) if host else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/probe/report")
|
||||
def report(body: Report, request: Request, authorization: str = Header(default="")) -> dict:
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
now = time.time()
|
||||
with db() as con:
|
||||
row = con.execute("SELECT * FROM probes WHERE token = ?", (token,)).fetchone() if token else None
|
||||
if not row:
|
||||
raise HTTPException(401, "Unknown probe token. Add the probe on the hub and use its install command.")
|
||||
address = row["address"]
|
||||
if not row["address_locked"]:
|
||||
address = (body.advertise_addr or "").strip() or _client_ip(request) or address
|
||||
con.execute(
|
||||
"UPDATE probes SET address = ?, port = ?, hostname = ?, version = ?, icmp = ?, last_seen = ?, last_error = NULL WHERE id = ?",
|
||||
(address, body.port, body.hostname, body.version, None if body.icmp is None else int(body.icmp), now, row["id"]),
|
||||
)
|
||||
con.executemany(
|
||||
"INSERT INTO measurements(ts, probe_id, target, label, kind, method, ok, latency, loss, mbps, error) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
[(m.ts, row["id"], m.target, m.label, m.kind, m.method, int(m.ok), m.latency, m.loss, m.mbps, m.error) for m in body.measurements],
|
||||
)
|
||||
for n in body.neighbors:
|
||||
devices.sighting(con, ip=n.ip, mac=n.mac, source="arp", seen=now)
|
||||
row = con.execute("SELECT * FROM probes WHERE id = ?", (row["id"],)).fetchone()
|
||||
return probe_config(con, row)
|
||||
131
app/hub/server.py
Normal file
131
app/hub/server.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"""The hub: web UI, JSON API for it, the probe report endpoint and background jobs."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.hub import adguard, db, dns, health, probes, settings
|
||||
from app.version import VERSION
|
||||
|
||||
log = logging.getLogger("hub")
|
||||
STATIC = Path(__file__).resolve().parent.parent / "static"
|
||||
|
||||
|
||||
async def _retention_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
def run():
|
||||
with db.db() as con:
|
||||
return health.prune(con, settings.get().retention_days)
|
||||
n = await asyncio.to_thread(run)
|
||||
if n:
|
||||
log.info("pruned %d old measurements", n)
|
||||
except Exception:
|
||||
log.exception("retention job failed")
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
# Startup work happens here, not at import: `update` imports app.main as a check.
|
||||
db.init()
|
||||
tasks = [asyncio.create_task(_retention_loop())]
|
||||
if settings.get().adguard_configured:
|
||||
tasks.append(asyncio.create_task(dns.discovery_loop()))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for t in tasks:
|
||||
t.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
|
||||
app = FastAPI(title="Network Monitor", version=VERSION, lifespan=lifespan,
|
||||
docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
|
||||
|
||||
|
||||
@app.exception_handler(adguard.NotConfigured)
|
||||
async def _not_configured(_req, exc):
|
||||
return JSONResponse({"detail": str(exc), "code": "adguard_not_configured"}, status_code=503)
|
||||
|
||||
|
||||
@app.exception_handler(adguard.AdGuardError)
|
||||
async def _adguard_error(_req, exc):
|
||||
return JSONResponse({"detail": str(exc), "code": "adguard_error"}, status_code=502)
|
||||
|
||||
|
||||
OPEN_PATHS = ("/healthz", "/api/probe/report")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def password(request: Request, call_next):
|
||||
"""Optional HTTP basic auth for the UI and its API (UI_PASSWORD). Probes use their own tokens."""
|
||||
pw = settings.get().ui_password
|
||||
if pw and not request.url.path.startswith(OPEN_PATHS):
|
||||
given = ""
|
||||
auth = request.headers.get("authorization", "")
|
||||
if auth.lower().startswith("basic "):
|
||||
try:
|
||||
given = base64.b64decode(auth[6:]).decode().split(":", 1)[-1]
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
given = ""
|
||||
if not secrets.compare_digest(given.encode(), pw.encode()):
|
||||
return Response("Password required", status_code=401, headers={"WWW-Authenticate": 'Basic realm="network monitor"'})
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
api = APIRouter()
|
||||
|
||||
|
||||
@api.get("/info")
|
||||
def info() -> dict:
|
||||
s = settings.get()
|
||||
return {"name": "Network Monitor", "role": "hub", "version": VERSION, "adguard": s.adguard_configured,
|
||||
"probe_interval": s.probe_interval, "retention_days": s.retention_days,
|
||||
"thresholds": {"lan_ms": s.slow_lan_ms, "wan_ms": s.slow_wan_ms, "dns_ms": s.slow_dns_ms},
|
||||
"dns_servers": s.dns_servers, "lan_dns_servers": s.lan_dns_servers, "dns_query_name": s.dns_query_name,
|
||||
"wan_http_urls": s.wan_http_urls, "vps_url": s.vps_url, "throughput_every": s.throughput_every,
|
||||
"throughput_bytes": s.throughput_bytes, "password": bool(s.ui_password),
|
||||
"install_mode": os.environ.get("INSTALL_MODE") or "docker",
|
||||
"update_command": os.environ.get("UPDATE_COMMAND") or "docker exec network-monitor update",
|
||||
"env_file": f"{os.environ.get('INSTALL_DIR') or '/opt/network-monitor'}/.env"}
|
||||
|
||||
|
||||
api.include_router(probes.router)
|
||||
api.include_router(health.router)
|
||||
api.include_router(dns.router)
|
||||
app.include_router(api, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/healthz", include_in_schema=False)
|
||||
def healthz() -> dict:
|
||||
return {"status": "ok", "version": VERSION, "role": "hub"}
|
||||
|
||||
|
||||
class Assets(StaticFiles):
|
||||
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
|
||||
|
||||
async def get_response(self, path, scope):
|
||||
response = await super().get_response(path, scope)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
app.mount("/static", Assets(directory=STATIC), name="static")
|
||||
|
||||
|
||||
@app.get("/{path:path}", include_in_schema=False)
|
||||
def spa(path: str) -> FileResponse:
|
||||
"""Every app path gets the shell; the client-side router picks the view."""
|
||||
if path.startswith(("api/", "static/")):
|
||||
raise HTTPException(404, "Not found")
|
||||
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
||||
69
app/hub/settings.py
Normal file
69
app/hub/settings.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""Hub settings, read from the environment (.env) on each call so tests can change them."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DEFAULT_PROBE_INSTALL_URL = "https://git.neilbantoc.dev/services/network-monitor/raw/branch/main/install-probe.sh"
|
||||
|
||||
|
||||
def _list(name: str, default: str) -> list[str]:
|
||||
return [x.strip() for x in os.environ.get(name, default).split(",") if x.strip()]
|
||||
|
||||
|
||||
def _num(name: str, default: float) -> float:
|
||||
try:
|
||||
return float(os.environ.get(name, "") or default)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
ui_password: str
|
||||
adguard_url: str
|
||||
adguard_username: str
|
||||
adguard_password: str
|
||||
probe_interval: int
|
||||
retention_days: float
|
||||
dns_servers: list[str]
|
||||
lan_dns_servers: list[str]
|
||||
dns_query_name: str
|
||||
wan_http_urls: list[str]
|
||||
vps_url: str
|
||||
slow_lan_ms: float
|
||||
slow_wan_ms: float
|
||||
slow_dns_ms: float
|
||||
throughput_every: int
|
||||
throughput_bytes: int
|
||||
probe_install_url: str
|
||||
hub_public_url: str
|
||||
|
||||
@property
|
||||
def adguard_configured(self) -> bool:
|
||||
return bool(self.adguard_url)
|
||||
|
||||
|
||||
def get() -> Settings:
|
||||
adguard_url = os.environ.get("ADGUARD_URL", "").strip().rstrip("/")
|
||||
lan_default = urlparse(adguard_url).hostname or "" if adguard_url else ""
|
||||
return Settings(
|
||||
ui_password=os.environ.get("UI_PASSWORD", ""),
|
||||
adguard_url=adguard_url,
|
||||
adguard_username=os.environ.get("ADGUARD_USERNAME", ""),
|
||||
adguard_password=os.environ.get("ADGUARD_PASSWORD", ""),
|
||||
probe_interval=max(5, int(_num("PROBE_INTERVAL", 30))),
|
||||
retention_days=max(1.0, _num("RETENTION_DAYS", 14)),
|
||||
dns_servers=_list("DNS_SERVERS", "1.1.1.1,8.8.8.8,9.9.9.9"),
|
||||
lan_dns_servers=_list("LAN_DNS_SERVERS", lan_default),
|
||||
dns_query_name=os.environ.get("DNS_QUERY_NAME", "example.com").strip() or "example.com",
|
||||
wan_http_urls=_list("WAN_HTTP_URLS", "http://connectivitycheck.gstatic.com/generate_204"),
|
||||
vps_url=os.environ.get("VPS_URL", "").strip().rstrip("/"),
|
||||
slow_lan_ms=_num("SLOW_LAN_MS", 100),
|
||||
slow_wan_ms=_num("SLOW_WAN_MS", 200),
|
||||
slow_dns_ms=_num("SLOW_DNS_MS", 250),
|
||||
throughput_every=max(0, int(_num("THROUGHPUT_EVERY", 10))),
|
||||
throughput_bytes=int(min(_num("THROUGHPUT_BYTES", 4_000_000), 50_000_000)),
|
||||
probe_install_url=os.environ.get("PROBE_INSTALL_URL", DEFAULT_PROBE_INSTALL_URL).strip(),
|
||||
hub_public_url=os.environ.get("HUB_PUBLIC_URL", "").strip().rstrip("/"),
|
||||
)
|
||||
28
app/main.py
Normal file
28
app/main.py
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"""Entry point for both roles. ROLE=hub (the default) serves the web UI and API;
|
||||
ROLE=probe runs a network probe. `update` imports this module as its pre-flight check."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
if os.environ.get("ROLE", "hub").strip().lower() == "probe":
|
||||
from app.probe.server import app
|
||||
else:
|
||||
from app.hub.server import app
|
||||
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
|
||||
_role_lifespan = app.router.lifespan_context
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(a):
|
||||
# Startup work goes here, not at import time: `update` imports this module as a check
|
||||
# before restarting. Shared by both roles; each role's own startup runs inside.
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
async with _role_lifespan(a):
|
||||
yield
|
||||
|
||||
|
||||
app.router.lifespan_context = lifespan
|
||||
|
||||
__all__ = ["app"]
|
||||
0
app/probe/__init__.py
Normal file
0
app/probe/__init__.py
Normal file
208
app/probe/checks.py
Normal file
208
app/probe/checks.py
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
"""The probe's measurements. Each returns a measurement dict the hub stores as is."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from icmplib import async_ping
|
||||
from icmplib.exceptions import ICMPLibError, SocketPermissionError
|
||||
|
||||
PROC_NET = os.environ.get("PROC_NET", "/proc/net")
|
||||
|
||||
|
||||
def m(target, label, kind, method, ok, latency=None, loss=None, mbps=None, error=None) -> dict:
|
||||
r = lambda v, d=2: None if v is None else round(v, d)
|
||||
return {"ts": time.time(), "target": target, "label": label, "kind": kind, "method": method, "ok": bool(ok),
|
||||
"latency": r(latency), "loss": r(loss, 3), "mbps": r(mbps), "error": (error or None) and str(error)[:300]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ICMP
|
||||
|
||||
ICMP_STATE = {"ok": None} # None = untried, True = works, False = not permitted on this host
|
||||
ICMP_HINT = "ICMP not permitted: set net.ipv4.ping_group_range on the host (install-probe.sh does this)"
|
||||
|
||||
|
||||
async def icmp(host: str, target: str, label: str, kind: str, count: int = 4) -> dict | None:
|
||||
if ICMP_STATE["ok"] is False:
|
||||
return None
|
||||
try:
|
||||
h = await async_ping(host, count=count, interval=0.2, timeout=1.5, privileged=False)
|
||||
except SocketPermissionError:
|
||||
ICMP_STATE["ok"] = False
|
||||
return None
|
||||
except (ICMPLibError, OSError) as e:
|
||||
return m(target, label, kind, "icmp", False, loss=1.0, error=f"{e.__class__.__name__}: {e}")
|
||||
ICMP_STATE["ok"] = True
|
||||
if not h.is_alive:
|
||||
return m(target, label, kind, "icmp", False, loss=1.0, error="no reply")
|
||||
return m(target, label, kind, "icmp", True, latency=h.avg_rtt, loss=h.packet_loss)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP
|
||||
|
||||
async def http(client: httpx.AsyncClient, url: str, target: str, label: str, kind: str) -> dict:
|
||||
t = time.perf_counter()
|
||||
try:
|
||||
r = await client.get(url, headers={"Cache-Control": "no-cache"})
|
||||
ms = (time.perf_counter() - t) * 1000
|
||||
if r.status_code >= 400:
|
||||
return m(target, label, kind, "http", False, latency=ms, error=f"HTTP {r.status_code}")
|
||||
return m(target, label, kind, "http", True, latency=ms)
|
||||
except httpx.HTTPError as e:
|
||||
return m(target, label, kind, "http", False, error=_err(e))
|
||||
|
||||
|
||||
async def throughput(client: httpx.AsyncClient, base: str, n_bytes: int, target: str, label: str) -> dict:
|
||||
t = time.perf_counter()
|
||||
got = 0
|
||||
try:
|
||||
async with client.stream("GET", f"{base}/probe/blob", params={"bytes": n_bytes}, timeout=60) as r:
|
||||
r.raise_for_status()
|
||||
async for chunk in r.aiter_bytes():
|
||||
got += len(chunk)
|
||||
secs = time.perf_counter() - t
|
||||
return m(target, label, "lan", "throughput", True, latency=secs * 1000, mbps=got * 8 / secs / 1e6)
|
||||
except httpx.HTTPError as e:
|
||||
return m(target, label, "lan", "throughput", False, error=_err(e))
|
||||
|
||||
|
||||
def _err(e: Exception) -> str:
|
||||
name = e.__class__.__name__
|
||||
text = str(e)
|
||||
return f"{name}: {text}" if text else name
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- DNS (one A query over UDP)
|
||||
|
||||
def dns_query_packet(name: str, qid: int) -> bytes:
|
||||
header = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, 0) # recursion desired
|
||||
qname = b"".join(bytes([len(p)]) + p.encode() for p in name.strip(".").split(".")) + b"\0"
|
||||
return header + qname + struct.pack("!HH", 1, 1) # A, IN
|
||||
|
||||
|
||||
RCODES = {1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", 5: "REFUSED"}
|
||||
|
||||
|
||||
async def dns(server: str, name: str, target: str, label: str, kind: str, timeout: float = 2.0, port: int = 53) -> dict:
|
||||
loop = asyncio.get_running_loop()
|
||||
qid = random.randrange(65536)
|
||||
fut = loop.create_future()
|
||||
|
||||
class Proto(asyncio.DatagramProtocol):
|
||||
def datagram_received(self, data, addr):
|
||||
if len(data) >= 12 and struct.unpack("!H", data[:2])[0] == qid and not fut.done():
|
||||
fut.set_result(data)
|
||||
|
||||
def error_received(self, exc):
|
||||
if not fut.done():
|
||||
fut.set_exception(exc)
|
||||
|
||||
family = socket.AF_INET6 if ":" in server else socket.AF_INET
|
||||
t = time.perf_counter()
|
||||
transport = None
|
||||
try:
|
||||
transport, _ = await loop.create_datagram_endpoint(Proto, remote_addr=(server, port), family=family)
|
||||
transport.sendto(dns_query_packet(name, qid))
|
||||
data = await asyncio.wait_for(fut, timeout)
|
||||
ms = (time.perf_counter() - t) * 1000
|
||||
flags, _, ancount = struct.unpack("!HHH", data[2:8])
|
||||
rcode = flags & 0xF
|
||||
if rcode:
|
||||
return m(target, label, kind, "dns", False, latency=ms, error=RCODES.get(rcode, f"rcode {rcode}"))
|
||||
if not ancount:
|
||||
return m(target, label, kind, "dns", False, latency=ms, error="empty answer")
|
||||
return m(target, label, kind, "dns", True, latency=ms)
|
||||
except TimeoutError:
|
||||
return m(target, label, kind, "dns", False, error="timeout")
|
||||
except OSError as e:
|
||||
return m(target, label, kind, "dns", False, error=f"{e.__class__.__name__}: {e}")
|
||||
finally:
|
||||
if transport:
|
||||
transport.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- host network facts
|
||||
# Linux reads /proc/net (host networking, LXC or bare metal). macOS has no /proc, so it asks
|
||||
# `route` and `arp` instead.
|
||||
|
||||
def _run(*cmd: str) -> str:
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, text=True, timeout=5, check=False).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return ""
|
||||
|
||||
|
||||
def default_gateway() -> str | None:
|
||||
if sys.platform == "darwin":
|
||||
return parse_route_get(_run("/sbin/route", "-n", "get", "default"))
|
||||
try:
|
||||
with open(f"{PROC_NET}/route") as f:
|
||||
next(f)
|
||||
for line in f:
|
||||
parts = line.split()
|
||||
if len(parts) > 3 and parts[1] == "00000000" and int(parts[3], 16) & 2:
|
||||
return socket.inet_ntoa(struct.pack("<L", int(parts[2], 16)))
|
||||
except (OSError, ValueError, StopIteration):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def parse_route_get(text: str) -> str | None:
|
||||
"""`route -n get default` on macOS: a line like ' gateway: 192.168.1.1'."""
|
||||
for line in text.splitlines():
|
||||
key, _, value = line.strip().partition(":")
|
||||
if key == "gateway" and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
|
||||
# Container, VM and VPN interfaces: their neighbors are containers or tunnels, not devices on the network.
|
||||
VIRTUAL_IFACES = ("docker", "br-", "veth", "virbr", "cni", "flannel", "cali", "lxc", "vnet", "tun", "tap", "wg", "zt",
|
||||
"tailscale", "utun", "bridge", "vmenet", "awdl", "llw", "anpi", "ap1")
|
||||
|
||||
|
||||
def neighbors() -> list[dict]:
|
||||
"""Complete ARP entries on physical interfaces."""
|
||||
if sys.platform == "darwin":
|
||||
return parse_arp_an(_run("/usr/sbin/arp", "-an"))
|
||||
out = []
|
||||
try:
|
||||
with open(f"{PROC_NET}/arp") as f:
|
||||
next(f)
|
||||
for line in f:
|
||||
p = line.split()
|
||||
if len(p) >= 6 and p[5].startswith(VIRTUAL_IFACES):
|
||||
continue
|
||||
if len(p) >= 4 and p[2] != "0x0" and p[3] != "00:00:00:00:00:00":
|
||||
out.append({"ip": p[0], "mac": p[3].lower()})
|
||||
except (OSError, StopIteration):
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
_ARP_LINE = re.compile(r"\((?P<ip>[0-9.]+)\) at (?P<mac>[0-9a-fA-F:]+) on (?P<iface>\S+)")
|
||||
|
||||
|
||||
def parse_arp_an(text: str) -> list[dict]:
|
||||
"""`arp -an` on macOS: '? (192.168.1.1) at 0:11:32:a:b:c on en0 ifscope [ethernet]'.
|
||||
macOS drops leading zeros in MAC octets, so they are padded back."""
|
||||
out = []
|
||||
for line in text.splitlines():
|
||||
m = _ARP_LINE.search(line)
|
||||
if not m or m["iface"].startswith(VIRTUAL_IFACES) or "permanent" in line:
|
||||
continue
|
||||
octets = m["mac"].split(":")
|
||||
if len(octets) != 6:
|
||||
continue
|
||||
mac = ":".join(o.zfill(2) for o in octets).lower()
|
||||
if mac in ("00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff") or m["ip"].endswith(".255") or m["ip"].startswith(("224.", "239.")):
|
||||
continue
|
||||
out.append({"ip": m["ip"], "mac": mac})
|
||||
return out
|
||||
210
app/probe/server.py
Normal file
210
app/probe/server.py
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
"""The probe: a tiny HTTP server other probes test against, plus a loop that measures the
|
||||
mesh and the ISP link and reports to the hub. With no HUB_URL it only serves (e.g. on a VPS)."""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from app.probe import checks
|
||||
from app.version import VERSION
|
||||
|
||||
log = logging.getLogger("probe")
|
||||
BUFFER_MAX = 20000 # measurements kept while the hub is unreachable (hours at the default interval)
|
||||
SEND_BATCH = 2000
|
||||
|
||||
state = {
|
||||
"hub_url": "", "registered": None, "last_report": None, "last_error": None, "cycles": 0,
|
||||
"buffered": 0, "config": None, "started": time.time(),
|
||||
}
|
||||
|
||||
|
||||
def env() -> dict:
|
||||
return {
|
||||
"hub_url": os.environ.get("HUB_URL", "").strip().rstrip("/"),
|
||||
"token": os.environ.get("PROBE_TOKEN", "").strip(),
|
||||
"port": int(os.environ.get("PORT", "8765")),
|
||||
"advertise": os.environ.get("ADVERTISE_ADDR", "").strip(),
|
||||
}
|
||||
|
||||
|
||||
async def run_checks(cfg: dict, cycle: int) -> list[dict]:
|
||||
jobs = []
|
||||
async with httpx.AsyncClient(timeout=4, follow_redirects=False) as client:
|
||||
for p in cfg.get("peers", []):
|
||||
target, label = f"probe:{p['id']}", p["name"]
|
||||
jobs.append(checks.icmp(p["host"], target, label, "lan"))
|
||||
base = f"http://{_hostport(p['host'], p['port'])}"
|
||||
jobs.append(checks.http(client, f"{base}/probe/ping", target, label, "lan"))
|
||||
gw = checks.default_gateway()
|
||||
if gw:
|
||||
jobs.append(checks.icmp(gw, "gateway", f"Gateway {gw}", "lan"))
|
||||
for d in cfg.get("dns", []):
|
||||
target = f"dns:{d['server']}"
|
||||
jobs.append(checks.dns(d["server"], cfg.get("dns_name", "example.com"), target, d["label"], d["kind"]))
|
||||
jobs.append(checks.icmp(d["server"], target, d["label"], d["kind"]))
|
||||
for h in cfg.get("http", []):
|
||||
jobs.append(checks.http(client, h["url"], h["target"], h["label"], h["kind"]))
|
||||
results = [r for r in await asyncio.gather(*jobs) if r]
|
||||
# Throughput runs after the latency checks, one peer at a time, so it doesn't skew them.
|
||||
every = cfg.get("throughput_every") or 0
|
||||
if every and cycle % every == 0:
|
||||
for p in cfg.get("peers", []):
|
||||
base = f"http://{_hostport(p['host'], p['port'])}"
|
||||
results.append(await checks.throughput(client, base, cfg.get("throughput_bytes", 4_000_000), f"probe:{p['id']}", p["name"]))
|
||||
return results
|
||||
|
||||
|
||||
def _hostport(host: str, port: int) -> str:
|
||||
return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
||||
|
||||
|
||||
async def report(client: httpx.AsyncClient, e: dict, buffer: deque, cycle: int) -> dict | None:
|
||||
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None."""
|
||||
config = None
|
||||
for _ in range(10):
|
||||
batch = [buffer[i] for i in range(min(SEND_BATCH, len(buffer)))]
|
||||
body = {"version": VERSION, "hostname": socket.gethostname(), "port": e["port"],
|
||||
"advertise_addr": e["advertise"] or None, "icmp": checks.ICMP_STATE["ok"],
|
||||
"measurements": batch, "neighbors": checks.neighbors() if cycle % 2 == 0 and config is None else []}
|
||||
r = await client.post(f"{e['hub_url']}/api/probe/report", json=body, headers={"Authorization": f"Bearer {e['token']}"})
|
||||
if r.status_code == 401:
|
||||
state["registered"] = False
|
||||
raise RuntimeError("the hub doesn't know this probe's token (removed on the hub?)")
|
||||
r.raise_for_status()
|
||||
state["registered"] = True
|
||||
config = r.json()
|
||||
for _ in batch:
|
||||
buffer.popleft()
|
||||
if not buffer:
|
||||
break
|
||||
return config
|
||||
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"interval": 30, "peers": [], "http": [], "dns_name": "example.com",
|
||||
"dns": [{"server": "1.1.1.1", "label": "DNS 1.1.1.1", "kind": "wan"}],
|
||||
}
|
||||
|
||||
|
||||
def _config_file():
|
||||
return Path(os.environ.get("DATA_DIR", "data")) / "probe-config.json"
|
||||
|
||||
|
||||
def load_config() -> dict | None:
|
||||
try:
|
||||
return json.loads(_config_file().read_text())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def save_config(cfg: dict) -> None:
|
||||
try:
|
||||
_config_file().parent.mkdir(parents=True, exist_ok=True)
|
||||
_config_file().write_text(json.dumps(cfg))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
async def probe_loop() -> None:
|
||||
"""Measure, then report; the hub's reply says what to measure next time. The last reply is
|
||||
cached on disk so a probe that restarts while the hub is down keeps testing its peers."""
|
||||
e = env()
|
||||
state["hub_url"] = e["hub_url"]
|
||||
buffer: deque = deque(maxlen=BUFFER_MAX)
|
||||
cfg = load_config() or DEFAULT_CONFIG
|
||||
state["config"] = load_config()
|
||||
await asyncio.sleep(random.uniform(0, 5)) # spread probes out
|
||||
cycle = 0
|
||||
async with httpx.AsyncClient(timeout=10) as hub:
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
buffer.extend(await run_checks(cfg, cycle))
|
||||
except Exception as ex:
|
||||
log.exception("checks failed")
|
||||
state["last_error"] = f"checks failed: {ex}"
|
||||
try:
|
||||
new = await report(hub, e, buffer, cycle)
|
||||
if new:
|
||||
if new != state["config"]:
|
||||
if state["config"] is None:
|
||||
log.info("registered with %s as %r (probe %s)", e["hub_url"], new.get("name"), new.get("probe_id"))
|
||||
save_config(new)
|
||||
cfg = state["config"] = new
|
||||
state["last_report"] = time.time()
|
||||
state["last_error"] = None
|
||||
except (httpx.HTTPError, RuntimeError, ValueError) as ex:
|
||||
state["last_error"] = f"report to hub failed: {checks._err(ex)}"
|
||||
log.warning(state["last_error"])
|
||||
state["buffered"] = len(buffer)
|
||||
state["cycles"] = cycle = cycle + 1
|
||||
await asyncio.sleep(max(1.0, cfg.get("interval", 30) - (time.monotonic() - started)))
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
task = None
|
||||
e = env()
|
||||
if e["hub_url"] and e["token"]:
|
||||
task = asyncio.create_task(probe_loop())
|
||||
elif e["hub_url"] or e["token"]:
|
||||
state["last_error"] = "set both HUB_URL and PROBE_TOKEN to report to a hub"
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if task:
|
||||
task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
|
||||
app = FastAPI(title="Network Monitor probe", version=VERSION, lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz() -> dict:
|
||||
return {"status": "ok", "version": VERSION, "role": "probe"}
|
||||
|
||||
|
||||
@app.get("/probe/ping")
|
||||
def ping() -> dict:
|
||||
return {"ok": True, "t": time.time()}
|
||||
|
||||
|
||||
CHUNK = b"\0" * 65536
|
||||
|
||||
|
||||
@app.get("/probe/blob")
|
||||
def blob(bytes: int = Query(1_000_000, ge=1, le=50_000_000)) -> StreamingResponse:
|
||||
def gen():
|
||||
left = bytes
|
||||
while left > 0:
|
||||
n = min(left, len(CHUNK))
|
||||
yield CHUNK[:n]
|
||||
left -= n
|
||||
return StreamingResponse(gen(), media_type="application/octet-stream",
|
||||
headers={"Content-Length": str(bytes), "Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def status() -> dict:
|
||||
cfg = state["config"] or {}
|
||||
return {
|
||||
"role": "probe", "version": VERSION, "hub_url": state["hub_url"] or None,
|
||||
"mode": "reporting" if state["hub_url"] else "serve only",
|
||||
"name": cfg.get("name"), "probe_id": cfg.get("probe_id"), "registered": state["registered"],
|
||||
"peers": len(cfg.get("peers", [])), "icmp": checks.ICMP_STATE["ok"], "gateway": checks.default_gateway(),
|
||||
"last_report": state["last_report"], "last_error": state["last_error"], "buffered": state["buffered"],
|
||||
"cycles": state["cycles"],
|
||||
}
|
||||
109
app/static/css/app.css
Normal file
109
app/static/css/app.css
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/* Network monitor: project rules on top of house.css. Chart colors come from the dataviz
|
||||
reference palette (status steps + categorical slots 1-2), stepped for each theme. */
|
||||
|
||||
:root {
|
||||
--viz-ok: #0ca30c;
|
||||
--viz-warn: #fab219;
|
||||
--viz-down: #d03b3b;
|
||||
--viz-none: var(--surface-2);
|
||||
--viz-1: #2a78d6;
|
||||
--viz-2: #eb6834;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme='light']) { --viz-1: #3987e5; --viz-2: #d95926; }
|
||||
}
|
||||
:root[data-theme='dark'] { --viz-1: #3987e5; --viz-2: #d95926; }
|
||||
|
||||
/* ---------- layout bits ---------- */
|
||||
.pane.fill { flex: 1; }
|
||||
.content { max-width: 1280px; padding: var(--space-4) var(--space-5) var(--space-10); }
|
||||
.content > .section-head:first-child, .content > .section-title:first-child { margin-top: 0; }
|
||||
.section-head { display: flex; align-items: baseline; gap: var(--space-3); flex-wrap: wrap; margin: var(--space-6) 0 var(--space-2); }
|
||||
.section-head .section-title { margin: 0; }
|
||||
.section-head .hint { font-size: var(--text-xs); color: var(--fg-muted); }
|
||||
.lede { margin: 0 0 var(--space-3); color: var(--fg-muted); }
|
||||
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: var(--space-5); }
|
||||
.cols > * { min-width: 0; }
|
||||
.kv { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px var(--space-4); margin: 0; font-size: var(--text-sm); }
|
||||
.kv dt { color: var(--fg-muted); }
|
||||
.kv dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
|
||||
.facts { display: flex; flex-wrap: wrap; gap: var(--space-2) var(--space-6); margin: var(--space-2) 0 var(--space-4); }
|
||||
.fact { display: grid; gap: 2px; }
|
||||
.fact .label { font-size: var(--text-2xs); }
|
||||
.fact strong { font-size: var(--text-lg); font-weight: var(--weight-semibold); }
|
||||
.title-row { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; }
|
||||
.title-row h2 { margin: 0; font-size: var(--text-xl); overflow-wrap: anywhere; }
|
||||
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: var(--space-3); max-width: 760px; }
|
||||
.form-grid .wide { grid-column: 1 / -1; }
|
||||
.cmd { display: flex; gap: var(--space-2); align-items: stretch; }
|
||||
.cmd pre { flex: 1; min-width: 0; margin: 0; padding: var(--space-2) var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--code-bg); font: var(--text-sm)/1.5 var(--font-mono); white-space: pre-wrap; word-break: break-all; }
|
||||
.more { display: flex; justify-content: center; padding: var(--space-3); }
|
||||
.toolbar .input { width: 220px; height: var(--control-h); padding: 0 10px; }
|
||||
.table a { color: inherit; text-decoration: none; }
|
||||
.table a:hover { color: var(--accent-text); text-decoration: underline; }
|
||||
.table td.mono, .table .mono { font-size: var(--text-xs); }
|
||||
.table .domain { overflow-wrap: anywhere; }
|
||||
.table tr.flagged td:first-child { box-shadow: inset 3px 0 0 var(--danger); }
|
||||
.chips { display: inline-flex; flex-wrap: wrap; gap: 4px; vertical-align: middle; }
|
||||
.callout { padding: var(--space-3) var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface-2); font-size: var(--text-sm); }
|
||||
.callout.error { border-color: var(--danger); background: var(--danger-soft); }
|
||||
.stale { opacity: 0.55; transition: opacity var(--dur-base); }
|
||||
|
||||
/* ---------- mesh matrix ---------- */
|
||||
.matrix th.row-head { text-align: left; position: sticky; left: 0; background: var(--surface); z-index: 1; }
|
||||
.matrix td { padding: 4px; }
|
||||
.cell { display: grid; gap: 1px; min-width: 92px; padding: 5px 8px; border-radius: var(--radius-control); background: var(--surface-2); color: var(--fg); text-decoration: none; font-size: var(--text-xs); border-left: 4px solid var(--viz-none); }
|
||||
.cell strong { font-size: var(--text-sm); font-variant-numeric: tabular-nums; }
|
||||
.cell.s-ok { border-left-color: var(--viz-ok); }
|
||||
.cell.s-degraded { border-left-color: var(--viz-warn); }
|
||||
.cell.s-down { border-left-color: var(--viz-down); background: var(--danger-soft); }
|
||||
.cell .muted { font-variant-numeric: tabular-nums; }
|
||||
.cell-empty { color: var(--fg-subtle); text-align: center; font-size: var(--text-xs); }
|
||||
|
||||
/* ---------- status strips ---------- */
|
||||
.strips { display: grid; gap: 6px; }
|
||||
.strip-row { display: grid; grid-template-columns: minmax(120px, 220px) minmax(0, 1fr) 64px; align-items: center; gap: var(--space-3); font-size: var(--text-sm); }
|
||||
.strip-row .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.strip-row .uptime { text-align: right; font-variant-numeric: tabular-nums; color: var(--fg-muted); font-size: var(--text-xs); }
|
||||
.strip-group + .strip-group { margin-top: var(--space-4); }
|
||||
.strip-group h3 { display: flex; align-items: center; gap: var(--space-2); margin: 0 0 6px; font-size: var(--text-sm); }
|
||||
.strip { display: grid; grid-template-columns: repeat(var(--n), minmax(0, 1fr)); gap: 2px; height: 22px; cursor: crosshair; }
|
||||
.strip span { border-radius: 2px; background: var(--viz-none); }
|
||||
.strip .s-ok, .viz-swatch.s-ok { background: var(--viz-ok); }
|
||||
.strip .s-degraded, .viz-swatch.s-degraded { background: var(--viz-warn); }
|
||||
.strip .s-down, .viz-swatch.s-down { background: var(--viz-down); }
|
||||
.strip .s-nodata, .viz-swatch.s-nodata { background: var(--viz-none); box-shadow: inset 0 0 0 1px var(--border); }
|
||||
.strip-axis { display: grid; grid-template-columns: minmax(120px, 220px) minmax(0, 1fr) 64px; gap: var(--space-3); font-size: var(--text-2xs); color: var(--fg-muted); }
|
||||
.strip-axis span:nth-child(2) { display: flex; justify-content: space-between; }
|
||||
|
||||
/* ---------- charts ---------- */
|
||||
.chart { position: relative; width: 100%; }
|
||||
.viz { display: block; overflow: visible; }
|
||||
.viz-grid { stroke: var(--border); stroke-width: 1; }
|
||||
.viz-axis { stroke: var(--border-strong); stroke-width: 1; }
|
||||
.viz-tick { fill: var(--fg-muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.viz-label { fill: var(--fg-muted); font-size: 11px; }
|
||||
.viz-cross { stroke: var(--fg-subtle); stroke-width: 1; }
|
||||
.viz-fail { fill: var(--viz-down); }
|
||||
.viz-hit:hover { fill: var(--surface-2); fill-opacity: 0.5; }
|
||||
.multiples { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); gap: var(--space-4); }
|
||||
.multiple { min-width: 0; padding: var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||
.multiple h4 { display: flex; align-items: center; gap: var(--space-2); margin: 0 0 4px; font-size: var(--text-sm); }
|
||||
.viz-legend { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); font-size: var(--text-xs); color: var(--fg-muted); }
|
||||
.viz-legend-item { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.viz-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; }
|
||||
.viz-linekey { display: inline-block; width: 14px; height: 2px; border-radius: 1px; }
|
||||
.viz-tip { position: fixed; z-index: var(--z-toast); pointer-events: none; min-width: 140px; max-width: 320px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); box-shadow: var(--shadow-popover); font-size: var(--text-xs); }
|
||||
.viz-tip-title { margin-bottom: 4px; color: var(--fg-muted); }
|
||||
.viz-tip-row { display: flex; align-items: center; gap: 6px; }
|
||||
.viz-tip-row strong { font-variant-numeric: tabular-nums; }
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.content { padding: var(--space-3) var(--space-3) var(--space-10); }
|
||||
.strip { gap: 1px; }
|
||||
.strip-row, .strip-axis { grid-template-columns: minmax(0, 1fr) 52px; }
|
||||
.strip-row .name { grid-column: 1 / -1; }
|
||||
.strip-row .strip { grid-column: 1; }
|
||||
.strip-axis { display: none; }
|
||||
.toolbar .input { width: 160px; }
|
||||
}
|
||||
390
app/static/css/house.css
Normal file
390
app/static/css/house.css
Normal file
|
|
@ -0,0 +1,390 @@
|
|||
/* =====================================================================
|
||||
House style: tokens, base and components.
|
||||
Copy into the project as-is (e.g. static/css/house.css) and put project
|
||||
rules in a second file loaded after it (e.g. app.css). Don't edit this
|
||||
copy for one project; override tokens in app.css instead.
|
||||
|
||||
The look: a dense, quiet utility UI. System fonts at 14px, neutral grays,
|
||||
one blue accent, 48px top bar + 216px sidebar, 30px controls, hairline
|
||||
borders instead of shadows. See references/house.md for the rules.
|
||||
|
||||
Allowed per-project override: the accent group (see house.md). Nothing else.
|
||||
===================================================================== */
|
||||
|
||||
:root {
|
||||
/* ---- Neutrals ------------------------------------------------------- */
|
||||
--bg: #f7f7f8;
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f0f1f3; /* wells, hover, segmented track, gutters */
|
||||
--border: #dfe1e5;
|
||||
--border-strong: #c9ccd2;
|
||||
--fg: #1c1e21;
|
||||
--fg-muted: #646a73;
|
||||
--fg-subtle: #8a8f98;
|
||||
|
||||
/* ---- Accent (the one per-project knob) ------------------------------ */
|
||||
--accent: #3b6ef5;
|
||||
--accent-hover: #2f62e6;
|
||||
--accent-fg: #ffffff; /* text on --accent */
|
||||
--accent-soft: #e6edfe; /* active nav, chips, icon tiles */
|
||||
--accent-text: #2f5fe0; /* accent-colored text and links on --bg/--surface */
|
||||
--sel: #dce6ff; /* selected rows */
|
||||
--ring: var(--accent);
|
||||
|
||||
/* ---- Semantic -------------------------------------------------------- */
|
||||
--ok: #1f8a4c; --ok-soft: #e3f4ea;
|
||||
--warn: #a35f00; --warn-soft: #fdf0dc;
|
||||
--danger: #c93a3a; --danger-soft: #fbe6e6;
|
||||
--info: #1b5fd1; --info-soft: #e4ecfb;
|
||||
--on-danger: #ffffff;
|
||||
|
||||
/* ---- Code and syntax ------------------------------------------------- */
|
||||
--code-bg: #f3f4f6;
|
||||
--tok-key: #8a3ab9;
|
||||
--tok-string: #0b7a3e;
|
||||
--tok-number: #1b5fd1;
|
||||
--tok-bool: #b5560b;
|
||||
--tok-null: #8a8f98;
|
||||
|
||||
/* ---- Type ------------------------------------------------------------ */
|
||||
--font-body: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--font-display: var(--font-body);
|
||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
|
||||
|
||||
--text-2xs: 11px; /* nav headings, badges, chips */
|
||||
--text-xs: 12px; /* status bar, hints, small buttons */
|
||||
--text-sm: 13px; /* buttons, menus, toasts, mono */
|
||||
--text-base: 14px; /* body */
|
||||
--text-md: 15px; /* brand, prose */
|
||||
--text-lg: 17px; /* modal and section titles */
|
||||
--text-xl: 20px; /* page h2 */
|
||||
--text-2xl: 26px; /* page h1 */
|
||||
--leading: 1.5;
|
||||
--leading-prose: 1.65;
|
||||
--tracking-label: 0.06em;
|
||||
--weight-medium: 500;
|
||||
--weight-semibold: 600;
|
||||
--weight-brand: 650;
|
||||
|
||||
/* ---- Space (4px base) ----------------------------------------------- */
|
||||
--space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px;
|
||||
--space-5: 20px; --space-6: 24px; --space-8: 32px; --space-10: 40px;
|
||||
--space-12: 48px;
|
||||
|
||||
/* ---- Shape, size, elevation ---------------------------------------- */
|
||||
--radius-sm: 4px; /* chips, mini buttons */
|
||||
--radius-control: 6px; /* buttons, selects, nav */
|
||||
--radius-md: 8px; /* inputs, menus, toasts */
|
||||
--radius-card: 10px; /* cards */
|
||||
--radius-lg: 12px; /* modals */
|
||||
--radius-full: 999px;
|
||||
|
||||
--control-h: 30px;
|
||||
--control-h-sm: 26px;
|
||||
--topbar: 48px;
|
||||
--sidebar: 216px;
|
||||
--content-max: 960px;
|
||||
--prose-max: 820px;
|
||||
|
||||
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.12);
|
||||
--shadow-popover: 0 6px 24px rgba(15, 20, 30, 0.12);
|
||||
--shadow-modal: 0 6px 24px rgba(15, 20, 30, 0.12);
|
||||
--backdrop: rgba(0, 0, 0, 0.45);
|
||||
--scrim: rgba(0, 0, 0, 0.35);
|
||||
|
||||
/* ---- Motion and layers ---------------------------------------------- */
|
||||
--ease-out: cubic-bezier(0.2, 0.7, 0.2, 1);
|
||||
--dur-fast: 120ms;
|
||||
--dur-base: 180ms;
|
||||
--dur-slow: 300ms;
|
||||
--z-sticky: 10; --z-scrim: 20; --z-drawer: 30; --z-dropdown: 40; --z-toast: 50;
|
||||
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* Dark: same tokens, redesigned values. Two blocks so the explicit
|
||||
data-theme toggle wins over the OS setting in both directions. */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme='light']) {
|
||||
--bg: #131417;
|
||||
--surface: #1b1d21;
|
||||
--surface-2: #24272c;
|
||||
--border: #33373e;
|
||||
--border-strong: #464b53;
|
||||
--fg: #e6e7e9;
|
||||
--fg-muted: #9aa0a9;
|
||||
--fg-subtle: #7d838c;
|
||||
--accent: #6b93ff;
|
||||
--accent-hover: #82a4ff;
|
||||
--accent-fg: #0d1220;
|
||||
--accent-soft: #232f4d;
|
||||
--accent-text: #7fa2ff;
|
||||
--sel: #2a3a63;
|
||||
--ok: #5fd08f; --ok-soft: #1c3527;
|
||||
--warn: #f0b45a; --warn-soft: #3a2e1a;
|
||||
--danger: #ff7b7b; --danger-soft: #3d2224;
|
||||
--info: #82aaff; --info-soft: #222f4a;
|
||||
--on-danger: #1b0d0d;
|
||||
--code-bg: #24272c;
|
||||
--tok-key: #d39cf5;
|
||||
--tok-string: #8bd49c;
|
||||
--tok-number: #82aaff;
|
||||
--tok-bool: #f4a85e;
|
||||
--tok-null: #8a8f98;
|
||||
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-popover: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||
--shadow-modal: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
:root[data-theme='dark'] {
|
||||
--bg: #131417;
|
||||
--surface: #1b1d21;
|
||||
--surface-2: #24272c;
|
||||
--border: #33373e;
|
||||
--border-strong: #464b53;
|
||||
--fg: #e6e7e9;
|
||||
--fg-muted: #9aa0a9;
|
||||
--fg-subtle: #7d838c;
|
||||
--accent: #6b93ff;
|
||||
--accent-hover: #82a4ff;
|
||||
--accent-fg: #0d1220;
|
||||
--accent-soft: #232f4d;
|
||||
--accent-text: #7fa2ff;
|
||||
--sel: #2a3a63;
|
||||
--ok: #5fd08f; --ok-soft: #1c3527;
|
||||
--warn: #f0b45a; --warn-soft: #3a2e1a;
|
||||
--danger: #ff7b7b; --danger-soft: #3d2224;
|
||||
--info: #82aaff; --info-soft: #222f4a;
|
||||
--on-danger: #1b0d0d;
|
||||
--code-bg: #24272c;
|
||||
--tok-key: #d39cf5;
|
||||
--tok-string: #8bd49c;
|
||||
--tok-number: #82aaff;
|
||||
--tok-bool: #f4a85e;
|
||||
--tok-null: #8a8f98;
|
||||
--shadow-raised: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-popover: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||
--shadow-modal: 0 6px 24px rgba(0, 0, 0, 0.45);
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* ---------- base ---------- */
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html, body { height: 100%; margin: 0; }
|
||||
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
|
||||
body { background: var(--bg); color: var(--fg); font: var(--text-base)/var(--leading) var(--font-body); -webkit-font-smoothing: antialiased; }
|
||||
h1, h2, h3, h4 { font-family: var(--font-display); text-wrap: balance; }
|
||||
a { color: var(--accent-text); }
|
||||
button, input, select, textarea { font: inherit; color: inherit; }
|
||||
img, svg, video, canvas { max-width: 100%; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: var(--sel); }
|
||||
:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; }
|
||||
textarea { tab-size: 4; }
|
||||
|
||||
.mono { font-family: var(--font-mono); font-size: var(--text-sm); }
|
||||
.muted { color: var(--fg-muted); }
|
||||
.small { font-size: var(--text-xs); }
|
||||
.strong { font-weight: var(--weight-semibold); }
|
||||
.nowrap { white-space: nowrap; }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.spacer { flex: 1; }
|
||||
.error-text { color: var(--danger); }
|
||||
.ok-text { color: var(--ok); }
|
||||
.label, .section-title { font-size: var(--text-xs); font-weight: var(--weight-semibold); letter-spacing: var(--tracking-label); text-transform: uppercase; color: var(--fg-muted); }
|
||||
.section-title { margin: var(--space-4) 0 6px; }
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: var(--sidebar) minmax(0, 1fr);
|
||||
grid-template-rows: var(--topbar) minmax(0, 1fr);
|
||||
grid-template-areas: 'top top' 'side main';
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
}
|
||||
.shell.bare { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; }
|
||||
.shell.bare .sidebar, .shell.bare .menu-btn, .shell.bare .scrim { display: none !important; }
|
||||
|
||||
.topbar { grid-area: top; display: flex; align-items: center; gap: 10px; padding: 0 var(--space-3); background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||
.brand { display: flex; align-items: center; gap: var(--space-2); color: var(--fg); text-decoration: none; font-weight: var(--weight-brand); font-size: var(--text-md); white-space: nowrap; }
|
||||
.brand-mark { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 7px; background: var(--accent); color: var(--accent-fg); font-size: var(--text-base); }
|
||||
.topbar-title { color: var(--fg-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
|
||||
.topbar-title:not(:empty)::before { content: '/'; margin-right: 10px; opacity: 0.5; }
|
||||
.icon-btn { display: inline-grid; place-items: center; width: 34px; height: 34px; border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--fg); cursor: pointer; font-size: 16px; }
|
||||
.icon-btn:hover { background: var(--surface-2); }
|
||||
.menu-btn { display: none; position: relative; }
|
||||
.menu-btn.has-badge::after { content: ''; position: absolute; top: 6px; right: 6px; width: 8px; height: 8px; border-radius: 50%; background: var(--danger); }
|
||||
|
||||
.sidebar { grid-area: side; overflow-y: auto; padding: var(--space-3) 10px; background: var(--surface); border-right: 1px solid var(--border); }
|
||||
.nav-filter { width: 100%; padding: 7px 10px; margin-bottom: 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--bg); }
|
||||
.nav-group { margin-top: 14px; }
|
||||
.nav-heading { padding: 0 var(--space-2) var(--space-1); font-size: var(--text-2xs); font-weight: var(--weight-semibold); letter-spacing: var(--tracking-label); text-transform: uppercase; color: var(--fg-muted); }
|
||||
.nav-item { display: flex; align-items: center; gap: 10px; padding: 6px var(--space-2); border-radius: var(--radius-control); color: var(--fg); text-decoration: none; }
|
||||
.nav-item:hover { background: var(--surface-2); }
|
||||
.nav-item.active { background: var(--accent-soft); color: var(--accent-text); font-weight: var(--weight-semibold); }
|
||||
.nav-icon { display: inline-grid; place-items: center; min-width: 26px; height: 22px; padding: 0 3px; border-radius: 5px; background: var(--surface-2); font: var(--weight-semibold) var(--text-2xs) var(--font-mono); color: var(--fg-muted); }
|
||||
.nav-item.active .nav-icon { background: var(--accent); color: var(--accent-fg); }
|
||||
.nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.scrim { display: none; }
|
||||
|
||||
.view { grid-area: main; min-width: 0; min-height: 0; overflow: auto; }
|
||||
.loading, .empty { padding: var(--space-12) var(--space-6); text-align: center; color: var(--fg-muted); }
|
||||
.empty .btn { margin-top: var(--space-2); }
|
||||
|
||||
/* ---------- pages (home, settings, anything that scrolls as a document) ---------- */
|
||||
.page { max-width: var(--content-max); margin: 0 auto; padding: var(--space-8) var(--space-6) var(--space-12); }
|
||||
.page h1 { margin: 0 0 var(--space-1); font-size: var(--text-2xl); }
|
||||
.page h2 { margin: var(--space-8) 0 var(--space-2); font-size: var(--text-xl); }
|
||||
.page-filter { width: 100%; max-width: 380px; margin: 18px 0 var(--space-5); padding: 9px var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||
.page > p + .card-grid, .page > h1 + .card-grid { margin-top: var(--space-5); }
|
||||
.card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-3); }
|
||||
.card-link { display: flex; gap: 14px; padding: var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-card); background: var(--surface); color: var(--fg); text-decoration: none; transition: border-color var(--dur-fast), transform var(--dur-fast); }
|
||||
.card-link:hover { border-color: var(--accent); transform: translateY(-1px); }
|
||||
.card-link-icon { flex: none; display: grid; place-items: center; width: 42px; height: 42px; border-radius: 9px; background: var(--accent-soft); color: var(--accent-text); font: 700 var(--text-base) var(--font-mono); }
|
||||
.card-link-name { font-weight: var(--weight-semibold); margin-bottom: 2px; }
|
||||
.card-link-desc { color: var(--fg-muted); font-size: var(--text-sm); }
|
||||
.card { padding: var(--space-4); border: 1px solid var(--border); border-radius: var(--radius-card); background: var(--surface); }
|
||||
|
||||
/* ---------- screen chrome: toolbar / pane / statusbar ---------- */
|
||||
.screen { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: var(--space-2) var(--space-3); background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||
.divider { width: 1px; height: 22px; margin: 0 var(--space-1); background: var(--border); }
|
||||
.pane { min-width: 0; min-height: 0; overflow: auto; background: var(--surface); }
|
||||
.pane-body { flex: 1; min-height: 0; overflow: auto; padding: var(--space-4); display: flex; flex-direction: column; gap: var(--space-2); }
|
||||
.statusbar { display: flex; align-items: center; gap: var(--space-1); padding: 5px var(--space-3); border-top: 1px solid var(--border); background: var(--surface); font-size: var(--text-xs); min-height: 28px; }
|
||||
.statusbar.ok { color: var(--ok); }
|
||||
.statusbar.error { color: var(--danger); }
|
||||
|
||||
/* Two panes side by side; data-mode='a' or 'b' shows one. */
|
||||
.split { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--border); }
|
||||
.split[data-mode='a'], .split[data-mode='b'] { grid-template-columns: 1fr; }
|
||||
.split[data-mode='a'] > :nth-child(2), .split[data-mode='b'] > :nth-child(1) { display: none; }
|
||||
|
||||
/* ---------- controls ---------- */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; gap: 6px; height: var(--control-h); padding: 0 11px;
|
||||
border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); color: var(--fg);
|
||||
cursor: pointer; text-decoration: none; font-size: var(--text-sm); white-space: nowrap;
|
||||
}
|
||||
.btn:hover { background: var(--surface-2); }
|
||||
.btn:disabled { opacity: 0.6; cursor: default; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); font-weight: var(--weight-semibold); }
|
||||
.btn.primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
|
||||
.btn.danger { color: var(--danger); }
|
||||
.btn.small { height: var(--control-h-sm); padding: 0 var(--space-2); font-size: var(--text-xs); }
|
||||
.select { height: var(--control-h); padding: 0 6px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); font-size: var(--text-sm); }
|
||||
.input, .textarea { width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); outline: none; }
|
||||
.input:focus, .textarea:focus { border-color: var(--accent); }
|
||||
.input[aria-invalid='true'], .textarea[aria-invalid='true'] { border-color: var(--danger); }
|
||||
.textarea { padding: var(--space-3) 14px; line-height: var(--leading); resize: vertical; }
|
||||
.textarea.code { font-family: var(--font-mono); font-size: var(--text-sm); white-space: pre; overflow: auto; }
|
||||
.field { display: grid; gap: var(--space-1); }
|
||||
.field > label { font-size: var(--text-sm); font-weight: var(--weight-medium); }
|
||||
.field > .hint { font-size: var(--text-xs); color: var(--fg-muted); }
|
||||
.field > .error { font-size: var(--text-xs); color: var(--danger); }
|
||||
.check { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-sm); white-space: nowrap; cursor: pointer; }
|
||||
.segmented { display: inline-flex; padding: 2px; border-radius: 7px; background: var(--surface-2); }
|
||||
.segmented button { height: var(--control-h-sm); padding: 0 var(--space-3); border: 0; border-radius: 5px; background: transparent; color: var(--fg-muted); cursor: pointer; font-size: var(--text-sm); }
|
||||
.segmented button[aria-checked='true'] { background: var(--surface); color: var(--fg); font-weight: var(--weight-semibold); box-shadow: var(--shadow-raised); }
|
||||
.linklike { padding: 0; border: 0; background: none; color: inherit; font-weight: var(--weight-semibold); text-decoration: underline; cursor: pointer; }
|
||||
.mini { width: 22px; height: 20px; padding: 0; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); color: var(--fg-muted); cursor: pointer; line-height: 1; }
|
||||
.mini:hover { color: var(--fg); }
|
||||
|
||||
/* ---------- lists and tables ---------- */
|
||||
.list-item { display: flex; align-items: center; gap: var(--space-3); padding: 6px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); }
|
||||
.list-item + .list-item { margin-top: 6px; }
|
||||
.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||
.table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
|
||||
.table th { position: sticky; top: 0; padding: 6px var(--space-3); background: var(--surface-2); border-bottom: 1px solid var(--border); color: var(--fg-muted); font-weight: var(--weight-semibold); text-align: left; white-space: nowrap; }
|
||||
.table td { padding: 6px var(--space-3); border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
.table tr:last-child td { border-bottom: 0; }
|
||||
.table tbody tr:hover { background: var(--surface-2); }
|
||||
.table tr.selected { background: var(--sel); }
|
||||
.table .num { text-align: right; }
|
||||
|
||||
/* ---------- badges, chips ---------- */
|
||||
.badge { min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: var(--danger); color: var(--on-danger); font: var(--weight-semibold) var(--text-2xs)/20px var(--font-body); text-align: center; }
|
||||
.chip { display: inline-block; padding: 1px 7px; border-radius: 9px; background: var(--surface-2); color: var(--fg-muted); font-size: var(--text-2xs); font-weight: var(--weight-semibold); }
|
||||
.chip.new, .chip.accent { background: var(--accent-soft); color: var(--accent-text); }
|
||||
.chip.ok { background: var(--ok-soft); color: var(--ok); }
|
||||
.chip.warn { background: var(--warn-soft); color: var(--warn); }
|
||||
.chip.danger { background: var(--danger-soft); color: var(--danger); }
|
||||
|
||||
/* ---------- toasts ---------- */
|
||||
.toasts { position: fixed; right: var(--space-4); bottom: var(--space-4); z-index: var(--z-toast); display: flex; flex-direction: column; gap: var(--space-2); align-items: flex-end; pointer-events: none; }
|
||||
.toast { max-width: min(420px, calc(100vw - 32px)); padding: 9px 14px; border-radius: var(--radius-md); background: var(--fg); color: var(--bg); box-shadow: var(--shadow-popover); font-size: var(--text-sm); animation: toast-in 0.15s ease-out; transition: opacity var(--dur-slow), transform var(--dur-slow); }
|
||||
.toast.error { background: var(--danger); color: var(--on-danger); }
|
||||
.toast.out { opacity: 0; transform: translateY(6px); }
|
||||
@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } }
|
||||
|
||||
/* ---------- dropdown menu ---------- */
|
||||
.dropdown { position: relative; display: inline-flex; }
|
||||
.caret { font-size: 10px; opacity: 0.7; }
|
||||
.menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: var(--z-dropdown); min-width: 200px; padding: var(--space-1); border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); box-shadow: var(--shadow-popover); }
|
||||
.menu-item { display: flex; align-items: center; gap: 10px; width: 100%; padding: 7px var(--space-2); border: 0; border-radius: 5px; background: none; color: var(--fg); text-align: left; cursor: pointer; font-size: var(--text-sm); }
|
||||
.menu-item:hover, .menu-item:focus-visible { background: var(--surface-2); outline: none; }
|
||||
|
||||
/* ---------- modal ---------- */
|
||||
.modal { width: min(560px, calc(100vw - 32px)); max-height: calc(100dvh - 48px); padding: 0; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--surface); color: var(--fg); box-shadow: var(--shadow-modal); }
|
||||
.modal.wide { width: min(980px, calc(100vw - 32px)); }
|
||||
.modal::backdrop { background: var(--backdrop); }
|
||||
.modal[open] { display: flex; flex-direction: column; }
|
||||
.modal-head { display: flex; align-items: center; padding: var(--space-3) var(--space-3) var(--space-3) var(--space-5); border-bottom: 1px solid var(--border); }
|
||||
.modal-head h2 { flex: 1; margin: 0; font-size: var(--text-lg); }
|
||||
.modal-body { overflow: auto; padding: var(--space-4) var(--space-5) var(--space-5); }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: var(--space-2); padding: var(--space-3) var(--space-5); border-top: 1px solid var(--border); }
|
||||
|
||||
/* ---------- prose (rendered Markdown, help text, long-form) ---------- */
|
||||
.prose { font-size: var(--text-md); line-height: var(--leading-prose); overflow-wrap: break-word; }
|
||||
.prose > :first-child { margin-top: 0; }
|
||||
.prose h1, .prose h2, .prose h3, .prose h4 { margin: 1.4em 0 0.5em; line-height: 1.25; }
|
||||
.prose h1 { font-size: 1.9em; padding-bottom: 0.25em; border-bottom: 1px solid var(--border); }
|
||||
.prose h2 { font-size: 1.45em; padding-bottom: 0.2em; border-bottom: 1px solid var(--border); }
|
||||
.prose h3 { font-size: 1.2em; }
|
||||
.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose table { margin: 0 0 1em; }
|
||||
.prose ul, .prose ol { padding-left: 1.6em; }
|
||||
.prose li + li { margin-top: 0.25em; }
|
||||
.prose li > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; }
|
||||
.prose li:has(> input[type='checkbox']) { list-style: none; }
|
||||
.prose code { padding: 0.15em 0.35em; border-radius: var(--radius-sm); background: var(--code-bg); font: 0.88em var(--font-mono); }
|
||||
.prose pre { padding: var(--space-3) 14px; border-radius: var(--radius-md); background: var(--code-bg); overflow: auto; }
|
||||
.prose pre code { padding: 0; background: none; font-size: var(--text-sm); }
|
||||
.prose blockquote { padding: 0 1em; border-left: 3px solid var(--border); color: var(--fg-muted); }
|
||||
.prose table { border-collapse: collapse; display: block; overflow-x: auto; }
|
||||
.prose th, .prose td { padding: 6px var(--space-3); border: 1px solid var(--border); }
|
||||
.prose th { background: var(--surface-2); }
|
||||
.prose img { max-width: 100%; }
|
||||
.prose hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; }
|
||||
|
||||
/* ---------- code view with line numbers ---------- */
|
||||
.code-view { flex: 1; min-height: 0; display: flex; overflow: auto; background: var(--surface); font: var(--text-sm)/20px var(--font-mono); }
|
||||
.code-lines { flex: none; padding: var(--space-3) 10px var(--space-10); background: var(--surface-2); color: var(--fg-muted); text-align: right; white-space: pre; user-select: none; position: sticky; left: 0; }
|
||||
.code-text { flex: 1; margin: 0; padding: var(--space-3) 14px var(--space-10); font: inherit; white-space: pre; }
|
||||
.code-view.wrap .code-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.code-view.wrap .code-lines { display: none; }
|
||||
.t-key { color: var(--tok-key); }
|
||||
.t-string { color: var(--tok-string); }
|
||||
.t-number { color: var(--tok-number); }
|
||||
.t-boolean { color: var(--tok-bool); }
|
||||
.t-null { color: var(--tok-null); }
|
||||
|
||||
/* ---------- narrow screens ---------- */
|
||||
@media (max-width: 800px) {
|
||||
.shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; }
|
||||
.menu-btn { display: inline-grid; }
|
||||
.sidebar { position: fixed; z-index: var(--z-drawer); top: var(--topbar); bottom: 0; left: 0; width: min(280px, 85vw); transform: translateX(-100%); transition: transform var(--dur-base) ease-out; box-shadow: var(--shadow-popover); }
|
||||
.drawer-open .sidebar { transform: none; }
|
||||
.drawer-open .scrim { display: block; position: fixed; inset: var(--topbar) 0 0 0; z-index: var(--z-scrim); background: var(--scrim); }
|
||||
/* one row that scrolls sideways, so the work area keeps the screen */
|
||||
.toolbar { padding: var(--space-2); flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; }
|
||||
.toolbar > * { flex: none; }
|
||||
.toolbar > .spacer { flex: 1 0 8px; }
|
||||
.page { padding: var(--space-5) var(--space-4) var(--space-10); }
|
||||
.split:not([data-mode='a']):not([data-mode='b']) { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; }
|
||||
}
|
||||
1
app/static/favicon.svg
Normal file
1
app/static/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><!-- House favicon: the brand tile. Set fill to the project's --accent. --><rect width="32" height="32" rx="7" fill="#3b6ef5"/><text x="16" y="16" dy="0.35em" text-anchor="middle" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="18" font-weight="700" fill="#fff">◎</text></svg>
|
||||
|
After Width: | Height: | Size: 373 B |
32
app/static/index.html
Normal file
32
app/static/index.html
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<!doctype html>
|
||||
<!-- House shell: see references/house.md ("Starting a project") for the placeholders. -->
|
||||
<html lang="en" data-app="network-monitor">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>network monitor</title>
|
||||
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="/static/css/house.css">
|
||||
<link rel="stylesheet" href="/static/css/app.css">
|
||||
<script type="module" src="/static/js/main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="topbar">
|
||||
<button class="icon-btn menu-btn" id="menu-btn" type="button" aria-label="Menu" aria-expanded="false">☰</button>
|
||||
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true">◎</span> network monitor</a>
|
||||
<span class="topbar-title" id="topbar-title"></span>
|
||||
<span class="spacer"></span>
|
||||
<button class="icon-btn" id="theme-btn" type="button" aria-label="Theme" title="Theme: auto"></button>
|
||||
</header>
|
||||
<nav class="sidebar" id="sidebar" aria-label="Main">
|
||||
<input type="search" id="nav-filter" class="nav-filter" placeholder="Find… /" aria-label="Find a page">
|
||||
<div id="nav-list"></div>
|
||||
</nav>
|
||||
<div class="scrim" id="scrim"></div>
|
||||
<main id="view" class="view"></main>
|
||||
</div>
|
||||
<div class="toasts" id="toasts" aria-live="polite"></div>
|
||||
</body>
|
||||
</html>
|
||||
24
app/static/js/api.js
Normal file
24
app/static/js/api.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
|
||||
export async function request(path, { method = 'GET', body, params } = {}) {
|
||||
const url = new URL(path, location.origin);
|
||||
for (const [k, v] of Object.entries(params || {})) if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, v);
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = res.statusText;
|
||||
try { const j = await res.json(); detail = typeof j.detail === 'string' ? j.detail : JSON.stringify(j.detail ?? j); } catch {}
|
||||
const err = new Error(detail || `HTTP ${res.status}`);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const get = (path, params) => request(path, { params });
|
||||
export const post = (path, body) => request(path, { method: 'POST', body });
|
||||
export const put = (path, body) => request(path, { method: 'PUT', body });
|
||||
export const patch = (path, body) => request(path, { method: 'PATCH', body });
|
||||
export const del = (path, params) => request(path, { method: 'DELETE', params });
|
||||
214
app/static/js/charts.js
Normal file
214
app/static/js/charts.js
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
// Inline SVG / HTML charts on the house tokens: status strips, line charts, stacked bars,
|
||||
// plus one shared tooltip. Labels go in with textContent only.
|
||||
import { el } from './ui.js';
|
||||
|
||||
const NS = 'http://www.w3.org/2000/svg';
|
||||
export function s(tag, attrs = {}, ...kids) {
|
||||
const n = document.createElementNS(NS, tag);
|
||||
for (const [k, v] of Object.entries(attrs)) if (v != null) n.setAttribute(k, v);
|
||||
for (const c of kids.flat()) if (c != null) n.append(c);
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---------- status ----------
|
||||
|
||||
export const STATUS = {
|
||||
ok: { label: 'OK', chip: 'ok' },
|
||||
degraded: { label: 'Degraded', chip: 'warn' },
|
||||
down: { label: 'Down', chip: 'danger' },
|
||||
nodata: { label: 'No data', chip: '' },
|
||||
};
|
||||
|
||||
export function statusChip(st, text) {
|
||||
const x = STATUS[st] || STATUS.nodata;
|
||||
return el(`span.chip${x.chip ? `.${x.chip}` : ''}`, {}, text || x.label);
|
||||
}
|
||||
|
||||
export function statusLegend() {
|
||||
return el('div.viz-legend', { 'aria-label': 'Legend' },
|
||||
...['ok', 'degraded', 'down', 'nodata'].map((k) => el('span.viz-legend-item', {}, el(`span.viz-swatch.s-${k}`), STATUS[k].label)));
|
||||
}
|
||||
|
||||
export function seriesLegend(items, kind = 'line') {
|
||||
return el('div.viz-legend', {},
|
||||
...items.map((it) => el('span.viz-legend-item', {}, el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${it.color}` }), it.name)));
|
||||
}
|
||||
|
||||
// ---------- tooltip ----------
|
||||
|
||||
let tip;
|
||||
export function showTip(x, y, content) {
|
||||
if (!tip) {
|
||||
tip = el('div.viz-tip', { role: 'tooltip', hidden: true });
|
||||
document.body.append(tip);
|
||||
}
|
||||
tip.replaceChildren(...content.filter(Boolean));
|
||||
tip.hidden = false;
|
||||
const r = tip.getBoundingClientRect();
|
||||
let left = x + 14;
|
||||
if (left + r.width > innerWidth - 8) left = x - 14 - r.width;
|
||||
let top = y + 14;
|
||||
if (top + r.height > innerHeight - 8) top = y - 14 - r.height;
|
||||
tip.style.left = `${Math.max(8, left)}px`;
|
||||
tip.style.top = `${Math.max(8, top)}px`;
|
||||
}
|
||||
export function hideTip() { if (tip) tip.hidden = true; }
|
||||
export const tipTitle = (t) => el('div.viz-tip-title', {}, t);
|
||||
export const tipRow = (value, label, color, kind = 'line') =>
|
||||
el('div.viz-tip-row', {}, color ? el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${color}` }) : null,
|
||||
el('strong', {}, value), label ? el('span.muted', {}, label) : null);
|
||||
|
||||
function hover(target, describe) {
|
||||
target.addEventListener('pointermove', (e) => { const c = describe(e); if (c) showTip(e.clientX, e.clientY, c); else hideTip(); });
|
||||
target.addEventListener('pointerleave', hideTip);
|
||||
}
|
||||
|
||||
// ---------- status strip: one cell per time bucket ----------
|
||||
|
||||
/** buckets: [{s, n, down, slow, latency} | null]; describe(i, bucket) -> tooltip nodes */
|
||||
export function strip(buckets, describe) {
|
||||
const n = buckets.length;
|
||||
const wrap = el('div.strip', { style: `--n:${n}` });
|
||||
for (const b of buckets) wrap.append(el(`span.s-${b ? b.s : 'nodata'}`));
|
||||
hover(wrap, (e) => {
|
||||
const r = wrap.getBoundingClientRect();
|
||||
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||
return describe(i, buckets[i]);
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// ---------- responsive SVG helper ----------
|
||||
|
||||
function responsive(draw, height) {
|
||||
const box = el('div.chart', { style: `height:${height}px` });
|
||||
let last = 0;
|
||||
const ro = new ResizeObserver(() => {
|
||||
const w = Math.floor(box.clientWidth);
|
||||
if (w && w !== last) { last = w; box.replaceChildren(draw(w)); }
|
||||
});
|
||||
ro.observe(box);
|
||||
return box;
|
||||
}
|
||||
|
||||
function niceMax(v) {
|
||||
if (!(v > 0)) return 1;
|
||||
const p = 10 ** Math.floor(Math.log10(v));
|
||||
for (const m of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (v <= m * p) return m * p;
|
||||
return 10 * p;
|
||||
}
|
||||
|
||||
// ---------- line chart ----------
|
||||
|
||||
/**
|
||||
* lineChart({ n, xLabel(i), series: [{name, color, values}], marks: [count per bucket],
|
||||
* fmt(v), height, describe(i) -> extra tooltip nodes })
|
||||
* Gaps (null) break the line. `marks` draws failure ticks along the baseline.
|
||||
*/
|
||||
export function lineChart(o) {
|
||||
const H = o.height || 150;
|
||||
return responsive((W) => {
|
||||
const padL = 48, padR = o.series.length > 1 ? 64 : 14, padT = 10, padB = 24;
|
||||
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||
const n = o.n;
|
||||
const all = o.series.flatMap((x) => x.values).filter((v) => v != null);
|
||||
const max = niceMax(Math.max(0, ...all));
|
||||
const x = (i) => padL + ((i + 0.5) / n) * iw;
|
||||
const y = (v) => padT + ih - (v / max) * ih;
|
||||
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||
|
||||
for (const t of [0, max / 2, max]) {
|
||||
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, o.fmt(t)));
|
||||
}
|
||||
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||
g.append(s('text', { x: x(i), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||
}
|
||||
(o.marks || []).forEach((m, i) => {
|
||||
if (m) g.append(s('rect', { x: x(i) - 1.5, y: padT + ih - 7, width: 3, height: 7, rx: 1, class: 'viz-fail' }));
|
||||
});
|
||||
|
||||
const labels = [];
|
||||
for (const ser of o.series) {
|
||||
let d = '';
|
||||
ser.values.forEach((v, i) => {
|
||||
if (v == null) return;
|
||||
const prev = ser.values[i - 1];
|
||||
d += `${prev == null ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`;
|
||||
const next = ser.values[i + 1];
|
||||
if (prev == null && next == null) g.append(s('circle', { cx: x(i), cy: y(v), r: 2.5, fill: ser.color }));
|
||||
});
|
||||
if (d) g.append(s('path', { d, fill: 'none', stroke: ser.color, 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }));
|
||||
const li = ser.values.findLastIndex((v) => v != null);
|
||||
if (o.series.length > 1 && li >= 0) labels.push({ y: y(ser.values[li]), text: ser.name, x: x(li) });
|
||||
}
|
||||
// Direct end labels; skip any that would collide (the legend still names it).
|
||||
labels.sort((a, b) => a.y - b.y);
|
||||
let lastY = -99;
|
||||
for (const l of labels) {
|
||||
if (l.y - lastY < 13) continue;
|
||||
lastY = l.y;
|
||||
g.append(s('text', { x: padL + iw + 6, y: l.y, dy: '0.32em', class: 'viz-label' }, l.text));
|
||||
}
|
||||
|
||||
const cross = s('line', { y1: padT, y2: padT + ih, class: 'viz-cross', visibility: 'hidden' });
|
||||
const hit = s('rect', { x: padL, y: 0, width: iw, height: H, fill: 'transparent' });
|
||||
g.append(cross, hit);
|
||||
hit.addEventListener('pointermove', (e) => {
|
||||
const r = hit.getBoundingClientRect();
|
||||
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||
cross.setAttribute('x1', x(i)); cross.setAttribute('x2', x(i)); cross.setAttribute('visibility', 'visible');
|
||||
showTip(e.clientX, e.clientY, [tipTitle(o.xLabel(i, true)),
|
||||
...o.series.map((ser) => tipRow(ser.values[i] == null ? 'no data' : o.fmt(ser.values[i]), o.series.length > 1 ? ser.name : '', ser.color)),
|
||||
...(o.describe ? o.describe(i) : [])]);
|
||||
});
|
||||
hit.addEventListener('pointerleave', () => { cross.setAttribute('visibility', 'hidden'); hideTip(); });
|
||||
return g;
|
||||
}, H);
|
||||
}
|
||||
|
||||
// ---------- stacked bars ----------
|
||||
|
||||
function topRounded(x, y, w, h, r) {
|
||||
r = Math.min(r, h, w / 2);
|
||||
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;
|
||||
}
|
||||
|
||||
/** stackedBars({ n, xLabel(i), series: [{name, color, values}], height }) – bottom series first. */
|
||||
export function stackedBars(o) {
|
||||
const H = o.height || 150;
|
||||
return responsive((W) => {
|
||||
const padL = 40, padR = 10, padT = 10, padB = 24;
|
||||
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||
const n = o.n;
|
||||
const totals = Array.from({ length: n }, (_, i) => o.series.reduce((a, ser) => a + (ser.values[i] || 0), 0));
|
||||
const max = niceMax(Math.max(1, ...totals));
|
||||
const slot = iw / n, bw = Math.min(24, slot * 0.7);
|
||||
const y = (v) => padT + ih - (v / max) * ih;
|
||||
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||
for (const t of [0, max / 2, max]) {
|
||||
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, Math.round(t).toLocaleString()));
|
||||
}
|
||||
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||
g.append(s('text', { x: padL + slot * (i + 0.5), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||
}
|
||||
for (let i = 0; i < n; i++) {
|
||||
const bx = padL + slot * i + (slot - bw) / 2;
|
||||
let acc = 0;
|
||||
const segs = o.series.map((ser) => ({ ser, v: ser.values[i] || 0 })).filter((x) => x.v > 0);
|
||||
segs.forEach((seg, k) => {
|
||||
const y0 = y(acc), y1 = y(acc + seg.v);
|
||||
const gap = k > 0 ? 2 : 0;
|
||||
const h = Math.max(0, y0 - y1 - gap);
|
||||
const top = k === segs.length - 1;
|
||||
g.append(top ? s('path', { d: topRounded(bx, y1, bw, h, 4), fill: seg.ser.color }) : s('rect', { x: bx, y: y1, width: bw, height: h, fill: seg.ser.color }));
|
||||
acc += seg.v;
|
||||
});
|
||||
const hit = s('rect', { x: padL + slot * i, y: padT, width: slot, height: ih, fill: 'transparent', class: 'viz-hit' });
|
||||
hover(hit, () => [tipTitle(o.xLabel(i, true)), ...o.series.map((ser) => tipRow((ser.values[i] || 0).toLocaleString(), ser.name, ser.color, 'box'))]);
|
||||
g.append(hit);
|
||||
}
|
||||
return g;
|
||||
}, H);
|
||||
}
|
||||
75
app/static/js/common.js
Normal file
75
app/static/js/common.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// Shared bits for the views.
|
||||
import { el } from './ui.js';
|
||||
|
||||
/** The screen frame: toolbar, scrolling pane, status bar. Returns the parts. */
|
||||
export function screen(root, toolbarItems) {
|
||||
const toolbar = el('div.toolbar', {}, ...toolbarItems);
|
||||
const body = el('div.content');
|
||||
const pane = el('div.pane.fill', {}, body);
|
||||
const status = el('div.statusbar', {}, 'Loading…');
|
||||
root.append(el('div.screen', {}, toolbar, pane, status));
|
||||
return {
|
||||
toolbar, body, pane, status,
|
||||
setStatus(text, kind = '') { status.textContent = text; status.className = `statusbar${kind ? ` ${kind}` : ''}`; },
|
||||
};
|
||||
}
|
||||
|
||||
/** replaceChildren without the "null" text nodes the DOM makes from empty slots. */
|
||||
export function fill(node, ...children) {
|
||||
node.replaceChildren(...children.flat().filter((c) => c != null && c !== false));
|
||||
return node;
|
||||
}
|
||||
|
||||
export const section = (title, hint, ...extra) =>
|
||||
el('div.section-head', {}, el('h2.section-title', {}, title), hint ? el('span.hint', {}, hint) : null, ...extra);
|
||||
|
||||
export function table(headers, rows, { empty = 'Nothing to show.' } = {}) {
|
||||
if (!rows.length) return el('div.callout', {}, empty);
|
||||
return el('div.table-wrap', {},
|
||||
el('table.table', {},
|
||||
el('thead', {}, el('tr', {}, ...headers.map((h) => (typeof h === 'string' ? el('th', {}, h) : el('th', h.props || {}, h.text))))),
|
||||
el('tbody', {}, ...rows)));
|
||||
}
|
||||
|
||||
export function errorBox(err, hint) {
|
||||
return el('div.callout.error', { role: 'alert' }, err.message || String(err), hint ? el('div.small.muted', {}, hint) : null);
|
||||
}
|
||||
|
||||
/** A notice for AdGuard-backed views when it isn't set up or reachable. */
|
||||
export function adguardProblem(err) {
|
||||
if (err.status === 503) {
|
||||
return el('div.empty', {},
|
||||
el('p', {}, 'AdGuard Home isn’t connected yet.'),
|
||||
el('p.small', {}, 'Set ADGUARD_URL, ADGUARD_USERNAME and ADGUARD_PASSWORD in the hub’s .env, then restart the hub. Settings shows where that file is.'),
|
||||
el('a.btn', { href: '/settings' }, 'Open settings'));
|
||||
}
|
||||
return errorBox(err, err.status === 502 ? 'Check that AdGuard Home is running and the hub’s .env points at its web address.' : '');
|
||||
}
|
||||
|
||||
export const domainLink = (d) => el('a.domain', { href: `/domains/${encodeURIComponent(d)}` }, d);
|
||||
|
||||
export function clientLink(ip, device, fallbackName) {
|
||||
const name = device?.name || fallbackName || ip;
|
||||
const href = device ? `/clients/${encodeURIComponent(device.key)}` : `/queries?ip=${encodeURIComponent(ip)}`;
|
||||
return el('span.chips', {},
|
||||
el('a', { href, title: ip }, name),
|
||||
name !== ip ? el('span.muted.small', {}, ip) : null,
|
||||
device?.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null);
|
||||
}
|
||||
|
||||
export function resultChip(r) {
|
||||
if (r.blocked) return el('span.chip.danger', { title: r.rule || r.reason }, 'Blocked');
|
||||
if (r.reason?.startsWith('Rewrite') || r.reason === 'FilteredSafeSearch') return el('span.chip.accent', { title: r.reason }, 'Rewritten');
|
||||
if (r.reason === 'NotFilteredWhiteList') return el('span.chip.ok', { title: r.rule }, 'Allowed by rule');
|
||||
if (r.status && r.status !== 'NOERROR') return el('span.chip.warn', {}, r.status);
|
||||
return el('span.chip', {}, 'OK');
|
||||
}
|
||||
|
||||
export const RANGES = [['1h', '1 h'], ['6h', '6 h'], ['24h', '24 h'], ['7d', '7 d'], ['30d', '30 d']];
|
||||
export const SPANS = { '1h': 3600, '6h': 21600, '24h': 86400, '7d': 604800, '30d': 2592000 };
|
||||
|
||||
/** Re-run fn every `ms` while the tab is visible; returns a stop function. */
|
||||
export function every(ms, fn) {
|
||||
const t = setInterval(() => { if (!document.hidden) fn(); }, ms);
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
32
app/static/js/fmt.js
Normal file
32
app/static/js/fmt.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// Formatting for times, durations and measurements.
|
||||
export const dash = '—';
|
||||
|
||||
export function ago(ts) {
|
||||
if (!ts) return dash;
|
||||
const s = Date.now() / 1000 - ts;
|
||||
if (s < 45) return 'just now';
|
||||
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
||||
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
|
||||
return `${Math.round(s / 86400)} d ago`;
|
||||
}
|
||||
|
||||
export const clock = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
export const hm = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
export const when = (ts) => (ts ? new Date(ts * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : dash);
|
||||
export const day = (ts) => new Date(ts * 1000).toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
|
||||
export function dur(s) {
|
||||
if (s == null) return dash;
|
||||
if (s < 60) return `${Math.round(s)} s`;
|
||||
if (s < 3600) return `${Math.round(s / 60)} min`;
|
||||
if (s < 86400) return `${(s / 3600).toFixed(1)} h`;
|
||||
return `${(s / 86400).toFixed(1)} d`;
|
||||
}
|
||||
|
||||
export const ms = (v) => (v == null ? dash : v < 10 ? `${v.toFixed(1)} ms` : `${Math.round(v).toLocaleString()} ms`);
|
||||
export const pct = (v, digits = 0) => (v == null ? dash : `${(v * 100).toFixed(digits)}%`);
|
||||
export const num = (n) => (n == null ? dash : Number(n).toLocaleString());
|
||||
export const mbps = (v) => (v == null ? dash : `${v < 10 ? v.toFixed(1) : Math.round(v)} Mbps`);
|
||||
|
||||
/** A time label fitting the span: clock for short ranges, date + hour for long ones. */
|
||||
export const axisTime = (span) => (ts) => (span > 2 * 86400 ? `${day(ts)} ${hm(ts)}` : hm(ts));
|
||||
38
app/static/js/main.js
Normal file
38
app/static/js/main.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Plain ES modules, no bundler.
|
||||
import { startShell } from './shell.js';
|
||||
import { get } from './api.js';
|
||||
|
||||
let offline = 0;
|
||||
|
||||
startShell({
|
||||
name: 'network monitor',
|
||||
categories: ['Network', 'DNS', 'Hub'],
|
||||
views: [
|
||||
{ id: 'health', name: 'Network health', path: '/', category: 'Network', icon: '◎',
|
||||
description: 'Mesh and internet health as the probes see it: now, over time, and every outage.', load: () => import('./views/health.js') },
|
||||
{ id: 'probes', name: 'Probes', path: '/probes', category: 'Network', icon: 'P',
|
||||
description: 'Add, place and remove the machines that test the network.', load: () => import('./views/probes.js'),
|
||||
badge: () => offline },
|
||||
{ id: 'clients', name: 'Clients', path: '/clients', category: 'DNS', icon: '▣',
|
||||
description: 'Every device seen on the network, with your names, categories and flags.', load: () => import('./views/clients.js') },
|
||||
{ id: 'queries', name: 'Query log', path: '/queries', category: 'DNS', icon: 'Q?',
|
||||
description: 'Sift through DNS requests from AdGuard Home.', load: () => import('./views/queries.js') },
|
||||
{ id: 'domains', name: 'Domains', path: '/domains', category: 'DNS', icon: '.com',
|
||||
description: 'Most requested domains, and who asks for each one.', load: () => import('./views/domains.js') },
|
||||
{ id: 'blocked', name: 'Blocked domains', path: '/blocked', category: 'DNS', icon: '⊘',
|
||||
description: 'What AdGuard Home blocked, how often, and for whom.', load: () => import('./views/blocked.js') },
|
||||
{ id: 'settings', name: 'Settings', path: '/settings', category: 'Hub', icon: '⚙',
|
||||
description: 'What the hub tests, its thresholds and its AdGuard connection.', load: () => import('./views/settings.js') },
|
||||
],
|
||||
});
|
||||
|
||||
// Offline probes show as a count on the Probes nav item.
|
||||
async function pollProbes() {
|
||||
try {
|
||||
const { probes } = await get('/api/probes');
|
||||
offline = probes.filter((p) => !p.online).length;
|
||||
window.dispatchEvent(new Event('app:badges'));
|
||||
} catch {}
|
||||
}
|
||||
pollProbes();
|
||||
setInterval(pollProbes, 60000);
|
||||
278
app/static/js/shell.js
Normal file
278
app/static/js/shell.js
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
// House app shell: top bar, sidebar nav (a drawer on phones), theme toggle,
|
||||
// "/" to find a view, client-side routing and a home grid, all built from one
|
||||
// list of views. Copy into the project (e.g. static/js/shell.js) unchanged and
|
||||
// call startShell() from the project's own main.js. Expects the markup in
|
||||
// index.html (ids: view, nav-list, nav-filter, topbar-title, theme-btn,
|
||||
// menu-btn, scrim, sidebar).
|
||||
//
|
||||
// A view: {
|
||||
// id, name, path, // path '/x' owns /x and everything under /x/
|
||||
// category, icon, // sidebar group; 1-3 character monogram ('{ }', 'M↓', '⎘')
|
||||
// description, // home card text and nav search
|
||||
// load: () => import('./views/x.js'), // module exports mount(root, ctx)
|
||||
// badge?: () => number, // count on the nav item; dispatch 'app:badges' on window when it changes
|
||||
// }
|
||||
// mount(root, ctx) may return a cleanup function. ctx = {
|
||||
// rest, // path after the view's own, e.g. "abc123" for /paste/abc123
|
||||
// query, // URLSearchParams of the current URL
|
||||
// navigate, // navigate('/x/abc'): client-side navigation
|
||||
// setTitle, // setTitle('abc123'): extra text in the top bar and tab title
|
||||
// }
|
||||
// A view with path '/' replaces the home grid.
|
||||
import { el, store } from './ui.js';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let cfg, cleanup = null, routeSeq = 0;
|
||||
|
||||
/**
|
||||
* startShell({
|
||||
* name: 'tools', // shown in the tab title
|
||||
* views: [...],
|
||||
* categories: ['Text', 'Data'], // sidebar order; unknown ones go last, alphabetically
|
||||
* home: { title, intro }, // the home page heading and one-line description
|
||||
* sidebar: true, // false: top bar only (single-screen apps)
|
||||
* passthrough: ['/api/', '/static/'], // same-origin links the router must leave alone
|
||||
* })
|
||||
*/
|
||||
export function startShell(options) {
|
||||
cfg = { categories: [], sidebar: true, passthrough: ['/api/', '/static/'], home: {}, ...options };
|
||||
setupTheme();
|
||||
if (cfg.sidebar) setupNav();
|
||||
else document.querySelector('.shell')?.classList.add('bare');
|
||||
setupLinks();
|
||||
route();
|
||||
}
|
||||
|
||||
// ---------- theme: auto → light → dark, remembered per browser ----------
|
||||
|
||||
const THEMES = ['auto', 'light', 'dark'];
|
||||
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
|
||||
const THEME_ICON = {
|
||||
auto: svg('<circle cx="12" cy="12" r="9"/><path d="M12 3v18" /><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
|
||||
light: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'),
|
||||
dark: svg('<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>'),
|
||||
};
|
||||
|
||||
function setupTheme() {
|
||||
const btn = $('theme-btn');
|
||||
let theme = store.get('theme', 'auto');
|
||||
const apply = (t) => {
|
||||
if (t === 'auto') delete document.documentElement.dataset.theme;
|
||||
else document.documentElement.dataset.theme = t;
|
||||
if (btn) {
|
||||
btn.innerHTML = THEME_ICON[t];
|
||||
btn.title = `Theme: ${t}`;
|
||||
}
|
||||
};
|
||||
apply(theme);
|
||||
btn?.addEventListener('click', () => {
|
||||
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
|
||||
store.set('theme', theme);
|
||||
apply(theme);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- navigation ----------
|
||||
|
||||
function grouped(views) {
|
||||
const groups = new Map();
|
||||
for (const v of views) {
|
||||
const c = v.category || 'Other';
|
||||
if (!groups.has(c)) groups.set(c, []);
|
||||
groups.get(c).push(v);
|
||||
}
|
||||
const rank = (c) => (cfg.categories.includes(c) ? cfg.categories.indexOf(c) : 999);
|
||||
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
|
||||
}
|
||||
|
||||
function matches(v, q) {
|
||||
q = q.trim().toLowerCase();
|
||||
return !q || `${v.name} ${v.description || ''} ${v.category || ''}`.toLowerCase().includes(q);
|
||||
}
|
||||
|
||||
const listed = () => cfg.views.filter((v) => v.path !== '/');
|
||||
|
||||
function renderNav() {
|
||||
const q = $('nav-filter').value;
|
||||
const homeView = cfg.views.find((v) => v.path === '/');
|
||||
$('nav-list').replaceChildren(
|
||||
el('a.nav-item', { href: '/', dataset: { path: '/' } },
|
||||
el('span.nav-icon', {}, homeView?.icon || '⌂'), el('span.nav-label', {}, homeView?.name || 'Home')),
|
||||
...grouped(listed().filter((v) => matches(v, q))).map(([cat, views]) =>
|
||||
el('div.nav-group', {},
|
||||
el('div.nav-heading', {}, cat),
|
||||
views.map((v) => el('a.nav-item', { href: v.path, dataset: { path: v.path, view: v.id } },
|
||||
el('span.nav-icon', {}, v.icon), el('span.nav-label', {}, v.name), v.badge ? el('span.badge', { hidden: true }) : null)),
|
||||
),
|
||||
),
|
||||
);
|
||||
markActive();
|
||||
updateBadges();
|
||||
}
|
||||
|
||||
function updateBadges() {
|
||||
if (!cfg.sidebar) return;
|
||||
let total = 0;
|
||||
for (const v of cfg.views) {
|
||||
if (!v.badge) continue;
|
||||
let n = 0;
|
||||
try { n = v.badge() || 0; } catch {}
|
||||
total += n;
|
||||
const b = $('nav-list').querySelector(`.nav-item[data-view="${v.id}"] .badge`);
|
||||
if (b) {
|
||||
b.hidden = !n;
|
||||
b.textContent = n > 99 ? '99+' : String(n);
|
||||
b.title = `${n} new`;
|
||||
}
|
||||
}
|
||||
$('menu-btn')?.classList.toggle('has-badge', total > 0);
|
||||
}
|
||||
|
||||
function markActive() {
|
||||
if (!cfg.sidebar) return;
|
||||
const view = findView(location.pathname);
|
||||
for (const a of $('nav-list').querySelectorAll('.nav-item')) {
|
||||
const on = view ? a.dataset.path === view.path : a.dataset.path === '/';
|
||||
a.classList.toggle('active', on);
|
||||
if (on) a.setAttribute('aria-current', 'page');
|
||||
else a.removeAttribute('aria-current');
|
||||
}
|
||||
}
|
||||
|
||||
function setDrawer(open) {
|
||||
document.body.classList.toggle('drawer-open', open);
|
||||
$('menu-btn')?.setAttribute('aria-expanded', String(open));
|
||||
}
|
||||
|
||||
function setupNav() {
|
||||
const filter = $('nav-filter');
|
||||
filter.addEventListener('input', renderNav);
|
||||
filter.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
const first = listed().find((v) => matches(v, filter.value));
|
||||
if (first) {
|
||||
filter.value = '';
|
||||
renderNav();
|
||||
setDrawer(false);
|
||||
navigate(first.path);
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
filter.value = '';
|
||||
renderNav();
|
||||
filter.blur();
|
||||
setDrawer(false);
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const a = document.activeElement;
|
||||
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(a?.tagName) || a?.isContentEditable;
|
||||
if (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
e.preventDefault();
|
||||
setDrawer(true);
|
||||
filter.focus();
|
||||
}
|
||||
});
|
||||
$('menu-btn')?.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
|
||||
$('scrim')?.addEventListener('click', () => setDrawer(false));
|
||||
window.addEventListener('app:badges', updateBadges);
|
||||
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith(store.prefix)) updateBadges(); }); // other tabs
|
||||
setInterval(updateBadges, 60000);
|
||||
renderNav();
|
||||
}
|
||||
|
||||
// ---------- routing ----------
|
||||
|
||||
function findView(pathname) {
|
||||
return cfg.views.find((v) => (v.path === '/' ? pathname === '/' : pathname === v.path || pathname.startsWith(`${v.path}/`)));
|
||||
}
|
||||
|
||||
export function navigate(path, { replace = false } = {}) {
|
||||
if (path === location.pathname + location.search) return;
|
||||
history[replace ? 'replaceState' : 'pushState']({}, '', path);
|
||||
route();
|
||||
}
|
||||
|
||||
function setupLinks() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const a = e.target.closest('a[href]');
|
||||
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
|
||||
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const url = new URL(a.href, location.href);
|
||||
if (url.origin !== location.origin || cfg.passthrough.some((p) => url.pathname.startsWith(p))) return;
|
||||
if (url.pathname === location.pathname && url.search === location.search && url.hash) return; // in-page anchor
|
||||
e.preventDefault();
|
||||
setDrawer(false);
|
||||
navigate(url.pathname + url.search);
|
||||
});
|
||||
window.addEventListener('popstate', route);
|
||||
}
|
||||
|
||||
function setTitle(view, extra) {
|
||||
const isHome = !view || view.path === '/';
|
||||
const t = $('topbar-title');
|
||||
if (t) t.textContent = isHome ? '' : [view.name, extra].filter(Boolean).join(' · ');
|
||||
document.title = isHome ? cfg.name : `${[extra, view.name].filter(Boolean).join(' · ')} — ${cfg.name}`;
|
||||
}
|
||||
|
||||
async function route() {
|
||||
const seq = ++routeSeq;
|
||||
if (cleanup) {
|
||||
try { cleanup(); } catch (err) { console.error(err); }
|
||||
cleanup = null;
|
||||
}
|
||||
markActive();
|
||||
const root = $('view');
|
||||
const view = findView(location.pathname);
|
||||
document.body.dataset.view = view ? view.id : 'home';
|
||||
if (!view) {
|
||||
if (location.pathname !== '/') history.replaceState({}, '', '/');
|
||||
setTitle(null);
|
||||
renderHome(root);
|
||||
return;
|
||||
}
|
||||
setTitle(view);
|
||||
root.replaceChildren(el('div.loading', {}, 'Loading…'));
|
||||
try {
|
||||
const mod = await view.load();
|
||||
if (seq !== routeSeq) return; // navigated away while loading
|
||||
root.replaceChildren();
|
||||
const ctx = {
|
||||
rest: view.path === '/' ? '' : location.pathname.slice(view.path.length).replace(/^\//, ''),
|
||||
query: new URLSearchParams(location.search),
|
||||
navigate,
|
||||
setTitle: (extra) => setTitle(view, extra),
|
||||
};
|
||||
cleanup = (await mod.mount(root, ctx)) || null;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (seq === routeSeq) root.replaceChildren(el('div.empty', {}, `Couldn't load ${view.name}: ${err.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
function renderHome(root) {
|
||||
const filter = el('input.page-filter', { type: 'search', placeholder: 'Find…', 'aria-label': 'Filter' });
|
||||
const grid = el('div.card-grid');
|
||||
const draw = () =>
|
||||
grid.replaceChildren(
|
||||
...listed().filter((v) => matches(v, filter.value)).map((v) =>
|
||||
el('a.card-link', { href: v.path },
|
||||
el('div.card-link-icon', { 'aria-hidden': 'true' }, v.icon),
|
||||
el('div', {}, el('div.card-link-name', {}, v.name), el('div.card-link-desc', {}, v.description || '')),
|
||||
),
|
||||
),
|
||||
);
|
||||
filter.addEventListener('input', draw);
|
||||
filter.addEventListener('keydown', (e) => {
|
||||
const first = e.key === 'Enter' && grid.querySelector('a');
|
||||
if (first) navigate(new URL(first.href).pathname);
|
||||
});
|
||||
draw();
|
||||
root.replaceChildren(
|
||||
el('div.page', {},
|
||||
el('h1', {}, cfg.home.title || cfg.name),
|
||||
cfg.home.intro ? el('p.muted', {}, cfg.home.intro) : null,
|
||||
listed().length > 6 ? filter : null,
|
||||
grid,
|
||||
),
|
||||
);
|
||||
}
|
||||
253
app/static/js/ui.js
Normal file
253
app/static/js/ui.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// House UI helpers. Plain ES module, no dependencies; pairs with house.css.
|
||||
// Copy into the project (e.g. static/js/ui.js) unchanged.
|
||||
//
|
||||
// Per-browser storage is namespaced by <html data-app="<slug>"> so projects
|
||||
// on the same origin don't collide.
|
||||
|
||||
const NS = (document.documentElement.dataset.app || 'app') + ':';
|
||||
|
||||
/** el('button.primary', {onclick}, 'Save'): tag with optional .classes, props/attrs, children.
|
||||
* String values become attributes; set innerHTML with Object.assign (and only on sanitized HTML). */
|
||||
export function el(spec, props = {}, ...children) {
|
||||
const [tag, ...classes] = spec.split('.');
|
||||
const node = document.createElement(tag || 'div');
|
||||
if (classes.length) node.className = classes.join(' ');
|
||||
for (const [k, v] of Object.entries(props || {})) {
|
||||
if (v == null || v === false) continue;
|
||||
if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
|
||||
else if (k === 'dataset') Object.assign(node.dataset, v);
|
||||
else if (k in node && typeof v !== 'string') node[k] = v;
|
||||
else node.setAttribute(k, v === true ? '' : v);
|
||||
}
|
||||
for (const c of children.flat()) if (c != null && c !== false) node.append(c);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** A short confirmation in the corner: toast('Copied'), toast('Upload failed: too large', 'error'). */
|
||||
export function toast(message, kind = 'info') {
|
||||
let box = document.getElementById('toasts');
|
||||
if (!box) {
|
||||
box = el('div.toasts', { id: 'toasts', 'aria-live': 'polite' });
|
||||
document.body.append(box);
|
||||
}
|
||||
const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message);
|
||||
box.append(t);
|
||||
setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200);
|
||||
setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600);
|
||||
}
|
||||
|
||||
export async function copyText(text, what = 'Copied') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' });
|
||||
document.body.append(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
toast(what);
|
||||
}
|
||||
|
||||
/** Copies HTML as rich text (with a plain-text alternative) for pasting into docs and chat apps. */
|
||||
export async function copyRich(html, text, what = 'Copied') {
|
||||
try {
|
||||
if (!window.ClipboardItem || !navigator.clipboard?.write) throw new Error('no async clipboard');
|
||||
await navigator.clipboard.write([new ClipboardItem({
|
||||
'text/html': new Blob([html], { type: 'text/html' }),
|
||||
'text/plain': new Blob([text], { type: 'text/plain' }),
|
||||
})]);
|
||||
} catch {
|
||||
// Older browsers / insecure origins: select a rendered copy and use the legacy copy command.
|
||||
const holder = el('div', { contenteditable: 'true', style: 'position:fixed;left:-9999px;top:0' });
|
||||
holder.innerHTML = html;
|
||||
document.body.append(holder);
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(holder);
|
||||
const sel = getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand('copy');
|
||||
sel.removeAllRanges();
|
||||
holder.remove();
|
||||
}
|
||||
toast(what);
|
||||
}
|
||||
|
||||
export function downloadText(text, filename, type = 'text/plain') {
|
||||
const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` }));
|
||||
const a = el('a', { href: url, download: filename });
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Opens a file picker and resolves with {name, text}, or null if cancelled. */
|
||||
export function openTextFile(accept = '') {
|
||||
return new Promise((resolve) => {
|
||||
const input = el('input', { type: 'file', accept });
|
||||
input.addEventListener('change', async () => {
|
||||
const f = input.files[0];
|
||||
resolve(f ? { name: f.name, text: await f.text() } : null);
|
||||
});
|
||||
input.addEventListener('cancel', () => resolve(null));
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
// localStorage can be missing or throw (private windows, blocked storage); never let that break the page.
|
||||
export const store = {
|
||||
prefix: NS,
|
||||
get(key, fallback = null) {
|
||||
try {
|
||||
const v = localStorage.getItem(NS + key);
|
||||
return v == null ? fallback : JSON.parse(v);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
},
|
||||
set(key, value) {
|
||||
try {
|
||||
localStorage.setItem(NS + key, JSON.stringify(value));
|
||||
} catch {}
|
||||
},
|
||||
remove(key) {
|
||||
try {
|
||||
localStorage.removeItem(NS + key);
|
||||
} catch {}
|
||||
},
|
||||
};
|
||||
|
||||
export function formatBytes(n) {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
/** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */
|
||||
export function debounce(fn, ms) {
|
||||
let t, pending;
|
||||
const d = (...args) => {
|
||||
clearTimeout(t);
|
||||
pending = args;
|
||||
t = setTimeout(d.flush, ms);
|
||||
};
|
||||
d.flush = () => {
|
||||
clearTimeout(t);
|
||||
if (pending) {
|
||||
const args = pending;
|
||||
pending = null;
|
||||
fn(...args);
|
||||
}
|
||||
};
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */
|
||||
export function onLeave(fn) {
|
||||
window.addEventListener('pagehide', fn);
|
||||
return () => window.removeEventListener('pagehide', fn);
|
||||
}
|
||||
|
||||
/** A segmented control: segmented([['edit','Edit'],...], current, onChange, 'View'). Has .set(value). */
|
||||
export function segmented(options, current, onChange, label = '') {
|
||||
const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label });
|
||||
const buttons = options.map(([value, text, title]) =>
|
||||
el('button', {
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
title: title || text,
|
||||
'aria-checked': String(value === current),
|
||||
onclick: () => set(value, true),
|
||||
}, text),
|
||||
);
|
||||
function set(value, fire) {
|
||||
options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value)));
|
||||
if (fire) onChange(value);
|
||||
}
|
||||
wrap.append(...buttons);
|
||||
wrap.set = (v) => set(v, false);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */
|
||||
export function tabIndent(ta, unit = ' ') {
|
||||
ta.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
e.preventDefault();
|
||||
const { selectionStart: s, selectionEnd: end, value } = ta;
|
||||
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
|
||||
if (s === end && !e.shiftKey) {
|
||||
document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end');
|
||||
return;
|
||||
}
|
||||
const lines = value.slice(lineStart, end).split('\n');
|
||||
const out = e.shiftKey
|
||||
? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, '')))
|
||||
: lines.map((l) => unit + l);
|
||||
ta.setSelectionRange(lineStart, end);
|
||||
document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select');
|
||||
ta.setSelectionRange(lineStart, lineStart + out.join('\n').length);
|
||||
});
|
||||
}
|
||||
|
||||
/** A modal dialog: modal('Title', body, {wide, footer}). Returns the <dialog>; it removes itself when closed. */
|
||||
export function modal(title, body, { wide = false, footer = null } = {}) {
|
||||
const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title },
|
||||
el('div.modal-head', {},
|
||||
el('h2', {}, title),
|
||||
el('button.icon-btn', { type: 'button', 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'),
|
||||
),
|
||||
el('div.modal-body', {}, body),
|
||||
footer ? el('div.modal-foot', {}, footer) : null,
|
||||
);
|
||||
dlg.addEventListener('click', (e) => {
|
||||
if (e.target === dlg) dlg.close(); // click on the backdrop
|
||||
});
|
||||
dlg.addEventListener('close', () => dlg.remove());
|
||||
document.body.append(dlg);
|
||||
dlg.showModal();
|
||||
return dlg;
|
||||
}
|
||||
|
||||
/** Resolves true/false: await confirmDialog('Delete project?', 'This cannot be undone.', 'Delete project'). */
|
||||
export function confirmDialog(title, message, confirmLabel = 'Confirm', { danger = true } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let ok = false;
|
||||
const yes = el(`button.btn.${danger ? 'danger' : 'primary'}`, { type: 'button', onclick: () => { ok = true; dlg.close(); } }, confirmLabel);
|
||||
const no = el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel');
|
||||
const dlg = modal(title, el('p', {}, message), { footer: [no, yes] });
|
||||
dlg.addEventListener('close', () => resolve(ok));
|
||||
yes.focus();
|
||||
});
|
||||
}
|
||||
|
||||
/** A button that opens a menu: dropdown('Open in', [{label, icon?, onSelect}]). */
|
||||
export function dropdown(label, items) {
|
||||
const menu = el('div.menu', { role: 'menu', hidden: true });
|
||||
const btn = el('button.btn', { type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
toggle(menu.hidden);
|
||||
} }, label, el('span.caret', { 'aria-hidden': 'true' }, '▾'));
|
||||
for (const it of items) {
|
||||
menu.append(el('button.menu-item', { type: 'button', role: 'menuitem', onclick: () => { toggle(false); it.onSelect(); } },
|
||||
it.icon ? el('span.nav-icon', {}, it.icon) : null, it.label));
|
||||
}
|
||||
const outside = (e) => { if (!wrap.contains(e.target)) toggle(false); };
|
||||
const onKey = (e) => { if (e.key === 'Escape') { toggle(false); btn.focus(); } };
|
||||
function toggle(open) {
|
||||
menu.hidden = !open;
|
||||
btn.setAttribute('aria-expanded', String(open));
|
||||
if (open) {
|
||||
document.addEventListener('click', outside);
|
||||
document.addEventListener('keydown', onKey);
|
||||
menu.querySelector('button')?.focus();
|
||||
} else {
|
||||
document.removeEventListener('click', outside);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
}
|
||||
}
|
||||
const wrap = el('div.dropdown', {}, btn, menu);
|
||||
return wrap;
|
||||
}
|
||||
35
app/static/js/views/blocked.js
Normal file
35
app/static/js/views/blocked.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// Blocked domains: AdGuard's top blocked list plus what was blocked recently, and for whom.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ago, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root) {
|
||||
const ui = screen(root, [el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'), el('span.spacer'), el('a.btn', { href: '/queries?status=blocked' }, 'Blocked queries in the log')]);
|
||||
async function load() {
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const b = await get('/api/dns/blocked');
|
||||
fill(ui.body,
|
||||
el('p.lede', {}, b.num_queries ? `AdGuard Home blocked ${num(b.num_blocked)} of ${num(b.num_queries)} queries (${pct(b.num_blocked / b.num_queries, 1)}) in its stats period.` : 'No AdGuard stats yet.'),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Recently blocked', b.since ? `${num(b.sample)} blocked queries since ${when(b.since)}` : ''),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }, 'Clients', 'Last'],
|
||||
b.recent.map((r) => el('tr', {},
|
||||
el('td', {}, domainLink(r.domain), r.rule ? el('div.small.muted.mono', {}, r.rule) : null),
|
||||
el('td.num', {}, num(r.count)),
|
||||
el('td', {}, el('div', { style: 'display:grid;gap:2px' }, ...r.clients.slice(0, 4).map((c) => clientLink(c.ip, c.device)),
|
||||
r.clients.length > 4 ? el('span.small.muted', {}, `+${r.clients.length - 4} more`) : null)),
|
||||
el('td.nowrap', {}, ago(r.last)))), { empty: 'Nothing blocked recently.' })),
|
||||
el('div', {}, section('Most blocked', 'AdGuard stats period'),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }],
|
||||
b.top.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' }))),
|
||||
);
|
||||
ui.setStatus(`${b.recent.length} domains blocked recently`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
200
app/static/js/views/clients.js
Normal file
200
app/static/js/views/clients.js
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// Clients: every device seen, your labels for it, and one client's DNS activity.
|
||||
import { confirmDialog, debounce, el, store, toast } from '../ui.js';
|
||||
import { del, get, put } from '../api.js';
|
||||
import { ago, ms, num, when } from '../fmt.js';
|
||||
import { adguardProblem, domainLink, errorBox, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const SOURCE = { arp: 'Probe ARP', dhcp: 'DHCP lease', dns: 'DNS queries', adguard: 'AdGuard client' };
|
||||
const sourceName = (s) => SOURCE[s] || (s.startsWith('adguard-') ? `AdGuard ${s.slice(8)}` : s);
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : list(root, ctx);
|
||||
}
|
||||
|
||||
function list(root) {
|
||||
const f = store.get('client-filters', { q: '', cat: '', sus: false, online: false });
|
||||
const q = el('input.input', { type: 'search', value: f.q, placeholder: 'Name, IP or MAC', 'aria-label': 'Search clients' });
|
||||
const cat = el('select.select', { 'aria-label': 'Category' }, el('option', { value: '' }, 'All categories'));
|
||||
const sus = el('input', { type: 'checkbox', checked: f.sus });
|
||||
const online = el('input', { type: 'checkbox', checked: f.online });
|
||||
const ui = screen(root, [
|
||||
q, cat,
|
||||
el('label.check', {}, sus, 'Suspicious only'),
|
||||
el('label.check', {}, online, 'Active now'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
let data = null;
|
||||
|
||||
const save = () => store.set('client-filters', { q: q.value, cat: cat.value, sus: sus.checked, online: online.checked });
|
||||
const redraw = debounce(() => { save(); draw(); }, 120);
|
||||
for (const c of [q, cat, sus, online]) c.addEventListener('input', redraw);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
data = await get('/api/clients');
|
||||
if (cat.options.length === 1) {
|
||||
cat.append(...data.categories.map((c) => el('option', { value: c }, c)), el('option', { value: '-' }, 'No category'));
|
||||
cat.value = f.cat;
|
||||
}
|
||||
draw();
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const needle = q.value.trim().toLowerCase();
|
||||
const rows = data.clients.filter((c) =>
|
||||
(!needle || [c.display, c.hostname, c.ip, c.mac, c.name].some((v) => v && v.toLowerCase().includes(needle))) &&
|
||||
(!cat.value || (cat.value === '-' ? !c.category : c.category === cat.value)) &&
|
||||
(!sus.checked || c.suspicious) && (!online.checked || c.online));
|
||||
rows.sort((a, b) => (b.suspicious - a.suspicious) || ((b.queries || 0) - (a.queries || 0)) || a.display.localeCompare(b.display));
|
||||
const empty = data.clients.length
|
||||
? 'No clients match these filters.'
|
||||
: data.adguard ? 'No clients yet. They appear within a minute of AdGuard Home or a probe seeing them.'
|
||||
: 'No clients yet. Connect AdGuard Home (ADGUARD_URL in the hub’s .env) or add a probe; probes report the devices in their ARP table.';
|
||||
fill(ui.body, table(
|
||||
['Client', 'Category', 'IP', 'MAC', { text: 'Queries', props: { class: 'num', title: 'AdGuard Home stats period' } }, 'Last active', 'Seen by'],
|
||||
rows.map((c) => el(`tr${c.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, el('span.chips', {},
|
||||
el('a', { href: `/clients/${encodeURIComponent(c.key)}` }, el('strong', {}, c.display)),
|
||||
c.name && c.hostname && c.name !== c.hostname ? el('span.muted.small', {}, c.hostname) : null,
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null,
|
||||
c.new ? el('span.chip.new', { title: `First seen ${when(c.first_seen)}` }, 'New') : null)),
|
||||
el('td', {}, c.category || el('span.muted', {}, '—')),
|
||||
el('td.mono', {}, c.ip || '—'),
|
||||
el('td.mono', {}, c.mac || '—'),
|
||||
el('td.num', {}, num(c.queries)),
|
||||
el('td.nowrap', { title: when(c.last_seen) }, c.online ? el('span.chip.ok', {}, 'Active') : ago(c.last_seen)),
|
||||
el('td.small.muted', {}, c.sources.map(sourceName).join(', ')))),
|
||||
{ empty }));
|
||||
const n = data.clients;
|
||||
ui.setStatus(`${rows.length} of ${n.length} clients · ${n.filter((c) => c.online).length} active in the last 10 min · ${n.filter((c) => c.suspicious).length} suspicious`);
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(() => { if (!document.hidden) load(); }, 60000);
|
||||
return () => { clearInterval(t); redraw.flush(); };
|
||||
}
|
||||
|
||||
function detail(root, ctx, key) {
|
||||
const ui = screen(root, [
|
||||
el('button.btn.primary', { type: 'submit', form: 'client-form' }, 'Save changes'),
|
||||
el('a.btn', { href: `/queries?client=${encodeURIComponent(key)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn.danger', { type: 'button', onclick: () => forget() }, 'Forget client'),
|
||||
]);
|
||||
let c = null;
|
||||
let cursor = '';
|
||||
const qbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => loadQueries() }, 'Load older');
|
||||
const qwrap = el('div');
|
||||
const summary = el('div');
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
c = await get(`/api/clients/${encodeURIComponent(key)}`);
|
||||
ctx.setTitle(c.display);
|
||||
render();
|
||||
ui.setStatus(`${c.online ? 'Active now' : `Last active ${ago(c.last_seen)}`} · first seen ${when(c.first_seen)}`);
|
||||
loadSummary();
|
||||
loadQueries(true);
|
||||
} catch (err) {
|
||||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'No client with this id. It may have been merged into another entry once its MAC address was learned.', el('div', {}, el('a.btn', { href: '/clients' }, 'All clients'))) : errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
const name = el('input.input', { id: 'c-name', value: c.name, maxlength: 80, placeholder: c.hostname || c.ip || '' });
|
||||
const category = el('select.select', { id: 'c-cat' }, el('option', { value: '' }, 'No category'), ...c.categories.map((x) => el('option', { value: x }, x)));
|
||||
if (c.category && !c.categories.includes(c.category)) category.append(el('option', { value: c.category }, c.category));
|
||||
category.value = c.category;
|
||||
const suspicious = el('input', { type: 'checkbox', id: 'c-sus', checked: c.suspicious });
|
||||
const notes = el('textarea.textarea', { id: 'c-notes', rows: 3, maxlength: 2000, placeholder: 'Who owns it, why it is flagged…' });
|
||||
notes.value = c.notes;
|
||||
const form = el('form.form-grid', { id: 'client-form', onsubmit: async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
c = { ...c, ...(await put(`/api/clients/${encodeURIComponent(key)}`, { name: name.value, category: category.value, suspicious: suspicious.checked, notes: notes.value })) };
|
||||
ctx.setTitle(c.display);
|
||||
title.replaceWith(title = titleRow());
|
||||
toast('Changes saved');
|
||||
} catch (ex) { toast(ex.message, 'error'); }
|
||||
} },
|
||||
el('div.field', {}, el('label', { for: 'c-name' }, 'Name'), name, el('div.hint', {}, 'Shown everywhere instead of the hostname.')),
|
||||
el('div.field', {}, el('label', { for: 'c-cat' }, 'Category'), category),
|
||||
el('div.field.wide', {}, el('label.check', {}, suspicious, 'Suspicious: highlight this client in lists and query results')),
|
||||
el('div.field.wide', {}, el('label', { for: 'c-notes' }, 'Notes'), notes));
|
||||
const titleRow = () => el('div.title-row', {}, el('h2', {}, c.display),
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null, c.category ? el('span.chip', {}, c.category) : null,
|
||||
c.online ? el('span.chip.ok', {}, 'Active') : null);
|
||||
let title = titleRow();
|
||||
fill(ui.body,
|
||||
title,
|
||||
el('div.cols', { style: 'margin-top:12px' },
|
||||
el('dl.kv', {},
|
||||
el('dt', {}, 'IP address'), el('dd.mono', {}, c.ips.join(', ') || '—'),
|
||||
el('dt', {}, 'MAC address'), el('dd.mono', {}, c.mac || 'Unknown (no probe or DHCP lease has seen it)'),
|
||||
el('dt', {}, 'Hostname'), el('dd', {}, c.hostname || '—'),
|
||||
el('dt', {}, 'Queries'), el('dd', {}, c.queries == null ? '—' : `${num(c.queries)} in AdGuard’s stats period`),
|
||||
el('dt', {}, 'Seen by'), el('dd', {}, c.sources.map(sourceName).join(', ') || '—'),
|
||||
el('dt', {}, 'First seen'), el('dd', {}, when(c.first_seen)),
|
||||
el('dt', {}, 'Last active'), el('dd', {}, c.last_seen ? `${ago(c.last_seen)} (${when(c.last_seen)})` : '—')),
|
||||
form),
|
||||
summary,
|
||||
section('DNS requests', 'Newest first'),
|
||||
qwrap,
|
||||
);
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
summary.replaceChildren(section('Most requested domains'), el('div.loading', {}, 'Reading the query log…'));
|
||||
try {
|
||||
const s = await get(`/api/clients/${encodeURIComponent(key)}/summary`);
|
||||
summary.replaceChildren(
|
||||
section('Most requested domains', s.sample ? `From its last ${num(s.sample)} queries${s.since ? `, since ${when(s.since)}` : ''} · ${num(s.blocked)} blocked` : ''),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
s.top.map((d) => el('tr', {}, el('td', {}, domainLink(d.domain)), el('td.num', {}, num(d.count)), el('td.num', {}, d.blocked ? num(d.blocked) : '')),
|
||||
), { empty: 'No DNS queries from this client in the AdGuard query log.' }));
|
||||
} catch (err) {
|
||||
summary.replaceChildren(section('Most requested domains'), adguardProblem(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function loadQueries(reset = false) {
|
||||
if (reset) { cursor = ''; qbody.replaceChildren(); }
|
||||
more.disabled = true;
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { client: key, older_than: cursor, limit: 100 });
|
||||
cursor = r.oldest;
|
||||
qbody.append(...r.rows.map((q) => el(`tr${q.blocked ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, `${when(q.ts)}`),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!qbody.children.length) qwrap.replaceChildren(el('div.callout', {}, 'No DNS queries from this client in the AdGuard query log.'));
|
||||
else if (reset || !qwrap.querySelector('table')) qwrap.replaceChildren(
|
||||
el('div.table-wrap', {}, el('table.table', {}, el('thead', {}, el('tr', {}, ...['Time', 'Domain', 'Type', 'Result', 'Response'].map((h) => el('th', {}, h)))), qbody)),
|
||||
el('div.more', {}, more));
|
||||
more.hidden = r.done || !cursor;
|
||||
} catch (err) {
|
||||
qwrap.replaceChildren(adguardProblem(err));
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function forget() {
|
||||
if (!c) return;
|
||||
const ok = await confirmDialog(`Forget ${c.display}?`, 'Its name, category, flag and notes are deleted. If the device is still on the network it comes back as a new client.', 'Forget client');
|
||||
if (!ok) return;
|
||||
try { await del(`/api/clients/${encodeURIComponent(key)}`); toast(`Forgot ${c.display}`); ctx.navigate('/clients'); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
load();
|
||||
}
|
||||
107
app/static/js/views/domains.js
Normal file
107
app/static/js/views/domains.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// Domains: the most requested and most blocked, and one domain's detail.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { seriesLegend, stackedBars, hideTip } from '../charts.js';
|
||||
import { ago, hm, ms, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : overview(root, ctx);
|
||||
}
|
||||
|
||||
function openBox(ctx) {
|
||||
const input = el('input.input', { type: 'search', placeholder: 'example.com', 'aria-label': 'Domain to open' });
|
||||
const form = el('form', { style: 'display:contents', onsubmit: (e) => {
|
||||
e.preventDefault();
|
||||
const d = input.value.trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0];
|
||||
if (d) ctx.navigate(`/domains/${encodeURIComponent(d)}`);
|
||||
} }, input, el('button.btn', { type: 'submit' }, 'Open domain'));
|
||||
return form;
|
||||
}
|
||||
|
||||
function overview(root, ctx) {
|
||||
const ui = screen(root, [openBox(ctx), el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh')]);
|
||||
async function load() {
|
||||
try {
|
||||
const d = await get('/api/domains');
|
||||
const list = (rows) => table(['Domain', { text: 'Requests', props: { class: 'num' } }],
|
||||
rows.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' });
|
||||
fill(ui.body, el('div.cols', {},
|
||||
el('div', {}, section('Most requested'), list(d.top_queried)),
|
||||
el('div', {}, section('Most blocked'), list(d.top_blocked))));
|
||||
ui.setStatus(`${num(d.num_queries)} queries · ${num(d.num_blocked)} blocked in AdGuard’s stats period`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
|
||||
function detail(root, ctx, name) {
|
||||
ctx.setTitle(name);
|
||||
const ui = screen(root, [
|
||||
openBox(ctx),
|
||||
el('a.btn', { href: `/queries?domain=${encodeURIComponent(name)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
ui.setStatus('Reading the query log…');
|
||||
try {
|
||||
const d = await get(`/api/domains/${encodeURIComponent(name)}`);
|
||||
render(d);
|
||||
ui.setStatus(`Based on ${num(d.sample_rows)} queries for *.${d.base}${d.since ? ` since ${when(d.since)}` : ''}${d.complete ? ' (the whole AdGuard log)' : ''}`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(d) {
|
||||
const now = Date.now() / 1000;
|
||||
const hourLabel = (i, full) => {
|
||||
const t = now - (23 - i) * 3600;
|
||||
return full ? `${hm(t - 3600)} – ${hm(t)}` : i === 23 ? 'now' : `${23 - i} h ago`;
|
||||
};
|
||||
fill(ui.body,
|
||||
el('div.title-row', {}, el('h2', {}, d.domain),
|
||||
d.blocked ? el('span.chip.danger', {}, d.blocked === d.count ? 'Always blocked' : 'Sometimes blocked') : d.count ? el('span.chip.ok', {}, 'Allowed') : null,
|
||||
d.domain !== d.base ? el('a.chip', { href: `/domains/${encodeURIComponent(d.base)}` }, `part of ${d.base}`) : null),
|
||||
el('div.facts', {},
|
||||
fact('Requests', num(d.count), 'in the sample below'),
|
||||
fact('Blocked', d.count ? `${num(d.blocked)} (${pct(d.blocked / d.count)})` : '—'),
|
||||
fact('Clients', num(d.clients.length)),
|
||||
fact('Avg response', ms(d.avg_ms)),
|
||||
fact('Last request', d.last ? ago(d.last) : '—'),
|
||||
d.stats_count != null ? fact('AdGuard stats', num(d.stats_count), 'top-domain count for its stats period') : null),
|
||||
d.count ? el('div', {},
|
||||
section('Last 24 hours', 'Requests per hour'),
|
||||
seriesLegend([{ name: 'Allowed', color: 'var(--viz-1)' }, { name: 'Blocked', color: 'var(--viz-2)' }], 'box'),
|
||||
stackedBars({ n: 24, xLabel: hourLabel, height: 150, label: `Requests per hour for ${d.domain}`,
|
||||
series: [{ name: 'Allowed', color: 'var(--viz-1)', values: d.hours.map((h, i) => h - d.blocked_hours[i]) },
|
||||
{ name: 'Blocked', color: 'var(--viz-2)', values: d.blocked_hours }] })) : el('div.callout', { style: 'margin-top:12px' }, `No requests for ${d.domain} in the sample. Related domains under ${d.base} are below.`),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Clients requesting it'),
|
||||
table(['Client', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }, 'Last'],
|
||||
d.clients.map((c) => el(`tr${c.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, clientLink(c.ip, c.device, c.name)), el('td.num', {}, num(c.count)), el('td.num', {}, c.blocked ? num(c.blocked) : ''),
|
||||
el('td.nowrap', {}, ago(c.last)))), { empty: 'No clients in the sample.' })),
|
||||
el('div', {}, section(`Other names under ${d.base}`, 'Same domain, different subdomains'),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
d.related.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)), el('td.num', {}, r.blocked ? num(r.blocked) : ''))),
|
||||
{ empty: 'No other names under this domain in the sample.' }))),
|
||||
d.rules.length ? el('div', {}, section('Matching rules'), el('ul.mono', {}, ...d.rules.map(([r, n]) => el('li', {}, `${r} ×${n}`)))) : null,
|
||||
section('Recent requests'),
|
||||
table(['Time', 'Client', 'Type', 'Result', { text: 'Response', props: { class: 'num' } }],
|
||||
d.recent.map((q) => el('tr', {}, el('td.nowrap', {}, when(q.ts)), el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.mono', {}, q.type), el('td', {}, resultChip(q)), el('td.num', {}, ms(q.elapsed_ms)))), { empty: 'None in the sample.' }),
|
||||
);
|
||||
}
|
||||
const fact = (label, value, title) => el('div.fact', { title: title || '' }, el('span.label', {}, label), el('strong', {}, value));
|
||||
load();
|
||||
return hideTip;
|
||||
}
|
||||
130
app/static/js/views/health.js
Normal file
130
app/static/js/views/health.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// Network health: the live mesh matrix, status strips over time and the incident list.
|
||||
import { el, segmented, store } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { STATUS, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, showTip } from '../charts.js';
|
||||
import { axisTime, dur, ms, pct, when } from '../fmt.js';
|
||||
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
|
||||
|
||||
export function mount(root, ctx) {
|
||||
let range = store.get('health-range', '24h');
|
||||
const seg = segmented(RANGES, range, (v) => { range = v; store.set('health-range', v); load(); }, 'Time range');
|
||||
const ui = screen(root, [
|
||||
seg,
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
el('span.spacer'),
|
||||
el('a.btn', { href: '/probes' }, 'Manage probes'),
|
||||
]);
|
||||
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
try {
|
||||
const [mx, st, inc] = await Promise.all([
|
||||
get('/api/health/matrix', { window: 300 }),
|
||||
get('/api/health/strips', { range }),
|
||||
get('/api/health/incidents', { range }),
|
||||
]);
|
||||
render(mx, st, inc);
|
||||
const online = mx.probes.filter((p) => p.online).length;
|
||||
const ongoing = inc.incidents.filter((i) => i.ongoing).length;
|
||||
ui.setStatus(`${online} of ${mx.probes.length} probes reporting · ${inc.total} incidents in ${range}${ongoing ? ` · ${ongoing} ongoing` : ''} · updated ${new Date().toLocaleTimeString()}`,
|
||||
ongoing ? 'error' : '');
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(`Couldn't load health: ${err.message}`, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(mx, st, inc) {
|
||||
if (!mx.probes.length) {
|
||||
fill(ui.body, el('div.empty', {},
|
||||
el('p', {}, 'No probes yet. Probes are small containers on machines around the house that test the mesh and the internet link.'),
|
||||
el('a.btn.primary', { href: '/probes?add=1' }, 'Add a probe')));
|
||||
return;
|
||||
}
|
||||
fill(ui.body,
|
||||
section('Right now', 'Last 5 minutes, per probe and target. Select a probe for its charts.'),
|
||||
matrix(mx),
|
||||
section('Timeline', `${range} in ${st.buckets} slices of ${dur(st.width)}. A slice is down when half its checks fail, degraded when a fifth are slow or failing.`),
|
||||
statusLegend(),
|
||||
strips(st),
|
||||
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss.`),
|
||||
incidents(inc.incidents),
|
||||
);
|
||||
}
|
||||
|
||||
function matrix(mx) {
|
||||
if (!mx.targets.length) return el('div.callout', {}, 'No measurements in the last 5 minutes. Probes report every 30 seconds or so; check that they are running.');
|
||||
const byKey = new Map(mx.cells.map((c) => [`${c.probe_id}|${c.target}`, c]));
|
||||
const rows = mx.probes.map((p) => el('tr', {},
|
||||
el('th.row-head', {}, el('span.chips', {}, el('a', { href: `/probes/${p.id}` }, p.name), p.online ? null : el('span.chip.danger', {}, 'Offline'))),
|
||||
...mx.targets.map((t) => {
|
||||
const c = byKey.get(`${p.id}|${t.target}`);
|
||||
if (!c) return el('td', {}, el('div.cell-empty', {}, t.target === `probe:${p.id}` ? 'self' : '—'));
|
||||
const main = c.methods.icmp || c.methods.http || c.methods.dns;
|
||||
const loss = c.methods.icmp?.loss;
|
||||
const node = el(`a.cell.s-${c.status}`, { href: `/probes/${p.id}`, 'aria-label': `${p.name} to ${t.label}: ${STATUS[c.status].label}` },
|
||||
el('strong', {}, main?.latency != null ? ms(main.latency) : STATUS[c.status].label),
|
||||
el('span.muted', {}, [loss != null ? `${pct(loss)} loss` : null, c.status !== 'ok' ? STATUS[c.status].label : null].filter(Boolean).join(' · ') || 'OK'));
|
||||
const tip = () => [tipTitle(`${p.name} → ${t.label}`),
|
||||
...Object.entries(c.methods).map(([m, v]) => tipRow(v.latency != null ? ms(v.latency) : 'failed',
|
||||
`${METHOD[m] || m} · ${STATUS[v.status].label}${v.down ? ` · ${v.down}/${v.n} failed` : ''}${v.loss ? ` · ${pct(v.loss)} loss` : ''}`)),
|
||||
...Object.values(c.methods).filter((v) => v.error).slice(0, 1).map((v) => el('div.small.error-text', {}, v.error))];
|
||||
node.addEventListener('pointerenter', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||
node.addEventListener('pointermove', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||
node.addEventListener('pointerleave', hideTip);
|
||||
node.addEventListener('focus', () => { const r = node.getBoundingClientRect(); showTip(r.right, r.bottom, tip()); });
|
||||
node.addEventListener('blur', hideTip);
|
||||
return el('td', {}, node);
|
||||
})));
|
||||
return el('div.table-wrap', {}, el('table.table.matrix', {},
|
||||
el('thead', {}, el('tr', {}, el('th', {}, 'From ↓ / to →'), ...mx.targets.map((t) => el('th', { title: t.target }, t.label)))),
|
||||
el('tbody', {}, ...rows)));
|
||||
}
|
||||
|
||||
function strips(st) {
|
||||
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const groups = new Map();
|
||||
for (const s of st.series) {
|
||||
if (!groups.has(s.probe_id)) groups.set(s.probe_id, []);
|
||||
groups.get(s.probe_id).push(s);
|
||||
}
|
||||
const probe = new Map(st.probes.map((p) => [p.id, p]));
|
||||
const describe = (s) => (i, b) => {
|
||||
const t0 = st.since + i * st.width;
|
||||
return [tipTitle(`${when(t0)} – ${xt(t0 + st.width)}`),
|
||||
el('div', {}, el('strong', {}, `${probe.get(s.probe_id)?.name} → ${s.label}`)),
|
||||
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`)
|
||||
: tipRow('No data', 'no checks reported'),
|
||||
b?.latency != null ? tipRow(ms(b.latency), 'average') : null];
|
||||
};
|
||||
return el('div.strips', {},
|
||||
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||
...[...groups].map(([pid, list]) => el('div.strip-group', {},
|
||||
el('h3', {}, el('a', { href: `/probes/${pid}` }, probe.get(pid)?.name || `Probe ${pid}`), probe.get(pid)?.online ? null : el('span.chip.danger', {}, 'Offline')),
|
||||
...list.map((s) => el('div.strip-row', {},
|
||||
el('span.name', { title: s.target }, s.label),
|
||||
strip(s.buckets, describe(s)),
|
||||
el('span.uptime', { title: 'Share of checks that succeeded' }, s.uptime == null ? '—' : `${s.uptime}%`))))));
|
||||
}
|
||||
|
||||
function incidents(list) {
|
||||
return table(['Started', 'Lasted', 'Probe', 'Target', 'Type', 'Checks', 'Detail'], list.map((i) => el('tr', {},
|
||||
el('td.nowrap', { title: when(i.start) }, when(i.start)),
|
||||
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||
el('td', {}, el('a', { href: `/probes/${i.probe_id}` }, i.probe)),
|
||||
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||
el('td', {}, statusChip(i.type)),
|
||||
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')),
|
||||
)), { empty: `No incidents in the last ${range}.` });
|
||||
}
|
||||
|
||||
load();
|
||||
const stop = every(30000, load);
|
||||
return () => { stop(); hideTip(); };
|
||||
}
|
||||
253
app/static/js/views/probes.js
Normal file
253
app/static/js/views/probes.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// Probes: the list, adding one (with its install command), and one probe's detail and charts.
|
||||
import { confirmDialog, copyText, el, modal, segmented, store, toast } from '../ui.js';
|
||||
import { del, get, patch, post } from '../api.js';
|
||||
import { lineChart, seriesLegend, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, STATUS } from '../charts.js';
|
||||
import { ago, axisTime, dur, mbps, ms, pct, when } from '../fmt.js';
|
||||
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS', throughput: 'Throughput' };
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, Number(ctx.rest)) : list(root, ctx);
|
||||
}
|
||||
|
||||
function installCommand(info, token) {
|
||||
const hub = info.hub_url || location.origin;
|
||||
return `curl -fsSL ${info.install_url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`;
|
||||
}
|
||||
|
||||
function commandBlock(cmd) {
|
||||
const loopback = /^(localhost|127\.|\[::1\])/.test(location.hostname) && cmd.includes(location.origin);
|
||||
return el('div', { style: 'display:grid;gap:6px' },
|
||||
el('div.cmd', {}, el('pre', {}, cmd), el('button.btn', { type: 'button', onclick: () => copyText(cmd, 'Install command copied') }, 'Copy')),
|
||||
loopback ? el('div.callout.error', {}, `You opened this page at ${location.host}, which other machines can't reach. Replace HUB_URL with the hub's LAN address, or set HUB_PUBLIC_URL in the hub's .env.`) : null);
|
||||
}
|
||||
|
||||
function onlineChip(p) {
|
||||
if (!p.last_seen) return el('span.chip', {}, 'Never reported');
|
||||
return p.online ? el('span.chip.ok', {}, 'Reporting') : el('span.chip.danger', {}, 'Offline');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- list
|
||||
|
||||
function list(root, ctx) {
|
||||
const ui = screen(root, [
|
||||
el('button.btn.primary', { type: 'button', onclick: () => addProbe() }, 'Add probe'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
let info = null;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
info = await get('/api/probes');
|
||||
const rows = info.probes.map((p) => el('tr', {},
|
||||
el('td', {}, el('a', { href: `/probes/${p.id}` }, el('strong', {}, p.name))),
|
||||
el('td', {}, onlineChip(p)),
|
||||
el('td.mono', {}, p.address ? `${p.address}:${p.port || 8765}` : '—'),
|
||||
el('td', {}, p.hostname || '—'),
|
||||
el('td', {}, p.icmp == null ? '—' : p.icmp ? 'Yes' : el('span.chip.warn', { title: 'Run install-probe.sh again on that machine to enable ping' }, 'Not permitted')),
|
||||
el('td.mono', {}, p.version || '—'),
|
||||
el('td.nowrap', { title: when(p.last_seen) }, ago(p.last_seen)),
|
||||
));
|
||||
fill(ui.body,
|
||||
el('p.lede', {}, 'Each probe tests every other probe (ping, HTTP and throughput), the gateway, DNS servers and the internet, then reports here.'),
|
||||
table(['Name', 'Status', 'Address', 'Host', 'Ping', 'Version', 'Last report'], rows,
|
||||
{ empty: 'No probes yet. Add one, then run its install command on a machine on the network.' }),
|
||||
);
|
||||
const off = info.probes.filter((p) => !p.online).length;
|
||||
ui.setStatus(`${info.probes.length} probes · ${off} not reporting · they report every ${info.interval} s`, off ? 'error' : '');
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function addProbe() {
|
||||
const name = el('input.input', { id: 'probe-name', required: true, maxlength: 60, placeholder: 'Living room', autocomplete: 'off' });
|
||||
const err = el('div.error', { hidden: true });
|
||||
const submit = el('button.btn.primary', { type: 'submit', form: 'add-probe' }, 'Add probe');
|
||||
const form = el('form.field', { id: 'add-probe', onsubmit: async (e) => {
|
||||
e.preventDefault();
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const p = await post('/api/probes', { name: name.value.trim() });
|
||||
dlg.close();
|
||||
showInstall(p);
|
||||
load();
|
||||
} catch (ex) {
|
||||
err.textContent = ex.message; err.hidden = false; name.setAttribute('aria-invalid', 'true');
|
||||
submit.disabled = false;
|
||||
}
|
||||
} }, el('label', { for: 'probe-name' }, 'Name'), name,
|
||||
el('div.hint', {}, 'Where it sits, so the matrix reads well: Office, Garage, Upstairs AP.'), err);
|
||||
const dlg = modal('Add a probe', form, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), submit] });
|
||||
name.focus();
|
||||
}
|
||||
|
||||
function showInstall(p) {
|
||||
const cmd = installCommand(info, p.token);
|
||||
const dlg = modal(`Install “${p.name}”`, el('div', { style: 'display:grid;gap:12px' },
|
||||
el('p', { style: 'margin:0' }, 'Run this on the machine that will be the probe. It starts on boot and keeps running. On Linux hosts it uses Docker (installed if needed). On macOS and inside Proxmox LXC containers it installs natively as a system service; there, Linux needs root: put sudo env before HUB_URL.'),
|
||||
commandBlock(cmd),
|
||||
el('p.small.muted', { style: 'margin:0' }, `The probe reports to ${info.hub_url || location.origin}. If that address isn't reachable from the probe, change HUB_URL in the command. The command is also on the probe's page.`),
|
||||
), { wide: true, footer: [el('a.btn', { href: `/probes/${p.id}`, onclick: () => dlg.close() }, 'Open probe'), el('button.btn.primary', { type: 'button', onclick: () => dlg.close() }, 'Done')] });
|
||||
}
|
||||
|
||||
load();
|
||||
if (ctx.query.get('add')) { history.replaceState({}, '', '/probes'); setTimeout(addProbe, 0); }
|
||||
return every(30000, load);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- detail
|
||||
|
||||
function detail(root, ctx, id) {
|
||||
let range = store.get('probe-range', '24h');
|
||||
const seg = segmented(RANGES, range, (v) => { range = v; store.set('probe-range', v); load(); }, 'Time range');
|
||||
const ui = screen(root, [
|
||||
seg,
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => rename() }, 'Rename'),
|
||||
el('button.btn.danger', { type: 'button', onclick: () => remove() }, 'Remove probe'),
|
||||
]);
|
||||
let probe = null, listInfo = null;
|
||||
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
try {
|
||||
const [p, li, st, ser, inc] = await Promise.all([
|
||||
get(`/api/probes/${id}`), get('/api/probes'),
|
||||
get('/api/health/strips', { range, probe: id }), get('/api/health/series', { probe: id, range }),
|
||||
get('/api/health/incidents', { range, probe: id, limit: 50 }),
|
||||
]);
|
||||
probe = p; listInfo = li;
|
||||
ctx.setTitle(p.name);
|
||||
render(st, ser, inc);
|
||||
ui.setStatus(`${p.online ? 'Reporting' : 'Not reporting'} · last report ${ago(p.last_seen)} · ${inc.total} incidents in ${range}`, p.online ? '' : 'error');
|
||||
} catch (err) {
|
||||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'This probe was removed.', el('div', {}, el('a.btn', { href: '/probes' }, 'All probes'))) : errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(st, ser, inc) {
|
||||
const p = probe;
|
||||
const addr = el('input.input', { value: p.address_locked ? p.address : '', placeholder: p.address ? `${p.address} (detected)` : 'detected from reports', 'aria-label': 'Address other probes use', style: 'max-width:260px' });
|
||||
const saveAddr = el('button.btn.small', { type: 'button', onclick: async () => {
|
||||
try { probe = await patch(`/api/probes/${id}`, { address: addr.value.trim() }); toast(addr.value.trim() ? 'Address saved' : 'Address will be detected again'); load(); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
} }, 'Save');
|
||||
fill(ui.body,
|
||||
el('div.title-row', {}, el('h2', {}, p.name), onlineChip(p)),
|
||||
el('div.cols', {},
|
||||
el('dl.kv', {},
|
||||
el('dt', {}, 'Address'), el('dd', {}, el('span.chips', {}, addr, saveAddr)),
|
||||
el('dt', {}, 'Port'), el('dd.mono', {}, String(p.port || 8765)),
|
||||
el('dt', {}, 'Host'), el('dd', {}, p.hostname || '—'),
|
||||
el('dt', {}, 'Ping'), el('dd', {}, p.icmp == null ? '—' : p.icmp ? 'Works' : 'Not permitted on this host. Run install-probe.sh again, which sets net.ipv4.ping_group_range.'),
|
||||
el('dt', {}, 'Version'), el('dd.mono', {}, p.version || '—'),
|
||||
el('dt', {}, 'Added'), el('dd', {}, when(p.created)),
|
||||
el('dt', {}, 'Last report'), el('dd', {}, `${ago(p.last_seen)}${p.last_seen ? ` (${when(p.last_seen)})` : ''}`),
|
||||
),
|
||||
el('div', {},
|
||||
el('div.label', { style: 'margin-bottom:6px' }, 'Install or reinstall'),
|
||||
commandBlock(installCommand(listInfo, p.token)),
|
||||
el('p.small.muted', {}, 'Leave Address empty to use what the probe reports. Set it when other probes must reach this one at a different address.')),
|
||||
),
|
||||
section('Timeline', `${range} in slices of ${dur(st.width)}`),
|
||||
statusLegend(),
|
||||
stripsFor(st),
|
||||
section('Latency', 'Average per slice. Red ticks mark slices with failed checks.'),
|
||||
seriesLegend([{ name: 'Ping', color: 'var(--viz-1)' }, { name: 'HTTP or DNS', color: 'var(--viz-2)' }]),
|
||||
multiples(ser),
|
||||
throughputChart(ser),
|
||||
section('Incidents'),
|
||||
table(['Started', 'Lasted', 'Target', 'Type', 'Checks', 'Detail'], inc.incidents.map((i) => el('tr', {},
|
||||
el('td.nowrap', {}, when(i.start)),
|
||||
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||
el('td', {}, statusChip(i.type)),
|
||||
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')))), { empty: `No incidents in the last ${range}.` }),
|
||||
);
|
||||
}
|
||||
|
||||
function stripsFor(st) {
|
||||
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||
const xt = axisTime(SPANS[range]);
|
||||
return el('div.strips', {},
|
||||
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||
...st.series.map((s) => el('div.strip-row', {},
|
||||
el('span.name', { title: s.target }, s.label),
|
||||
strip(s.buckets, (i, b) => [tipTitle(`${when(st.since + i * st.width)} – ${xt(st.since + (i + 1) * st.width)}`),
|
||||
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`) : tipRow('No data', ''),
|
||||
b?.latency != null ? tipRow(ms(b.latency), 'average') : null]),
|
||||
el('span.uptime', {}, s.uptime == null ? '—' : `${s.uptime}%`))));
|
||||
}
|
||||
|
||||
function multiples(ser) {
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const xLabel = (i, full) => (full ? `${when(ser.since + i * ser.width)} – ${xt(ser.since + (i + 1) * ser.width)}` : xt(ser.since + (i + 0.5) * ser.width));
|
||||
const cards = ser.targets.filter((t) => t.methods.icmp || t.methods.http || t.methods.dns).map((t) => {
|
||||
const second = t.methods.http || t.methods.dns;
|
||||
const series = [];
|
||||
if (t.methods.icmp) series.push({ name: 'Ping', color: 'var(--viz-1)', values: t.methods.icmp.map((b) => b?.avg ?? null) });
|
||||
if (second) series.push({ name: t.methods.http ? 'HTTP' : 'DNS', color: 'var(--viz-2)', values: second.map((b) => b?.avg ?? null) });
|
||||
const methods = Object.entries(t.methods).filter(([m]) => m !== 'throughput');
|
||||
const marks = Array.from({ length: ser.buckets }, (_, i) => methods.reduce((a, [, arr]) => a + (arr[i]?.failed || 0), 0));
|
||||
return el('div.multiple', {},
|
||||
el('h4', {}, t.label, el('span.chip', {}, t.kind === 'lan' ? 'LAN' : 'Internet')),
|
||||
lineChart({ n: ser.buckets, xLabel, series, marks, fmt: ms, height: 140, label: `Latency to ${t.label}`,
|
||||
describe: (i) => {
|
||||
const out = [];
|
||||
for (const [m, arr] of methods) {
|
||||
const b = arr[i];
|
||||
if (b?.failed) out.push(el('div.small.error-text', {}, `${METHOD[m]}: ${b.failed} of ${b.n} failed`));
|
||||
if (m === 'icmp' && b?.loss) out.push(el('div.small', {}, `Ping loss ${pct(b.loss)}`));
|
||||
}
|
||||
return out;
|
||||
} }));
|
||||
});
|
||||
return cards.length ? el('div.multiples', {}, ...cards) : el('div.callout', {}, `No latency data in the last ${range}.`);
|
||||
}
|
||||
|
||||
function throughputChart(ser) {
|
||||
const tp = ser.targets.filter((t) => t.methods.throughput);
|
||||
if (!tp.length) return null;
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const xLabel = (i, full) => (full ? when(ser.since + i * ser.width) : xt(ser.since + (i + 0.5) * ser.width));
|
||||
return el('div', {},
|
||||
section('Throughput to other probes', 'A timed download from each peer, every few minutes.'),
|
||||
el('div.multiples', {}, ...tp.map((t) => el('div.multiple', {},
|
||||
el('h4', {}, t.label),
|
||||
lineChart({ n: ser.buckets, xLabel, fmt: mbps, height: 120, label: `Throughput from ${t.label}`,
|
||||
series: [{ name: 'Throughput', color: 'var(--viz-1)', values: t.methods.throughput.map((b) => b?.mbps ?? null) }],
|
||||
marks: t.methods.throughput.map((b) => b?.failed || 0) })))));
|
||||
}
|
||||
|
||||
async function rename() {
|
||||
const input = el('input.input', { value: probe?.name || '', maxlength: 60, 'aria-label': 'Name' });
|
||||
const save = el('button.btn.primary', { type: 'button', onclick: async () => {
|
||||
try { await patch(`/api/probes/${id}`, { name: input.value.trim() }); dlg.close(); toast('Renamed'); load(); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
} }, 'Save name');
|
||||
const dlg = modal('Rename probe', input, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), save] });
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') save.click(); });
|
||||
input.select();
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (!probe) return;
|
||||
const ok = await confirmDialog(`Remove ${probe.name}?`,
|
||||
'Its history is deleted and its token stops working. The probe keeps running on its machine until you uninstall it there; the installer printed the uninstall command, and the README lists it.', 'Remove probe');
|
||||
if (!ok) return;
|
||||
try { await del(`/api/probes/${id}`); toast(`Removed ${probe.name}`); ctx.navigate('/probes'); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
load();
|
||||
const stop = every(30000, load);
|
||||
return () => { stop(); hideTip(); };
|
||||
}
|
||||
67
app/static/js/views/queries.js
Normal file
67
app/static/js/views/queries.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// The DNS query log from AdGuard Home, with search, result filter and client filter.
|
||||
import { debounce, el, segmented } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ms, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
const params = ctx.query;
|
||||
let status = params.get('status') || 'all';
|
||||
const client = params.get('client') || '';
|
||||
const ip = params.get('ip') || '';
|
||||
const domain = params.get('domain') || '';
|
||||
const search = el('input.input', { type: 'search', value: params.get('q') || '', placeholder: 'Domain or client', 'aria-label': 'Search queries' });
|
||||
const seg = segmented([['all', 'All'], ['blocked', 'Blocked'], ['allowed', 'Allowed']], status, (v) => { status = v; sync(); load(true); }, 'Result');
|
||||
const filterChip = client || ip || domain
|
||||
? el('span.chip.accent', {}, `${client ? 'Client' : ip ? 'IP' : 'Domain'}: ${client || ip || domain} `,
|
||||
el('a', { href: '/queries', 'aria-label': 'Clear filter', style: 'color:inherit;text-decoration:none' }, '✕'))
|
||||
: null;
|
||||
const ui = screen(root, [search, seg, filterChip, el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load(true) }, 'Refresh')]);
|
||||
const tbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => load() }, 'Load older');
|
||||
let cursor = '', count = 0, seq = 0;
|
||||
|
||||
function sync() {
|
||||
const u = new URLSearchParams(location.search);
|
||||
search.value ? u.set('q', search.value) : u.delete('q');
|
||||
status !== 'all' ? u.set('status', status) : u.delete('status');
|
||||
history.replaceState({}, '', `/queries${u.size ? `?${u}` : ''}`);
|
||||
}
|
||||
search.addEventListener('input', debounce(() => { sync(); load(true); }, 350));
|
||||
|
||||
async function load(reset = false) {
|
||||
const my = ++seq;
|
||||
if (reset) { cursor = ''; count = 0; }
|
||||
more.disabled = true;
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { search: search.value.trim(), status, client, ip, domain, older_than: cursor, limit: 100 });
|
||||
if (my !== seq) return;
|
||||
if (reset) tbody.replaceChildren();
|
||||
cursor = r.oldest;
|
||||
count += r.rows.length;
|
||||
tbody.append(...r.rows.map((q) => el(`tr${q.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, when(q.ts)),
|
||||
el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!ui.body.querySelector('table')) {
|
||||
fill(ui.body, el('div.table-wrap', {}, el('table.table', {},
|
||||
el('thead', {}, el('tr', {}, ...['Time', 'Client', 'Domain', 'Type', 'Result', { t: 'Response', c: 'num' }].map((h) => el('th', h.c ? { class: h.c } : {}, h.t || h)))), tbody)),
|
||||
el('div.more', {}, more));
|
||||
}
|
||||
if (!count) fill(ui.body, el('div.empty', {}, 'No queries match.'));
|
||||
more.hidden = r.done || !cursor;
|
||||
ui.setStatus(`${count} queries${r.done ? ' · end of the AdGuard log' : ''}`);
|
||||
} catch (err) {
|
||||
if (my !== seq) return;
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
load(true);
|
||||
}
|
||||
42
app/static/js/views/settings.js
Normal file
42
app/static/js/views/settings.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Settings: what the hub is configured to do. Values live in the hub's .env.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { num } from '../fmt.js';
|
||||
|
||||
export async function mount(root) {
|
||||
const intro = el('p.muted', {}, 'These come from the hub’s .env file.');
|
||||
const page = el('div.page', {}, el('h1', {}, 'Settings'), intro);
|
||||
root.append(page);
|
||||
try {
|
||||
const [i, dns] = await Promise.all([get('/api/info'), get('/api/dns/status')]);
|
||||
intro.textContent = `These come from ${i.env_file} on the hub (${i.install_mode} install). Edit that file, then restart the hub to apply: ${i.install_mode === 'docker' ? 'docker restart network-monitor' : 'sudo systemctl restart network-monitor (macOS: sudo launchctl kickstart -k system/dev.neilbantoc.network-monitor)'}. Deploy new code with ${i.update_command}.`;
|
||||
const row = (k, v, env) => [el('dt', {}, k), el('dd', {}, v, env ? el('span.muted.small.mono', {}, ` ${env}`) : null)];
|
||||
const list = (xs) => (xs.length ? xs.join(', ') : 'none');
|
||||
page.append(
|
||||
el('h2', {}, 'AdGuard Home'),
|
||||
el('dl.kv', {},
|
||||
...row('Status', dns.ok ? el('span.chip.ok', {}, `Connected · ${dns.version}`) : el('span.chip.danger', {}, dns.configured ? 'Not reachable' : 'Not set up')),
|
||||
...(dns.url ? row('Address', dns.url, 'ADGUARD_URL') : []),
|
||||
...(dns.ok ? [] : row('Problem', dns.message))),
|
||||
el('h2', {}, 'Probes'),
|
||||
el('dl.kv', {},
|
||||
...row('Report every', `${i.probe_interval} s`, 'PROBE_INTERVAL'),
|
||||
...row('LAN DNS servers', list(i.lan_dns_servers), 'LAN_DNS_SERVERS'),
|
||||
...row('Public DNS servers', list(i.dns_servers), 'DNS_SERVERS'),
|
||||
...row('DNS test name', i.dns_query_name, 'DNS_QUERY_NAME'),
|
||||
...row('Internet HTTP checks', list(i.wan_http_urls), 'WAN_HTTP_URLS'),
|
||||
...row('VPS', i.vps_url || 'none', 'VPS_URL'),
|
||||
...row('Throughput test', i.throughput_every ? `${num(i.throughput_bytes / 1e6)} MB from each peer every ${i.throughput_every} reports` : 'off', 'THROUGHPUT_EVERY, THROUGHPUT_BYTES')),
|
||||
el('h2', {}, 'Thresholds and storage'),
|
||||
el('dl.kv', {},
|
||||
...row('Slow on the LAN', `over ${i.thresholds.lan_ms} ms`, 'SLOW_LAN_MS'),
|
||||
...row('Slow to the internet', `over ${i.thresholds.wan_ms} ms`, 'SLOW_WAN_MS'),
|
||||
...row('Slow DNS', `over ${i.thresholds.dns_ms} ms`, 'SLOW_DNS_MS'),
|
||||
...row('Keep measurements', `${i.retention_days} days`, 'RETENTION_DAYS'),
|
||||
...row('Password', i.password ? 'On' : 'Off: anyone on the network can open this page', 'UI_PASSWORD'),
|
||||
...row('Version', i.version)),
|
||||
);
|
||||
} catch (err) {
|
||||
page.append(el('div.callout.error', {}, err.message));
|
||||
}
|
||||
}
|
||||
0
app/static/vendor/.gitkeep
vendored
Normal file
0
app/static/vendor/.gitkeep
vendored
Normal file
3
app/version.py
Normal file
3
app/version.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import os
|
||||
|
||||
VERSION = os.environ.get("APP_VERSION", "dev")
|
||||
Loading…
Add table
Add a link
Reference in a new issue