diff --git a/web/app/errors.py b/web/app/errors.py new file mode 100644 index 0000000..3e0e2e7 --- /dev/null +++ b/web/app/errors.py @@ -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) diff --git a/web/app/main.py b/web/app/main.py index c59f41e..4034098 100644 --- a/web/app/main.py +++ b/web/app/main.py @@ -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, - }, - ) diff --git a/web/app/routers/dashboard.py b/web/app/routers/dashboard.py new file mode 100644 index 0000000..1853589 --- /dev/null +++ b/web/app/routers/dashboard.py @@ -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}, + ) diff --git a/web/app/routers/dev.py b/web/app/routers/dev.py new file mode 100644 index 0000000..3fae804 --- /dev/null +++ b/web/app/routers/dev.py @@ -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} diff --git a/web/app/templates/dashboard.html b/web/app/templates/dashboard.html index 436a3e4..12c3a14 100644 --- a/web/app/templates/dashboard.html +++ b/web/app/templates/dashboard.html @@ -1,70 +1,85 @@ {% extends "base.html" %} {% block title %}Dashboard — Firebreak{% endblock %} {% block content %} -
-
+
+ -
-
-

Active links

-

0

-

No repository snapshots published yet.

-
-
-

Default expiry

-

7 days

-

Applied to newly created links.

-
-
-

Audit events

-

0

-

Viewer activity will appear here.

-
-
- {% if not pat_registered %} -
-

Access token required

-

- Register a Forgejo access token to create share links. +

Dashboard

+

+ Welcome, {{ user.display_name or user.email }}. +

+

+ Private repository snapshots and access boundaries.

- Go to Settings +
+
+ {% if not user.has_pat %} +
+

Access token required

+

+ Register a Forgejo access token to fetch repositories and create share links. +

+ Go to Settings
{% endif %} -
-
-

Share links

-

Repository snapshots published from this account.

+ {% if user.has_pat %} +
+
+
+

Repositories

+

+ Your Forgejo repositories. Create a share link to grant temporary read-only access. +

+
+
Loading repositories…
+
-
-
- - - - - - - - - - - - - - - -
RepositoryCommitStatusViewsExpires
You have not created any share links yet.
-
-
-
+ {% endif %} +
+
+

Share links

+

+ Read-only repository snapshots published from this account. +

+
+
+ + + + + + + + + + + + + + + +
RepositoryCommitStatusViewsExpires
You have not created any share links yet.
+
+
+ {% endblock %} diff --git a/web/app/templates/partials/dashboard_repositories.html b/web/app/templates/partials/dashboard_repositories.html new file mode 100644 index 0000000..5f59931 --- /dev/null +++ b/web/app/templates/partials/dashboard_repositories.html @@ -0,0 +1,89 @@ +
+
+

+ Repositories + {% if repositories %} + {{ repositories|length }} + {% endif %} +

+

+ Your Forgejo repositories. Create a share link to grant temporary read-only access. +

+
+ {% if repo_error %} +
{{ repo_error }}
+ {% elif repositories %} +
+ + + + + + + + + + + + + {% for repo in repositories %} + + + + + + + + + {% endfor %} + +
RepositoryStatusBranchLanguageUpdatedActions
+ {% if repo.html_url %} + {{ repo.full_name }} + {% else %} + {{ repo.full_name }} + {% endif %} + {% if repo.description %} +

{{ repo.description }}

+ {% endif %} +
+
+ {% if repo.private %} + Private + {% else %} + Public + {% endif %} + {% if repo.archived %}Archived{% endif %} + {% if repo.empty %}Empty{% endif %} + {% if repo.fork %}Fork{% endif %} + {% if repo.mirror %}Mirror{% endif %} +
+
+ {{ repo.default_branch }} + + {% if repo.language %} + + {{ repo.language }} + + {% else %} + — + {% endif %} + + + + {% if repo.empty %} + Create Link + {% else %} + Create Link + {% endif %} +
+
+ {% else %} +
+ No repositories found in your Forgejo account. +
+ {% endif %} +
diff --git a/web/app/templating.py b/web/app/templating.py index 730f468..3de4ea4 100644 --- a/web/app/templating.py +++ b/web/app/templating.py @@ -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