0.51.0 gave every stack an icon, but a generic one: jellyfin got a clapperboard,
not the Jellyfin logo. Glyphs make a list readable; they do not make a stack
recognisable, which was the point. This resolves stacks against the selfh.st
icon catalog (~2900 self-hosted apps, the set Homarr and Homepage draw on), so
the row shows the thing people already recognise. All 83 bundled templates
resolve to their own logo.
The whole design question was *who* talks to the CDN. If the <img> points at
jsdelivr, then every client needs internet, every page load leaks the names of
somebody's stacks to a third party, and an air-gapped box gets nothing. So the
backend does it: the catalog on startup and weekly after, each logo once on
first use, both into ${DATA_DIR}/stack-icons/. Browsers keep reading icons from
the authenticated endpoint that already existed for uploads, and after the first
fetch the feature is fully offline. Logos are cached per *app*, not per stack —
verified: two stacks resolving to jellyfin produce one download.
Nothing here can fail loudly. Every entry point returns None rather than raising
when the network is absent, the catalog refresh is a task the lifespan does not
await, and an install with no outbound internet simply keeps 0.51.0's glyphs.
That fallback is also what covers a name the catalog does not know
("Mediaserver Wohnzimmer" is still a clapperboard), and the seconds after a
fresh install before the catalog lands. The glyph is derived even for stacks
that *do* have a logo, so an image that cannot be fetched degrades to something
meaningful instead of a box.
Matching gained a second source that turned out to matter more than expected:
the compose images. A stack called "medienserver" says nothing, but it pulls
lscr.io/linuxserver/jellyfin — strip the registry, the vendor and the tag and
the app is right there. Name first, then the longest run of words inside it,
then the images. It is deliberately cautious: a single word shorter than four
characters never claims a logo, because "web", "app" and "db" are all catalog
entries and a *wrong* logo is worse than a neutral glyph. A short alias table
covers what the catalog spells differently from Docker Hub (postgres →
postgresql, pihole → pi-hole, wg-easy → wireguard).
A slug arrives from the database and from query strings and then becomes a
filename, so it is pattern-checked before it is ever joined to a path, catalog
entries that are not slug-shaped are dropped on load, and a downloaded logo is
verified to start with the PNG magic bytes before being cached.
The picker searches the catalog too — pre-seeded with the stack's own name, so
opening it on "jellyfin" offers the Jellyfin logo first — which is how a wrong
match gets corrected, and how a stack can be given any app's logo on purpose.
Verified end to end against the live catalog and real downloads: list rows carry
the resolved logo, the icon endpoint serves real PNG bytes, an unmatched stack
404s (and falls through to its glyph), a hand-picked logo round-trips, reset
clears it, and a traversal slug 404s. 30 new backend tests and 12 new frontend
ones run without any network at all.
0.52.0 rather than amending 0.51.0: those images are already in the registry,
and rebuilding a published version tag with different content is exactly what
breaks the self-update checker.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
146 lines
4.5 KiB
Python
146 lines
4.5 KiB
Python
"""StackPilot backend — FastAPI application entry point."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from sqlmodel import Session
|
|
|
|
from config import settings
|
|
from version import APP_VERSION
|
|
from database import engine, init_db
|
|
from docker_client import DockerError
|
|
from routers import (
|
|
audit,
|
|
auth,
|
|
backups,
|
|
containers,
|
|
dashboard,
|
|
destinations,
|
|
editor,
|
|
files,
|
|
images,
|
|
networks,
|
|
ports,
|
|
schedules,
|
|
secrets,
|
|
settings as settings_router,
|
|
stacks,
|
|
system,
|
|
templates,
|
|
volumes,
|
|
ws,
|
|
)
|
|
from services import (
|
|
backup_destination_service,
|
|
image_status_store,
|
|
logo_service,
|
|
schedule_service,
|
|
stack_lock_service,
|
|
template_service,
|
|
update_service,
|
|
)
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger("stackpilot")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
init_db()
|
|
# Register stacks that already exist on disk.
|
|
try:
|
|
with Session(engine) as session:
|
|
stacks.sync_discovered_stacks(session)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Stack discovery failed: %s", exc)
|
|
# One-off: encrypt backup-destination credentials written before they were
|
|
# stored encrypted (see services/crypto_service.py).
|
|
try:
|
|
with Session(engine) as session:
|
|
encrypted = backup_destination_service.migrate_plaintext_configs(session)
|
|
if encrypted:
|
|
logger.info("Encrypted %d backup destination config(s) at rest", encrypted)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Destination config encryption migration failed: %s", exc)
|
|
try:
|
|
moved = template_service.migrate_legacy_db_templates()
|
|
if moved:
|
|
logger.info("Migrated %d custom template(s) from the database to folders", moved)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Legacy template migration failed: %s", exc)
|
|
# Runtime state that used to live in module dicts and was lost on restart.
|
|
try:
|
|
with Session(engine) as session:
|
|
stale = stack_lock_service.prune_expired(session)
|
|
if stale:
|
|
logger.info("Cleared %d stale stack lock(s) from a previous run", stale)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Could not prune stack locks: %s", exc)
|
|
try:
|
|
restored = image_status_store.install()
|
|
logger.info("Restored %d cached image update status(es)", restored)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Could not restore the image update cache: %s", exc)
|
|
|
|
update_task = asyncio.create_task(update_service.background_loop())
|
|
schedule_task = asyncio.create_task(schedule_service.scheduler_loop())
|
|
# App logos. Deliberately a task and not awaited: the catalog is a network
|
|
# download, and a box with no outbound internet must still start instantly
|
|
# (it just keeps the built-in glyphs).
|
|
logo_task = asyncio.create_task(logo_service.catalog_loop())
|
|
logger.info("StackPilot backend ready on port %s", settings.PORT)
|
|
yield
|
|
update_task.cancel()
|
|
schedule_task.cancel()
|
|
logo_task.cancel()
|
|
|
|
|
|
app = FastAPI(title="StackPilot", version=APP_VERSION, lifespan=lifespan)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.CORS_ORIGINS,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.exception_handler(DockerError)
|
|
async def docker_error_handler(_request: Request, exc: DockerError):
|
|
return JSONResponse(
|
|
status_code=502,
|
|
content={"error": exc.error, "detail": exc.detail},
|
|
)
|
|
|
|
|
|
app.include_router(auth.router)
|
|
app.include_router(stacks.router)
|
|
app.include_router(secrets.router)
|
|
app.include_router(containers.router)
|
|
app.include_router(dashboard.router)
|
|
app.include_router(system.router)
|
|
app.include_router(volumes.router)
|
|
app.include_router(editor.router)
|
|
app.include_router(files.router)
|
|
app.include_router(images.router)
|
|
app.include_router(ports.router)
|
|
app.include_router(templates.router)
|
|
app.include_router(audit.router)
|
|
app.include_router(settings_router.router)
|
|
app.include_router(backups.router)
|
|
app.include_router(destinations.router)
|
|
app.include_router(schedules.router)
|
|
app.include_router(networks.router)
|
|
app.include_router(ws.router)
|
|
|
|
|
|
@app.get("/api/health")
|
|
def health() -> dict:
|
|
return {"status": "ok", "version": APP_VERSION}
|