Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
refactor: rename homelab to infradeck everywhere, document the containers
karloks2005e765738b66c8
diff --git a/.claude/skills/security-audit/references/checklist-collector-agent.md b/.claude/skills/security-audit/references/checklist-collector-agent.mdindex 010943c..7e49cc7 100644--- a/.claude/skills/security-audit/references/checklist-collector-agent.md+++ b/.claude/skills/security-audit/references/checklist-collector-agent.md@@ -51,7 +51,7 @@ helper drže privilegije: najveća pažnja ide njima.rezultat koji bi ports "zatvorio"; ogromne datoteke ne troše memoriju.- [ ] **Ono što stiže s dashboarda** (odgovor na register/poll) tretira se nepouzdano: nemaizvršavanja, nema putanja, nema ciljeva za sondiranje iz odgovora. Mete provjere- interneta samo iz okoline kolektora (`HOMELAB_CONNECTIVITY_TARGETS`, ≤5, hostname ili+ interneta samo iz okoline kolektora (`INFRADECK_CONNECTIVITY_TARGETS`, ≤5, hostname iliIPv4), s tvrdim rokom.- [ ] Sondiranje: ne šalje podatke, samo TCP connect + DNS; ne može se usmjeriti naproizvoljnu metu; ograničenje trajanja kako check-in ne bi visio.diff --git a/.env.example b/.env.exampleindex 08e0b2e..a41ee6a 100644--- a/.env.example+++ b/.env.example@@ -15,14 +15,14 @@ AGENT_MODEL=models/gemini-3.5-flash# Servers join by clicking Add on the dashboard; no collector settings needed.# Optional: an enrollment key (Connect a server → Advanced) skips that approval.-# HOMELAB_ENROLL_KEY=+# INFRADECK_ENROLL_KEY=# Optional: override the name shown on the dashboard (defaults to the hostname).-HOMELAB_SERVER_NAME=+INFRADECK_SERVER_NAME=# --- Hosting on a remote server ---# Public HTTPS: point DOMAIN's DNS at the server, open ports 80/443, then run# docker compose --profile https up -d --build-# DOMAIN=homelab.example.com+# DOMAIN=infradeck.example.com# SESSION_COOKIE_SECURE=true# Keep the plain-HTTP dashboard port off the internet when Caddy is in front:# FRONTEND_BIND=127.0.0.1diff --git a/ODSTUPANJA.md b/ODSTUPANJA.mdindex 112ad91..78465f9 100644--- a/ODSTUPANJA.md+++ b/ODSTUPANJA.md@@ -1,7 +1,7 @@# Odstupanja od dizajnaPopis svega što se u implementaciji redizajna razlikuje od PDF-ova u `design/web/` i `design/mobile/`,-s razlogom i, gdje postoji, GitHub issueom. Stanje: 13. 10. 2026.+s razlogom i, gdje postoji, GitHub issueom. Stanje: 14. 10. 2026.Mobilni prikazi nisu odstupanja nego preostali posao; popisani su na kraju.@@ -12,7 +12,7 @@ su anotacije dizajna i namjerno nisu ugrađeni.| Dizajn | Implementacija | Razlog | Issue || --- | --- | --- | --- |-| „karlo's homelab" kao ime instance | Ime se izvodi iz imena prvog admina; može se promijeniti samo kroz API (`instance_name`), u Adminu nema polja | Admin stranica još nije redizajnirana | #106 |+| „karlo's homelab" kao ime instance | Zadano se izvodi iz imena prvog admina; mijenja se u Admin → General | – | – || „Owner" ispod imena korisnika | „Owner" se prikazuje svakom adminu, „Member" svima ostalima | Ne postoji uloga vlasnika | #106 || Verzija `v0.9.2` | Konstanta u `src/backend/config.py` i druga u `src/agent/collector.py` | Nema jednog izvora verzije pri buildu | #106 || Prečac `⌘K` | Na Linuxu i Windowsu piše `Ctrl K` | Prikazuje se prečac koji stvarno radi na tom sustavu | – |@@ -21,15 +21,15 @@ su anotacije dizajna i namjerno nisu ugrađeni.| Dizajn | Implementacija | Razlog | Issue || --- | --- | --- | --- |-| Agentova bilješka na svakom incidentu („Agent: limit is 4 GB…") | Stupac postoji i puni se ako backend pošalje `agent_note`; backend ga još ne šalje, pa je prazan | Agent još ne dijagnosticira incidente | #95, #93 |-| „Open diagnosis" i „Ask the agent" otvaraju taj incident / razgovor o tom kontejneru | Vode na `/agent` bez konteksta | Agent stranica je još placeholder | #95 |-| Zadnji incident: „Resolved 2 h ago · memory limit raised to 6 GB" | Piše samo kada je riješen i na kojem serveru | Nitko ne bilježi kako je incident riješen | #95 |-| „You'll get a push on ntfy if that changes" | Rečenica je izostavljena | Infradeck nema ntfy obavijesti | #50 |+| Agentova bilješka na svakom incidentu („Agent: limit is 4 GB…") | Bilješka dolazi iz lokalne dijagnoze po pravilima, ne od jezičnog modela | Automatska LLM dijagnoza ne postoji | #93 |+| „Ask the agent" otvara razgovor o tom kontejneru | Vodi na `/agent` bez konteksta kontejnera („Open diagnosis" otvara točno taj incident) | Chat još ne prima kontekst kontejnera | – |+| Zadnji incident: „Resolved 2 h ago · memory limit raised to 6 GB" | Piše samo kada je riješen i na kojem serveru | Nitko ne upisuje kako je incident riješen | – |+| „You'll get a push on ntfy if that changes" | Rečenica je izostavljena | Obavijesti ovise o kanalima koje je svaki korisnik postavio, pa rečenica ne bi vrijedila za svakoga | – || Gumbi Logs i Restart u proširenom redu kontejnera | Prikazani, ali onemogućeni, s objašnjenjem u tooltipu | Dogovoreno: aplikacija ostaje read-only dok se to sigurnosno ne pregleda | #100 |-| „Monitor this machine": „Check every 15 s · change later in Admin" | „Checks every minute at first · change it once it reports" | Novi server počinje s intervalom od 60 s; interval se mijenja na Overviewu | #97 |+| „Monitor this machine": „Check every 15 s · change later in Admin" | „Checks every minute at first · change it once it reports" | Novi server počinje s intervalom od 60 s; interval se mijenja na Overviewu ili u Adminu | – || „Another machine": jedna `docker run` naredba | Dvije `docker run` naredbe (collector i docker-proxy) | Collector namjerno nema Docker socket; drži ga zaseban read-only proxy | – || „Another machine": polje samo za ime | Dodano je i polje za adresu na koju se novi stroj javlja | Bez ispravne adrese naredba ne radi (localhost, VPN) | – |-| Brisanje servera nije na Overviewu | „Remove this server" je u System tabu | Admin još nema pravi popis servera | #97 |+| Brisanje servera nije na Overviewu | „Remove this server" je i u System tabu, uz Admin → Servers | Zgodno je imati ga uz podatke servera | – || Kartica „What you'll get": „Kept for a year as 30-minute points" | „Kept as rolled-up points for as long as you set in Admin" | Zadržavanje je postavka, a točke nisu uvijek 30-minutne | – || „The agent only sends data to your model provider when it diagnoses an incident" | „…when you ask it something" | Automatska dijagnoza ne postoji | #93 |@@ -52,7 +52,7 @@ su anotacije dizajna i namjerno nisu ugrađeni.| System: `/var/lib/docker` s uređajem i tipom `overlay2` | Uređaj „—", tip „images + cache" | `/system/df` je namjerno sveden na šest brojeva | – || Events: „Events are kept for 90 days, then only alerts are kept for a year" | „Events are kept for N days" (postavka zadržavanja) | Ne postoji zasebno pravilo za alerte | #58 || Events: „watchtower pulled new images…", „restarted by a user through Portainer" | Generičke rečenice („now run a different image build") | Infradeck ne zna tko je pokrenuo promjenu | – |-| Events: „alert sent to ntfy and email" | Ne piše kamo je alert poslan | Nema kanala obavijesti | #50 |+| Events: „alert sent to ntfy and email" | Ne piše kamo je alert poslan | Ne bilježi se slanje po kanalu | – |## Prijava i registracija (`09-login.pdf`, `mobile/06-login.pdf`)diff --git a/README.md b/README.mdindex 1716063..f819050 100644--- a/README.md+++ b/README.md@@ -140,8 +140,8 @@ docker compose down # stop (data volumes are kep```To try **Connect a server** on the same machine, set `COLLECTOR_IMAGE` and-`DOCKER_PROXY_IMAGE` in `.env` to `homelab-collector:latest` and-`homelab-docker-proxy:latest` (the images Compose just built). Other machines+`DOCKER_PROXY_IMAGE` in `.env` to `infradeck-collector:latest` and+`infradeck-docker-proxy:latest` (the images Compose just built). Other machinesneed published images; see [Publishing the collector images](docs/deployment.md#publishing-the-collector-images).## Deploying on a server@@ -169,6 +169,7 @@ Full documentation is in the [`docs/`](docs/README.md) folder:| [The dashboard and system health](docs/dashboard.md) | Fleet cards, storage, the Network and System rows, the optional system helper. || [Alerts and incidents](docs/alerts.md) | Every rule and its default thresholds. || [Accounts and two-factor sign-in](docs/accounts.md) | Roles, passwords, authenticator codes, recovery and reset. |+| [The containers](docs/containers.md) | What each container (backend, PostgreSQL, Redis, collector, Docker proxy, helpers) does and why it is there. || [Deploying](docs/deployment.md), [Adding servers](docs/adding-servers.md), [Configuration](docs/configuration.md), [Troubleshooting](docs/troubleshooting.md) | Installing, running and fixing it. || [Development](docs/development.md), [Database schema](docs/database.md), [API overview](docs/api.md), [Homie assistant](docs/assistant.md) | For contributors. |diff --git a/SECURITY.md b/SECURITY.mdindex 62e7204..d9215e6 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -342,7 +342,7 @@ The collector's network checks are passive or opt-in, and add no privileges:looked up, by their full ID.- **The internet check is off by default.** When enabled it only opens a TCP connection and looks thename up, sending nothing. Its targets come from the collector's own environment- (`HOMELAB_CONNECTIVITY_TARGETS`), never from the dashboard, so a compromised dashboard can't point+ (`INFRADECK_CONNECTIVITY_TARGETS`), never from the dashboard, so a compromised dashboard can't pointprobes at anything. Targets are limited to five hostnames or IPv4 addresses, and a probe cannot delaya check-in beyond a fixed deadline.- **Unreadable never means closed.** If any network table can't be read, or is too large to readdiff --git a/SETUP_DATABASES.md b/SETUP_DATABASES.mdindex 464a37e..569acd8 100644--- a/SETUP_DATABASES.md+++ b/SETUP_DATABASES.md@@ -16,18 +16,18 @@ docker compose up -d## PostgreSQL credentials-- Database: `homelab`-- User: `homelab`-- Password: `homelab_dev`+- Database: `infradeck`+- User: `infradeck`+- Password: `infradeck_dev`## Quick checks```bash# PostgreSQL readiness-docker compose exec postgres pg_isready -U homelab -d homelab+docker compose exec postgres pg_isready -U infradeck -d infradeck# Check the users table-docker compose exec postgres psql -U homelab -d homelab -c "SELECT id, email, role FROM users;"+docker compose exec postgres psql -U infradeck -d infradeck -c "SELECT id, email, role FROM users;"# Redis pingdocker compose exec redis redis-cli ping@@ -45,3 +45,29 @@ For a simple starter, Redis can handle:It is not the place for your main relational data model.For users, roles, permissions, and long-term analytics, PostgreSQL should still be the source of truth.+++## Upgrading an install from before the rename to Infradeck++Older installs created the database and its user as `homelab`. The compose files now default to `infradeck`,+so after `git pull` either keep the old names by adding these two lines to `.env`:++```+POSTGRES_DB=homelab+POSTGRES_USER=homelab+```++or rename them once (back up first; the backend and collector must be stopped so nothing is connected):++```bash+docker compose exec -T postgres pg_dump -U homelab -d homelab -Fc > before-rename.dump+docker compose stop backend collector+docker compose exec -T postgres psql -U homelab -d postgres -c "CREATE ROLE infradeck_rename SUPERUSER LOGIN;" -c "ALTER DATABASE homelab RENAME TO infradeck;"+docker compose exec -T postgres psql -U infradeck_rename -d postgres -c "ALTER ROLE homelab RENAME TO infradeck;"+docker compose exec -T postgres psql -U infradeck -d postgres -c "DROP ROLE infradeck_rename;"+docker compose up -d --build+```++The password stays the same (it is stored as SCRAM, which a rename keeps). Redis keys under the old `homelab:` prefix+move to `infradeck:` on the backend's next start, so nobody is signed out. Collectors already installed on other+machines keep working: their `HOMELAB_*` variables and their old state folder are still read.diff --git a/TESTS.md b/TESTS.mdindex b6962d5..fd2f135 100644--- a/TESTS.md+++ b/TESTS.md@@ -500,7 +500,7 @@ validation of container data, because everything a collector reports is untruste| `test_only_latest_claimant_is_dashboard_host_and_flag_can_be_dropped` | Only one machine can be the dashboard host at a time, and a collector that stops claiming it loses the flag. || `test_history_returns_recent_samples_oldest_first` | The charts' history contains only the requested window, for the right server, in time order. || `test_history_of_unknown_server_is_404` | History for an unknown server is a clean 404. |-| `test_collector_sends_flag_only_when_configured` | The collector marks itself as the dashboard host only when `HOMELAB_DASHBOARD_HOST` is set. |+| `test_collector_sends_flag_only_when_configured` | The collector marks itself as the dashboard host only when `INFRADECK_DASHBOARD_HOST` is set. || `test_overview_lists_only_containers_from_latest_check_in` | The container list shows what the latest check-in reported, not every container ever seen. || `test_overview_lists_no_containers_when_latest_check_in_had_none` | If the latest check-in had no containers, none are shown even though older samples exist. || `test_overview_counts_active_alerts_per_server` | Each server's incident badge counts only its own open incidents, not resolved ones. |diff --git a/collector-compose.yml b/collector-compose.ymlindex a9bf6c4..5bded05 100644--- a/collector-compose.yml+++ b/collector-compose.yml@@ -1,5 +1,5 @@# Collector-only stack that builds the images locally, an alternative to the signed images the compose-# command from the dashboard (Connect a server) installs. Set HOMELAB_API_URL (e.g. in a .env next to+# command from the dashboard (Connect a server) installs. Set INFRADECK_API_URL (e.g. in a .env next to# this file) and run:# docker compose -f collector-compose.yml up -d --build# The server then appears on the dashboard under "New servers detected"; click@@ -10,21 +10,21 @@ services:build:context: .dockerfile: docker/collector.Dockerfile- image: ${HOMELAB_COLLECTOR_IMAGE:-homelab-collector:latest}- container_name: homelab-collector+ image: ${INFRADECK_COLLECTOR_IMAGE:-infradeck-collector:latest}+ container_name: infradeck-collectorrestart: unless-stoppedenvironment:- HOMELAB_API_URL: ${HOMELAB_API_URL:?Set HOMELAB_API_URL to your backend address}- HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}- HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}+ INFRADECK_API_URL: ${INFRADECK_API_URL:?Set INFRADECK_API_URL to your backend address}+ INFRADECK_ENROLL_KEY: ${INFRADECK_ENROLL_KEY:-}+ INFRADECK_SERVER_NAME: ${INFRADECK_SERVER_NAME:-}# Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.- HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}+ INFRADECK_CONNECTIVITY_TARGETS: ${INFRADECK_CONNECTIVITY_TARGETS:-}# Docker data comes through the read-only proxy; the collector has no Docker socket.- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock+ INFRADECK_DOCKER_HOST: /run/docker-proxy/docker.sockvolumes:- /proc:/host/proc:ro- /:/hostfs:ro- - collector_state:/var/lib/homelab-collector+ - collector_state:/var/lib/infradeck-collector# Summary from the optional system helper (read-only; empty unless that profile runs).- system_events:/helper:ro- docker_proxy_socket:/run/docker-proxy:ro@@ -36,14 +36,14 @@ services:- no-new-privileges:true# The only container that mounts the Docker socket (a mount flag can't make it read-only).- # It answers a handful of read requests and nothing else. It has no network at all: the collector+ # It answers six kinds of read request and nothing else. It has no network at all: the collector# reaches it through a Unix socket in a volume only the two of them share. See SECURITY.md.docker-proxy:build:context: .dockerfile: docker/docker-proxy.Dockerfile- image: homelab-docker-proxy:latest- container_name: homelab-docker-proxy+ image: infradeck-docker-proxy:latest+ container_name: infradeck-docker-proxyrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -64,8 +64,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-system-helper+ image: infradeck-system-helper:latest+ container_name: infradeck-system-helperrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -89,8 +89,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-port-owners+ image: infradeck-system-helper:latest+ container_name: infradeck-port-ownersrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -101,7 +101,7 @@ services:- no-new-privileges:true- apparmor=unconfinedenvironment:- HOMELAB_HELPER_MODE: port-owners+ INFRADECK_HELPER_MODE: port-ownersvolumes:- /proc:/host/proc:ro- system_events:/outdiff --git a/compose.yml b/compose.ymlindex ce09ce6..2758d29 100644--- a/compose.yml+++ b/compose.yml@@ -2,25 +2,25 @@services:postgres:image: postgres:16-alpine- container_name: homelab-postgres+ container_name: infradeck-postgresrestart: unless-stoppednetworks: [data]environment:- POSTGRES_DB: homelab- POSTGRES_USER: homelab+ POSTGRES_DB: ${POSTGRES_DB:-infradeck}+ POSTGRES_USER: ${POSTGRES_USER:-infradeck}POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}volumes:- postgres_data:/var/lib/postgresql/data- ./docker/postgres/init:/docker-entrypoint-initdb.dhealthcheck:- test: ["CMD-SHELL", "pg_isready -U homelab -d homelab"]+ test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-infradeck} -d $${POSTGRES_DB:-infradeck}"]interval: 10stimeout: 5sretries: 5redis:image: redis:7-alpine- container_name: homelab-redis+ container_name: infradeck-redisrestart: unless-stoppednetworks: [data]# Needs a password: Redis holds the login sessions, so nothing that can merely reach it on the network@@ -40,12 +40,12 @@ services:build:context: .dockerfile: docker/backend.Dockerfile- container_name: homelab-backend- image: homelab-backend:latest+ container_name: infradeck-backend+ image: infradeck-backend:latestrestart: unless-stoppednetworks: [data, front]environment:- DATABASE_URL: postgresql+psycopg://homelab:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/homelab+ DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-infradeck}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/${POSTGRES_DB:-infradeck}REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}@redis:6379/0GEMINI_API_KEY: ${GEMINI_API_KEY:-}AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}@@ -90,26 +90,26 @@ services:build:context: .dockerfile: docker/collector.Dockerfile- image: homelab-collector:latest- container_name: homelab-collector+ image: infradeck-collector:latest+ container_name: infradeck-collectorrestart: unless-stoppednetworks: [front]environment:- HOMELAB_API_URL: http://backend:8000+ INFRADECK_API_URL: http://backend:8000# Marks this collector as the machine running the dashboard (the charts at the top).- HOMELAB_DASHBOARD_HOST: "true"+ INFRADECK_DASHBOARD_HOST: "true"# Nothing to configure: this machine shows up under "New servers detected"# on the dashboard. An optional enrollment key skips that approval.- HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}- HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}+ INFRADECK_ENROLL_KEY: ${INFRADECK_ENROLL_KEY:-}+ INFRADECK_SERVER_NAME: ${INFRADECK_SERVER_NAME:-}# Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.- HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}+ INFRADECK_CONNECTIVITY_TARGETS: ${INFRADECK_CONNECTIVITY_TARGETS:-}# Docker data comes through the read-only proxy; the collector has no Docker socket.- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock+ INFRADECK_DOCKER_HOST: /run/docker-proxy/docker.sockvolumes:- /proc:/host/proc:ro- /:/hostfs:ro- - collector_state:/var/lib/homelab-collector+ - collector_state:/var/lib/infradeck-collector# Summary from the optional system helper (read-only; empty unless that profile runs).- system_events:/helper:ro- docker_proxy_socket:/run/docker-proxy:ro@@ -124,14 +124,14 @@ services:condition: service_healthy# The only container that mounts the Docker socket (a mount flag can't make it read-only).- # It answers four read requests and nothing else. It has no network at all: the collector+ # It answers six kinds of read request and nothing else. It has no network at all: the collector# reaches it through a Unix socket in a volume only the two of them share. See SECURITY.md.docker-proxy:build:context: .dockerfile: docker/docker-proxy.Dockerfile- image: homelab-docker-proxy:latest- container_name: homelab-docker-proxy+ image: infradeck-docker-proxy:latest+ container_name: infradeck-docker-proxyrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -152,8 +152,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-system-helper+ image: infradeck-system-helper:latest+ container_name: infradeck-system-helperrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -177,8 +177,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-port-owners+ image: infradeck-system-helper:latest+ container_name: infradeck-port-ownersrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -189,7 +189,7 @@ services:- no-new-privileges:true- apparmor=unconfinedenvironment:- HOMELAB_HELPER_MODE: port-owners+ INFRADECK_HELPER_MODE: port-ownersvolumes:- /proc:/host/proc:ro- system_events:/out@@ -200,7 +200,7 @@ services:dockerfile: docker/frontend.Dockerfileargs:VITE_API_BASE_URL: /api- container_name: homelab-frontend+ container_name: infradeck-frontendrestart: unless-stoppednetworks: [front]# Serves the dashboard and proxies /api to the backend. Reach it directly over@@ -214,7 +214,7 @@ services:# Optional public HTTPS entry point: docker compose --profile https up -dcaddy:image: caddy:2-alpine- container_name: homelab-caddy+ container_name: infradeck-caddyprofiles: ["https"]restart: unless-stoppednetworks: [front]diff --git a/docker-compose.server.yml b/docker-compose.server.ymlindex 099c913..f6203f5 100644--- a/docker-compose.server.yml+++ b/docker-compose.server.yml@@ -7,25 +7,25 @@services:postgres:image: postgres:16-alpine- container_name: homelab-postgres+ container_name: infradeck-postgresrestart: unless-stoppednetworks: [data]environment:- POSTGRES_DB: homelab- POSTGRES_USER: homelab+ POSTGRES_DB: ${POSTGRES_DB:-infradeck}+ POSTGRES_USER: ${POSTGRES_USER:-infradeck}POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}volumes:- postgres_data:/var/lib/postgresql/data- ./docker/postgres/init:/docker-entrypoint-initdb.dhealthcheck:- test: ["CMD-SHELL", "pg_isready -U homelab -d homelab"]+ test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-infradeck} -d $${POSTGRES_DB:-infradeck}"]interval: 10stimeout: 5sretries: 5redis:image: redis:7-alpine- container_name: homelab-redis+ container_name: infradeck-redisrestart: unless-stoppednetworks: [data]# Needs a password: Redis holds the login sessions, so nothing that can merely reach it on the network@@ -45,12 +45,12 @@ services:build:context: .dockerfile: docker/backend.Dockerfile- container_name: homelab-backend- image: homelab-backend:latest+ container_name: infradeck-backend+ image: infradeck-backend:latestrestart: unless-stoppednetworks: [data, front]environment:- DATABASE_URL: postgresql+psycopg://homelab:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/homelab+ DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-infradeck}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/${POSTGRES_DB:-infradeck}REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}@redis:6379/0GEMINI_API_KEY: ${GEMINI_API_KEY:-}AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}@@ -103,29 +103,29 @@ services:build:context: .dockerfile: docker/collector.Dockerfile- image: homelab-collector:latest- container_name: homelab-collector+ image: infradeck-collector:latest+ container_name: infradeck-collectorrestart: unless-stoppednetworks: [collector]environment:# Through the gate's internal listener (not published); the public listener refuses collectors.- HOMELAB_API_URL: http://collector-gate:8080/api+ INFRADECK_API_URL: http://collector-gate:8080/api# Marks this collector as the machine running the dashboard (the charts at the top).- HOMELAB_DASHBOARD_HOST: "true"+ INFRADECK_DASHBOARD_HOST: "true"# Nothing to configure: this machine shows up under "New servers detected"# on the dashboard. An optional enrollment key skips that approval.- HOMELAB_ENROLL_KEY: ${HOMELAB_ENROLL_KEY:-}- HOMELAB_SERVER_NAME: ${HOMELAB_SERVER_NAME:-}+ INFRADECK_ENROLL_KEY: ${INFRADECK_ENROLL_KEY:-}+ INFRADECK_SERVER_NAME: ${INFRADECK_SERVER_NAME:-}# Optional internet check, off when empty: comma-separated host:port targets this collector tries to reach.- HOMELAB_CONNECTIVITY_TARGETS: ${HOMELAB_CONNECTIVITY_TARGETS:-}+ INFRADECK_CONNECTIVITY_TARGETS: ${INFRADECK_CONNECTIVITY_TARGETS:-}# Docker data comes through the read-only proxy; the collector has no Docker socket.- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock- HOMELAB_CHECK_INTERVAL_SECONDS: ${HOMELAB_CHECK_INTERVAL_SECONDS:-60}- HOMELAB_MACHINE_ID: ${HOMELAB_MACHINE_ID:-}+ INFRADECK_DOCKER_HOST: /run/docker-proxy/docker.sock+ INFRADECK_CHECK_INTERVAL_SECONDS: ${INFRADECK_CHECK_INTERVAL_SECONDS:-60}+ INFRADECK_MACHINE_ID: ${INFRADECK_MACHINE_ID:-}volumes:- /proc:/host/proc:ro- /:/hostfs:ro- - collector_state:/var/lib/homelab-collector+ - collector_state:/var/lib/infradeck-collector# Summary from the optional system helper (read-only; empty unless that profile runs).- system_events:/helper:ro- docker_proxy_socket:/run/docker-proxy:ro@@ -146,7 +146,7 @@ services:# published ports bypass ufw and similar firewalls, so never bind it to 0.0.0.0 and rely on those.collector-gate:image: nginx:alpine- container_name: homelab-collector-gate+ container_name: infradeck-collector-gaterestart: unless-stoppednetworks: [front, collector]ports:@@ -166,14 +166,14 @@ services:condition: service_healthy# The only container that mounts the Docker socket (a mount flag can't make it read-only).- # It answers four read requests and nothing else. It has no network at all: the collector+ # It answers six kinds of read request and nothing else. It has no network at all: the collector# reaches it through a Unix socket in a volume only the two of them share. See SECURITY.md.docker-proxy:build:context: .dockerfile: docker/docker-proxy.Dockerfile- image: homelab-docker-proxy:latest- container_name: homelab-docker-proxy+ image: infradeck-docker-proxy:latest+ container_name: infradeck-docker-proxyrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -194,8 +194,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-system-helper+ image: infradeck-system-helper:latest+ container_name: infradeck-system-helperrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -219,8 +219,8 @@ services:build:context: .dockerfile: docker/system-helper.Dockerfile- image: homelab-system-helper:latest- container_name: homelab-port-owners+ image: infradeck-system-helper:latest+ container_name: infradeck-port-ownersrestart: unless-stoppeduser: "0:0"cap_drop: [ALL]@@ -231,7 +231,7 @@ services:- no-new-privileges:true- apparmor=unconfinedenvironment:- HOMELAB_HELPER_MODE: port-owners+ INFRADECK_HELPER_MODE: port-ownersvolumes:- /proc:/host/proc:ro- system_events:/out@@ -243,7 +243,7 @@ services:args:VITE_API_BASE_URL: /apiVITE_LIVE_GRAPH_REFRESH_INTERVAL_SECONDS: ${LIVE_GRAPH_REFRESH_INTERVAL_SECONDS:-3}- container_name: homelab-frontend+ container_name: infradeck-frontendrestart: unless-stopped# Serves the dashboard and proxies /api to the backend; Traefik publishes it# over HTTPS on your domain. The plain-HTTP port is bound to localhost only@@ -261,10 +261,10 @@ services:# All values come from .env: DASHBOARD_DOMAIN (required), TRAEFIK_ROUTER, TRAEFIK_ENTRYPOINT,# TRAEFIK_CERT_RESOLVER and TRAEFIK_NETWORK (defaults shown).- traefik.docker.network=${TRAEFIK_NETWORK:-traefik_default}- - traefik.http.routers.${TRAEFIK_ROUTER:-homelab}.rule=Host(`${DASHBOARD_DOMAIN:?Set DASHBOARD_DOMAIN in .env}`)- - traefik.http.routers.${TRAEFIK_ROUTER:-homelab}.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}- - traefik.http.routers.${TRAEFIK_ROUTER:-homelab}.tls.certresolver=${TRAEFIK_CERT_RESOLVER:-letsencrypt}- - traefik.http.services.${TRAEFIK_ROUTER:-homelab}.loadbalancer.server.port=80+ - traefik.http.routers.${TRAEFIK_ROUTER:-infradeck}.rule=Host(`${DASHBOARD_DOMAIN:?Set DASHBOARD_DOMAIN in .env}`)+ - traefik.http.routers.${TRAEFIK_ROUTER:-infradeck}.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}+ - traefik.http.routers.${TRAEFIK_ROUTER:-infradeck}.tls.certresolver=${TRAEFIK_CERT_RESOLVER:-letsencrypt}+ - traefik.http.services.${TRAEFIK_ROUTER:-infradeck}.loadbalancer.server.port=80depends_on:backend:condition: service_healthydiff --git a/docker/collector.Dockerfile b/docker/collector.Dockerfileindex e863f4d..ae1264c 100644--- a/docker/collector.Dockerfile+++ b/docker/collector.Dockerfile@@ -4,12 +4,12 @@ FROM python:3.12-alpineWORKDIR /appCOPY src/agent/collector.py ./collector.py-ENV HOMELAB_STATE_DIR=/var/lib/homelab-collector \+ENV INFRADECK_STATE_DIR=/var/lib/infradeck-collector \HOST_PROC=/host/proc \HOST_ROOT=/hostfs \DOCKER_SOCKET_PATH=/var/run/docker.sock \PYTHONUNBUFFERED=1-VOLUME ["/var/lib/homelab-collector"]+VOLUME ["/var/lib/infradeck-collector"]CMD ["python", "/app/collector.py"]diff --git a/docker/docker-proxy.Dockerfile b/docker/docker-proxy.Dockerfileindex 8efc01f..9bf4699 100644--- a/docker/docker-proxy.Dockerfile+++ b/docker/docker-proxy.Dockerfile@@ -6,7 +6,7 @@ WORKDIR /appCOPY src/agent/docker_proxy.py ./docker_proxy.pyENV DOCKER_SOCKET_PATH=/var/run/docker.sock \- HOMELAB_DOCKER_PROXY_SOCKET=/run/docker-proxy/docker.sock \+ INFRADECK_DOCKER_PROXY_SOCKET=/run/docker-proxy/docker.sock \PYTHONUNBUFFERED=1USER 0:0diff --git a/docker/system-helper.Dockerfile b/docker/system-helper.Dockerfileindex 240454b..17e45a5 100644--- a/docker/system-helper.Dockerfile+++ b/docker/system-helper.Dockerfile@@ -6,8 +6,8 @@ WORKDIR /appCOPY src/agent/system_helper.py ./system_helper.pyENV HOST_PROC=/proc \- HOMELAB_WTMP_PATH=/host/wtmp \- HOMELAB_HELPER_OUTPUT=/out/system.json \+ INFRADECK_WTMP_PATH=/host/wtmp \+ INFRADECK_HELPER_OUTPUT=/out/system.json \PYTHONUNBUFFERED=1# Nothing to write to except the shared output volume.diff --git a/docs/README.md b/docs/README.mdindex d262af9..1aca812 100644--- a/docs/README.md+++ b/docs/README.md@@ -17,6 +17,7 @@ The [README](../README.md) is the short version: what the project is, how to sta| Page | What is in it ||---|---|+| [The containers and why each one exists](containers.md) | Every container in the stack: what it does, how it works, why it is separate, and what happens when it stops. || [Deploying on a server](deployment.md) | The server stack behind Traefik, the VPN collector gate, publishing the collector images, updating, running without Traefik. || [Adding servers](adding-servers.md) | **Connect a server**, what its command does, how registration and approval work, networking. || [Configuration](configuration.md) | Every `.env` setting for the stack, the collector and the frontend build. |diff --git a/docs/adding-servers.md b/docs/adding-servers.mdindex 0d48c89..8ca9b24 100644--- a/docs/adding-servers.md+++ b/docs/adding-servers.md@@ -15,7 +15,7 @@ enrollment key are admin-only.compose plugin, and a route to the address above (the VPN).4. Within a few seconds the machine appears under **New servers detected** with a**JOIN TOKEN** badge and a pairing code (also printed in- `docker logs homelab-collector`). Click **Add**. It starts reporting on its+ `docker logs infradeck-collector`). Click **Add**. It starts reporting on itsnext check, without a restart.<ui - The Connect a server panel: the address field, the Generate command button with its single-use / expires note, and the copyable compose command>@@ -24,28 +24,28 @@ enrollment key are admin-only.The machine running the dashboard is added the same way (its collector startswith the stack, over the gate's internal listener). That collector has-`HOMELAB_DASHBOARD_HOST=true` set in the Compose files, which makes it the machine+`INFRADECK_DASHBOARD_HOST=true` set in the Compose files, which makes it the machineshown in the charts at the top of the dashboard and first in the server list.Collectors installed on other machines don't set it.## What the command does-It starts a small compose project named `homelab-collector` from the YAML on its+It starts a small compose project named `infradeck-collector` from the YAML on itsstandard input (shortened here):```bash-docker compose -p homelab-collector -f - up -d <<'EOF'+docker compose -p infradeck-collector -f - up -d <<'EOF'services:collector:image: ghcr.io/…/collector@sha256:…environment:- HOMELAB_API_URL: http://10.8.0.1:8081/api- HOMELAB_JOIN_TOKEN: hlj_…- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock+ INFRADECK_API_URL: http://10.8.0.1:8081/api+ INFRADECK_JOIN_TOKEN: hlj_…+ INFRADECK_DOCKER_HOST: /run/docker-proxy/docker.sockvolumes:- /proc:/host/proc:ro- /:/hostfs:ro- - collector_state:/var/lib/homelab-collector+ - collector_state:/var/lib/infradeck-collector- docker_proxy_socket:/run/docker-proxy:rocap_drop: [ALL]read_only: true@@ -62,8 +62,8 @@ EOF| Part | Purpose ||---|---|-| `HOMELAB_API_URL` | Where the collector gate is. |-| `HOMELAB_JOIN_TOKEN` | Proves an admin asked this machine to join. Single use, expires. |+| `INFRADECK_API_URL` | Where the collector gate is. |+| `INFRADECK_JOIN_TOKEN` | Proves an admin asked this machine to join. Single use, expires. || `image: …@sha256:…` | Signed images pinned by digest. No code is downloaded from the dashboard. || `/proc:/host/proc:ro` | Host CPU, memory, load, network, uptime, boot ID, OOM counter and kernel flags. || `/:/hostfs:ro` | Disk usage of every mounted filesystem, hostname, OS name and `/etc/machine-id`. |@@ -74,8 +74,8 @@ EOFTo remove a collector completely:```bash-docker rm -f homelab-collector homelab-docker-proxy-docker volume rm homelab-collector_collector_state homelab-collector_docker_proxy_socket+docker rm -f infradeck-collector infradeck-docker-proxy+docker volume rm infradeck-collector_collector_state infradeck-collector_docker_proxy_socket```## How registration works@@ -101,11 +101,11 @@ docker volume rm homelab-collector_collector_state homelab-collector_docker_proxAlternatives:- **Enrollment key (no approval step):** for scripted installs, generate a key- under **Connect a server → Advanced** and add `HOMELAB_ENROLL_KEY: <key>` to the+ under **Connect a server → Advanced** and add `INFRADECK_ENROLL_KEY: <key>` to thecollector's environment. Only a hash of the key is stored; rotating or revokingit does not affect servers that are already connected.- **Compose from the repository:** copy the repository to the machine, set- `HOMELAB_API_URL` (and `HOMELAB_JOIN_TOKEN`) in a `.env` next to+ `INFRADECK_API_URL` (and `INFRADECK_JOIN_TOKEN`) in a `.env` next to`collector-compose.yml`, and run`docker compose -f collector-compose.yml up -d --build`. This builds the imageslocally instead of pulling them.diff --git a/docs/configuration.md b/docs/configuration.mdindex 24069ff..8a0885e 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -24,7 +24,7 @@| `BACKEND_PORT` | `8060` | Development stack only: the host port (on `127.0.0.1`) where the backend is published for debugging. The server stack publishes no backend port. || `FRONTEND_PORT` | `5173` | Dashboard port on the host. || `DASHBOARD_DOMAIN` | *(required on a server)* | Domain of the dashboard, without `https://` (server file). |-| `TRAEFIK_ENTRYPOINT` / `TRAEFIK_CERT_RESOLVER` / `TRAEFIK_NETWORK` / `TRAEFIK_ROUTER` | `websecure` / `letsencrypt` / `traefik_default` / `homelab` | Your Traefik names (server file). |+| `TRAEFIK_ENTRYPOINT` / `TRAEFIK_CERT_RESOLVER` / `TRAEFIK_NETWORK` / `TRAEFIK_ROUTER` | `websecure` / `letsencrypt` / `traefik_default` / `infradeck` | Your Traefik names (server file). || `CORS_ORIGINS` | `http://localhost:5173` (dev), `https://<DASHBOARD_DOMAIN>` (server file) | Comma-separated origins. Also the allow-list for the cross-site request check: a state-changing request from any other origin is refused unless its `Origin` matches the `Host` the dashboard was reached on. Add your dashboard URL if something in front rewrites `Host`. || `LOGIN_RATE_LIMIT` / `LOGIN_RATE_WINDOW_SECONDS` | `5` / `60` | Login attempts per IP and per email. || `REGISTER_RATE_LIMIT` / `REGISTER_RATE_WINDOW_SECONDS` | `3` / `3600` | Registrations per IP. |@@ -33,33 +33,33 @@| `COLLECTOR_IMAGE` / `DOCKER_PROXY_IMAGE` | empty | Digest-pinned images remote machines install. **Connect a server** needs both. || `JOIN_TOKEN_TTL_SECONDS` | `900` | How long a generated join token stays valid. || `COLLECTOR_ACCESS` | `open` (dev), `strict` (server file) | `strict` makes the backend answer collector endpoints only when they came through the collector gate. |-| `HOMELAB_ENROLL_KEY` | empty | Lets the stack's own collector skip approval. |-| `HOMELAB_SERVER_NAME` | host's hostname | Name shown for the stack's own machine. |+| `INFRADECK_ENROLL_KEY` | empty | Lets the stack's own collector skip approval. |+| `INFRADECK_SERVER_NAME` | host's hostname | Name shown for the stack's own machine. || `DOMAIN` | `localhost` | Domain for the optional Caddy profile. || `COMPOSE_FILE` | – | Set to `docker-compose.server.yml` on a server so plain `docker compose` uses it. || `LIVE_GRAPH_REFRESH_INTERVAL_SECONDS` | `3` | How often the dashboard refreshes (server file; applied when the frontend image is built). |-| `HOMELAB_CHECK_INTERVAL_SECONDS` | `60` | Initial check interval of the stack's own collector (server file); the dashboard setting overrides it. |+| `INFRADECK_CHECK_INTERVAL_SECONDS` | `60` | Initial check interval of the stack's own collector (server file); the dashboard setting overrides it. |## Collector (environment of the collector container)| Variable | Default | Description ||---|---|---|-| `HOMELAB_API_URL` | `http://localhost:8060` | Dashboard API address, e.g. `https://dashboard.example.com/api`. |-| `HOMELAB_JOIN_TOKEN` | empty | Single-use token from **Connect a server**; required over the VPN listener. |-| `HOMELAB_ENROLL_KEY` | empty | Join immediately instead of waiting for approval. |-| `HOMELAB_SERVER_NAME` | host's `/etc/hostname` | Name shown on the dashboard. |-| `HOMELAB_CONNECTIVITY_TARGETS` | empty (check off) | Optional internet check: up to 5 comma-separated `host:port` targets (hostnames or IPv4), e.g. `1.1.1.1:443,9.9.9.9:443`. The collector opens a TCP connection and looks the name up; it sends nothing. Set on each collector; the dashboard cannot set it. |-| `HOMELAB_STATE_DIR` | `/var/lib/homelab-collector` | Where the token is saved (mount a volume here). |-| `HOMELAB_MACHINE_ID` | host's `/etc/machine-id` | Identity used to recognise reinstalled machines. |-| `HOMELAB_DASHBOARD_HOST` | empty | `true` marks this machine as the one running the dashboard (set in the Compose files for the stack's own collector; leave it unset elsewhere). |-| `HOMELAB_SERVER_ID` / `HOMELAB_COLLECTOR_TOKEN` | empty | Explicit credentials (legacy; overrides everything else). |+| `INFRADECK_API_URL` | `http://localhost:8060` | Dashboard API address, e.g. `https://dashboard.example.com/api`. |+| `INFRADECK_JOIN_TOKEN` | empty | Single-use token from **Connect a server**; required over the VPN listener. |+| `INFRADECK_ENROLL_KEY` | empty | Join immediately instead of waiting for approval. |+| `INFRADECK_SERVER_NAME` | host's `/etc/hostname` | Name shown on the dashboard. |+| `INFRADECK_CONNECTIVITY_TARGETS` | empty (check off) | Optional internet check: up to 5 comma-separated `host:port` targets (hostnames or IPv4), e.g. `1.1.1.1:443,9.9.9.9:443`. The collector opens a TCP connection and looks the name up; it sends nothing. Set on each collector; the dashboard cannot set it. |+| `INFRADECK_STATE_DIR` | `/var/lib/infradeck-collector` | Where the token is saved (mount a volume here). |+| `INFRADECK_MACHINE_ID` | host's `/etc/machine-id` | Identity used to recognise reinstalled machines. |+| `INFRADECK_DASHBOARD_HOST` | empty | `true` marks this machine as the one running the dashboard (set in the Compose files for the stack's own collector; leave it unset elsewhere). |+| `INFRADECK_SERVER_ID` / `INFRADECK_COLLECTOR_TOKEN` | empty | Explicit credentials (legacy; overrides everything else). || `HOST_PROC` / `HOST_ROOT` | `/host/proc` and `/hostfs` if mounted, else `/proc` and `/` | Where the host's `/proc` and filesystem are. |-| `HOMELAB_DOCKER_HOST` | empty | Socket of the read-only Docker proxy, e.g. `/run/docker-proxy/docker.sock`. Preferred over `DOCKER_SOCKET_PATH`. |-| `DOCKER_SOCKET_PATH` | `/var/run/docker.sock` | Direct Docker socket, used only when `HOMELAB_DOCKER_HOST` is unset (not recommended). Without any Docker access only host metrics are sent. |-| `HOMELAB_HELPER_FILE` | `/helper/system.json` | Where the optional system helper's summary is read from. |+| `INFRADECK_DOCKER_HOST` | empty | Socket of the read-only Docker proxy, e.g. `/run/docker-proxy/docker.sock`. Preferred over `DOCKER_SOCKET_PATH`. |+| `DOCKER_SOCKET_PATH` | `/var/run/docker.sock` | Direct Docker socket, used only when `INFRADECK_DOCKER_HOST` is unset (not recommended). Without any Docker access only host metrics are sent. |+| `INFRADECK_HELPER_FILE` | `/helper/system.json` | Where the optional system helper's summary is read from. |-The system helper has `HOMELAB_HELPER_INTERVAL_SECONDS` (default `30`, minimum-`10`); the Docker proxy listens on `HOMELAB_DOCKER_PROXY_SOCKET` and forwards to+The system helper has `INFRADECK_HELPER_INTERVAL_SECONDS` (default `30`, minimum+`10`); the Docker proxy listens on `INFRADECK_DOCKER_PROXY_SOCKET` and forwards to`DOCKER_SOCKET_PATH`. Both are set in their images and rarely need changing.The check interval is set per server on the dashboard; collectors pick it updiff --git a/docs/containers.md b/docs/containers.mdnew file mode 100644index 0000000..bb1c20e--- /dev/null+++ b/docs/containers.md@@ -0,0 +1,336 @@+[← Documentation](README.md)++# The containers and why each one exists++Infradeck runs as a handful of small containers rather than one big one. Each has one job and only the+access that job needs. This page goes through them one by one: what it does, how it works, why it is a+separate container, and what happens when it stops.++For the exact permissions of each piece and the limits of each protection, see [SECURITY.md](../SECURITY.md).+For the settings, see [Configuration](configuration.md).++## At a glance++| Container | Image | Runs on | Required? | Job |+|---|---|---|---|---|+| `infradeck-frontend` | built from `docker/frontend.Dockerfile` (nginx) | dashboard machine | yes | Serves the web app and passes `/api` to the backend. |+| `infradeck-backend` | built from `docker/backend.Dockerfile` (Python, FastAPI) | dashboard machine | yes | The API: sign-in, metrics intake, alerts, statistics, notifications, the assistant. |+| `infradeck-postgres` | `postgres:16-alpine` | dashboard machine | yes | Everything that must be kept: accounts, servers, metric history, incidents, settings. |+| `infradeck-redis` | `redis:7-alpine` | dashboard machine | yes | Short-lived state: sign-in sessions, rate-limit counters, pending two-factor logins, a small cache. |+| `infradeck-collector` | built from `docker/collector.Dockerfile` | every monitored machine | yes, one per machine | Reads the machine's CPU, memory, disks, network and containers and sends them to the backend. |+| `infradeck-docker-proxy` | built from `docker/docker-proxy.Dockerfile` | every monitored machine | yes, next to each collector | The only container with the Docker socket; answers six read-only questions. |+| `infradeck-collector-gate` | `nginx:alpine` | dashboard machine, server stack only | yes in `docker-compose.server.yml` | The only door to the collector endpoints, published on your VPN address. |+| `infradeck-system-helper` | built from `docker/system-helper.Dockerfile` | any monitored machine | optional (`--profile system-events`) | Reads the kernel log and wtmp: OOM kills, kernel errors, crash vs clean shutdown. |+| `infradeck-port-owners` | same image as the system helper | any monitored machine | optional (`--profile port-owners`) | Names the process behind each listening port in the Network tab. |+| `infradeck-caddy` | `caddy:2-alpine` | dashboard machine, `compose.yml` only | optional (`--profile https`) | HTTPS with an automatic Let's Encrypt certificate when there is no Traefik. |++A remote server you add with **Connect a server** runs only the collector-side containers: the+collector, the Docker proxy, and the optional helpers ([collector-compose.yml](../collector-compose.yml)).+The dashboard machine runs everything, because it monitors itself as well.++## How they fit together++```+ browser+ │ HTTPS (Traefik or Caddy) or plain HTTP on the LAN+ ▼+ ┌─────────────────┐+ │ frontend │ nginx: web app + /api → backend+ └────────┬────────┘+ │ network "front"+ remote collectors ▼+ over VPN ──► collector-gate ──► ┌─────────────────┐+ │ backend │+ local collector ──► gate :8080 ►│ FastAPI │+ └───┬─────────┬───┘+ │ │ network "data" (internal, no route out)+ ▼ ▼+ postgres redis+++ On every monitored machine:++ /proc, / (read-only) ──► collector ──► HTTPS to the backend (through the gate)+ ▲ ▲+ Unix socket in a volume │ │ JSON file in a volume+ │ │+ docker-proxy system-helper / port-owners+ │+ /var/run/docker.sock+```++Three Docker networks keep each container to what it needs:++- **`data`** is `internal: true`: it has no route to the outside. Only the backend, PostgreSQL and Redis+ are on it, so nothing but the backend can talk to the databases, and the databases can't reach the+ internet.+- **`front`** connects the frontend, the backend and the gate.+- **`collector`** (server stack) holds only the local collector and the gate, so the collector can reach+ the gate and nothing else.++The Docker proxy, the system helper and the port-owners helper have **no network at all**+(`network_mode: none`). They talk to the collector only through files and a Unix socket in shared volumes.++---++## infradeck-frontend++**What it does.** Serves the dashboard (a React app built with Vite) and forwards every request under+`/api/` to the backend.++**How it works.** The image is built in two stages: Node builds the app into static files, then only+those files are copied into a plain `nginx:alpine` image. Node and the source code are not in the+running container. nginx sets the security headers (Content-Security-Policy, Permissions-Policy and+others) and proxies `/api/` to `backend:8000`. On the server stack it uses+[`docker/nginx.strict.conf`](../docker/nginx.strict.conf), which additionally **refuses** the collector+endpoints: on the public side nobody can register a collector or send metrics.++**Why this approach.**+- *One address for the app and the API.* The browser loads the page and calls the API on the same origin,+ so the sign-in cookie can be `SameSite` and `HttpOnly`, and no cross-origin (CORS) exceptions are+ needed.+- *The backend is never exposed directly.* Only nginx is published; the backend's port is bound to+ `127.0.0.1` (development) or not published at all (server).+- *nginx is better at serving files than Python.* Static files, compression and caching are what nginx+ does best, and the backend stays focused on the API.++**If it stops.** The dashboard can't be opened. Collectors are unaffected on the server stack (they go+through the gate); on the development stack the local collector talks to the backend directly.++## infradeck-backend++**What it does.** The whole application logic:++- sign-in, sessions, two-factor codes, roles, invites, API tokens;+- registering collectors and receiving their check-ins (`/monitoring/metrics/ingest`);+- the alert rules, incidents and notification channels (email/webhook, quiet hours);+- statistics, rollups (summarised history) and retention;+- the optional Homie assistant, which talks to Gemini when `GEMINI_API_KEY` is set.++**How it works.** A FastAPI app run by uvicorn on port 8000. At startup it creates any missing tables and+columns in PostgreSQL, moves old Redis keys to the current prefix, and prints the first-run setup token+if no account exists yet. Two background threads run inside it: one marks servers offline when their+collector stops checking in, the other sends notifications for opened and resolved incidents.+`GET /health` reports whether PostgreSQL and Redis answer; Docker's healthcheck uses it, and the other+containers wait for it before they start.++**Why this approach.**+- *Python* because the collector and helpers are Python too, so validation and parsing code is shared and+ understood the same way on both sides.+- *FastAPI* validates every request against a typed model before any code sees it. That matters here,+ because collectors on remote machines are treated as untrusted input.+- *One process, no separate worker container.* The background jobs are small and periodic; a separate+ queue and worker would add two more containers for no gain at homelab scale.+- *Stateless.* Everything the backend keeps lives in PostgreSQL or Redis, so the container can be rebuilt+ or restarted at any time without losing anything.++**If it stops.** The dashboard shows errors, and collectors keep retrying until it is back. Check-ins sent+while it was down are lost (the collector does not queue them), so the history has a gap.++## infradeck-postgres++**What it does.** Stores everything that must survive a restart:++- users, roles, preferences, API tokens, invites, notification channels;+- servers and their system information, pending (not yet approved) collectors;+- every metric sample (host and per-container) and the summarised rollups for long ranges;+- incidents and their history, alert rule settings, global settings.++The full list of tables is in [Database schema](database.md).++**How it works.** The official `postgres:16-alpine` image with its data in the `postgres_data` volume.+On the very first start, [`docker/postgres/init/`](../docker/postgres/init) creates the users table; the+backend creates and upgrades everything else itself at startup. The healthcheck (`pg_isready`) holds the+backend back until the database accepts connections. The container is on the internal `data` network+only and publishes no port.++**Why this approach.**+- *Many writers at once.* Every collector checks in every minute while the background threads and+ users read and write at the same time. PostgreSQL handles concurrent writes properly; SQLite locks the+ whole file for each write. (The tests do use SQLite, because they run in one process.)+- *Time-series queries.* Statistics group, average and take maximums over millions of samples;+ PostgreSQL's indexes and planner do that well.+- *Reliability.* Transactions, crash recovery and standard backup tools (`pg_dump`, see+ [SETUP_DATABASES.md](../SETUP_DATABASES.md)).+- *Why not a dedicated time-series database (InfluxDB, Prometheus).* Accounts, incidents and metrics would+ then live in two databases with two backup routines. With rollups and retention, PostgreSQL is fast+ enough for the scale this project is built for.++**If it stops.** The backend reports `degraded` on `/health`, and almost every page and every check-in+fails until it is back. Nothing already stored is lost: it is all in the volume.++## infradeck-redis++**What it does.** Holds small, short-lived values that expire by themselves:++| Key (prefix `infradeck:`) | What it is | Lives for |+|---|---|---|+| `session:…` | A signed-in browser session. | 24 hours, or 30 days with *Remember me* |+| `user-sessions:…` | Which sessions belong to which user (the *Sessions* list on the Account page, "sign out everywhere"). | as long as the sessions |+| `2fa-pending:…` and its attempt counter | A password check that still waits for the authenticator code. | 5 minutes |+| `rate-limit:…` | Attempt counters for sign-in, registration, two-factor, password change, collector registration, invite checks, the assistant chat, notification tests and more. | the length of each window (e.g. 60 s) |+| `stats:…` | Cached fleet statistics, so the Statistics page doesn't recompute them on every load. | 60 seconds |++Session IDs and the values limited per address or email are stored only as SHA-256 digests, so a copy of+Redis doesn't hand out working sessions or a list of email addresses.++**How it works.** The official `redis:7-alpine` image with a password (`REDIS_PASSWORD`) and append-only+persistence (`--appendonly yes`) into the `redis_data` volume, so people stay signed in across a restart.+It is on the internal `data` network only and publishes no port; the backend connects with `REDIS_URL`.++**Why Redis is a required part, and why not just PostgreSQL.**+- *Sessions are checked on every request.* Each API call looks up its session. Redis answers that from+ memory in well under a millisecond and doesn't add load to the database that is busy taking check-ins.+- *Expiry is built in.* Every key above is written with a lifetime and Redis deletes it on time. In+ PostgreSQL we would need expiry columns, a cleanup job and indexes to do the same.+- *Rate limiting must be exact under load.* A limit like "5 sign-in attempts per minute" needs a counter+ that many requests increase at the same moment. Redis `INCR` + `EXPIRE` in one pipeline is atomic, so+ parallel attempts can't slip past the limit.+- *Server-side sessions instead of tokens in the browser (JWT).* Because the session lives in Redis, signing+ out, "sign out everywhere", a password reset or an admin disabling a user takes effect immediately. A+ self-contained token would stay valid until it expires.+- *It works when the backend restarts or runs several copies.* Counters and sessions kept in the+ backend's memory would vanish on every rebuild and would not be shared between processes.++**If it stops.** It fails **closed**: sign-in, registration and every other rate-limited action answer+`503 Rate limiting service unavailable` instead of running without limits, and existing sessions can't be+checked, so users appear signed out. `/health` shows `redis: down`. Collectors keep checking in (they+authenticate with their own credentials stored in PostgreSQL), so no monitoring data is lost. When Redis+comes back, sessions saved in its volume work again.++## infradeck-collector++**What it does.** Measures the machine it runs on and sends one check-in to the backend every 60 seconds+(`INFRADECK_CHECK_INTERVAL_SECONDS`): CPU, load, memory, swap, disks and inodes, network traffic,+listening ports, uptime and boot ID, system information, and for every Docker container its state,+health, restarts, CPU, memory, swap and volumes. Each figure is explained in [Metrics](metrics.md).++**How it works.**+- It is one Python file using only the standard library: no third-party packages to audit or keep updated.+- It reads the host's `/proc` and its filesystem through **read-only** mounts (`/proc:/host/proc:ro`,+ `/:/hostfs:ro`). It runs with **all capabilities dropped**, a read-only root filesystem and+ `no-new-privileges`, so although it runs as root it can't read other users' private files (SSH keys,+ `.env` files) on the host.+- Container data comes from the Docker proxy through a Unix socket, not from Docker directly; the+ collector has no Docker socket.+- If the optional helpers run, it also reads their summary files from the shared `system_events` volume.+- **Registration:** on first start it registers with the backend and appears under *New servers detected*;+ once an admin approves it (or it was started with a join token or enrollment key), it receives its own+ credentials and saves them in the `collector_state` volume. Later restarts reuse them.++**Why this approach.**+- *Push, not pull.* The collector calls the backend; the backend never connects to your servers. Servers+ behind NAT or a home router need no open port, and the dashboard holds no SSH keys or passwords for them.+- *A container rather than an installed agent.* Installing, updating and removing it is one compose+ command, it runs the same on every distribution, and its permissions are written down in the compose file.+- *Least privilege.* The part that sends data over the network can read only public host information.+ Everything that needs more access is split into the separate containers below.++**If it stops.** After a few missed check-ins the backend marks the server offline and opens a+*server offline* incident.++## infradeck-docker-proxy++**What it does.** Lets the collector read container information without giving it the Docker socket.++**How it works.** It is the only container that mounts `/var/run/docker.sock`. It listens on a Unix+socket inside the `docker_proxy_socket` volume, which only it and the collector share. It answers exactly+six kinds of `GET` request (list containers, inspect one, its stats, one-shot stats, the Docker version,+disk usage) and refuses everything else. It also cuts each answer down to the fields the collector uses:+for example environment variables, which often contain passwords, and all labels except the compose+project name never leave the proxy. It has no network, no capabilities, and a read-only filesystem.++**Why this approach.**+- *The Docker socket is all or nothing.* Anything that can talk to it can start a privileged container,+ which is the same as root on the host, and a `:ro` mount flag doesn't change that. Keeping the socket+ in a tiny container with no network means that the container with network access (the collector) can+ never send a write request to Docker.+- *Why our own proxy instead of an existing one* (such as `tecnativa/docker-socket-proxy`). Those filter+ by URL path but pass Docker's full answers through, including every container's environment variables.+ Ours matches the exact request strings with no decoding and returns only the needed fields. It is about+ 200 lines of standard-library Python that can be read in one sitting.++**If it stops.** The Containers tab for that server goes empty and container alerts stop; host metrics+keep coming.++## infradeck-collector-gate (server stack only)++**What it does.** The only way to reach the four collector endpoints (register, poll registration,+enroll, ingest) when the stack runs behind Traefik.++**How it works.** A plain `nginx:alpine` with [`docker/nginx.collector.conf`](../docker/nginx.collector.conf)+and two listeners:++- **`:8081` (VPN).** Publish it on your VPN address only (`COLLECTOR_BIND`). Remote collectors use it, and+ registration there needs a join token from **Connect a server**.+- **`:8080` (internal).** Never published. Only the local collector on the `collector` network uses it.++Everything else answers `404`. The gate marks each request with the listener it came through, and the+backend (with `COLLECTOR_ACCESS=strict`) accepts collector traffic only when that mark is present. The+gate is not on Traefik's network, so other apps behind the same Traefik can't reach the collector+endpoints either.++**Why this approach.** The dashboard itself may be public on the internet, but the endpoints that+create servers and accept data shouldn't be. Separating them into a different container and port means+that the reverse proxy, the firewall and the VPN each decide on their own who may reach them. Docker's+published ports bypass `ufw`, so the bind address, not the firewall, is what protects the port.++**If it stops.** No collector can check in (including the local one), and the servers go offline on the+dashboard. The web app keeps working.++## infradeck-system-helper (optional)++**What it does.** Adds things the collector can't see with its limited access: processes killed by the+out-of-memory killer, kernel errors, and whether the last reboot was a crash or a clean shutdown.++**How it works.** Every 30 seconds it reads the kernel log and the host's `/var/log/wtmp` (read-only),+removes anything that isn't needed, and writes a short JSON summary (`system.json`) into the+`system_events` volume, which the collector reads and sends along. Its only privilege is `CAP_SYSLOG`+(needed for the kernel log). It has no network and a read-only filesystem. Turn it on with+`docker compose --profile system-events up -d`.++**Why a separate, optional container.** Reading the kernel log needs a capability the collector should not+have. Kept apart, the extra access sits in a container that can't send anything anywhere; only the+summary reaches the collector. It is optional because not everyone wants to grant that privilege.++**If it stops or is off.** The System tab shows these events as unavailable; nothing else changes.++## infradeck-port-owners (optional, off by default)++**What it does.** Names the process behind each listening port (for example `5432 → postgres`) in the+Network tab.++**How it works.** The same image as the system helper, started with `INFRADECK_HELPER_MODE=port-owners`.+It reads the host's `/proc`, matches listening sockets to processes, and writes only protocol, port and+process name to `ports.json` in the `system_events` volume. Turn it on with+`docker compose --profile port-owners up -d`.++**Why it is separate and off by default.** Looking into other users' processes needs `CAP_SYS_PTRACE`,+`CAP_DAC_READ_SEARCH`, the host's `/proc`, and no AppArmor confinement. Together those can read any+file on the host, which makes this the most privileged piece of the project. It therefore has no network+and a read-only filesystem, and it is opt-in. Read [SECURITY.md](../SECURITY.md) before enabling it.++**If it stops or is off.** The Network tab lists ports without process names.++## infradeck-caddy (optional, `compose.yml` only)++**What it does.** Puts HTTPS in front of the frontend on a public domain when you don't run Traefik.++**How it works.** The official `caddy:2-alpine` image with [`docker/Caddyfile`](../docker/Caddyfile):+it obtains and renews a Let's Encrypt certificate for `DOMAIN` and proxies everything to `frontend:80`.+Start it with `docker compose --profile https up -d`.++**Why Caddy here.** It handles certificates with no configuration beyond the domain name. The server+stack doesn't include it because it expects an existing Traefik to handle HTTPS (see+[Deploying](deployment.md)).++## Volumes++| Volume | Used by | Holds | Safe to delete? |+|---|---|---|---|+| `postgres_data` | postgres | The database. | **No**: all accounts, servers and history are lost. |+| `redis_data` | redis | Sessions and counters. | Yes, but everyone is signed out. |+| `collector_state` | collector | This machine's collector credentials. | The server has to be approved again and appears as a new server. |+| `docker_proxy_socket` | docker-proxy, collector | The Unix socket between them. | Yes, it is recreated. |+| `system_events` | helpers (write), collector (read) | The helpers' JSON summaries. | Yes, it is recreated. |+| `caddy_data`, `caddy_config` | caddy | Certificates. | Yes, but Caddy requests new certificates (Let's Encrypt has rate limits). |diff --git a/docs/deployment.md b/docs/deployment.mdindex 0e569e9..8d78cbb 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -28,7 +28,7 @@ Then set at least these:| `TRAEFIK_ENTRYPOINT` | `websecure` | Your Traefik HTTPS entrypoint name. || `TRAEFIK_CERT_RESOLVER` | `letsencrypt` | Your Traefik certificate resolver name. || `TRAEFIK_NETWORK` | `traefik_default` | The Docker network Traefik is attached to. |-| `TRAEFIK_ROUTER` | `homelab` | Name of this dashboard's Traefik router and service; change it only if it clashes with another one. |+| `TRAEFIK_ROUTER` | `infradeck` | Name of this dashboard's Traefik router and service; change it only if it clashes with another one. || `COMPOSE_FILE` | `docker-compose.server.yml` | Makes plain `docker compose ...` commands use the server file (see below). |Find the network with `docker network ls` ordiff --git a/docs/development.md b/docs/development.mdindex f17c114..1df8782 100644--- a/docs/development.md+++ b/docs/development.md@@ -12,7 +12,7 @@ in place of PostgreSQL.```bashpython -m venv venv && source venv/bin/activatepip install -r requirements.txt-docker run -d --name homelab-dev-redis -p 127.0.0.1:6379:6379 redis:7-alpine # if Redis isn't running (no password: for local development only)+docker run -d --name infradeck-dev-redis -p 127.0.0.1:6379:6379 redis:7-alpine # if Redis isn't running (no password: for local development only)DATABASE_URL=sqlite:///./dev.db REDIS_URL=redis://localhost:6379/0 \uvicorn src.backend.main:app --reload --host 0.0.0.0 --port 8060```diff --git a/docs/metrics.md b/docs/metrics.mdindex 38fd909..ab5e86c 100644--- a/docs/metrics.md+++ b/docs/metrics.md@@ -134,7 +134,7 @@ Passive, and only what the collector can read without privileges.|---|---|| **Listening ports** | Which TCP/UDP ports the host listens on, and whether each is reachable from other machines or only from the machine itself (**scope**). Protocol, port and scope only, with no process names. Short-lived programs on random high ports are ignored. || **Firewall** | A hash and a rule count of the known firewall configuration files, plus whether `ufw` is enabled. Never the rules themselves, and not the live ruleset. A changed hash raises an informational incident. |-| **Internet reachability** | Off unless you set `HOMELAB_CONNECTIVITY_TARGETS` on that collector. `ok` (all targets reachable), `degraded` (some), `dns_failed` (names don't resolve and nothing else is wrong) or `down`; plus the median connection time in milliseconds. |+| **Internet reachability** | Off unless you set `INFRADECK_CONNECTIVITY_TARGETS` on that collector. `ok` (all targets reachable), `degraded` (some), `dns_failed` (names don't resolve and nothing else is wrong) or `down`; plus the median connection time in milliseconds. |## Collector self-metricsdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 191a679..024e006 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -4,11 +4,11 @@| Symptom | Check ||---|---|-| A new machine never shows up under **New servers detected** | `docker logs homelab-collector` on that machine. "Could not reach …" means the address in the command isn't reachable from it (firewall, `localhost`, wrong IP/domain). |+| A new machine never shows up under **New servers detected** | `docker logs infradeck-collector` on that machine. "Could not reach …" means the address in the command isn't reachable from it (firewall, `localhost`, wrong IP/domain). || Collector log says "Backend no longer accepts server …" | The server was deleted on the dashboard; it is asking to join again, so click **Add** or **Dismiss**. || `network traefik_default declared as external, but could not be found` | You're using `docker-compose.server.yml` on a machine without that Traefik network. Use `compose.yml` for development, or set `TRAEFIK_NETWORK` in `.env` to the network Traefik is really on. || Dashboard shows old behaviour after a code change or `git pull` | Rebuild **all** services with `docker compose up -d --build` (with `-f docker-compose.server.yml` on a server unless `COMPOSE_FILE` is set) and hard-refresh the browser (Ctrl+Shift+R). |-| "The machine running the dashboard isn't reporting yet" at the top | The stack's own collector hasn't checked in: add it under **New servers detected**, then wait one check interval. If it is reporting, its image is outdated: `docker exec homelab-collector grep -c dashboard_host /app/collector.py` prints `0`. Rebuild it (`docker compose build --no-cache collector && docker compose up -d collector`). |+| "The machine running the dashboard isn't reporting yet" at the top | The stack's own collector hasn't checked in: add it under **New servers detected**, then wait one check interval. If it is reporting, its image is outdated: `docker exec infradeck-collector grep -c dashboard_host /app/collector.py` prints `0`. Rebuild it (`docker compose build --no-cache collector && docker compose up -d collector`). || A server shows only `/` and no **Storage** bars for other disks | Its collector predates per-mount reporting. Install a newer collector image (run a freshly generated command, or `docker compose -f collector-compose.yml up -d --build`). A disk mounted after the collector started appears after a collector restart. || Logged out after opening the dashboard at a new address | Login cookies belong to the address they were set on; log in again. || Login fails behind HTTPS with `SESSION_COOKIE_SECURE=true` | The cookie is only sent over HTTPS; open the `https://` address, not `http://…:5173`. |@@ -20,7 +20,7 @@| The **System** row shows *unknown* for last shutdown or has no kernel messages | The optional system helper isn't running. Start it with `docker compose --profile system-events up -d`. *Unknown* for reboot-required on non-Debian hosts is expected. || `Error response … cannot assign requested address` for the collector gate | `COLLECTOR_BIND` is set to an address that doesn't exist yet (VPN not up). Start the VPN first, or fix the address. || The **Network** row says *no config found* for the firewall | None of the known firewall files exist on that host (`/etc/ufw`, `/etc/nftables.conf`, `/etc/iptables/rules.v4`). The check reads configuration, not the live ruleset, so a host that configures its firewall some other way shows this. |-| The **Network** row says *not checked* for the internet | The check is opt-in. Set `HOMELAB_CONNECTIVITY_TARGETS` on that collector (for example `1.1.1.1:443`). |+| The **Network** row says *not checked* for the internet | The check is opt-in. Set `INFRADECK_CONNECTIVITY_TARGETS` on that collector (for example `1.1.1.1:443`). || Listeners show *unknown* or the Network row is empty | The collector couldn't read the host's network tables (older collector, or a table with more than 500,000 sockets). An unreadable report never raises a "port closed" alert. || "Invalid code." although the code looks right | Codes depend on the clock: check the phone's time is automatic. A code also can't be used twice, so wait for the next one. Five wrong codes lock the code step for 5 minutes. || Two-factor setup says it is not available | `SECRETS_KEY` is missing or invalid in `.env`. Generate one (see [Two-factor sign-in](accounts.md#two-factor-sign-in)) and restart the backend. The backend log shows a SECURITY WARNING while the key is missing. |@@ -31,7 +31,7 @@| The backend log says `AuthenticationError` or `invalid password` for Redis, or `/health` shows Redis down | `REDIS_PASSWORD` in `.env` doesn't match the password Redis was started with, or contains characters that don't fit in a URL (`@`, `:`, `/`, `%`). Use letters and digits only, and recreate both containers: `docker compose up -d --force-recreate redis backend`. || A collector log says "Check-ins are arriving faster than this server's interval allows" (HTTP 429) | The collector reports more often than a quarter of the server's check interval. It retries by itself; check that only one collector uses that server's token, or adjust `INGEST_MIN_SPACING_RATIO`. || Enrolling gives HTTP 429 "Too many attempts" | The enrollment key is limited to `ENROLL_RATE_LIMIT` (30) enrollments per address per hour. If many collectors reach the dashboard from one address (NAT), raise it in `.env`. |-| A new server shows up as `name (2)` | Another server already had that name (often a default such as `raspberrypi`). The number tells the two apart. Give one machine a different hostname (or `HOMELAB_SERVER_NAME`) if you want to avoid it. |+| A new server shows up as `name (2)` | Another server already had that name (often a default such as `raspberrypi`). The number tells the two apart. Give one machine a different hostname (or `INFRADECK_SERVER_NAME`) if you want to avoid it. || "This install already has the most servers it allows" | `MAX_SERVERS` (default 200) is reached. Remove servers you no longer need, or raise it in `.env`. || A warning "The credentials of <server> were replaced" | Someone used the enrollment key on a machine whose ID is already known, which signs the previous collector out. Expected after you reinstall that machine with the key; if it wasn't you, rotate the key under *Connect a server → Advanced* and inspect the machine. || "Enter your current password to set up two-factor." | Turning on two-factor from a normal session asks for your password again. Type it in the field that appears. |diff --git a/example.env b/example.envindex 5ff0793..644aabf 100644--- a/example.env+++ b/example.env@@ -32,7 +32,7 @@ TRAEFIK_ENTRYPOINT=websecureTRAEFIK_CERT_RESOLVER=letsencryptTRAEFIK_NETWORK=traefik_default# Name of this dashboard's Traefik router and service; only change it if it clashes with another one.-TRAEFIK_ROUTER=homelab+TRAEFIK_ROUTER=infradeck# URL(s) the dashboard is opened from, comma-separated, if it differs from https://<DASHBOARD_DOMAIN># (for example a second address). Browser requests from other origins are rejected. Include@@ -136,18 +136,18 @@ ADMIN_ALERT_WEBHOOK_URL=# New machines appear under "New servers detected" on the dashboard and must# be approved. Set an enrollment key (dashboard: Connect a server -> Advanced)# to have this machine approved automatically. Leave empty to approve by hand.-HOMELAB_ENROLL_KEY=+INFRADECK_ENROLL_KEY=# Name shown on the dashboard for this machine. Empty = use its hostname.-HOMELAB_SERVER_NAME=+INFRADECK_SERVER_NAME=# How often the collector sends metrics, in seconds. Minimum 15.-HOMELAB_CHECK_INTERVAL_SECONDS=60+INFRADECK_CHECK_INTERVAL_SECONDS=60# Unique ID of this machine. Empty = read /etc/machine-id from the host.# Set it only if several machines share the same machine-id (e.g. cloned VMs)# and would otherwise show up as one server.-HOMELAB_MACHINE_ID=+INFRADECK_MACHINE_ID=# =============================================================================# Dashboard (frontend)@@ -162,7 +162,7 @@ FRONTEND_PORT=5173# Optional internet-reachability check run by the collector, off when empty. Comma-separated# host:port targets (hostnames or IPv4, at most 5); it only opens a TCP connection and looks the name# up, sending nothing. Set per collector, never from the dashboard. Example: 1.1.1.1:443,9.9.9.9:443-HOMELAB_CONNECTIVITY_TARGETS=+INFRADECK_CONNECTIVITY_TARGETS=# --- Connecting remote servers over a VPN (docker-compose.server.yml) ---# Collectors never use the public address. They report to the collector gate, which you@@ -187,7 +187,7 @@ LIVE_GRAPH_REFRESH_INTERVAL_SECONDS=3# =============================================================================# Not configurable here# =============================================================================-# The code also reads DATABASE_URL, REDIS_URL, HOMELAB_API_URL, PROMPTS_DIR,-# DOCKER_SOCKET_PATH, HOST_PROC, HOST_ROOT, HOMELAB_STATE_DIR and+# The code also reads DATABASE_URL, REDIS_URL, INFRADECK_API_URL, PROMPTS_DIR,+# DOCKER_SOCKET_PATH, HOST_PROC, HOST_ROOT, INFRADECK_STATE_DIR and# VITE_API_BASE_URL. The compose file sets these to match its own containers,# volumes and ports, so setting them in .env has no effect.diff --git a/src/agent/SYSTEM_PROMPT.md b/src/agent/SYSTEM_PROMPT.mdindex 2be3a12..df4bf84 100644--- a/src/agent/SYSTEM_PROMPT.md+++ b/src/agent/SYSTEM_PROMPT.md@@ -1,4 +1,4 @@-Name: Homie (Homelab Health Monitor)+Name: Infradeck incident agent[ROLE]You are a security-first homelab monitoring assistant. You can explain health findings and request only one predefined, read-only health check. You cannot execute commands, write files, change configuration, access secrets, restart services, or take remediation actions.diff --git a/src/agent/collector.py b/src/agent/collector.pyindex c45bdc8..49481ed 100644--- a/src/agent/collector.py+++ b/src/agent/collector.py@@ -1,11 +1,11 @@"""Read-only host and Docker metrics collector for a registered Infradeck server.-Only HOMELAB_API_URL is required. On first start the collector asks to join and+Only INFRADECK_API_URL is required. On first start the collector asks to join andappears on the dashboard under "New servers detected"; once someone clicks Add-it receives its token (no restart) and saves it under HOMELAB_STATE_DIR.-HOMELAB_JOIN_TOKEN (from the dashboard's Connect a server command) proves who asked it to join.-HOMELAB_ENROLL_KEY skips the approval step for automated installs, and-HOMELAB_SERVER_ID / HOMELAB_COLLECTOR_TOKEN still work as explicit credentials.+it receives its token (no restart) and saves it under INFRADECK_STATE_DIR.+INFRADECK_JOIN_TOKEN (from the dashboard's Connect a server command) proves who asked it to join.+INFRADECK_ENROLL_KEY skips the approval step for automated installs, and+INFRADECK_SERVER_ID / INFRADECK_COLLECTOR_TOKEN still work as explicit credentials.Run with ``python -m src.agent.collector`` or as a standalone script (standardlibrary only; it ships as a container image). Docker access is optional; whenthe socket is unavailable, host metrics continue to be sent.@@ -33,6 +33,11 @@ from typing import AnyMiB = 1024 * 1024GiB = 1024**3# In a container the host is mounted at /host/proc and /hostfs; fall back to our own view otherwise.+# Installs from before the rename to Infradeck set HOMELAB_* variables; they keep working unchanged.+for _name, _value in list(os.environ.items()):+ if _name.startswith("HOMELAB_"):+ os.environ.setdefault("INFRADECK_" + _name[len("HOMELAB_"):], _value)+HOST_PROC = Path(os.getenv("HOST_PROC") or ("/host/proc" if Path("/host/proc").is_dir() else "/proc"))HOST_ROOT = Path(os.getenv("HOST_ROOT") or ("/hostfs" if Path("/hostfs").is_dir() else "/"))@@ -218,9 +223,9 @@ CONNECTIVITY_DEADLINE_SECONDS = 6.0def _connectivity_targets() -> list[tuple[str, int]]:- """``host:port`` entries from HOMELAB_CONNECTIVITY_TARGETS (hostnames or IPv4 only). Empty means the check is off."""+ """``host:port`` entries from INFRADECK_CONNECTIVITY_TARGETS (hostnames or IPv4 only). Empty means the check is off."""targets: list[tuple[str, int]] = []- for entry in os.getenv("HOMELAB_CONNECTIVITY_TARGETS", "").split(","):+ for entry in os.getenv("INFRADECK_CONNECTIVITY_TARGETS", "").split(","):host, _, port = entry.strip().rpartition(":")# A name whose last label is all digits isn't a valid hostname; it is a mistyped IP address.valid_host = _IPV4.fullmatch(host) and all(int(part) <= 255 for part in host.split(".")) or (_HOSTNAME.fullmatch(host) and not host.rsplit(".", 1)[-1].isdigit())@@ -256,7 +261,7 @@ def summarise_connectivity(results: list[dict[str, Any]]) -> str:def collect_connectivity() -> dict[str, Any]:- """Can this host reach the internet? Off unless HOMELAB_CONNECTIVITY_TARGETS is set on this collector.+ """Can this host reach the internet? Off unless INFRADECK_CONNECTIVITY_TARGETS is set on this collector.The targets come from the collector's own environment, never from the dashboard, so a compromiseddashboard can't point these probes anywhere.@@ -457,7 +462,7 @@ HELPER_MAX_AGE_SECONDS = 300def _helper_path() -> Path:- return Path(os.getenv("HOMELAB_HELPER_FILE", "/helper/system.json"))+ return Path(os.getenv("INFRADECK_HELPER_FILE", "/helper/system.json"))def collect_helper(boot_id: str | None, path: Path | None = None, now: float | None = None) -> dict[str, Any]:@@ -713,7 +718,7 @@ MAX_PORT_OWNERS = 512def _port_owners_path() -> Path:- return Path(os.getenv("HOMELAB_PORT_OWNERS_FILE", "/helper/ports.json"))+ return Path(os.getenv("INFRADECK_PORT_OWNERS_FILE", "/helper/ports.json"))def collect_port_owners(path: Path | None = None, now: float | None = None) -> list[dict[str, Any]] | None:@@ -777,7 +782,7 @@ def collect_system_info(listeners: list[dict[str, Any]] | None, reboot_required:def registration_details() -> dict[str, Any]:"""What a collector found on its machine, shown next to the Add button before anyone approves it."""- socket_path = os.getenv("HOMELAB_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")+ socket_path = os.getenv("INFRADECK_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")try:containers = len(_docker_request(socket_path, "/containers/json?all=1")) if Path(socket_path).exists() else Noneexcept (OSError, ValueError, TypeError, http.client.HTTPException):@@ -785,7 +790,7 @@ def registration_details() -> dict[str, Any]:return {"cpu_cores": _host_cpu_cores(), "containers": containers, "mounts": len(collect_mounts()),"helper_installed": _helper_path().exists(),- "dashboard_host": os.getenv("HOMELAB_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"},+ "dashboard_host": os.getenv("INFRADECK_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"},}@@ -832,7 +837,7 @@ def collect_host() -> tuple[dict[str, Any], dict[str, Any]]:"system": collect_system_info(host["listeners"], host.get("reboot_required"), host["mounts"]),}# Set only on the collector in the dashboard's own compose stack; the dashboard's top charts follow it.- if os.getenv("HOMELAB_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"}:+ if os.getenv("INFRADECK_DASHBOARD_HOST", "").lower() in {"1", "true", "yes"}:server["dashboard_host"] = Truereturn server, host@@ -845,7 +850,7 @@ def _memory_total_gb() -> float:def _host_hostname() -> str:- override = os.getenv("HOMELAB_SERVER_NAME")+ override = os.getenv("INFRADECK_SERVER_NAME")if override:return overridetry:@@ -925,7 +930,7 @@ def _docker_failure_reason(error: BaseException) -> str:def collect_containers(socket_path: str | None = None, info: dict[str, Any] | None = None) -> list[dict[str, Any]]:"""Every container with its state and usage. ``info`` receives how long listing them took."""# The read-only proxy is preferred: it keeps the Docker socket, which is root on the host, out of this container.- socket_path = socket_path or os.getenv("HOMELAB_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")+ socket_path = socket_path or os.getenv("INFRADECK_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")if not Path(socket_path).exists():return []listing_started = time.monotonic()@@ -1023,7 +1028,7 @@ def collect_docker(socket_path: str | None = None) -> tuple[list[dict[str, Any]]"No Docker on this host" is not an error, and an empty list is not proof of a problem, so thebackend only alerts on ``unreachable`` for a host that had Docker working before."""- explicit = socket_path or os.getenv("HOMELAB_DOCKER_HOST")+ explicit = socket_path or os.getenv("INFRADECK_DOCKER_HOST")target = explicit or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")if not Path(target).exists():# A proxy that is configured but missing is a failure; a host that simply has no Docker socket is not.@@ -1184,7 +1189,7 @@ def send_payload(api_url: str, server_id: int, token: str, payload: dict[str, Andef _machine_id() -> str | None:- override = os.getenv("HOMELAB_MACHINE_ID")+ override = os.getenv("INFRADECK_MACHINE_ID")if override:return override.strip()for candidate in ("etc/machine-id", "var/lib/dbus/machine-id"):@@ -1197,8 +1202,18 @@ def _machine_id() -> str | None:return None+LEGACY_STATE_DIR = Path("/var/lib/homelab-collector")++def _credentials_path() -> Path:- return Path(os.getenv("HOMELAB_STATE_DIR", "/var/lib/homelab-collector")) / "credentials.json"+ """Where this collector keeps its credentials. A collector installed before the rename to Infradeck has its state+ volume mounted at the old path; it keeps using that, so an image update doesn't make it ask to join again."""+ configured = os.getenv("INFRADECK_STATE_DIR")+ if configured:+ return Path(configured) / "credentials.json"+ current = Path("/var/lib/infradeck-collector") / "credentials.json"+ legacy = LEGACY_STATE_DIR / "credentials.json"+ return legacy if not current.exists() and LEGACY_STATE_DIR.is_dir() else currentdef load_credentials(path: Path | None = None) -> tuple[int, str] | None:@@ -1257,7 +1272,7 @@ def request_approval(api_url: str) -> tuple[int, str]:base = api_url.rstrip("/")while True:try:- registration = _post_json(f"{base}/monitoring/collectors/register", {"hostname": _host_hostname(), "machine_id": _machine_id(), "os_info": _host_os_info(), "join_token": os.getenv("HOMELAB_JOIN_TOKEN", "").strip() or None, "details": registration_details()})+ registration = _post_json(f"{base}/monitoring/collectors/register", {"hostname": _host_hostname(), "machine_id": _machine_id(), "os_info": _host_os_info(), "join_token": os.getenv("INFRADECK_JOIN_TOKEN", "").strip() or None, "details": registration_details()})except urllib.error.HTTPError as exc:print(f"Registration refused (HTTP {exc.code}): {_error_detail(exc)}; retrying in 5 minutes", flush=True)time.sleep(300)@@ -1294,13 +1309,13 @@ def request_approval(api_url: str) -> tuple[int, str]:def resolve_credentials(api_url: str) -> tuple[int, str]:"""Explicit env credentials win, then saved credentials, then an enrollment key, then dashboard approval."""- if os.getenv("HOMELAB_SERVER_ID") and os.getenv("HOMELAB_COLLECTOR_TOKEN"):- return int(os.environ["HOMELAB_SERVER_ID"]), os.environ["HOMELAB_COLLECTOR_TOKEN"]+ if os.getenv("INFRADECK_SERVER_ID") and os.getenv("INFRADECK_COLLECTOR_TOKEN"):+ return int(os.environ["INFRADECK_SERVER_ID"]), os.environ["INFRADECK_COLLECTOR_TOKEN"]saved = load_credentials()if saved:return savedcredentials = None- enroll_key = os.getenv("HOMELAB_ENROLL_KEY", "").strip()+ enroll_key = os.getenv("INFRADECK_ENROLL_KEY", "").strip()if enroll_key:try:credentials = enroll(api_url, enroll_key)@@ -1319,9 +1334,9 @@ def resolve_credentials(api_url: str) -> tuple[int, str]:def run_collector() -> None:- api_url = os.getenv("HOMELAB_API_URL", "http://localhost:8060")+ api_url = os.getenv("INFRADECK_API_URL", "http://localhost:8060")server_id, token = resolve_credentials(api_url)- interval = max(15, int(os.getenv("HOMELAB_CHECK_INTERVAL_SECONDS", "60")))+ interval = max(15, int(os.getenv("INFRADECK_CHECK_INTERVAL_SECONDS", "60")))print(f"Collector started for server {server_id}; API={api_url}", flush=True)while True:started = time.monotonic()@@ -1336,7 +1351,7 @@ def run_collector() -> None:print(f"Sent host metrics and {len(containers)} container records; next check in {interval}s", flush=True)delay = max(0, interval - (time.monotonic() - started))except urllib.error.HTTPError as exc:- if exc.code in (401, 404) and not os.getenv("HOMELAB_SERVER_ID"):+ if exc.code in (401, 404) and not os.getenv("INFRADECK_SERVER_ID"):# Removed from the dashboard: ask to join again. This needs a fresh Add, so a# deleted server never comes back on its own.print(f"Backend no longer accepts server {server_id} (HTTP {exc.code}); requesting approval again", flush=True)@@ -1348,7 +1363,7 @@ def run_collector() -> None:passdelay = 0elif exc.code in (401, 404):- print(f"Backend rejected server {server_id} (HTTP {exc.code}); check HOMELAB_SERVER_ID / HOMELAB_COLLECTOR_TOKEN", flush=True)+ print(f"Backend rejected server {server_id} (HTTP {exc.code}); check INFRADECK_SERVER_ID / INFRADECK_COLLECTOR_TOKEN", flush=True)delay = 300else:print(f"Send failed (HTTP {exc.code})", flush=True)diff --git a/src/agent/docker_proxy.py b/src/agent/docker_proxy.pyindex bf35ca1..fbd8901 100644--- a/src/agent/docker_proxy.py+++ b/src/agent/docker_proxy.py@@ -32,8 +32,13 @@ from http.server import BaseHTTPRequestHandlerfrom pathlib import Pathfrom typing import Any, Callable+# Installs from before the rename to Infradeck set HOMELAB_* variables; they keep working unchanged.+for _name, _value in list(os.environ.items()):+ if _name.startswith("HOMELAB_"):+ os.environ.setdefault("INFRADECK_" + _name[len("HOMELAB_"):], _value)+SOCKET_PATH = os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")-LISTEN_PATH = os.getenv("HOMELAB_DOCKER_PROXY_SOCKET", "/run/docker-proxy/docker.sock")+LISTEN_PATH = os.getenv("INFRADECK_DOCKER_PROXY_SOCKET", "/run/docker-proxy/docker.sock")MAX_RESPONSE_BYTES = 8 * 1024 * 1024UPSTREAM_TIMEOUT_SECONDS = 10@@ -137,7 +142,7 @@ class _UnixHTTPConnection(http.client.HTTPConnection):class ProxyHandler(BaseHTTPRequestHandler):- server_version = "homelab-docker-proxy"+ server_version = "infradeck-docker-proxy"socket_path = SOCKET_PATHdef _send(self, status: int, body: bytes = b"", content_type: str = "text/plain") -> None:diff --git a/src/agent/health_checks.py b/src/agent/health_checks.pyindex 2b12c18..cc05865 100644--- a/src/agent/health_checks.py+++ b/src/agent/health_checks.py@@ -25,7 +25,7 @@ class AdminNotifier:return {"status": "not_configured"}webhook_request = request.Request(webhook_url,- data=json.dumps({"source": "homelab-health", "finding": finding}).encode(),+ data=json.dumps({"source": "infradeck-health", "finding": finding}).encode(),headers={"Content-Type": "application/json"},method="POST",)diff --git a/src/agent/system_helper.py b/src/agent/system_helper.pyindex 2d3dff6..4f4b5c1 100644--- a/src/agent/system_helper.py+++ b/src/agent/system_helper.py@@ -10,7 +10,7 @@ with fixed patterns, strings are reduced to printable text and truncated, and thfixed schema. The helper is stateless; each run re-reads the kernel ring buffer and publishesa snapshot, and the backend de-duplicates events by their key.-A second, separate mode (``HOMELAB_HELPER_MODE=port-owners``, the ``port-owners`` compose profile) names the+A second, separate mode (``INFRADECK_HELPER_MODE=port-owners``, the ``port-owners`` compose profile) names theprocess behind each listening port. That needs far more than the kernel log does: the host's /proc and theright to look at other users' processes (CAP_SYS_PTRACE and CAP_DAC_READ_SEARCH), which together can readany file on the host. It therefore runs as its own container, so enabling the kernel-log helper never grants@@ -31,9 +31,14 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any+# Installs from before the rename to Infradeck set HOMELAB_* variables; they keep working unchanged.+for _name, _value in list(os.environ.items()):+ if _name.startswith("HOMELAB_"):+ os.environ.setdefault("INFRADECK_" + _name[len("HOMELAB_"):], _value)+HOST_PROC = Path(os.getenv("HOST_PROC") or "/proc")-WTMP_PATH = Path(os.getenv("HOMELAB_WTMP_PATH", "/host/wtmp"))-OUTPUT_PATH = Path(os.getenv("HOMELAB_HELPER_OUTPUT", "/out/system.json"))+WTMP_PATH = Path(os.getenv("INFRADECK_WTMP_PATH", "/host/wtmp"))+OUTPUT_PATH = Path(os.getenv("INFRADECK_HELPER_OUTPUT", "/out/system.json"))SYSLOG_ACTION_READ_ALL = 3 # reads the ring buffer without clearing itSYSLOG_ACTION_SIZE_BUFFER = 10@@ -142,9 +147,9 @@ def classify_last_shutdown(records: list[tuple[int, str, int]], boot_time: floatreturn "unclean" if any(is_shutdown(record) for record in records[:latest]) else "unknown"-PORTS_OUTPUT_PATH = Path(os.getenv("HOMELAB_PORT_OWNERS_OUTPUT", "/out/ports.json"))+PORTS_OUTPUT_PATH = Path(os.getenv("INFRADECK_PORT_OWNERS_OUTPUT", "/out/ports.json"))# Where the host's /proc is mounted for the port-owners mode (its own /proc only shows this container).-PORTS_HOST_PROC = Path(os.getenv("HOMELAB_PORT_OWNERS_PROC", "/host/proc"))+PORTS_HOST_PROC = Path(os.getenv("INFRADECK_PORT_OWNERS_PROC", "/host/proc"))MAX_SOCKET_LINES = 200_000MAX_PROCESSES = 20_000MAX_FDS_PER_PROCESS = 4096@@ -254,8 +259,8 @@ def write_snapshot(snapshot: dict[str, Any], path: Path = OUTPUT_PATH) -> None:def run() -> None:- interval = max(10, int(os.getenv("HOMELAB_HELPER_INTERVAL_SECONDS", "30")))- ports_mode = os.getenv("HOMELAB_HELPER_MODE", "").strip().lower() == "port-owners"+ interval = max(10, int(os.getenv("INFRADECK_HELPER_INTERVAL_SECONDS", "30")))+ ports_mode = os.getenv("INFRADECK_HELPER_MODE", "").strip().lower() == "port-owners"output = PORTS_OUTPUT_PATH if ports_mode else OUTPUT_PATHprint(f"{'Port-owners' if ports_mode else 'System'} helper started; writing {output} every {interval}s", flush=True)while True:diff --git a/src/backend/auth.py b/src/backend/auth.pyindex 0e72aac..e397032 100644--- a/src/backend/auth.py+++ b/src/backend/auth.py@@ -50,7 +50,7 @@ def _session_key(session_id: str) -> str:def _key_for_digest(digest: str) -> str:- return f"homelab:session:{digest}"+ return f"infradeck:session:{digest}"def session_lifetime(stage: str, remember: bool) -> int:@@ -73,15 +73,15 @@ def _delete_session(redis_client, session_id: str):def _user_sessions_key(user_id: int) -> str:- return f"homelab:user-sessions:{user_id}"+ return f"infradeck:user-sessions:{user_id}"def _pending_key(token: str) -> str:- return f"homelab:2fa-pending:{_digest(token)}"+ return f"infradeck:2fa-pending:{_digest(token)}"def _attempts_key(token: str) -> str:- return f"homelab:2fa-attempts:{_digest(token)}"+ return f"infradeck:2fa-attempts:{_digest(token)}"def _printable(text: str | None, limit: int) -> str | None:@@ -232,16 +232,38 @@ def delete_pending_two_factor(redis_client, token: str) -> None:redis_client.delete(_pending_key(token), _attempts_key(token))+LEGACY_KEY_PREFIX = "homelab:"+KEY_PREFIX = "infradeck:"+++def migrate_key_prefix(redis_client) -> int:+ """Move what Redis holds under the name used before the rename to Infradeck (sessions, rate limits, notification+ markers) to the new prefix, so an upgrade signs nobody out and sends no alert twice. A key that already exists+ under the new name is left alone. Safe to run at every start; returns how many keys moved."""+ moved = 0+ try:+ for key in list(redis_client.scan_iter(match=f"{LEGACY_KEY_PREFIX}*")):+ name = key.decode() if isinstance(key, bytes) else key+ target = KEY_PREFIX + name[len(LEGACY_KEY_PREFIX):]+ if redis_client.exists(target):+ continue+ redis_client.rename(name, target)+ moved += 1+ except Exception: # a missing key or a Redis hiccup must not stop the backend from starting+ return moved+ return moved++def purge_legacy_session_keys(redis_client) -> int:"""Delete session data written before session IDs were hashed: the keys that still contain a raw session ID orpending-login token, and the per-user indexes that point at them. Those sessions stopped working when theformat changed; this stops their secrets from sitting in Redis until they expire. Returns how many were removed."""removed = 0try:- for key in list(redis_client.scan_iter(match="homelab:session:*")) + list(redis_client.scan_iter(match="homelab:2fa-pending:*")) + list(redis_client.scan_iter(match="homelab:2fa-attempts:*")):+ for key in list(redis_client.scan_iter(match="infradeck:session:*")) + list(redis_client.scan_iter(match="infradeck:2fa-pending:*")) + list(redis_client.scan_iter(match="infradeck:2fa-attempts:*")):if not _DIGEST.fullmatch(key.rsplit(":", 1)[-1]):removed += int(bool(redis_client.delete(key)))- for key in redis_client.scan_iter(match="homelab:user-sessions:*"):+ for key in redis_client.scan_iter(match="infradeck:user-sessions:*"):if any(not _DIGEST.fullmatch(value) for value in redis_client.hvals(key)):removed += int(bool(redis_client.delete(key)))except Exception:diff --git a/src/backend/config.py b/src/backend/config.pyindex 22d72d1..a66c5f7 100644--- a/src/backend/config.py+++ b/src/backend/config.py@@ -11,7 +11,7 @@ APP_VERSION = "0.9.2"DATABASE_URL = os.getenv("DATABASE_URL",- "postgresql+psycopg://homelab:homelab_dev@localhost:5432/homelab",+ "postgresql+psycopg://infradeck:infradeck_dev@localhost:5432/infradeck",)REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "86400"))diff --git a/src/backend/incidents.py b/src/backend/incidents.pyindex d50e3cc..282c203 100644--- a/src/backend/incidents.py+++ b/src/backend/incidents.py@@ -188,7 +188,7 @@ def _host_diagnosis(db, alert: IncidentAlert, server: Server, kind: str, since:PLAYBOOKS: dict[str, list[dict]] = {SERVER_OFFLINE_RULE: [_step("Check that the machine is up", "If it answers a ping, the machine is fine and the collector or the network path is the problem.", None, None, True),- _step("Look at the collector on that machine", "It logs why it could not send.", "docker compose -p homelab-collector logs --tail 50 collector", "shell"),+ _step("Look at the collector on that machine", "It logs why it could not send.", "docker compose -p infradeck-collector logs --tail 50 collector", "shell"),_step("Confirm it's back", "This incident resolves on the collector's next check-in."),],"network:port": [diff --git a/src/backend/main.py b/src/backend/main.pyindex b79691d..b58b36b 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -371,6 +371,8 @@ def startup_event():if require_admin_two_factor(db) and not secrets_box.available():print("SECURITY WARNING: two-factor is required for administrators, but SECRETS_KEY is missing or invalid, so it is NOT being enforced. ""Generate a key with `python -m src.backend.secrets_box` and set SECRETS_KEY in .env.", flush=True)+ if moved := auth.migrate_key_prefix(redis_client):+ print(f"Moved {moved} Redis keys from the old homelab: prefix to infradeck:.", flush=True)if removed := auth.purge_legacy_session_keys(redis_client):print(f"Removed {removed} session records written in the old format (sign-ins before this version ended).", flush=True)if warning := registration_warning(db):@@ -1341,7 +1343,7 @@ def fleet_statistics(range_name: Annotated[RangeName, Query(alias="range")] = "2"""Incidents over time and per-server availability for the Statistics page's all-servers view."""_current_user(session_id, db)# Keyed only by the validated range, so a request can't create an unbounded number of cache entries.- cache_key = f"homelab:stats:fleet:{range_name}"+ cache_key = f"infradeck:stats:fleet:{range_name}"try:cached = redis_client.get(cache_key)if cached:@@ -1362,7 +1364,7 @@ def _cached_server_stats(db, server_id: int, name: str, range_name: str, build)server = db.query(Server).filter(Server.id == server_id).first()if not server:raise HTTPException(status_code=404, detail="Server not found.")- cache_key = f"homelab:stats:{name}:{server.id}:{range_name}"+ cache_key = f"infradeck:stats:{name}:{server.id}:{range_name}"try:cached = redis_client.get(cache_key)if cached:@@ -1409,7 +1411,7 @@ def server_heatmap(if not server:raise HTTPException(status_code=404, detail="Server not found.")# Only existing servers, known metrics and a bounded offset get this far, so the cache can't grow without limit.- cache_key = f"homelab:stats:heatmap:{server.id}:{metric}:{offset}"+ cache_key = f"infradeck:stats:heatmap:{server.id}:{metric}:{offset}"try:cached = redis_client.get(cache_key)if cached:@@ -2209,7 +2211,7 @@ def _enforce_ingest_spacing(server: Server) -> None:returnspacing = max(INGEST_MIN_SPACING_SECONDS, int(server.check_interval_seconds * INGEST_MIN_SPACING_RATIO))try:- allowed = redis_client.set(f"homelab:ingest:{server.id}", "1", nx=True, ex=spacing)+ allowed = redis_client.set(f"infradeck:ingest:{server.id}", "1", nx=True, ex=spacing)except Exception: # losing the limit during a Redis outage is better than losing the monitoringreturnif not allowed:@@ -2596,7 +2598,7 @@ def _agent_note(db, alert: IncidentAlert, server: Server | None) -> str | None:Overview is polled every few seconds and working it out reads samples."""if server is None:return None- key = f"homelab:incident-note:{alert.id}"+ key = f"infradeck:incident-note:{alert.id}"try:cached = redis_client.get(key)if cached is not None:@@ -2942,7 +2944,7 @@ def dispatch_notifications(db, now: datetime | None = None) -> int:wanted = [channel for channel in channels if routing.get(str(channel.id), notify.DEFAULT_ROUTING[event])]if not wanted or (event != "critical" and notify.in_quiet_hours(preferences["quiet"], preferences["display"]["timezone"], now)):continue- marker = f"homelab:notified:{alert.id}:{user_id}:{event}"+ marker = f"infradeck:notified:{alert.id}:{user_id}:{event}"try:if not redis_client.set(marker, "1", nx=True, ex=NOTIFY_MARK_SECONDS):continuediff --git a/src/backend/rate_limit.py b/src/backend/rate_limit.pyindex 99feb58..5e46c68 100644--- a/src/backend/rate_limit.py+++ b/src/backend/rate_limit.py@@ -7,7 +7,7 @@ from fastapi import HTTPExceptiondef _key(scope: str, value: str) -> str:digest = hashlib.sha256(value.encode("utf-8")).hexdigest()- return f"homelab:rate-limit:{scope}:{digest}"+ return f"infradeck:rate-limit:{scope}:{digest}"def _record_attempt(redis_client, key: str, limit: int, window_seconds: int) -> None:diff --git a/src/frontend/src/admin/AdminPage.jsx b/src/frontend/src/admin/AdminPage.jsxindex b6c591d..8a4876e 100644--- a/src/frontend/src/admin/AdminPage.jsx+++ b/src/frontend/src/admin/AdminPage.jsx@@ -34,7 +34,46 @@ function Servers({ overview }) {}return (<div className="card overflow-hidden">- <div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[820px] border-collapse text-left text-[13px]">+ {/* Phones: one block per server instead of a table that scrolls sideways. */}+ <ul className="m-0 list-none divide-y divide-line p-0 md:hidden">+ {servers.map((server) => {+ const version = server.system?.collector_version+ const outdated = !version || version !== overview.version+ const renaming = editing?.id === server.id+ return (+ <li key={server.id} className="px-4 py-3.5">+ {renaming+ ? <form className="flex items-center gap-2" onSubmit={(event) => { event.preventDefault(); save(server, { hostname: editing.name }).then(() => setEditing(null)) }}>+ <input className="field h-10 min-w-0 flex-1" autoFocus maxLength={253} aria-label={`New name for ${server.hostname}`} value={editing.name} onChange={(event) => setEditing({ id: server.id, name: event.target.value })} />+ <button type="submit" className="btn btn-primary h-10" disabled={state.busy}>Save</button>+ <button type="button" className="btn btn-ghost h-10" onClick={() => setEditing(null)}>Cancel</button>+ </form>+ : <div className="flex items-start gap-2.5">+ <span className={`dot mt-[7px] ${STATE_DOT[serverState(server)]}`} />+ <span className="min-w-0 flex-1"><span className="block break-all text-sm font-semibold leading-5 text-paper">{server.hostname}</span>{server.is_dashboard_host && <span className="chip mt-1.5">this machine</span>}</span>+ <button type="button" className="link shrink-0 text-xs" onClick={() => setEditing({ id: server.id, name: server.hostname })}>Edit</button>+ </div>}+ <dl className="m-0 mt-3 grid grid-cols-2 gap-x-4 gap-y-2.5 text-xs">+ <div><dt className="text-muted">Address</dt><dd className="mono m-0 mt-0.5 break-all text-soft">{server.ip_address || '—'}</dd></div>+ <div><dt className="text-muted">Collector</dt><dd className="m-0 mt-0.5"><span className="mono text-paper">{version || 'older'}</span>{outdated && <span className="ml-2 text-warn">update</span>}</dd></div>+ <div><dt className="text-muted">Last check-in</dt><dd className="m-0 mt-0.5 text-soft">{ago(server.last_seen_at)}</dd></div>+ <div><dt className="text-muted">System helper</dt><dd className="m-0 mt-1"><span className={`chip ${server.system?.helper_installed ? 'chip-ok' : ''}`}>{server.system?.helper_installed ? 'installed' : 'not installed'}</span></dd></div>+ </dl>+ <div className="mt-3 flex items-center justify-between gap-3">+ <label className="flex items-center gap-2.5 text-xs text-muted">Check every+ <select className="select h-10" aria-label={`Check interval of ${server.hostname}`} value={server.check_interval_seconds} onChange={(event) => save(server, { check_interval_seconds: Number(event.target.value) })}>+ {!INTERVALS.some(([value]) => value === server.check_interval_seconds) && <option value={server.check_interval_seconds}>{intervalLabel(server.check_interval_seconds)}</option>}+ {INTERVALS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </label>+ <button type="button" className="btn btn-ghost h-10 text-signal" onClick={() => remove(server)}>Remove</button>+ </div>+ </li>+ )+ })}+ {!servers.length && <li className="px-4 py-6 text-center text-xs text-muted">No servers yet. Connect one below.</li>}+ </ul>+ <div className="custom-scroll hidden overflow-x-auto md:block"><table className="w-full min-w-[820px] border-collapse text-left text-[13px]"><thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">Server</th><th className="font-medium">Address</th><th className="font-medium">Collector</th><th className="font-medium">Check every</th><th className="font-medium">Last check-in</th><th className="font-medium">System helper</th><th className="pr-[18px]" /></tr></thead><tbody>{servers.map((server) => {diff --git a/src/frontend/src/dashboard/Containers.jsx b/src/frontend/src/dashboard/Containers.jsxindex 4f62671..1819025 100644--- a/src/frontend/src/dashboard/Containers.jsx+++ b/src/frontend/src/dashboard/Containers.jsx@@ -12,7 +12,7 @@ import {const COLUMNS = 'grid-cols-[196px_minmax(140px,1.1fr)_128px_150px_161px_minmax(150px,1fr)_52px_72px]'const READ_ONLY_NOTE = 'Infradeck only reads from Docker for now, so it cannot fetch logs or restart a container yet.'const FILTER_LABELS = { all: 'All', problems: 'Problems', exposed: 'Exposed', restarted: 'Restarted', stopped: 'Stopped' }-const APP_PROJECT = /infradeck|homelab|homie/i+const APP_PROJECT = /infradeck|homie/ifunction statusTone(container) {if (container.status === 'running') return container.healthcheck_status === 'unhealthy' ? 'text-signal' : 'text-ok'diff --git a/src/frontend/src/dashboard/EmptyFleet.jsx b/src/frontend/src/dashboard/EmptyFleet.jsxindex 401fe73..28f777a 100644--- a/src/frontend/src/dashboard/EmptyFleet.jsx+++ b/src/frontend/src/dashboard/EmptyFleet.jsx@@ -139,7 +139,7 @@ function EnrollmentKey() {return (<div className="mt-2.5 text-xs">- <p className="m-0 text-muted">For scripted installs where nobody clicks Add: collectors started with <span className="mono text-soft">HOMELAB_ENROLL_KEY</span> join immediately. Servers already connected are unaffected by rotating or revoking it.</p>+ <p className="m-0 text-muted">For scripted installs where nobody clicks Add: collectors started with <span className="mono text-soft">INFRADECK_ENROLL_KEY</span> join immediately. Servers already connected are unaffected by rotating or revoking it.</p>{error && <div className="mt-2.5"><Notice>{error}</Notice></div>}{!keyInfo ? <p className="mb-0 mt-2.5 text-muted">Loading…</p> : enrollKey ? <><p className="mb-0 mt-2.5 text-warn">Copy this key now. It is shown only once.</p>diff --git a/src/frontend/src/dashboard/ServerPanel.jsx b/src/frontend/src/dashboard/ServerPanel.jsxindex 65db7fd..a862073 100644--- a/src/frontend/src/dashboard/ServerPanel.jsx+++ b/src/frontend/src/dashboard/ServerPanel.jsx@@ -43,7 +43,7 @@ function HealthChecks({ server }) {</li>))}</ul>- {help && <p className="mb-0 mt-2 text-[11px] leading-[18px] text-muted">The internet check is off until this machine's collector is given targets: set <span className="mono text-soft">HOMELAB_CONNECTIVITY_TARGETS</span> (for example <span className="mono text-soft">1.1.1.1:443,dns.google:443</span>) in its environment and restart it.</p>}+ {help && <p className="mb-0 mt-2 text-[11px] leading-[18px] text-muted">The internet check is off until this machine's collector is given targets: set <span className="mono text-soft">INFRADECK_CONNECTIVITY_TARGETS</span> (for example <span className="mono text-soft">1.1.1.1:443,dns.google:443</span>) in its environment and restart it.</p>}</div>)}diff --git a/src/frontend/src/dashboard/logic.js b/src/frontend/src/dashboard/logic.jsindex 378d3ea..eb75245 100644--- a/src/frontend/src/dashboard/logic.js+++ b/src/frontend/src/dashboard/logic.js@@ -611,27 +611,27 @@ export function eventsToCsv(events) {// The same two hardened containers (collector plus read-only Docker proxy), three ways to start them.export function installCommands({ url, token, name, collectorImage, proxyImage }) {- const nameLine = name ? `\n HOMELAB_SERVER_NAME: ${name}` : ''+ const nameLine = name ? `\n INFRADECK_SERVER_NAME: ${name}` : ''const compose = `services:collector:image: ${collectorImage}- container_name: homelab-collector+ container_name: infradeck-collectorrestart: unless-stoppedenvironment:- HOMELAB_API_URL: ${url}- HOMELAB_JOIN_TOKEN: ${token}${nameLine}- HOMELAB_DOCKER_HOST: /run/docker-proxy/docker.sock+ INFRADECK_API_URL: ${url}+ INFRADECK_JOIN_TOKEN: ${token}${nameLine}+ INFRADECK_DOCKER_HOST: /run/docker-proxy/docker.sockvolumes:- /proc:/host/proc:ro- /:/hostfs:ro- - collector_state:/var/lib/homelab-collector+ - collector_state:/var/lib/infradeck-collector- docker_proxy_socket:/run/docker-proxy:rocap_drop: [ALL]read_only: truesecurity_opt: [no-new-privileges:true]docker-proxy:image: ${proxyImage}- container_name: homelab-docker-proxy+ container_name: infradeck-docker-proxyrestart: unless-stoppeduser: "0:0"network_mode: none@@ -645,19 +645,19 @@ volumes:collector_state:docker_proxy_socket:`const hardened = '--restart unless-stopped --cap-drop ALL --read-only --security-opt no-new-privileges:true'- const nameFlag = name ? ` \\\n -e HOMELAB_SERVER_NAME=${name}` : ''- const dockerRun = `docker run -d --name homelab-docker-proxy ${hardened} \\+ const nameFlag = name ? ` \\\n -e INFRADECK_SERVER_NAME=${name}` : ''+ const dockerRun = `docker run -d --name infradeck-docker-proxy ${hardened} \\--user 0:0 --network none \\-v /var/run/docker.sock:/var/run/docker.sock \\- -v homelab_docker_proxy_socket:/run/docker-proxy \\+ -v infradeck_docker_proxy_socket:/run/docker-proxy \\${proxyImage}-docker run -d --name homelab-collector ${hardened} \\- -e HOMELAB_API_URL=${url} \\- -e HOMELAB_JOIN_TOKEN=${token}${nameFlag} \\- -e HOMELAB_DOCKER_HOST=/run/docker-proxy/docker.sock \\+docker run -d --name infradeck-collector ${hardened} \\+ -e INFRADECK_API_URL=${url} \\+ -e INFRADECK_JOIN_TOKEN=${token}${nameFlag} \\+ -e INFRADECK_DOCKER_HOST=/run/docker-proxy/docker.sock \\-v /proc:/host/proc:ro -v /:/hostfs:ro \\- -v homelab_collector_state:/var/lib/homelab-collector \\- -v homelab_docker_proxy_socket:/run/docker-proxy:ro \\+ -v infradeck_collector_state:/var/lib/infradeck-collector \\+ -v infradeck_docker_proxy_socket:/run/docker-proxy:ro \\${collectorImage}`const systemd = `sudo mkdir -p /etc/infradeck-collectorsudo tee /etc/infradeck-collector/compose.yml >/dev/null <<'EOF'@@ -672,13 +672,13 @@ After=docker.service network-online.target[Service]Type=oneshotRemainAfterExit=yes-ExecStart=/usr/bin/docker compose -p homelab-collector -f /etc/infradeck-collector/compose.yml up -d-ExecStop=/usr/bin/docker compose -p homelab-collector -f /etc/infradeck-collector/compose.yml down+ExecStart=/usr/bin/docker compose -p infradeck-collector -f /etc/infradeck-collector/compose.yml up -d+ExecStop=/usr/bin/docker compose -p infradeck-collector -f /etc/infradeck-collector/compose.yml down[Install]WantedBy=multi-user.targetEOFsudo systemctl daemon-reloadsudo systemctl enable --now infradeck-collector`- return { 'docker run': dockerRun, compose: `docker compose -p homelab-collector -f - up -d <<'EOF'\n${compose}\nEOF`, systemd }+ return { 'docker run': dockerRun, compose: `docker compose -p infradeck-collector -f - up -d <<'EOF'\n${compose}\nEOF`, systemd }}diff --git a/src/frontend/src/statistics/StatisticsPage.jsx b/src/frontend/src/statistics/StatisticsPage.jsxindex d723a87..012139a 100644--- a/src/frontend/src/statistics/StatisticsPage.jsx+++ b/src/frontend/src/statistics/StatisticsPage.jsx@@ -16,7 +16,7 @@ import { Timeline } from './Timeline.jsx'import { RANGES, RANGE_BY_ID, deltaPoints, eventMarks, findGaps, findings, formatMoment, summarize, timelineCsv } from './logic.js'const DEFAULT_RANGE = '7d'-const RANGE_KEY = 'homelab.statisticsRange'+const RANGE_KEY = 'infradeck.statisticsRange'const COMPARE_KEY = 'infradeck.statistics.compare'// Only short ranges change from one minute to the next.const LIVE = new Set(['1h', '6h', '24h'])diff --git a/src/frontend/tests/dashboardLogic.test.js b/src/frontend/tests/dashboardLogic.test.jsindex 92c96bd..03cdc92 100644--- a/src/frontend/tests/dashboardLogic.test.js+++ b/src/frontend/tests/dashboardLogic.test.js@@ -182,5 +182,5 @@ test('the install commands carry the token and the chosen name three ways', () =for (const command of Object.values(commands)) {assert.ok(command.includes('jt_abc') && command.includes('homelab-01') && command.includes('ghcr.io/x/proxy@sha256:2'))}- assert.ok(!installCommands({ url: 'u', token: 't', name: '', collectorImage: 'c', proxyImage: 'p' }).compose.includes('HOMELAB_SERVER_NAME'))+ assert.ok(!installCommands({ url: 'u', token: 't', name: '', collectorImage: 'c', proxyImage: 'p' }).compose.includes('INFRADECK_SERVER_NAME'))})diff --git a/tests/accounts/test_account_security.py b/tests/accounts/test_account_security.pyindex 7cf0246..e942e84 100644--- a/tests/accounts/test_account_security.py+++ b/tests/accounts/test_account_security.py@@ -911,7 +911,7 @@ def test_the_sessions_index_keeps_digests_not_session_ids(app):def test_a_session_stored_under_the_raw_cookie_value_is_not_accepted(app):"""What an old-format key (or a guess at one) looks like: the cookie value itself in the key."""- app.redis.set("homelab:session:planted-cookie-value", json.dumps({"user_id": 1, "email": "[email protected]", "name": "A", "role": "admin", "stage": "full", "public_id": "0" * 16}))+ app.redis.set("infradeck:session:planted-cookie-value", json.dumps({"user_id": 1, "email": "[email protected]", "name": "A", "role": "admin", "stage": "full", "public_id": "0" * 16}))client = TestClient(main.app, cookies={COOKIE: "planted-cookie-value"})assert client.get("/monitoring/overview").status_code == 401@@ -930,19 +930,19 @@ def test_listing_and_ending_sessions_still_work_with_digests(app):def test_old_format_session_data_is_removed_at_start_and_new_data_is_kept(app):client = _signed_in("[email protected]")- old_session, old_pending, old_attempts = "homelab:session:" + "a" * 43, "homelab:2fa-pending:" + "b" * 43, "homelab:2fa-attempts:" + "c" * 43+ old_session, old_pending, old_attempts = "infradeck:session:" + "a" * 43, "infradeck:2fa-pending:" + "b" * 43, "infradeck:2fa-attempts:" + "c" * 43for key in (old_session, old_pending, old_attempts):app.redis.set(key, "x")- app.redis.hset("homelab:user-sessions:9", "0123456789abcdef", "raw-session-id-not-a-digest")- before = len(app.redis.keys("homelab:session:*"))+ app.redis.hset("infradeck:user-sessions:9", "0123456789abcdef", "raw-session-id-not-a-digest")+ before = len(app.redis.keys("infradeck:session:*"))removed = auth.purge_legacy_session_keys(app.redis)assert removed == 4for key in (old_session, old_pending, old_attempts):assert app.redis.get(key) is None- assert app.redis.hgetall("homelab:user-sessions:9") == {}- assert len(app.redis.keys("homelab:session:*")) == before - 1 and client.get("/auth/me").status_code == 200 # the live session survived+ assert app.redis.hgetall("infradeck:user-sessions:9") == {}+ assert len(app.redis.keys("infradeck:session:*")) == before - 1 and client.get("/auth/me").status_code == 200 # the live session surviveddef test_the_cleanup_of_old_session_data_never_stops_the_backend_from_starting(app):@@ -956,7 +956,7 @@ def test_the_cleanup_of_old_session_data_never_stops_the_backend_from_starting(a# --- staying signed in, and what the sign-in page may know ----------------------------------------------def _session_ttls(app):- return sorted(ttl for key, ttl in app.redis.ttls.items() if key.startswith("homelab:session:"))+ return sorted(ttl for key, ttl in app.redis.ttls.items() if key.startswith("infradeck:session:"))def _cookie_max_age(response):@@ -1024,3 +1024,21 @@ def test_a_new_install_has_no_name_yet(app):config = TestClient(main.app).get("/auth/config").json()assert config["bootstrap_required"] is True and config["instance_name"] is None+++def test_redis_keys_from_before_the_rename_move_to_the_new_prefix_once(app):+ """An upgrade from the homelab: prefix keeps everyone signed in and remembers which alerts went out."""+ client = _signed_in("[email protected]")+ session_key = next(key for key in app.redis.keys("infradeck:session:*"))+ index_key = "infradeck:user-sessions:2"+ app.redis.rename(session_key, "homelab:" + session_key[len("infradeck:"):])+ app.redis.rename(index_key, "homelab:user-sessions:2")+ app.redis.set("homelab:notified:7:1:critical", "1", ex=100)+ app.redis.set("infradeck:notified:8:1:critical", "new")+ app.redis.set("homelab:notified:8:1:critical", "old")+ assert client.get("/auth/me").status_code == 401 # not found under the new name yet++ assert auth.migrate_key_prefix(app.redis) == 3+ assert client.get("/auth/me").status_code == 200 and app.redis.hgetall(index_key)+ assert app.redis.ttl("infradeck:notified:7:1:critical") == 100 and app.redis.get("infradeck:notified:8:1:critical") == "new"+ assert auth.migrate_key_prefix(app.redis) == 0diff --git a/tests/accounts/test_admin.py b/tests/accounts/test_admin.pyindex ea92a25..b4b9bbc 100644--- a/tests/accounts/test_admin.py+++ b/tests/accounts/test_admin.py@@ -154,7 +154,7 @@ def test_admin_can_turn_agent_chat_off_and_on(fleet, monkeypatch):result = main.update_admin_settings(main.AdminSettingsRequest(agent_chat_enabled=False), session_id="s", db=fleet)- assert result == {"instance_name": main.get_instance_name(fleet), "metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": False, "require_2fa_for_everyone": False, "disabled_rules": []}+ assert result == {"instance_name": main.get_instance_name(fleet), "metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": main.secrets_box.available(), "require_2fa_for_everyone": False, "disabled_rules": []}_login_as(monkeypatch, 2)assert main.agent_config(session_id="s", db=fleet) == {"chat_enabled": False}diff --git a/tests/collectors/test_dashboard_host.py b/tests/collectors/test_dashboard_host.pyindex 0a02944..9c12eda 100644--- a/tests/collectors/test_dashboard_host.py+++ b/tests/collectors/test_dashboard_host.py@@ -69,10 +69,10 @@ def test_history_of_unknown_server_is_404(db):def test_collector_sends_flag_only_when_configured(monkeypatch):- monkeypatch.setenv("HOMELAB_DASHBOARD_HOST", "true")+ monkeypatch.setenv("INFRADECK_DASHBOARD_HOST", "true")assert collector.collect_host()[0]["dashboard_host"] is True- monkeypatch.delenv("HOMELAB_DASHBOARD_HOST")+ monkeypatch.delenv("INFRADECK_DASHBOARD_HOST")assert "dashboard_host" not in collector.collect_host()[0]diff --git a/tests/collectors/test_enrollment.py b/tests/collectors/test_enrollment.pyindex beea3db..9bb675a 100644--- a/tests/collectors/test_enrollment.py+++ b/tests/collectors/test_enrollment.py@@ -103,10 +103,10 @@ def test_recently_seen_server_is_not_offline(db):def test_collector_prefers_saved_credentials_over_enrolling(tmp_path, monkeypatch):- monkeypatch.setenv("HOMELAB_STATE_DIR", str(tmp_path))- monkeypatch.delenv("HOMELAB_SERVER_ID", raising=False)- monkeypatch.delenv("HOMELAB_COLLECTOR_TOKEN", raising=False)- monkeypatch.setenv("HOMELAB_ENROLL_KEY", "hlk_key")+ monkeypatch.setenv("INFRADECK_STATE_DIR", str(tmp_path))+ monkeypatch.delenv("INFRADECK_SERVER_ID", raising=False)+ monkeypatch.delenv("INFRADECK_COLLECTOR_TOKEN", raising=False)+ monkeypatch.setenv("INFRADECK_ENROLL_KEY", "hlk_key")collector.save_credentials(7, "saved-token")monkeypatch.setattr(collector, "enroll", lambda *args: pytest.fail("should not enroll"))@@ -114,10 +114,10 @@ def test_collector_prefers_saved_credentials_over_enrolling(tmp_path, monkeypatcdef test_collector_enrolls_and_saves_when_no_credentials(tmp_path, monkeypatch):- monkeypatch.setenv("HOMELAB_STATE_DIR", str(tmp_path))- monkeypatch.delenv("HOMELAB_SERVER_ID", raising=False)- monkeypatch.delenv("HOMELAB_COLLECTOR_TOKEN", raising=False)- monkeypatch.setenv("HOMELAB_ENROLL_KEY", "hlk_key")+ monkeypatch.setenv("INFRADECK_STATE_DIR", str(tmp_path))+ monkeypatch.delenv("INFRADECK_SERVER_ID", raising=False)+ monkeypatch.delenv("INFRADECK_COLLECTOR_TOKEN", raising=False)+ monkeypatch.setenv("INFRADECK_ENROLL_KEY", "hlk_key")monkeypatch.setattr(collector, "enroll", lambda api_url, key: (9, "new-token"))assert collector.resolve_credentials("http://backend") == (9, "new-token")@@ -128,7 +128,19 @@ def test_collector_enrolls_and_saves_when_no_credentials(tmp_path, monkeypatch):def test_machine_id_read_from_host_root(tmp_path, monkeypatch):(tmp_path / "etc").mkdir()(tmp_path / "etc/machine-id").write_text("abc123\n")- monkeypatch.delenv("HOMELAB_MACHINE_ID", raising=False)+ monkeypatch.delenv("INFRADECK_MACHINE_ID", raising=False)monkeypatch.setattr(collector, "HOST_ROOT", tmp_path)assert collector._machine_id() == "abc123"+++def test_a_collector_from_before_the_rename_keeps_its_credentials_and_settings(tmp_path, monkeypatch):+ from src.agent import collector+ legacy = tmp_path / "homelab-collector"+ legacy.mkdir()+ (legacy / "credentials.json").write_text('{"server_id": 4, "token": "t"}')+ monkeypatch.delenv("INFRADECK_STATE_DIR", raising=False)+ monkeypatch.setattr(collector, "LEGACY_STATE_DIR", legacy)+ assert collector._credentials_path() == legacy / "credentials.json"+ monkeypatch.setenv("INFRADECK_STATE_DIR", str(tmp_path / "new"))+ assert collector._credentials_path() == tmp_path / "new" / "credentials.json"diff --git a/tests/collectors/test_ingest_validation.py b/tests/collectors/test_ingest_validation.pyindex 54e5618..2bc686e 100644--- a/tests/collectors/test_ingest_validation.py+++ b/tests/collectors/test_ingest_validation.py@@ -229,7 +229,7 @@ def test_a_check_in_that_follows_the_last_one_too_closely_is_refused(app, spaceddef test_the_next_check_in_is_accepted_when_the_slot_has_passed(app, spaced):ingest(app, 1, {"host": {}})- main.redis_client.delete("homelab:ingest:1") # the key expires after the spacing+ main.redis_client.delete("infradeck:ingest:1") # the key expires after the spacingassert ingest(app, 1, {"host": {}}).status_code == 200diff --git a/tests/collectors/test_pending_collectors.py b/tests/collectors/test_pending_collectors.pyindex 320b61f..0ea370d 100644--- a/tests/collectors/test_pending_collectors.py+++ b/tests/collectors/test_pending_collectors.py@@ -148,8 +148,8 @@ def test_collector_waits_for_approval_without_restart(monkeypatch):def test_collector_without_key_or_credentials_requests_approval(tmp_path, monkeypatch):- monkeypatch.setenv("HOMELAB_STATE_DIR", str(tmp_path))- for name in ("HOMELAB_SERVER_ID", "HOMELAB_COLLECTOR_TOKEN", "HOMELAB_ENROLL_KEY"):+ monkeypatch.setenv("INFRADECK_STATE_DIR", str(tmp_path))+ for name in ("INFRADECK_SERVER_ID", "INFRADECK_COLLECTOR_TOKEN", "INFRADECK_ENROLL_KEY"):monkeypatch.delenv(name, raising=False)monkeypatch.setattr(collector, "request_approval", lambda api_url: (11, "approved-token"))@@ -166,7 +166,7 @@ def test_collector_sends_its_join_token_when_registering(monkeypatch):return {"request_secret": "s", "pairing_code": "ABC-123", "poll_interval_seconds": 2}return {"status": "approved", "server_id": 4, "collector_token": "tok"}- monkeypatch.setenv("HOMELAB_JOIN_TOKEN", "hlj_abc ")+ monkeypatch.setenv("INFRADECK_JOIN_TOKEN", "hlj_abc ")monkeypatch.setattr(collector, "_post_json", fake_post)monkeypatch.setattr(collector.time, "sleep", lambda seconds: None)@@ -176,7 +176,7 @@ def test_collector_sends_its_join_token_when_registering(monkeypatch):def test_collector_without_a_join_token_sends_none(monkeypatch):sent = []- monkeypatch.delenv("HOMELAB_JOIN_TOKEN", raising=False)+ monkeypatch.delenv("INFRADECK_JOIN_TOKEN", raising=False)monkeypatch.setattr(collector, "_post_json", lambda url, payload, bearer=None: sent.append(payload) or {"request_secret": "s", "pairing_code": "A", "poll_interval_seconds": 2} if url.endswith("/register") else {"status": "approved", "server_id": 1, "collector_token": "t"})monkeypatch.setattr(collector.time, "sleep", lambda seconds: None)collector.request_approval("http://dash/api")diff --git a/tests/fakes.py b/tests/fakes.pyindex 21f28c7..587ccc5 100644--- a/tests/fakes.py+++ b/tests/fakes.py@@ -39,6 +39,20 @@ class FakeRedis:self.ttls[key] = secondsreturn True+ def exists(self, *keys):+ return sum(int(key in self.store or key in self.hashes) for key in keys)++ def rename(self, key, target):+ if key in self.store:+ self.store[target] = self.store.pop(key)+ elif key in self.hashes:+ self.hashes[target] = self.hashes.pop(key)+ else:+ raise KeyError(key)+ if key in self.ttls:+ self.ttls[target] = self.ttls.pop(key)+ return True+def ttl(self, key):return self.ttls.get(key, -1)diff --git a/tests/history/test_stats.py b/tests/history/test_stats.pyindex 5aa7fca..0c7e660 100644--- a/tests/history/test_stats.py+++ b/tests/history/test_stats.py@@ -206,7 +206,7 @@ def test_answers_are_cached_for_a_minute_per_range_only(db, client, monkeypatch)client.get("/stats/fleet?range=7d"); client.get("/stats/fleet?range=7d"); client.get("/stats/fleet?range=30d")assert calls == ["7d", "30d"]- assert sorted(key for key in main.redis_client.keys("*")) == ["homelab:stats:fleet:30d", "homelab:stats:fleet:7d"]+ assert sorted(key for key in main.redis_client.keys("*")) == ["infradeck:stats:fleet:30d", "infradeck:stats:fleet:7d"]def test_a_broken_cache_does_not_break_the_page(db, client, monkeypatch):@@ -286,11 +286,11 @@ def test_the_heatmap_is_the_same_before_and_after_summarising(db):def test_the_heatmap_endpoint_validates_everything_and_caches_per_server_metric_and_offset(db, client):assert client.get("/stats/servers/1/heatmap?metric=cpu&offset=60").status_code == 200assert client.get("/stats/servers/1/heatmap?metric=cpu&offset=60").status_code == 200- assert main.redis_client.keys("*") == ["homelab:stats:heatmap:1:cpu:60"]+ assert main.redis_client.keys("*") == ["infradeck:stats:heatmap:1:cpu:60"]for query in ("metric=disk", "metric=cpu;x", "offset=900", "offset=-900", "offset=abc", "offset=1.5"):assert client.get(f"/stats/servers/1/heatmap?{query}").status_code == 422assert client.get("/stats/servers/999/heatmap").status_code == 404- assert main.redis_client.keys("*") == ["homelab:stats:heatmap:1:cpu:60"] # refused requests left nothing behind+ assert main.redis_client.keys("*") == ["infradeck:stats:heatmap:1:cpu:60"] # refused requests left nothing behinddef test_the_heatmap_endpoint_needs_a_session(db, monkeypatch):diff --git a/tests/monitoring/test_container_checks.py b/tests/monitoring/test_container_checks.pyindex 880b4e4..a1d05ca 100644--- a/tests/monitoring/test_container_checks.py+++ b/tests/monitoring/test_container_checks.py@@ -52,7 +52,7 @@ def _events(db, *kinds):# --- collector: Docker status (#22) -----------------------------------------------------------------def _clear_docker_env(monkeypatch, tmp_path):- monkeypatch.delenv("HOMELAB_DOCKER_HOST", raising=False)+ monkeypatch.delenv("INFRADECK_DOCKER_HOST", raising=False)monkeypatch.setenv("DOCKER_SOCKET_PATH", str(tmp_path / "no-such-docker.sock"))@@ -63,7 +63,7 @@ def test_a_host_without_docker_is_not_configured_not_broken(monkeypatch, tmp_patdef test_a_configured_but_missing_proxy_socket_is_unreachable(monkeypatch, tmp_path):- monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(tmp_path / "proxy.sock"))+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", str(tmp_path / "proxy.sock"))_containers, status = collector.collect_docker()@@ -75,7 +75,7 @@ def test_a_stale_socket_nobody_listens_on_is_reported_as_refused(monkeypatch, tmlistener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)listener.bind(path)listener.close() # leaves the socket file behind, like a stopped proxy- monkeypatch.setenv("HOMELAB_DOCKER_HOST", path)+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", path)containers, status = collector.collect_docker()@@ -96,7 +96,7 @@ def test_a_working_daemon_reports_ok_with_its_latency(monkeypatch, tmp_path):cid = "c" * 64answers = {"/containers/json?all=1": [{"Id": cid, "Names": ["/web"]}], f"/containers/{cid}/json": {"Name": "/web", "State": {"Status": "running"}, "Config": {"Image": "nginx"}}}monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: answers.get(endpoint, {}))- monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", str(socket_path))containers, status = collector.collect_docker()@@ -108,7 +108,7 @@ def test_a_daemon_error_during_listing_is_unreachable(monkeypatch, tmp_path):socket_path = tmp_path / "docker.sock"socket_path.touch()monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: (_ for _ in ()).throw(OSError("Docker API returned HTTP 502")))- monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", str(socket_path))containers, status = collector.collect_docker()@@ -128,7 +128,7 @@ def test_one_container_vanishing_mid_collection_does_not_fail_the_rest(monkeypatreturn {"Name": "/web", "State": {"Status": "exited"}}monkeypatch.setattr(collector, "_docker_request", request)- monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", str(socket_path))containers, status = collector.collect_docker()@@ -145,7 +145,7 @@ def test_when_nothing_can_be_inspected_the_daemon_is_failing_not_empty(monkeypatraise OSError("Docker API returned HTTP 502")monkeypatch.setattr(collector, "_docker_request", request)- monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))+ monkeypatch.setenv("INFRADECK_DOCKER_HOST", str(socket_path))containers, status = collector.collect_docker()diff --git a/tests/monitoring/test_network_checks.py b/tests/monitoring/test_network_checks.pyindex 56a737b..39763e3 100644--- a/tests/monitoring/test_network_checks.py+++ b/tests/monitoring/test_network_checks.py@@ -177,7 +177,7 @@ def test_the_listener_report_is_capped(tmp_path, monkeypatch):# --- collector: connectivity ------------------------------------------------------------------------def test_connectivity_is_off_unless_targets_are_configured(monkeypatch):- monkeypatch.delenv("HOMELAB_CONNECTIVITY_TARGETS", raising=False)+ monkeypatch.delenv("INFRADECK_CONNECTIVITY_TARGETS", raising=False)assert collector.collect_connectivity() == {"internet_status": None, "internet_latency_ms": None}@@ -187,14 +187,14 @@ def test_connectivity_is_off_unless_targets_are_configured(monkeypatch):("a.com:1,b.com:2,c.com:3,d.com:4,e.com:5,f.com:6,g.com:7", [("a.com", 1), ("b.com", 2), ("c.com", 3), ("d.com", 4), ("e.com", 5)]),])def test_valid_targets_are_parsed_deduplicated_and_capped(monkeypatch, value, expected):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", value)+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", value)assert collector._connectivity_targets() == expected@pytest.mark.parametrize("bad", ["", "nohost", ":443", "host:", "host:0", "host:65536", "host:abc", "host:-1", "http://example.com:443", "exa mple.com:443", "example.com;rm -rf /:443","999.1.1.1:443", "1.1.1:443", "[::1]:443", "-bad.com:443", "a" * 300 + ".com:443", "user@host:443", "host:443/path", "host\n:443"])def test_malformed_targets_are_ignored(monkeypatch, bad):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", bad)+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", bad)assert collector._connectivity_targets() == []@@ -210,7 +210,7 @@ def test_results_are_summarised(results, status):def test_a_reachable_target_reports_ok_with_its_latency(monkeypatch):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "example.com:443,1.1.1.1:443")+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", "example.com:443,1.1.1.1:443")monkeypatch.setattr(collector.socket, "getaddrinfo", lambda host, port, **kw: [(None, None, None, "", ("93.184.216.34", port))])class Connection:@@ -225,14 +225,14 @@ def test_a_reachable_target_reports_ok_with_its_latency(monkeypatch):def test_unresolvable_names_are_reported_as_dns_failure(monkeypatch):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "example.com:443")+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", "example.com:443")monkeypatch.setattr(collector.socket, "getaddrinfo", lambda *a, **k: (_ for _ in ()).throw(OSError("no dns")))assert collector.collect_connectivity()["internet_status"] == "dns_failed"def test_a_hung_probe_cannot_stall_the_check_in(monkeypatch):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "1.1.1.1:443")+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", "1.1.1.1:443")monkeypatch.setattr(collector, "CONNECTIVITY_DEADLINE_SECONDS", 0.3)monkeypatch.setattr(collector.socket, "create_connection", lambda address, timeout: time.sleep(3))@@ -243,7 +243,7 @@ def test_a_hung_probe_cannot_stall_the_check_in(monkeypatch):def test_probes_only_connect_and_never_send_data(monkeypatch):- monkeypatch.setenv("HOMELAB_CONNECTIVITY_TARGETS", "1.1.1.1:443")+ monkeypatch.setenv("INFRADECK_CONNECTIVITY_TARGETS", "1.1.1.1:443")sent = []class Connection:diff --git a/tests/security/test_second_review.py b/tests/security/test_second_review.pyindex 195af67..95090a0 100644--- a/tests/security/test_second_review.py+++ b/tests/security/test_second_review.py@@ -326,7 +326,7 @@ def test_a_limited_session_expires_sooner_than_a_full_one(app):_, _ = auth.create_session(app.redis, user, stage=auth.STAGE_ENROLLMENT)_, _ = auth.create_session(app.redis, user, stage=auth.STAGE_FULL)- lifetimes = sorted(app.redis.ttls[key] for key in app.redis.store if key.startswith("homelab:session:"))+ lifetimes = sorted(app.redis.ttls[key] for key in app.redis.store if key.startswith("infradeck:session:"))assert lifetimes == [auth.ENROLLMENT_SESSION_TTL_SECONDS, auth.SESSION_TTL_SECONDS] and auth.ENROLLMENT_SESSION_TTL_SECONDS <= 1800