import asyncio import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, HTTPException, Request, status from fastapi.concurrency import run_in_threadpool from fastapi.responses import FileResponse, JSONResponse from app import __version__ from app.api import admin, auth, clips, files, health, projects, tokens, users, ws from app.config import get_settings from app.db import _session_factory from app.middleware import ( BodySizeLimitMiddleware, OriginCheckMiddleware, SecurityHeadersMiddleware, ) from app.services import files as file_service from app.services.access import ProjectNotFound, ReadOnly from app.services.auth import delete_old_login_attempts from app.services.sessions import delete_expired_sessions from app.services.users import UserError, bootstrap_initial_admin from app.ws.hub import hub logger = logging.getLogger(__name__) CLEANUP_INTERVAL_SECONDS = 3600 def _cleanup() -> list[tuple[int, set[int]]]: """Hourly housekeeping; returns (clip_id, audience) of expired file clips.""" with _session_factory()() as db: sessions = delete_expired_sessions(db) attempts = delete_old_login_attempts(db) expired = file_service.delete_expired(db) orphans = file_service.remove_orphans(db) if sessions or attempts or expired or orphans: logger.info( "Cleanup: %d sessions, %d login attempts, %d expired files, %d orphans removed", sessions, attempts, len(expired), orphans, ) return expired async def _cleanup_loop() -> None: while True: try: for clip_id, audience in await run_in_threadpool(_cleanup): for user_id in audience: await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}}) except Exception: logger.exception("Cleanup failed") await asyncio.sleep(CLEANUP_INTERVAL_SECONDS) def _bootstrap_admin() -> None: settings = get_settings() if not (settings.initial_admin_username and settings.initial_admin_password): return with _session_factory()() as db: try: user = bootstrap_initial_admin( db, settings.initial_admin_username, settings.initial_admin_password ) except UserError as exc: logger.error("INITIAL_ADMIN_* ignored: %s", exc) return if user is not None: logger.warning( "Initial admin '%s' created from INITIAL_ADMIN_*; remove these from .env now.", user.username, ) else: logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.") @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: await run_in_threadpool(_bootstrap_admin) task = asyncio.create_task(_cleanup_loop()) try: yield finally: task.cancel() # Hashed build output never changes; everything else must be revalidated so updates arrive _IMMUTABLE = "public, max-age=31536000, immutable" _REVALIDATE = "no-cache" _MEDIA_TYPES = {".webmanifest": "application/manifest+json"} def _cache_control(relative: str) -> str: if relative.startswith("assets/") or relative.startswith("workbox-"): return _IMMUTABLE if relative.startswith("icons/"): return "public, max-age=86400" return _REVALIDATE # index.html, sw.js, manifest.webmanifest def _register_frontend(app: FastAPI, static_dir: Path) -> None: """Serve the built Vue SPA; unknown non-API paths fall back to index.html.""" root = static_dir.resolve() index_file = root / "index.html" @app.get("/{path:path}", include_in_schema=False) def spa(path: str) -> FileResponse: if path == "api" or path.startswith("api/") or not index_file.is_file(): raise HTTPException(status_code=404) candidate = (root / path).resolve() if path and candidate.is_relative_to(root) and candidate.is_file(): return FileResponse( candidate, media_type=_MEDIA_TYPES.get(candidate.suffix), headers={"Cache-Control": _cache_control(path)}, ) # Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes segments = path.split("/") if "." in segments[-1] or any(seg.startswith(".") for seg in segments): raise HTTPException(status_code=404) return FileResponse(index_file, headers={"Cache-Control": _REVALIDATE}) def create_app() -> FastAPI: settings = get_settings() app = FastAPI( title="LAN-Clipboard", version=__version__, docs_url="/api/docs" if settings.enable_api_docs else None, openapi_url="/api/openapi.json" if settings.enable_api_docs else None, redoc_url=None, lifespan=lifespan, ) # Last added runs first: security headers wrap every response, including rejections app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list) app.add_middleware( BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes, exempt=frozenset({("POST", files.UPLOAD_PATH)}), ) app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list) app.include_router(health.router, prefix="/api") app.include_router(auth.router, prefix="/api") app.include_router(admin.router, prefix="/api") app.include_router(clips.router, prefix="/api") app.include_router(projects.router, prefix="/api") app.include_router(files.router, prefix="/api") app.include_router(users.router, prefix="/api") app.include_router(tokens.router, prefix="/api") app.include_router(ws.router, prefix="/api") @app.exception_handler(UserError) def user_error_handler(_request: Request, exc: UserError) -> JSONResponse: return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST) @app.exception_handler(file_service.FileRejected) def file_rejected_handler(_request: Request, exc: file_service.FileRejected) -> JSONResponse: return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) @app.exception_handler(ReadOnly) def read_only_handler(_request: Request, exc: ReadOnly) -> JSONResponse: return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_403_FORBIDDEN) @app.exception_handler(ProjectNotFound) def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse: # Same answer for foreign and missing projects, so ids of other users are not revealed return JSONResponse( {"detail": "Projekt nicht gefunden."}, status_code=status.HTTP_404_NOT_FOUND ) _register_frontend(app, settings.static_dir) return app app = create_app()