Compare commits

...

2 commits

Author SHA1 Message Date
Zach Tatman
1740441e48
Merge 442261f403 into b04d7475ad 2026-06-05 15:19:46 +00:00
ZTatman
442261f403 fix(web): mypy fixes, Starlette exception handler, disable CTA without PAT
- Fix return type annotations to use Response for TemplateResponse returns
- Fix db.scalar nullability with `or 0` for mypy
- Catch StarletteHTTPException for 404/405 error page rendering
- Disable "Create share link" button when PAT not registered
- Formatter/linter cleanup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-05 11:19:36 -04:00
9 changed files with 94 additions and 86 deletions

View file

@ -62,7 +62,7 @@ uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_
Add the output to your `.env` file (or your deployment platform's environment variables): Add the output to your `.env` file (or your deployment platform's environment variables):
``` ```bash
TOKEN_ENCRYPTION_KEY=your-generated-key-here TOKEN_ENCRYPTION_KEY=your-generated-key-here
``` ```

View file

@ -103,7 +103,9 @@ async def get_optional_session(
return await lookup_session(db, firebreak_session) return await lookup_session(db, firebreak_session)
async def revoke_session(db: AsyncSession, response: Response, firebreak_session: str | None) -> None: async def revoke_session(
db: AsyncSession, response: Response, firebreak_session: str | None
) -> None:
"""Delete the browser cookie and mark the matching session as revoked.""" """Delete the browser cookie and mark the matching session as revoked."""
response.delete_cookie( response.delete_cookie(

View file

@ -4,9 +4,11 @@ from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from typing import Annotated from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Request from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles 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 import func as sql_func, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
@ -86,8 +88,10 @@ ERROR_TITLES = {
} }
@app.exception_handler(HTTPException) @app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: HTTPException) -> HTMLResponse | JSONResponse: async def http_exception_handler(
request: Request, exc: StarletteHTTPException
) -> Response:
"""Render a styled error page for browser requests, JSON for API clients.""" """Render a styled error page for browser requests, JSON for API clients."""
accept = request.headers.get("accept", "") accept = request.headers.get("accept", "")
if "text/html" in accept: if "text/html" in accept:
@ -107,7 +111,7 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> HTMLRe
@app.get("/", response_class=HTMLResponse) @app.get("/", response_class=HTMLResponse)
async def root( async def root(
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)] request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
) -> HTMLResponse: ) -> Response:
return templates.TemplateResponse( return templates.TemplateResponse(
request, request,
"index.html", "index.html",
@ -118,7 +122,7 @@ async def root(
@app.get("/dashboard", response_class=HTMLResponse) @app.get("/dashboard", response_class=HTMLResponse)
async def dashboard( async def dashboard(
request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)] request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)]
) -> HTMLResponse: ) -> Response:
return templates.TemplateResponse( return templates.TemplateResponse(
request, request,
"dashboard.html", "dashboard.html",

View file

@ -8,11 +8,7 @@ class SetupRequiredMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next) -> Response: async def dispatch(self, request: Request, call_next) -> Response:
path = request.url.path path = request.url.path
if ( if path.startswith("/setup") or path.startswith("/static") or path == "/favicon.ico":
path.startswith("/setup")
or path.startswith("/static")
or path == "/favicon.ico"
):
return await call_next(request) return await call_next(request)
if request.app.state.app_settings is None: if request.app.state.app_settings is None:

View file

@ -5,6 +5,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.responses import Response
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.crypto import encrypt_optional from app.auth.crypto import encrypt_optional
@ -21,7 +22,7 @@ router = APIRouter(prefix="/settings", tags=["settings"])
async def settings_page( async def settings_page(
request: Request, request: Request,
sess: Annotated[UserBrowserSession, Depends(get_current_session)], sess: Annotated[UserBrowserSession, Depends(get_current_session)],
) -> HTMLResponse: ) -> Response:
return templates.TemplateResponse( return templates.TemplateResponse(
request, request,
"settings.html", "settings.html",

View file

@ -3,7 +3,8 @@ from __future__ import annotations
from typing import Annotated from typing import Annotated
from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import RedirectResponse
from starlette.responses import Response
from sqlalchemy import func as sql_func, select from sqlalchemy import func as sql_func, select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@ -32,7 +33,7 @@ async def _require_auth_if_configured(
return return
# If no users exist, allow access — the setup token still protects POST # If no users exist, allow access — the setup token still protects POST
user_count = await db.scalar(select(sql_func.count()).select_from(User)) user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
if user_count == 0: if user_count == 0:
return return
@ -44,16 +45,17 @@ async def _require_auth_if_configured(
) )
@router.get("", dependencies=[Depends(_require_auth_if_configured)], response_class=HTMLResponse) @router.get("", dependencies=[Depends(_require_auth_if_configured)])
async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_db)]) -> HTMLResponse: async def setup_page(
request: Request, db: Annotated[AsyncSession, Depends(get_db)]
) -> Response:
"""Render the setup wizard. Pre-fills fields when reconfiguring.""" """Render the setup wizard. Pre-fills fields when reconfiguring."""
existing = request.app.state.app_settings existing = request.app.state.app_settings
user_count = await db.scalar(select(sql_func.count()).select_from(User)) user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
has_users = user_count > 0 has_users = user_count > 0
public_base = ( public_base = (existing.firebreak_public_base_url if existing else "") or str(
(existing.firebreak_public_base_url if existing else "") request.base_url
or str(request.base_url).rstrip("/") ).rstrip("/")
)
ctx = { ctx = {
"reconfiguring": existing is not None and has_users, "reconfiguring": existing is not None and has_users,
"forgejo_base_url": existing.forgejo_base_url if existing else "", "forgejo_base_url": existing.forgejo_base_url if existing else "",
@ -75,7 +77,7 @@ async def setup_submit(
setup_token: Annotated[str, Form()] = "", setup_token: Annotated[str, Form()] = "",
) -> RedirectResponse: ) -> RedirectResponse:
"""Process the setup wizard — creates or updates Forgejo settings.""" """Process the setup wizard — creates or updates Forgejo settings."""
user_count = await db.scalar(select(sql_func.count()).select_from(User)) user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
has_users = user_count > 0 has_users = user_count > 0
is_reconfiguring = request.app.state.app_settings is not None and has_users is_reconfiguring = request.app.state.app_settings is not None and has_users

View file

@ -1,65 +1,70 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Dashboard — Firebreak{% endblock %} {% block title %}Dashboard — Firebreak{% endblock %}
{% block content %} {% block content %}
<div class="flex flex-col gap-6"> <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"> <section class="flex flex-col justify-between gap-4 pb-6 border-b border-border sm:flex-row sm:items-end">
<div> <div>
<h1 class="mt-2 text-3xl font-semibold leading-10 tracking-normal">Welcome,</h1> <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> <p class=" text-2xl text-muted-foreground">{{ user.display_name or user.email }}.</p>
</div> </div>
<a href="/links/create" class="btn btn-primary w-fit">Create share link</a> {% if pat_registered %}
</section> <a href="/links/create" class="btn btn-primary w-fit">Create share link</a>
<section class="grid gap-4 md:grid-cols-3"> {% else %}
<div class="p-4 card"> <span class="btn btn-primary w-fit opacity-50 pointer-events-none"
<p class="section-header-subtle">Active links</p> aria-disabled="true">Create share link</span>
<p class="mt-3 text-2xl font-semibold text-foreground">0</p> {% endif %}
<p class="mt-2 text-xs text-muted-foreground">No repository snapshots published yet.</p> </section>
</div> <section class="grid gap-4 md:grid-cols-3">
<div class="p-4 card"> <div class="p-4 card">
<p class="section-header-subtle">Default expiry</p> <p class="section-header-subtle">Active links</p>
<p class="mt-3 text-2xl font-semibold text-foreground">7 days</p> <p class="mt-3 text-2xl font-semibold text-foreground">0</p>
<p class="mt-2 text-xs text-muted-foreground">Applied to newly created links.</p> <p class="mt-2 text-xs text-muted-foreground">No repository snapshots published yet.</p>
</div> </div>
<div class="p-4 card"> <div class="p-4 card">
<p class="section-header-subtle">Audit events</p> <p class="section-header-subtle">Default expiry</p>
<p class="mt-3 text-2xl font-semibold text-foreground">0</p> <p class="mt-3 text-2xl font-semibold text-foreground">7 days</p>
<p class="mt-2 text-xs text-muted-foreground">Viewer activity will appear here.</p> <p class="mt-2 text-xs text-muted-foreground">Applied to newly created links.</p>
</div> </div>
</section> <div class="p-4 card">
{% if not pat_registered %} <p class="section-header-subtle">Audit events</p>
<div class="rounded-lg border border-warning-muted bg-warning-muted/40 px-5 py-4"> <p class="mt-3 text-2xl font-semibold text-foreground">0</p>
<p class="text-sm font-semibold text-warning-foreground">Access token required</p> <p class="mt-2 text-xs text-muted-foreground">Viewer activity will appear here.</p>
<p class="mt-1 text-sm text-muted-foreground">
Register a Forgejo access token to create share links.
</p>
<a href="/settings" class="btn btn-sm btn-primary mt-3 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>
</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> </div>
</section> </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>
<a href="/settings" class="btn btn-sm btn-primary mt-3 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>
</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>
</div> </div>
</div>
{% endblock %} {% endblock %}

View file

@ -111,7 +111,7 @@
"He doesn't bite. He just harvests.", "He doesn't bite. He just harvests.",
"Move along. Nothing to scrape here.", "Move along. Nothing to scrape here.",
"Unauthorized. The Zuck abides.", "Unauthorized. The Zuck abides.",
"ACCESS DENIED. Deploying Cuckerberg.", "ACCESS DENIED. Deploying Cuckerberg."
] %} ] %}
<p class="mt-2 text-xs italic text-[#f7f2e8]/30">{{ quips | random }}</p> <p class="mt-2 text-xs italic text-[#f7f2e8]/30">{{ quips | random }}</p>
{% endif %} {% endif %}

View file

@ -64,9 +64,7 @@
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 font-mono text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10" class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 font-mono text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
placeholder="Paste the token from your server logs" placeholder="Paste the token from your server logs"
required /> required />
<p class="mt-1.5 text-xs text-[#f7f2e8]/30"> <p class="mt-1.5 text-xs text-[#f7f2e8]/30">Printed to the server console on first boot.</p>
Printed to the server console on first boot.
</p>
</div> </div>
{% endif %} {% endif %}
<div> <div>