Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docsview): serve the documentation read-only behind a key

Pouzora7f64408ab98
diff --git a/.env.example b/.env.example
index 77d3db2..da5b10c 100644
--- a/.env.example
+++ b/.env.example
@@ -66,6 +66,13 @@ MCP_SERVICE_KEY=svc_changeme
# Generate: python3 -c "import secrets; print(secrets.token_urlsafe(32))"
# LIVEVIEW_KEY=
+# Documentation view — read-only public documentation at /docs?key=<value>
+# Off by default. Set to a random secret to enable.
+# Anyone with the URL reads EVERY document, including any image a document
+# embeds. Its own key, separate from LIVEVIEW_KEY.
+# Generate: python3 -c "import secrets; print(secrets.token_urlsafe(32))"
+# DOCS_VIEW_KEY=
+
# Gethomepage widget — read-only stats at /api/v1/stats/summary
# Off by default. Set to a random secret to enable; clients must send
# the same value in the `X-API-Key` header.
diff --git a/README.md b/README.md
index a4c9f31..01da534 100644
--- a/README.md
+++ b/README.md
@@ -300,6 +300,40 @@ The page shows your canvas in pan/zoom-only mode — no editing, no credentials
---
+## Documentation View (read-only public documentation)
+
+Documentation View shares your documentation space — the tree, the pages and their
+version history — with anyone on your network, no login required. It is disabled by
+default, and uses its own key: enabling Live View does not enable this.
+
+### Activation
+
+Add `DOCS_VIEW_KEY` to your `.env`:
+
+`DOCS_VIEW_KEY=your-secret-key`
+
+Generate one with `python3 -c "import secrets; print(secrets.token_urlsafe(32))"`, then
+restart the backend:
+
+`docker compose restart backend`
+
+### Usage
+
+Use this URL to read your documentation:
+
+`http://<your-homelab-ip>/docs?key=your-secret-key`
+
+The page shows the document tree, the filter box and any page you pick, plus its earlier
+versions. Nothing can be written: no editing, no restoring, no deleting. Your device
+inventory and your canvases are not reachable through it.
+
+> **Anyone holding that URL reads every document**, and every image a document embeds —
+> uploaded media is served without authentication. There is no per-document opt-in: the
+> key is all or nothing. Keep documentation you would not share out of Homelable, or
+> leave this off.
+
+---
+
## Gethomepage Widget (read-only stats)
Homelable can expose a small JSON stats endpoint that [gethomepage](https://gethomepage.dev) consumes through its built-in `customapi` widget. Disabled by default.
diff --git a/backend/app/api/routes/docsview.py b/backend/app/api/routes/docsview.py
new file mode 100644
index 0000000..3b0c34a
--- /dev/null
+++ b/backend/app/api/routes/docsview.py
@@ -0,0 +1,151 @@
+"""Documentation view — the read-only public documentation space.
+
+Disabled by default. Setting `DOCS_VIEW_KEY` in `.env` opens `/docs?key=<value>`,
+which serves the documentation space to anyone holding the URL: the tree, a
+page, and that page's earlier versions. The same bargain as live view, one knob,
+off until someone turns it on.
+
+Two rules shape this module, and both are structural rather than a matter of
+being careful:
+
+- **It reads.** No POST, PATCH or DELETE is declared here, so there is no write
+ to forget to guard. Reading an old version is a read; *restoring* one is not,
+ and the restore route stays where it was, behind a session.
+- **It answers with its own schemas.** The `Public*` models in
+ `schemas.documents` name their fields one by one instead of inheriting from
+ the authenticated ones, so a document's links to a device, a canvas node or a
+ design — handles onto rows this key grants nothing of — never ride along.
+"""
+
+import hmac
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.deps import get_current_user
+from app.core.config import settings
+from app.db.database import get_db
+from app.db.models import Document, DocumentRevision
+from app.schemas.documents import (
+ PublicDocumentResponse,
+ PublicDocumentSummary,
+ PublicRevisionResponse,
+ PublicRevisionSummary,
+)
+
+router = APIRouter()
+
+
+class DocsViewConfigResponse(BaseModel):
+ """Whether the documentation view is enabled, plus the key (admin-only)."""
+
+ enabled: bool
+ key: str | None = None
+
+
+async def require_key(key: str | None = Query(default=None)) -> None:
+ """Gate every public route below on the configured key.
+
+ No key configured means the feature is off and the answer is 403 whatever is
+ presented — the key is never compared against an unset value, so enabling
+ this is always a deliberate edit to `.env`.
+ """
+ if not settings.docs_view_key:
+ raise HTTPException(status_code=403, detail="Documentation view is disabled")
+ if not key or not hmac.compare_digest(key, settings.docs_view_key):
+ raise HTTPException(status_code=403, detail="Invalid documentation view key")
+
+
[email protected]("/config", response_model=DocsViewConfigResponse)
+async def docsview_config(
+ _: str = Depends(get_current_user),
+) -> DocsViewConfigResponse:
+ """Authenticated: expose the configured key so the UI can build a
+ ready-to-use link (`/docs?key=...`).
+
+ Only reachable by a logged-in user — the key is never exposed publicly.
+ """
+ key = settings.docs_view_key or None
+ return DocsViewConfigResponse(enabled=bool(key), key=key)
+
+
[email protected]("/tree", response_model=list[PublicDocumentSummary])
+async def docsview_tree(
+ _: None = Depends(require_key),
+ db: AsyncSession = Depends(get_db),
+) -> list[PublicDocumentSummary]:
+ """Every document as a summary, in the order the tree renders them.
+
+ Bodies stay out, as they do for the authenticated listing: the tree badges
+ from the frontmatter cache, and the filter box narrows what is already here
+ without asking the server anything.
+ """
+ docs = (
+ await db.execute(select(Document).order_by(Document.sort_order, Document.title))
+ ).scalars().all()
+ return [PublicDocumentSummary.model_validate(doc) for doc in docs]
+
+
[email protected]("/revisions/{revision_id}", response_model=PublicRevisionResponse)
+async def docsview_revision(
+ revision_id: str,
+ _: None = Depends(require_key),
+ db: AsyncSession = Depends(get_db),
+) -> PublicRevisionResponse:
+ """One earlier version, to read. Declared above `/{document_id}` so
+ "revisions" is never read as a document id."""
+ revision = await db.get(DocumentRevision, revision_id)
+ if not revision:
+ raise HTTPException(404, "Revision not found")
+ return PublicRevisionResponse(
+ id=revision.id,
+ document_id=revision.document_id,
+ title=revision.title,
+ reason=revision.reason,
+ saved_at=revision.saved_at,
+ size=len(revision.body or ""),
+ body=revision.body or "",
+ )
+
+
[email protected]("/{document_id}", response_model=PublicDocumentResponse)
+async def docsview_document(
+ document_id: str,
+ _: None = Depends(require_key),
+ db: AsyncSession = Depends(get_db),
+) -> PublicDocumentResponse:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ return PublicDocumentResponse.model_validate(doc)
+
+
[email protected]("/{document_id}/revisions", response_model=list[PublicRevisionSummary])
+async def docsview_revisions(
+ document_id: str,
+ _: None = Depends(require_key),
+ db: AsyncSession = Depends(get_db),
+) -> list[PublicRevisionSummary]:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ revisions = (
+ await db.execute(
+ select(DocumentRevision)
+ .where(DocumentRevision.document_id == document_id)
+ .order_by(DocumentRevision.saved_at.desc(), DocumentRevision.id.desc())
+ )
+ ).scalars().all()
+ return [
+ PublicRevisionSummary(
+ id=r.id,
+ document_id=r.document_id,
+ title=r.title,
+ reason=r.reason,
+ saved_at=r.saved_at,
+ size=len(r.body or ""),
+ )
+ for r in revisions
+ ]
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index b681d4e..eceb932 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -194,6 +194,13 @@ class Settings(BaseSettings):
# Leave unset (or empty) to keep the feature disabled (default).
liveview_key: str | None = None
+ # Documentation view — optional read-only public documentation space.
+ # Set to a random secret string to enable /api/v1/docsview?key=<value>.
+ # Leave unset (or empty) to keep the feature disabled (default).
+ # Its own key, deliberately not liveview_key's: an install already sharing a
+ # canvas must not start serving every document because it upgraded.
+ docs_view_key: str | None = None
+
# Homepage widget — optional read-only stats endpoint for gethomepage.
# Set to a random secret to enable /api/v1/stats/summary (X-API-Key header).
# Leave empty to keep the feature disabled (default).
diff --git a/backend/app/main.py b/backend/app/main.py
index c9545dd..cbe2499 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -12,6 +12,7 @@ from app.api.routes import (
auth,
canvas,
designs,
+ docsview,
documents,
edges,
liveview,
@@ -99,6 +100,7 @@ app.include_router(proxmox.router, prefix="/api/v1/proxmox", tags=["proxmox"])
app.include_router(stats.router, prefix="/api/v1/stats", tags=["stats"])
app.include_router(media.router, prefix="/api/v1/media", tags=["media"])
app.include_router(documents.router, prefix="/api/v1/documents", tags=["documents"])
+app.include_router(docsview.router, prefix="/api/v1/docsview", tags=["docsview"])
@app.get("/api/v1/health")
diff --git a/backend/app/schemas/documents.py b/backend/app/schemas/documents.py
index e298fd8..baa1e07 100644
--- a/backend/app/schemas/documents.py
+++ b/backend/app/schemas/documents.py
@@ -129,6 +129,62 @@ class RevisionResponse(RevisionSummary):
body: str = ""
+# ── Public (documentation view) ─────────────────────────────────────────────
+# What DOCS_VIEW_KEY opens to anyone holding the URL.
+#
+# Written out field by field rather than subclassed from the models above, and
+# that is the whole point: inheriting would enrol every field added to
+# `DocumentSummary` later into the public payload by default. What is missing
+# here is missing on purpose — `device_id`, `node_id`, `design_id`,
+# `facts_snapshot`, `facts_synced_at`, `drifted` and `template_id` are handles
+# onto inventory and canvas rows this key grants nothing of.
+
+
+class PublicDocumentSummary(BaseModel):
+ """What the public tree needs: placement, naming, badges. Never a body."""
+
+ id: str
+ kind: str
+ title: str
+ slug: str
+ icon: str | None = None
+ parent_id: str | None = None
+ sort_order: int = 0
+ tags: list[str] = []
+ # Parsed out of a body this key already serves, and what the tree badges
+ # "due for review" from — so it carries nothing the reader cannot see.
+ frontmatter: dict[str, Any] = {}
+ starred: bool = False
+ reviewed_at: datetime | None = None
+ edited_at: datetime | None = None
+ created_at: datetime
+ updated_at: datetime
+
+ model_config = {"from_attributes": True}
+
+
+class PublicDocumentResponse(PublicDocumentSummary):
+ body: str = ""
+
+
+class PublicRevisionSummary(BaseModel):
+ """One earlier version, listed. Reading history is a read; restoring is not,
+ and the public router offers no way to take one."""
+
+ id: str
+ document_id: str
+ title: str
+ reason: str
+ saved_at: datetime
+ size: int = 0
+
+ model_config = {"from_attributes": True}
+
+
+class PublicRevisionResponse(PublicRevisionSummary):
+ body: str = ""
+
+
class SearchHit(BaseModel):
doc_id: str
title: str
diff --git a/backend/tests/test_docsview.py b/backend/tests/test_docsview.py
new file mode 100644
index 0000000..0498f9e
--- /dev/null
+++ b/backend/tests/test_docsview.py
@@ -0,0 +1,275 @@
+"""
+Tests for the /api/v1/docsview read-only public documentation endpoints.
+
+The contract mirrors liveview:
+ - Disabled by default (DOCS_VIEW_KEY not set) → 403
+ - 403 for a missing or wrong key even when enabled
+ - Tree, page and revisions for a valid key (no JWT required)
+
+Plus the one this feature owns: the public payload must not carry a document's
+links to the inventory or a canvas, nor the fields derived from them.
+"""
+
+import pytest
+from httpx import AsyncClient
+
+from app.core.config import settings
+
+
[email protected](autouse=True)
+def reset_docs_view_key():
+ """Restore docs_view_key after each test so tests are isolated."""
+ original = settings.docs_view_key
+ yield
+ settings.docs_view_key = original
+
+
+async def _make_page(client: AsyncClient, headers: dict[str, str], title: str) -> dict:
+ res = await client.post(
+ "/api/v1/documents", json={"kind": "page", "title": title}, headers=headers
+ )
+ assert res.status_code == 201
+ return res.json()
+
+
+# ── Disabled (no key configured) ─────────────────────────────────────────────
+
+async def test_docsview_disabled_by_default(client: AsyncClient):
+ settings.docs_view_key = None
+ res = await client.get("/api/v1/docsview/tree?key=anything")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "Documentation view is disabled"
+
+
+async def test_docsview_disabled_when_key_empty(client: AsyncClient):
+ settings.docs_view_key = ""
+ res = await client.get("/api/v1/docsview/tree?key=anything")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "Documentation view is disabled"
+
+
+async def test_docsview_disabled_is_not_opened_by_the_liveview_key(client: AsyncClient):
+ """Sharing a canvas must never start serving documents."""
+ settings.docs_view_key = None
+ settings.liveview_key = "canvas-secret"
+ try:
+ res = await client.get("/api/v1/docsview/tree?key=canvas-secret")
+ assert res.status_code == 403
+ finally:
+ settings.liveview_key = None
+
+
+# ── Enabled but wrong / missing key ──────────────────────────────────────────
+
+async def test_docsview_wrong_key(client: AsyncClient):
+ settings.docs_view_key = "correct-secret"
+ res = await client.get("/api/v1/docsview/tree?key=wrong-key")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "Invalid documentation view key"
+
+
+async def test_docsview_missing_key_param(client: AsyncClient):
+ settings.docs_view_key = "correct-secret"
+ res = await client.get("/api/v1/docsview/tree")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "Invalid documentation view key"
+
+
+async def test_docsview_page_and_revisions_need_the_key(client: AsyncClient, headers):
+ settings.docs_view_key = "correct-secret"
+ doc = await _make_page(client, headers, "Offsite backups")
+
+ for path in (f"/api/v1/docsview/{doc['id']}", f"/api/v1/docsview/{doc['id']}/revisions"):
+ assert (await client.get(path)).status_code == 403
+ assert (await client.get(f"{path}?key=nope")).status_code == 403
+
+
+# ── Valid key — no JWT needed ────────────────────────────────────────────────
+
+async def test_docsview_tree_lists_documents(client: AsyncClient, headers):
+ settings.docs_view_key = "my-secret-key"
+ await _make_page(client, headers, "Offsite backups")
+ await _make_page(client, headers, "Where mail is hosted")
+
+ res = await client.get("/api/v1/docsview/tree?key=my-secret-key")
+ assert res.status_code == 200
+ titles = [d["title"] for d in res.json()]
+ assert "Offsite backups" in titles
+ assert "Where mail is hosted" in titles
+
+
+async def test_docsview_does_not_require_jwt(client: AsyncClient):
+ """No Authorization header anywhere — the key is the whole credential."""
+ settings.docs_view_key = "open-sesame"
+ res = await client.get("/api/v1/docsview/tree?key=open-sesame")
+ assert res.status_code == 200
+
+
+async def test_docsview_serves_the_body(client: AsyncClient, headers):
+ settings.docs_view_key = "test-key"
+ doc = await _make_page(client, headers, "Runbook")
+ await client.patch(
+ f"/api/v1/documents/{doc['id']}",
+ json={"body": "# Runbook\n\nPull the blue lever.\n"},
+ headers=headers,
+ )
+
+ res = await client.get(f"/api/v1/docsview/{doc['id']}?key=test-key")
+ assert res.status_code == 200
+ assert "Pull the blue lever." in res.json()["body"]
+
+
+async def test_docsview_unknown_document_is_404(client: AsyncClient):
+ settings.docs_view_key = "test-key"
+ res = await client.get("/api/v1/docsview/does-not-exist?key=test-key")
+ assert res.status_code == 404
+ assert res.json()["detail"] == "Document not found"
+
+
+# ── Revisions — readable, never restorable ───────────────────────────────────
+
+async def test_docsview_lists_and_reads_revisions(client: AsyncClient, headers):
+ settings.docs_view_key = "test-key"
+ doc = await _make_page(client, headers, "Runbook")
+ await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": "first version\n"}, headers=headers
+ )
+ await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": "second version\n"}, headers=headers
+ )
+
+ listed = await client.get(f"/api/v1/docsview/{doc['id']}/revisions?key=test-key")
+ assert listed.status_code == 200
+ revisions = listed.json()
+ assert len(revisions) == 2
+
+ body = await client.get(f"/api/v1/docsview/revisions/{revisions[0]['id']}?key=test-key")
+ assert body.status_code == 200
+ assert body.json()["body"] == "first version\n"
+
+
+async def test_docsview_unknown_revision_is_404(client: AsyncClient):
+ settings.docs_view_key = "test-key"
+ res = await client.get("/api/v1/docsview/revisions/nope?key=test-key")
+ assert res.status_code == 404
+ assert res.json()["detail"] == "Revision not found"
+
+
+async def test_docsview_offers_no_write_verbs(client: AsyncClient, headers):
+ """The router declares reads only, so every write is unroutable — including
+ restore, which is the one write a reader might otherwise reach for."""
+ settings.docs_view_key = "test-key"
+ doc = await _make_page(client, headers, "Runbook")
+ await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": "v1\n"}, headers=headers
+ )
+ revision = (
+ await client.get(f"/api/v1/docsview/{doc['id']}/revisions?key=test-key")
+ ).json()[0]
+
+ assert (await client.patch(
+ f"/api/v1/docsview/{doc['id']}?key=test-key", json={"body": "hacked"}
+ )).status_code == 405
+ assert (await client.delete(f"/api/v1/docsview/{doc['id']}?key=test-key")).status_code == 405
+ assert (await client.post(
+ f"/api/v1/docsview/{doc['id']}/revisions/{revision['id']}/restore?key=test-key"
+ )).status_code in (404, 405)
+
+
+# ── The public payload carries nothing but the document ──────────────────────
+
+async def test_docsview_payload_hides_inventory_and_canvas_handles(
+ client: AsyncClient, headers
+):
+ """A device document must not ship the ids it is linked by, nor the drift
+ fields derived from the inventory row behind them."""
+ settings.docs_view_key = "test-key"
+ device = (
+ await client.post(
+ "/api/v1/scan/pending", json={"hostname": "nas-01", "ip": "192.168.1.10"}, headers=headers
+ )
+ ).json()
+ doc = (
+ await client.post(
+ "/api/v1/documents",
+ json={"kind": "device", "title": "NAS", "device_id": device["id"]},
+ headers=headers,
+ )
+ ).json()
+
+ leaked = {"device_id", "node_id", "design_id", "facts_snapshot", "facts_synced_at", "drifted", "template_id"}
+
+ page = await client.get(f"/api/v1/docsview/{doc['id']}?key=test-key")
+ assert page.status_code == 200
+ assert leaked & page.json().keys() == set()
+
+ tree = await client.get("/api/v1/docsview/tree?key=test-key")
+ assert tree.status_code == 200
+ for summary in tree.json():
+ assert leaked & summary.keys() == set()
+
+ # The authenticated route still carries them — this is a public-payload
+ # rule, not a change to what the app itself reads.
+ authed = await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)
+ assert authed.json()["device_id"] == device["id"]
+
+
+# ── Re-disable after enabling ────────────────────────────────────────────────
+
+async def test_docsview_disabled_after_key_cleared(client: AsyncClient):
+ settings.docs_view_key = "was-enabled"
+ assert (await client.get("/api/v1/docsview/tree?key=was-enabled")).status_code == 200
+
+ settings.docs_view_key = None
+ res = await client.get("/api/v1/docsview/tree?key=was-enabled")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "Documentation view is disabled"
+
+
+# ── /config (authenticated) — key used to build the link ─────────────────────
+
+async def test_docsview_config_requires_auth(client: AsyncClient):
+ """The config endpoint exposes the key, so it must reject unauthenticated calls."""
+ settings.docs_view_key = "secret"
+ res = await client.get("/api/v1/docsview/config")
+ assert res.status_code == 401
+
+
+async def test_docsview_config_returns_key_when_enabled(client: AsyncClient, headers):
+ settings.docs_view_key = "share-me"
+ res = await client.get("/api/v1/docsview/config", headers=headers)
+ assert res.status_code == 200
+ assert res.json() == {"enabled": True, "key": "share-me"}
+
+
+async def test_docsview_config_disabled_hides_key(client: AsyncClient, headers):
+ settings.docs_view_key = None
+ res = await client.get("/api/v1/docsview/config", headers=headers)
+ assert res.status_code == 200
+ assert res.json() == {"enabled": False, "key": None}
+
+
+async def test_docsview_config_empty_key_disabled(client: AsyncClient, headers):
+ settings.docs_view_key = ""
+ res = await client.get("/api/v1/docsview/config", headers=headers)
+ assert res.status_code == 200
+ assert res.json() == {"enabled": False, "key": None}