refactor(web): decompose main.py into a composition root

Move page routes to routers/dashboard.py, the content-negotiated error
handler to errors.py (register_error_handlers), and the dev css-mtime
endpoint to routers/dev.py (included only when debug). main.py shrinks to
lifespan + wiring + the / landing route.

Dashboard repos now load lazily via an htmx fragment so a slow/unreachable
Forgejo instance never blocks first paint; Forgejo html_url is sanitized
against non-http(s) schemes before rendering into href.
This commit is contained in:
ZTatman 2026-06-10 16:59:06 -04:00
parent e3ead49f13
commit a0617c6be4
7 changed files with 318 additions and 106 deletions

45
web/app/errors.py Normal file
View file

@ -0,0 +1,45 @@
"""Application error rendering — content-negotiated HTML/JSON error responses."""
from __future__ import annotations
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import Response
from app.templating import templates
ERROR_TITLES = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
503: "Service Unavailable",
}
async def http_exception_handler(request: Request, exc: Exception) -> Response:
"""Render a styled error page for browser requests, JSON for API clients."""
# Starlette only routes StarletteHTTPException here; narrow for the type
# checker and re-raise anything unexpected to the default handler.
if not isinstance(exc, StarletteHTTPException):
raise exc
accept = request.headers.get("accept", "")
if "text/html" in accept:
return templates.TemplateResponse(
request,
"error.html",
{
"status_code": exc.status_code,
"title": ERROR_TITLES.get(exc.status_code, "Error"),
"detail": exc.detail,
},
status_code=exc.status_code,
)
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
def register_error_handlers(app: FastAPI) -> None:
"""Wire the application's exception handlers onto the app."""
app.add_exception_handler(StarletteHTTPException, http_exception_handler)

View file

@ -5,21 +5,21 @@ from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import Response
from sqlalchemy import func as sql_func, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app import models as _models # noqa: F401 - register ORM tables on metadata
from app.auth.session import get_current_session, get_optional_session
from app.config import get_settings
from app.auth.session import get_optional_session
from app.config import get_settings, set_app_settings
from app.database import Base
from app.errors import register_error_handlers
from app.middleware import SetupRequiredMiddleware
from app.models.app_settings import AppSettings
from app.models.session import Session as UserBrowserSession
from app.routers import auth, links, settings, setup
from app.routers import auth, dashboard, dev, links, settings, setup
from app.templating import templates
@ -47,7 +47,7 @@ async def lifespan(app: FastAPI):
row = result.scalar_one_or_none()
user_count = await db.scalar(select(sql_func.count()).select_from(User))
app.state.app_settings = row
set_app_settings(app, row)
# Generate a setup token whenever no users exist yet — whether it's
# a fresh install or a retry after bad OAuth config.
@ -74,36 +74,14 @@ app.add_middleware(SetupRequiredMiddleware)
app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")
app.include_router(auth.router)
app.include_router(dashboard.router)
app.include_router(links.router)
app.include_router(settings.router)
app.include_router(setup.router)
if get_settings().debug:
app.include_router(dev.router)
ERROR_TITLES = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
503: "Service Unavailable",
}
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Response:
"""Render a styled error page for browser requests, JSON for API clients."""
accept = request.headers.get("accept", "")
if "text/html" in accept:
return templates.TemplateResponse(
request,
"error.html",
{
"status_code": exc.status_code,
"title": ERROR_TITLES.get(exc.status_code, "Error"),
"detail": exc.detail,
},
status_code=exc.status_code,
)
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
register_error_handlers(app)
@app.get("/", response_class=HTMLResponse)
@ -115,17 +93,3 @@ async def root(
"index.html",
{"user": sess.user if sess else None},
)
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(
request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)]
) -> Response:
return templates.TemplateResponse(
request,
"dashboard.html",
{
"user": sess.user,
"pat_registered": sess.user.has_pat,
},
)

View file

@ -0,0 +1,75 @@
from __future__ import annotations
from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse
from starlette.responses import Response
from app.auth import tokens
from app.auth.session import get_current_session
from app.config import get_app_settings
from app.models.app_settings import AppSettings
from app.models.session import Session as UserBrowserSession
from app.services import forgejo
from app.templating import templates
router = APIRouter(tags=["dashboard"])
@router.get("/dashboard", response_class=HTMLResponse)
async def dashboard(
request: Request,
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
) -> Response:
return templates.TemplateResponse(
request,
"dashboard.html",
{"user": sess.user},
)
@router.get("/dashboard/repositories", response_class=HTMLResponse)
async def dashboard_repositories(
request: Request,
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
) -> Response:
"""Lazy-loaded fragment: fetch the user's Forgejo repositories.
The dashboard pulls this in via htmx after first paint, so a slow or
unreachable Forgejo instance never blocks the page from rendering.
"""
repositories: list[dict] = []
repo_error: str | None = None
if sess.user.has_pat:
pat = tokens.decrypt_pat(sess.user)
if pat:
try:
repos = await forgejo.get(
app_settings,
"/api/v1/user/repos",
token=pat,
params={"limit": 50, "sort": "updated"},
timeout=10.0,
)
repositories = [r for r in repos if r.get("permissions", {}).get("pull", True)]
# Defend against a hostile/MITM'd Forgejo returning a
# javascript: (or other non-http) URL we'd render into href.
for r in repositories:
url = r.get("html_url")
if not isinstance(url, str) or not url.startswith(("http://", "https://")):
r["html_url"] = ""
except forgejo.ForgejoError as exc:
repo_error = (
"Could not reach your Forgejo instance."
if exc.unreachable
else "Could not fetch repositories from Forgejo."
)
return templates.TemplateResponse(
request,
"partials/dashboard_repositories.html",
{"repositories": repositories, "repo_error": repo_error},
)

19
web/app/routers/dev.py Normal file
View file

@ -0,0 +1,19 @@
"""Development-only endpoints. Included on the app only when debug is enabled."""
from __future__ import annotations
from pathlib import Path
from fastapi import APIRouter
router = APIRouter(prefix="/api/dev", tags=["dev"])
_CSS_OUTPUT = Path(__file__).parent.parent / "static" / "css" / "output.css"
@router.get("/css-mtime")
async def css_mtime() -> dict:
"""Report the built CSS file's mtime so the browser can live-reload on change."""
if _CSS_OUTPUT.exists():
return {"mtime": _CSS_OUTPUT.stat().st_mtime}
return {"mtime": 0}

View file

@ -1,70 +1,85 @@
{% extends "base.html" %}
{% block title %}Dashboard — Firebreak{% endblock %}
{% block content %}
<div class="flex flex-col gap-6">
<section class="flex flex-col justify-between gap-4 pb-6 border-b border-border sm:flex-row sm:items-end">
<div class="flex flex-col gap-10">
<section class="page-header">
<div>
<h1 class="mt-2 text-3xl font-semibold leading-10 tracking-normal">Welcome,</h1>
<p class=" text-2xl text-muted-foreground">{{ user.display_name or user.email }}.</p>
</div>
{% if pat_registered %}
<a href="/links/create" class="btn btn-primary w-fit">Create Share Link</a>
{% else %}
<span class="btn btn-primary w-fit opacity-50 pointer-events-none"
aria-disabled="true">Create Share Link</span>
{% endif %}
</section>
<section class="grid gap-4 md:grid-cols-3">
<div class="p-4 card">
<p class="section-header-subtle">Active links</p>
<p class="mt-3 text-2xl font-semibold text-foreground">0</p>
<p class="mt-2 text-xs text-muted-foreground">No repository snapshots published yet.</p>
</div>
<div class="p-4 card">
<p class="section-header-subtle">Default expiry</p>
<p class="mt-3 text-2xl font-semibold text-foreground">7 days</p>
<p class="mt-2 text-xs text-muted-foreground">Applied to newly created links.</p>
</div>
<div class="p-4 card">
<p class="section-header-subtle">Audit events</p>
<p class="mt-3 text-2xl font-semibold text-foreground">0</p>
<p class="mt-2 text-xs text-muted-foreground">Viewer activity will appear here.</p>
</div>
</section>
{% if not pat_registered %}
<div class="rounded-lg border border-warning-muted bg-warning-muted/40 px-5 py-4">
<p class="text-sm font-semibold text-warning-foreground">Access token required</p>
<p class="mt-1 text-sm text-muted-foreground">
Register a Forgejo access token to create share links.
<p class="text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground">Dashboard</p>
<h1 class="mt-3 text-3xl font-semibold leading-tight text-foreground sm:text-4xl">
Welcome, {{ user.display_name or user.email }}.
</h1>
<p class="mt-2 text-base leading-7 text-foreground/68 sm:text-lg">
Private repository snapshots and access boundaries.
</p>
<a href="/settings" class="btn btn-sm btn-primary mt-3 w-fit">Go to Settings</a>
</div>
</section>
{% if not user.has_pat %}
<div class="notice-rail">
<p class="text-sm font-semibold text-warning-foreground">Access token required</p>
<p class="mt-1 text-sm leading-6 text-muted-foreground">
Register a Forgejo access token to fetch repositories and create share links.
</p>
<a href="/settings" class="mt-3 btn btn-sm btn-link w-fit">Go to Settings</a>
</div>
{% endif %}
<div class="space-y-3">
<div>
<h2 class="text-base font-semibold">Share links</h2>
<p class="mt-2 text-sm text-muted-foreground">Repository snapshots published from this account.</p>
{% if user.has_pat %}
<div hx-get="/dashboard/repositories"
hx-trigger="load"
hx-swap="innerHTML">
<section class="table-panel">
<div class="flex flex-col gap-1 px-5 py-4 border-b border-border">
<h2 class="text-base font-semibold text-foreground">Repositories</h2>
<p class="text-sm leading-6 text-muted-foreground">
Your Forgejo repositories. Create a share link to grant temporary read-only access.
</p>
</div>
<div class="px-5 py-8 text-sm text-center text-muted-foreground">Loading repositories…</div>
</section>
</div>
<section class="card">
<div class="overflow-x-auto">
<table class="w-full min-w-[720px] text-left text-sm">
<thead class="bg-muted text-xs font-semibold uppercase tracking-[0.05em] text-muted-foreground">
<tr>
<th class="px-4 py-3">Repository</th>
<th class="px-4 py-3">Commit</th>
<th class="px-4 py-3">Status</th>
<th class="px-4 py-3">Views</th>
<th class="px-4 py-3">Expires</th>
</tr>
</thead>
<tbody class="divide-y divide-border-subtle">
<tr class="text-muted-foreground text-center">
<td class="px-4 py-5" colspan="5">You have not created any share links yet.</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
{% endif %}
<section class="table-panel">
<div class="flex flex-col gap-1 px-5 py-4 border-b border-border">
<h2 class="text-base font-semibold text-foreground">Share links</h2>
<p class="text-sm leading-6 text-muted-foreground">
Read-only repository snapshots published from this account.
</p>
</div>
<div class="table-shell">
<table class="data-table">
<thead>
<tr>
<th>Repository</th>
<th>Commit</th>
<th>Status</th>
<th>Views</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
<tr class="table-empty">
<td colspan="5">You have not created any share links yet.</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
<script>
function localizeDates(root) {
(root || document).querySelectorAll("time[data-local-date]").forEach((time) => {
const value = time.getAttribute("datetime");
if (!value) return;
const date = new Date(value);
if (Number.isNaN(date.valueOf())) return;
time.textContent = new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
year: "numeric",
}).format(date);
});
}
localizeDates(document);
// Repositories load lazily via htmx, so re-localize their dates after swap.
document.body.addEventListener("htmx:afterSwap", (event) => localizeDates(event.target));
</script>
{% endblock %}

View file

@ -0,0 +1,89 @@
<section class="table-panel">
<div class="flex flex-col gap-1 px-5 py-4 border-b border-border">
<h2 class="text-base font-semibold text-foreground">
Repositories
{% if repositories %}
<span class="ml-1.5 text-sm font-normal text-muted-foreground">{{ repositories|length }}</span>
{% endif %}
</h2>
<p class="text-sm leading-6 text-muted-foreground">
Your Forgejo repositories. Create a share link to grant temporary read-only access.
</p>
</div>
{% if repo_error %}
<div class="px-5 py-8 text-sm text-center text-muted-foreground">{{ repo_error }}</div>
{% elif repositories %}
<div class="table-shell">
<table class="data-table">
<thead>
<tr>
<th>Repository</th>
<th>Status</th>
<th>Branch</th>
<th>Language</th>
<th>Updated</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
{% for repo in repositories %}
<tr>
<td>
{% if repo.html_url %}
<a href="{{ repo.html_url }}"
target="_blank"
rel="noopener"
class="font-medium text-foreground hover:text-brand-flame">{{ repo.full_name }}</a>
{% else %}
<span class="font-medium text-foreground">{{ repo.full_name }}</span>
{% endif %}
{% if repo.description %}
<p class="mt-0.5 max-w-md truncate text-xs text-muted-foreground">{{ repo.description }}</p>
{% endif %}
</td>
<td>
<div class="flex flex-wrap items-center gap-1.5">
{% if repo.private %}
<span class="badge-warning">Private</span>
{% else %}
<span class="badge-slate">Public</span>
{% endif %}
{% if repo.archived %}<span class="badge-expired">Archived</span>{% endif %}
{% if repo.empty %}<span class="badge-danger">Empty</span>{% endif %}
{% if repo.fork %}<span class="badge-slate">Fork</span>{% endif %}
{% if repo.mirror %}<span class="badge-slate">Mirror</span>{% endif %}
</div>
</td>
<td>
<span class="inline-block rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-muted-foreground">{{ repo.default_branch }}</span>
</td>
<td class="whitespace-nowrap text-muted-foreground">
{% if repo.language %}
<span class="inline-flex items-center gap-1.5">
<span class="rounded-full size-2 bg-brand-flame/70" aria-hidden="true"></span>{{ repo.language }}
</span>
{% else %}
<span class="text-muted-foreground/50">—</span>
{% endif %}
</td>
<td class="whitespace-nowrap text-muted-foreground">
<time datetime="{{ repo.updated_at }}" data-local-date>{{ repo.updated_at }}</time>
</td>
<td class="text-right">
{% if repo.empty %}
<span class="btn btn-sm btn-disabled" aria-disabled="true">Create Link</span>
{% else %}
<a href="/links/create" class="btn btn-sm btn-primary">Create Link</a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="px-5 py-8 text-sm text-center text-muted-foreground">
No repositories found in your Forgejo account.
</div>
{% endif %}
</section>

View file

@ -4,6 +4,11 @@ from pathlib import Path
from jinja2_fragments.fastapi import Jinja2Blocks
from app.config import get_settings
TEMPLATES_DIR = Path(__file__).parent / "templates"
templates = Jinja2Blocks(directory=str(TEMPLATES_DIR))
# Expose the debug flag to every template (gates the dev-only CSS live reload).
templates.env.globals["debug"] = get_settings().debug