Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(unifi): import known and active clients alongside infrastructure
Pouzore3ae78723a05
diff --git a/backend/app/api/routes/unifi.py b/backend/app/api/routes/unifi.pyindex cdc66f7..3ec4292 100644--- a/backend/app/api/routes/unifi.py+++ b/backend/app/api/routes/unifi.py@@ -16,17 +16,32 @@ from app.db.models import InventoryDevice, ScanRunfrom app.schemas.unifi import (UnifiConfig,UnifiConnectionRequest,+ UnifiImportModes,UnifiImportResponse,UnifiSyncConfig,UnifiTestConnectionResponse,)from app.services.discovery_sources import add_source-from app.services.unifi_service import fetch_unifi_inventory, test_unifi_connection+from app.services.unifi_service import (+ SOURCE_CLIENT,+ SOURCE_INFRA,+ fetch_unifi_inventory,+ test_unifi_connection,+)logger = logging.getLogger(__name__)router = APIRouter()-_UNIFI_SOURCE = "unifi"+_UNIFI_SOURCE = SOURCE_INFRA+++def _configured_modes() -> UnifiImportModes:+ """The import modes persisted in scan_config.json, used by the sync paths."""+ return UnifiImportModes(+ infrastructure=settings.unifi_import_infrastructure,+ known_clients=settings.unifi_import_known_clients,+ active_clients=settings.unifi_import_active_clients,+ )def _resolve_credentials(payload: UnifiConnectionRequest) -> tuple[str, str]:@@ -73,6 +88,9 @@ async def import_unifi_pending(username=username,password=password,verify_tls=payload.verify_tls,+ infrastructure=payload.modes.infrastructure,+ known_clients=payload.modes.known_clients,+ active_clients=payload.modes.active_clients,)except ConnectionError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@@ -102,6 +120,9 @@ async def sync_unifi_now(username=settings.unifi_username,password=settings.unifi_password,verify_tls=settings.unifi_verify_tls,+ infrastructure=settings.unifi_import_infrastructure,+ known_clients=settings.unifi_import_known_clients,+ active_clients=settings.unifi_import_active_clients,)except Exception as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@@ -119,6 +140,7 @@ async def get_unifi_config(_: str = Depends(get_current_user)) -> UnifiConfig:sync_enabled=settings.unifi_sync_enabled,sync_interval=settings.unifi_sync_interval,credentials_configured=bool(settings.unifi_username and settings.unifi_password),+ modes=_configured_modes(),)@@ -137,6 +159,9 @@ async def save_unifi_config(try:settings.unifi_sync_enabled = payload.sync_enabledsettings.unifi_sync_interval = payload.sync_interval+ settings.unifi_import_infrastructure = payload.modes.infrastructure+ settings.unifi_import_known_clients = payload.modes.known_clients+ settings.unifi_import_active_clients = payload.modes.active_clientssettings.save_overrides()set_unifi_sync_enabled(payload.sync_enabled)if payload.sync_enabled:@@ -175,6 +200,8 @@ async def _persist_devices() -> UnifiImportResponse:pending_created = 0pending_updated = 0+ infra_count = 0+ client_count = 0for dev in devices:ieee = dev.get("ieee_address")@@ -182,6 +209,11 @@ async def _persist_devices(continueip = dev.get("ip")mac = dev.get("mac")+ source = dev.get("source") or _UNIFI_SOURCE+ if source == SOURCE_CLIENT:+ client_count += 1+ else:+ infra_count += 1existing = await _find_existing(db, ieee, mac)@@ -197,15 +229,15 @@ async def _persist_devices(model=dev.get("model"),properties=dev.get("properties", []),status="pending",- discovery_source=_UNIFI_SOURCE,- discovery_sources=[_UNIFI_SOURCE],+ discovery_source=source,+ discovery_sources=[source],)db.add(row)pending_created += 1else:existing.discovery_sources = add_source(list(existing.discovery_sources or []),- _UNIFI_SOURCE,+ source,)existing.ieee_address = existing.ieee_address or ieeeexisting.ip = ip or existing.ip@@ -226,6 +258,8 @@ async def _persist_devices(device_count=len(devices),pending_created=pending_created,pending_updated=pending_updated,+ infra_count=infra_count,+ client_count=client_count,)@@ -239,6 +273,9 @@ async def _background_unifi_sync(run_id: str) -> None:username=settings.unifi_username,password=settings.unifi_password,verify_tls=settings.unifi_verify_tls,+ infrastructure=settings.unifi_import_infrastructure,+ known_clients=settings.unifi_import_known_clients,+ active_clients=settings.unifi_import_active_clients,)result = await _persist_devices(db, devices)run = await db.get(ScanRun, run_id)diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex eb3e7e8..fff41d2 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -267,6 +267,11 @@ class Settings(BaseSettings):unifi_verify_tls: bool = Falseunifi_sync_enabled: bool = Falseunifi_sync_interval: int = 3600+ # Which controller inventories to import. Clients are opt-in: list/user+ # holds every client ever seen and carries no IP.+ unifi_import_infrastructure: bool = True+ unifi_import_known_clients: bool = False+ unifi_import_active_clients: bool = False@propertydef unifi_effective_host(self) -> str:@@ -335,6 +340,10 @@ class Settings(BaseSettings):self.unifi_sync_enabled = bool(data["unifi_sync_enabled"])if "unifi_sync_interval" in data:self.unifi_sync_interval = int(data["unifi_sync_interval"])+ for mode in ("infrastructure", "known_clients", "active_clients"):+ key = f"unifi_import_{mode}"+ if key in data:+ setattr(self, key, bool(data[key]))if "unifi_host" in data:self.unifi_host = str(data["unifi_host"])if "unifi_port" in data:@@ -372,6 +381,9 @@ class Settings(BaseSettings):# Credentials (username/password) are env-only and never written here."unifi_sync_enabled": self.unifi_sync_enabled,"unifi_sync_interval": self.unifi_sync_interval,+ "unifi_import_infrastructure": self.unifi_import_infrastructure,+ "unifi_import_known_clients": self.unifi_import_known_clients,+ "unifi_import_active_clients": self.unifi_import_active_clients,"unifi_host": self.unifi_host,"unifi_port": self.unifi_port,"unifi_site": self.unifi_site,diff --git a/backend/app/schemas/unifi.py b/backend/app/schemas/unifi.pyindex f1d0265..eeddbfd 100644--- a/backend/app/schemas/unifi.py+++ b/backend/app/schemas/unifi.py@@ -1,6 +1,30 @@"""Pydantic v2 schemas for UniFi Network Controller import."""-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validator+++class UnifiImportModes(BaseModel):+ """Which of the controller's three inventories to import.++ They answer different questions, so they are opt-in separately:+ ``stat/device`` is the adopted gear, ``list/user`` every client ever seen+ (no IP, and long on a real site), ``stat/sta`` the live sessions.+ """++ infrastructure: bool = Field(True, description="stat/device — adopted APs, switches, gateways")+ known_clients: bool = Field(False, description="list/user — every client the controller knows")+ active_clients: bool = Field(False, description="stat/sta — clients connected right now")++ @model_validator(mode="after")+ def _at_least_one(self) -> "UnifiImportModes":+ if not (self.infrastructure or self.known_clients or self.active_clients):+ raise ValueError("Select at least one UniFi source to import.")+ return self+++def _default_modes() -> UnifiImportModes:+ """Infrastructure only — the conservative default for both entry points."""+ return UnifiImportModes(infrastructure=True, known_clients=False, active_clients=False)class UnifiConnectionRequest(BaseModel):@@ -10,6 +34,10 @@ class UnifiConnectionRequest(BaseModel):username: str | None = Field(None, description="Controller username (falls back to server env)")password: str | None = Field(None, description="Controller password (falls back to server env)")verify_tls: bool = Field(False, description="Verify TLS certificate (usually false for local controllers)")+ modes: UnifiImportModes = Field(+ default_factory=_default_modes,+ description="Which sources to import (infrastructure only by default)",+ )class UnifiTestConnectionResponse(BaseModel):@@ -33,6 +61,8 @@ class UnifiImportResponse(BaseModel):device_count: intpending_created: intpending_updated: int+ infra_count: int = 0+ client_count: int = 0class UnifiConfig(BaseModel):@@ -43,8 +73,10 @@ class UnifiConfig(BaseModel):sync_enabled: boolsync_interval: intcredentials_configured: bool+ modes: UnifiImportModesclass UnifiSyncConfig(BaseModel):sync_enabled: boolsync_interval: int = Field(3600, ge=300)+ modes: UnifiImportModes = Field(default_factory=_default_modes)diff --git a/backend/app/services/unifi_service.py b/backend/app/services/unifi_service.pyindex 9e6c8a2..b2ffdd6 100644--- a/backend/app/services/unifi_service.py+++ b/backend/app/services/unifi_service.py@@ -22,6 +22,11 @@ class UnifiApiError(ConnectionError):"""+# discovery_source values. Infrastructure and clients are told apart in the+# data; the UI buckets both under one UniFi filter.+SOURCE_INFRA = "unifi"+SOURCE_CLIENT = "unifi-client"+# Map UniFi device type codes to homelable node types_TYPE_MAP: dict[str, str] = {"ugw": "router", # UniFi Security Gateway@@ -65,19 +70,65 @@ async def fetch_unifi_inventory(username: str,password: str,verify_tls: bool = False,+ infrastructure: bool = True,+ known_clients: bool = False,+ active_clients: bool = False,) -> list[dict[str, Any]]:- """Fetch all devices from the UniFi controller and return normalized dicts."""+ """Fetch the selected UniFi sources and return normalized dicts.++ Three sources, three different things (see README):++ - ``infrastructure`` — ``stat/device``, the adopted gear (AP, switch,+ gateway). Carries IP, model and firmware.+ - ``known_clients`` — ``list/user``, every client the controller has ever+ recorded. Persistent but thin: no IP, no point of attachment.+ - ``active_clients`` — ``stat/sta``, the sessions live right now. Carries+ the IP and the AP or switch port the client hangs off.++ A MAC seen by more than one source is merged once, live data winning over+ the persistent record.+ """client = httpx.AsyncClient(verify=verify_tls, timeout=15.0)try:cookies = await _login(client, host, port, username, password)if not cookies:raise ConnectionError("UniFi login failed: invalid credentials or unreachable host")- raw = await _fetch_devices(client, host, port, site, cookies)- return [_normalize(d) for d in raw]++ # Weakest source first: later sources overwrite the fields they know+ # better, and `list/user` knows the least.+ merged: dict[str, dict[str, Any]] = {}+ if known_clients:+ for raw in await _fetch_known_clients(client, host, port, site, cookies):+ _merge(merged, _normalize_client(raw))+ if active_clients:+ for raw in await _fetch_clients(client, host, port, site, cookies):+ _merge(merged, _normalize_client(raw))+ if infrastructure:+ for raw in await _fetch_devices(client, host, port, site, cookies):+ _merge(merged, _normalize(raw))+ return list(merged.values())finally:await client.aclose()+def _merge(acc: dict[str, dict[str, Any]], dev: dict[str, Any] | None) -> None:+ """Add ``dev`` to ``acc``, keyed by ieee, filling blanks on a known key."""+ if dev is None:+ return+ key = dev["ieee_address"]+ prev = acc.get(key)+ if prev is None:+ acc[key] = dev+ return+ # Same device from a richer source: take its values, keep what it lacks.+ for field, value in dev.items():+ if field == "properties":+ names = {p["name"] for p in value}+ value = value + [p for p in prev["properties"] if p["name"] not in names]+ if value:+ prev[field] = value++async def _login(client: httpx.AsyncClient,host: str,@@ -277,6 +328,31 @@ async def _fetch_clients()+async def _fetch_known_clients(+ client: httpx.AsyncClient,+ host: str,+ port: int,+ site: str,+ cookies: dict[str, str],+) -> list[dict[str, Any]]:+ """Fetch every client the controller knows of (``list/user``).++ Persistent records, kept after the client disconnects — and thin: a manual+ entry carries little more than a MAC, a name and an OUI.+ """+ return await _get_list(+ client,+ host,+ port,+ cookies,+ [+ f"/proxy/network/api/s/{site}/list/user",+ f"/api/s/{site}/list/user",+ ],+ "known client",+ )++def _normalize(d: dict[str, Any]) -> dict[str, Any]:"""Convert a raw UniFi device record to a homelable-compatible dict."""raw_type = (d.get("type") or "").lower()@@ -312,4 +388,52 @@ def _normalize(d: dict[str, Any]) -> dict[str, Any]:"model": model,"properties": props,"raw_type": raw_type,+ "source": SOURCE_INFRA,+ }+++def _normalize_client(d: dict[str, Any]) -> dict[str, Any] | None:+ """Convert a UniFi client record (``list/user`` or ``stat/sta``) to a dict.++ Returns None for a record with no MAC — the only key both endpoints+ guarantee, and the one the inventory dedupes on.+ """+ mac = (d.get("mac") or "").lower()+ if not mac:+ return None++ name = d.get("name") or d.get("hostname") or d.get("display_name") or mac+ # stat/sta carries the live lease; list/user only ever a reservation.+ ip = d.get("ip") or d.get("fixed_ip") or None+ wired = d.get("is_wired")++ props: list[dict[str, str]] = []+ if wired is not None:+ props.append({"name": "Connection", "value": "wired" if wired else "wifi"})+ uplink = d.get("sw_mac") or d.get("ap_mac")+ if uplink:+ label = "Switch" if d.get("sw_mac") else "Access point"+ props.append({"name": label, "value": str(uplink).lower()})+ port = d.get("sw_port")+ if port is not None:+ props.append({"name": "Switch port", "value": str(port)})+ for key, label in (("essid", "SSID"), ("network", "Network"), ("oui", "OUI")):+ value = d.get(key)+ if value:+ props.append({"name": label, "value": str(value)})++ return {+ "ieee_address": f"unifi-{mac}",+ "mac": mac,+ "ip": ip,+ "hostname": name,+ "label": name,+ # UniFi says nothing reliable about what a client *is*; the user retypes+ # it on approve, like any other discovery.+ "type": "computer",+ "vendor": d.get("oui") or None,+ "model": None,+ "properties": props,+ "raw_type": "client",+ "source": SOURCE_CLIENT,}diff --git a/backend/tests/test_unifi_router.py b/backend/tests/test_unifi_router.pyindex 87a51c2..9f4ae22 100644--- a/backend/tests/test_unifi_router.py+++ b/backend/tests/test_unifi_router.py@@ -134,3 +134,110 @@ async def test_approved_device_stays_approved(db_session: AsyncSession) -> None:assert updated.status == "approved", (f"Status changed to '{updated.status}'; auto-sync must not un-approve devices")+# --- import modes ----------------------------------------------------------++async def test_config_exposes_the_import_modes(client: AsyncClient, headers: dict) -> None:+ res = await client.get("/api/v1/unifi/config", headers=headers)+ assert res.status_code == 200+ modes = res.json()["modes"]+ # Infrastructure only by default: list/user is long and IP-less.+ assert modes == {+ "infrastructure": True,+ "known_clients": False,+ "active_clients": False,+ }+++async def test_import_with_no_source_selected_is_rejected(+ client: AsyncClient, headers: dict+) -> None:+ res = await client.post(+ "/api/v1/unifi/import-pending",+ headers=headers,+ json={+ "host": "unifi.local",+ "username": "admin",+ "password": "pw",+ "modes": {+ "infrastructure": False,+ "known_clients": False,+ "active_clients": False,+ },+ },+ )+ assert res.status_code == 422+++async def test_clients_persist_under_their_own_source(db_session: AsyncSession) -> None:+ """A client keeps discovery_source "unifi-client", infra keeps "unifi"."""+ devices = [+ {+ "ieee_address": "unifi-00:27:22:e0:00:02",+ "mac": "00:27:22:e0:00:02",+ "ip": "192.168.1.101",+ "hostname": "USW Ultra",+ "label": "USW Ultra",+ "type": "switch",+ "vendor": "Ubiquiti",+ "properties": [],+ "source": "unifi",+ },+ {+ "ieee_address": "unifi-bc:24:11:8d:26:ed",+ "mac": "bc:24:11:8d:26:ed",+ "ip": None,+ "hostname": "Paperless",+ "label": "Paperless",+ "type": "computer",+ "vendor": "Proxmox Server Solutions GmbH",+ "properties": [],+ "source": "unifi-client",+ },+ ]+ result = await _persist_devices(db_session, devices)+ assert (result.infra_count, result.client_count) == (1, 1)+ assert result.pending_created == 2++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ by_mac = {r.mac: r for r in rows}+ assert by_mac["00:27:22:e0:00:02"].discovery_sources == ["unifi"]+ assert by_mac["bc:24:11:8d:26:ed"].discovery_sources == ["unifi-client"]+ # Clients are approvable like any other discovery: they land pending with a+ # suggested type.+ assert by_mac["bc:24:11:8d:26:ed"].status == "pending"+ assert by_mac["bc:24:11:8d:26:ed"].suggested_type == "computer"+++async def test_an_ip_scan_row_gains_the_unifi_client_source(+ db_session: AsyncSession,+) -> None:+ """The same machine found by nmap and by UniFi stays one inventory row."""+ row = InventoryDevice(+ ip="192.168.1.50",+ mac="bc:24:11:8d:26:ed",+ status="pending",+ discovery_source="arp",+ discovery_sources=["arp"],+ )+ db_session.add(row)+ await db_session.commit()++ await _persist_devices(db_session, [{+ "ieee_address": "unifi-bc:24:11:8d:26:ed",+ "mac": "bc:24:11:8d:26:ed",+ "ip": "192.168.1.50",+ "hostname": "paperless",+ "label": "paperless",+ "type": "computer",+ "vendor": "Proxmox Server Solutions GmbH",+ "properties": [],+ "source": "unifi-client",+ }])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 1+ assert rows[0].discovery_sources == ["arp", "unifi-client"]diff --git a/backend/tests/test_unifi_service.py b/backend/tests/test_unifi_service.pyindex 9d11593..8f62dc9 100644--- a/backend/tests/test_unifi_service.py+++ b/backend/tests/test_unifi_service.py@@ -200,3 +200,130 @@ async def test_inventory_maps_unifi_types_to_node_types() -> None:assert ap["vendor"] == "Ubiquiti"assert ap["model"] == "U7PRO"assert {"name": "Firmware", "value": "8.6.11.18870"} in ap["properties"]+++# ── import modes ────────────────────────────────────────────────────────────++_KNOWN_CLIENTS = [+ # A hand-added client: what list/user really carries — no IP, no uplink.+ {+ "_id": "6aaef4dff140c244eb55edbd",+ "mac": "bc:24:11:8d:26:ed",+ "name": "Paperless",+ "oui": "Proxmox Server Solutions GmbH",+ "is_wired": True,+ "noted": True,+ },+ {"mac": "bc:24:11:00:00:99", "hostname": "nas", "oui": "Synology"},+]++_ACTIVE_CLIENTS = [+ # Same MAC as Paperless above, seen live: this is where the IP lives.+ {+ "mac": "bc:24:11:8d:26:ed",+ "ip": "192.168.1.50",+ "hostname": "paperless",+ "is_wired": True,+ "sw_mac": "00:27:22:e0:00:02",+ "sw_port": 7,+ "network": "LAN",+ },+]+++def _full_controller(site: str = "default"):+ """A controller serving all three inventories on the legacy paths."""++ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == _LOGIN_OS:+ return _err("api.err.LoginRequired")+ if path == _LOGIN_LEGACY:+ return httpx.Response(+ 200,+ json={"meta": {"rc": "ok"}, "data": []},+ headers={"set-cookie": "unifises=abc123; Path=/; HttpOnly"},+ )+ if path.startswith("/proxy/network/"):+ return httpx.Response(404, text="<html>HTTP Status 404</html>")+ if path == f"/api/s/{site}/stat/device":+ return _ok(_DEVICES)+ if path == f"/api/s/{site}/list/user":+ return _ok(_KNOWN_CLIENTS)+ if path == f"/api/s/{site}/stat/sta":+ return _ok(_ACTIVE_CLIENTS)+ return _err("api.err.NoSiteContext")++ return handler+++async def _fetch(**modes):+ ctx, factory = _patch(_full_controller())+ with ctx:+ devices = await fetch_unifi_inventory(+ "unifi.local", 8443, "default", "admin", "pw", **modes+ )+ return devices, [r.url.path for r in factory.requests]+++async def test_infrastructure_only_is_the_default() -> None:+ devices, paths = await _fetch()+ assert len(devices) == 3+ assert {d["source"] for d in devices} == {"unifi"}+ # No client endpoint is even contacted.+ assert not any("list/user" in p or "stat/sta" in p for p in paths)+++async def test_known_clients_can_be_imported_alone() -> None:+ devices, paths = await _fetch(infrastructure=False, known_clients=True)+ assert [d["hostname"] for d in devices] == ["Paperless", "nas"]+ assert {d["source"] for d in devices} == {"unifi-client"}+ assert all(d["type"] == "computer" for d in devices)+ # list/user carries no address — the entry lands without one.+ assert devices[0]["ip"] is None+ assert devices[0]["vendor"] == "Proxmox Server Solutions GmbH"+ assert not any("stat/device" in p for p in paths)+++async def test_active_clients_carry_the_live_attachment() -> None:+ devices, _ = await _fetch(infrastructure=False, active_clients=True)+ assert len(devices) == 1+ props = {p["name"]: p["value"] for p in devices[0]["properties"]}+ assert devices[0]["ip"] == "192.168.1.50"+ assert props["Switch"] == "00:27:22:e0:00:02"+ assert props["Switch port"] == "7"+ assert props["Connection"] == "wired"+++async def test_a_client_in_both_sources_is_merged_once() -> None:+ devices, _ = await _fetch(+ infrastructure=False, known_clients=True, active_clients=True+ )+ macs = [d["mac"] for d in devices]+ assert macs.count("bc:24:11:8d:26:ed") == 1+ paperless = next(d for d in devices if d["mac"] == "bc:24:11:8d:26:ed")+ # Live data wins for the IP, and the OUI from list/user survives.+ assert paperless["ip"] == "192.168.1.50"+ assert paperless["vendor"] == "Proxmox Server Solutions GmbH"+ assert {p["name"] for p in paperless["properties"]} >= {"Switch port", "OUI"}+++async def test_every_source_at_once() -> None:+ devices, _ = await _fetch(+ infrastructure=True, known_clients=True, active_clients=True+ )+ assert len(devices) == 5 # 3 infra + 2 distinct clients+ assert [d["source"] for d in devices].count("unifi") == 3+ assert [d["source"] for d in devices].count("unifi-client") == 2+++async def test_a_client_without_a_mac_is_skipped() -> None:+ from app.services.unifi_service import _normalize_client++ assert _normalize_client({"name": "ghost"}) is None