From 8e56a5bb1c63fc6b15e8ec946c32336a9e7baffc Mon Sep 17 00:00:00 2001 From: ZTatman Date: Wed, 3 Jun 2026 11:15:44 -0400 Subject: [PATCH] =?UTF-8?q?feat(web):=20setup=20wizard,=20settings=20page,?= =?UTF-8?q?=20and=20Myst=20=E2=86=92=20Firebreak=20rename?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace manual .env configuration with a browser-based setup wizard. New users deploy with `docker compose up` and configure Forgejo OAuth credentials through /setup on first visit. Existing users can reconfigure via the same page (auth-gated post-setup). Key changes: Rename (Myst → Firebreak): - Config fields, env vars, session cookie, templates, docker-compose, README all renamed from Myst to Firebreak Setup wizard (/setup): - New AppSettings single-row DB table stores Forgejo config - Auto-generates Fernet encryption key on first setup - SetupRequiredMiddleware redirects all routes to /setup pre-config - Reconfigure mode pre-fills existing values, requires auth - Landing page links to /setup for recovery if OAuth breaks Settings page (/settings): - PAT registration moved out of dashboard into dedicated page - Token card with registration date, delete, and update actions - Dashboard shows CTA linking to settings when no PAT registered Auth updates: - Routes use AppSettings from DB instead of env-based Settings - OAuth callback redirects new users to /settings for PAT setup - Forgejo API errors no longer leak upstream response bodies - Decrypt failures return actionable 503 instead of unhandled 500 Code quality: - Extracted templating.py to eliminate circular import hacks - AppSettings.get_fernet() caches Fernet cipher instance - User.has_pat property replaces scattered None checks - lookup_session promoted to public API - Dead code removed, return type annotations added - PAT input fields use type="password" - CSRF gap documented in agents.md for future addressing Co-Authored-By: Claude Opus 4.6 --- README.md | 97 +++++++-------------- agents.md | 6 ++ docker-compose.yml | 10 +-- web/app/auth/identity.py | 11 +-- web/app/auth/session.py | 40 +++------ web/app/config.py | 33 +++++--- web/app/main.py | 80 ++++++++---------- web/app/middleware.py | 25 ++++++ web/app/models/__init__.py | 3 +- web/app/models/app_settings.py | 38 +++++++++ web/app/models/user.py | 5 ++ web/app/routers/auth.py | 139 ++++++++++--------------------- web/app/routers/links.py | 7 +- web/app/routers/settings.py | 76 +++++++++++++++++ web/app/routers/setup.py | 117 ++++++++++++++++++++++++++ web/app/static/css/input.css | 4 + web/app/templates/base.html | 5 +- web/app/templates/dashboard.html | 60 ++----------- web/app/templates/index.html | 7 +- web/app/templates/settings.html | 134 +++++++++++++++++++++++++++++ web/app/templates/setup.html | 118 ++++++++++++++++++++++++++ web/app/templating.py | 9 ++ 22 files changed, 702 insertions(+), 322 deletions(-) create mode 100644 web/app/middleware.py create mode 100644 web/app/models/app_settings.py create mode 100644 web/app/routers/settings.py create mode 100644 web/app/routers/setup.py create mode 100644 web/app/templates/settings.html create mode 100644 web/app/templates/setup.html create mode 100644 web/app/templating.py diff --git a/README.md b/README.md index 17639c6..65872a7 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# Myst +# Firebreak -> My stuff, kept private. +> Fight fire with fire. Your code. Your rules. -Myst is a companion service for Forgejo that lets repo owners create expiring, revocable, read-only share links for code snapshots. +Firebreak is a companion service for Forgejo that lets repo owners create expiring, revocable, read-only share links for code snapshots. ## System Diagram -This diagram shows how traffic moves through the public internet, the VPS or self-hosted server, the host firewall, the platform router, Myst, Forgejo, and Postgres. +This diagram shows how traffic moves through the public internet, the VPS or self-hosted server, the host firewall, the platform router, Firebreak, Forgejo, and Postgres. -[![Myst system routing diagram](docs/diagrams/system-routing.svg)](docs/diagrams/system-routing.svg) +[![Firebreak system routing diagram](docs/diagrams/system-routing.svg)](docs/diagrams/system-routing.svg) Click the diagram to open the full-size SVG. @@ -33,8 +33,8 @@ Click the diagram to open the full-size SVG. | Purpose | Method | |---------|--------| -| User Identity | Forgejo Sessions | -| Data Access | Dedicated Forgejo User PAT | +| User Identity | Forgejo OAuth | +| Data Access | User's Forgejo PAT | ### Tech Stack @@ -46,91 +46,50 @@ HTMX provides interactivity (filtering, form submissions) with minimal JavaScrip ## Quick Start -### 1. Run `myst config init` +### 1. Deploy with Docker Compose ```bash -myst config init -``` - -Prompts for: - -- Forgejo API URL — Docker: `http://forgejo:3000`, bare metal: `http://localhost:3000`, cross-host: `https://git.example.com` -- Forgejo PAT (with `read:user` and `read:repository` scopes) - -### 2. Deploy with Docker Compose - -```bash -cp examples/.env.example .env -# Edit .env with your FORGEJO_BASE_URL and FORGEJO_PAT docker compose up -d ``` -The DATABASE_URL is injected automatically by Docker Compose. +### 2. Run the Setup Wizard -### 3. Alternative Deployments +Open `http://localhost:8000` in your browser. On first boot, Firebreak redirects to a setup wizard where you configure: -For non-Docker deployments, you must supply DATABASE_URL yourself: +- **Forgejo instance URL** — where your Forgejo server lives +- **OAuth credentials** — register an OAuth application in Forgejo first (Settings → Applications → Create OAuth2 Application), then paste the Client ID and Client Secret +- **Public base URL** (optional) — your production domain for OAuth redirects -- VPS deployment: Hostinger or another VPS with Dokploy, Traefik, UFW, Myst, Forgejo, and a shared Postgres instance that contains separate `forgejo` and `myst` databases. -- Self-hosted server deployment: a home server, mini PC, NAS, or other self-hosted Linux machine running Myst with Docker, Podman, Docker Compose, Coolify, Caddy, Nginx, or another reverse proxy. +The setup wizard auto-generates an encryption key for token storage. -Myst should not assume a VPS-only environment. The requirement is an existing Forgejo instance, Myst's own database, and a way to route the public and admin hostnames to the Myst app. +### 3. Sign In and Register Your Token -## Example Configuration +After setup, sign in with your Forgejo account via OAuth. On first login, Firebreak prompts you to register a `read:repository`-scoped Personal Access Token (PAT) to enable share link viewing. -Create a `.env` file with: +### 4. Alternative Deployments -```env -# Docker (same Compose network): -FORGEJO_BASE_URL=http://forgejo:3000 -# Bare metal / non-container: -# FORGEJO_BASE_URL=http://localhost:3000 -# Cross-host: -# FORGEJO_BASE_URL=https://git.example.com -FORGEJO_PAT=forgejo_pat_xxxxxxxxxxxx -``` +For non-Docker deployments, supply `DATABASE_URL` yourself: -When using the provided Docker Compose example, DATABASE_URL is injected automatically. For other deployment approaches (e.g., bare metal, Kubernetes), you must supply DATABASE_URL yourself. +- VPS deployment: Hostinger or another VPS with Dokploy, Traefik, UFW, Firebreak, Forgejo, and a shared Postgres instance that contains separate `forgejo` and `firebreak` databases. +- Self-hosted server deployment: a home server, mini PC, NAS, or other self-hosted Linux machine running Firebreak with Docker, Podman, Docker Compose, Coolify, Caddy, Nginx, or another reverse proxy. -### 4. Register an OAuth application in Forgejo - -The web service authenticates users via Forgejo OAuth. You need to register Myst as an OAuth consumer: - -1. In Forgejo, go to **Settings** → **Applications** → **Create OAuth2 Application** -2. Set the redirect URI to `https://your-myst-domain.com/auth/callback/forgejo` (or `http://localhost:8000/auth/callback/forgejo` for local dev) -3. Copy the **Client ID** and **Client Secret** Forgejo gives you -4. Generate a Fernet encryption key for token storage: - - ```bash - python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" - ``` - -5. Add these to your `.env`: - - ```env - FORGEJO_OAUTH_CLIENT_ID=your_client_id - FORGEJO_OAUTH_CLIENT_SECRET=your_client_secret - TOKEN_ENCRYPTION_KEY=your_fernet_key_from_step_4 - MYST_PUBLIC_BASE_URL=https://your-myst-domain.com # omit trailing slash; omit for local dev - ``` - - `MYST_PUBLIC_BASE_URL` is used as the OAuth redirect URI base. In local development, the redirect URI is inferred from the request (Default: `http://localhost:8000/auth/callback/forgejo`). In production, set this to your public Myst domain. +Firebreak should not assume a VPS-only environment. The requirement is an existing Forgejo instance, Firebreak's own database, and a way to route the public and admin hostnames to the Firebreak app. ## Phase 1 Progress -- [x] Project renamed from Embargo to Myst -- [x] CLI scaffold (`myst config init`) +- [x] Project renamed from Embargo to Firebreak +- [x] CLI scaffold (`firebreak config init`) - [x] Config generation (`.env`) - [ ] Service foundation (FastAPI + PostgreSQL) -- [x] `myst config verify` — verify Forgejo connectivity -- [x] `myst config verify --diagnostic` — comprehensive diagnostics -- [x] `myst config view` — show current config -- [ ] Forgejo session authentication +- [x] `firebreak config verify` — verify Forgejo connectivity +- [x] `firebreak config verify --diagnostic` — comprehensive diagnostics +- [x] `firebreak config view` — show current config +- [x] Forgejo OAuth authentication - [ ] Repo ownership verification - [ ] Private link creation (email-verified) - [ ] Public link creation (time-expired) - [ ] Web-based code viewer -- [ ] User dashboard +- [x] User dashboard - [ ] SMTP configuration UI - [ ] Access logs diff --git a/agents.md b/agents.md index b2cba3f..ffce1d3 100644 --- a/agents.md +++ b/agents.md @@ -116,6 +116,12 @@ This file is the single source of truth for codebase obstacles, oddities, and th **Solution/Workaround:** Use a real video-frame poster image (`firebreak-hero-poster.jpg`) or omit `poster`; do not use logo assets as full-bleed video posters. **Preference:** Keep logo sizing in the logo `` and use a frame still for video loading states. +### POST forms lack CSRF tokens +**Area:** web/app/routers/setup.py, web/app/routers/settings.py, web/app/templates/setup.html, web/app/templates/settings.html +**Obstacle:** All state-changing forms (`/setup`, `/settings/pat`, `/settings/pat/delete`) use plain POST with no CSRF token. SameSite=Lax on the session cookie mitigates most cross-origin attacks, but does not fully cover same-site subdomain scenarios. +**Solution/Workaround:** Deferred. Low practical risk since Firebreak runs behind a VPN. Add server-generated CSRF tokens (hidden form field + server-side check) before exposing the app to the public internet. +**Preference:** Use a FastAPI CSRF middleware or manual double-submit cookie pattern when addressing this. + ### Firebreak UI is currently dark-only **Area:** web/app/templates/base.html, web/app/static/css/input.css **Obstacle:** Theme switching and persisted localStorage theme state conflicted with the current Firebreak brand pass, especially on the cinematic landing page. diff --git a/docker-compose.yml b/docker-compose.yml index 3da7862..3fdbff6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: - "8000:8000" env_file: ./web/.env environment: - - DATABASE_URL=postgresql+asyncpg://myst:myst@db:5432/myst_db + - DATABASE_URL=postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db depends_on: db: condition: service_healthy @@ -17,13 +17,13 @@ services: ports: - "5432:5432" environment: - POSTGRES_USER: myst - POSTGRES_PASSWORD: myst - POSTGRES_DB: myst_db + POSTGRES_USER: firebreak + POSTGRES_PASSWORD: firebreak + POSTGRES_DB: firebreak_db volumes: - postgres_data:/var/lib/postgresql/data healthcheck: - test: ["CMD-SHELL", "pg_isready -U myst -d myst_db"] + test: ["CMD-SHELL", "pg_isready -U firebreak -d firebreak_db"] interval: 5s timeout: 5s retries: 5 diff --git a/web/app/auth/identity.py b/web/app/auth/identity.py index 556ae95..7462a62 100644 --- a/web/app/auth/identity.py +++ b/web/app/auth/identity.py @@ -6,14 +6,14 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import selectinload -from app.auth.crypto import encrypt_optional, fernet_from_encryption_key -from app.config import Settings +from app.auth.crypto import encrypt_optional +from app.models.app_settings import AppSettings from app.models.user import LinkedIdentity, User async def find_or_create_user( db: AsyncSession, - settings: Settings, + app_settings: AppSettings, *, provider: str, provider_user_id: str, @@ -25,10 +25,8 @@ async def find_or_create_user( ) -> User: """Find or create a user based on the given provider and identity details.""" - # Create a Fernet instance for encrypting tokens if a key is available - fernet = fernet_from_encryption_key(settings.token_encryption_key) + fernet = app_settings.get_fernet() - # Query the database for an existing identity result = await db.execute( select(LinkedIdentity) .options(selectinload(LinkedIdentity.user)) @@ -39,7 +37,6 @@ async def find_or_create_user( ) identity = result.scalar_one_or_none() - # Update the identity and user if identity exists if identity: identity.provider_username = provider_username if access_token_raw is not None: diff --git a/web/app/auth/session.py b/web/app/auth/session.py index 52b69a1..fac193a 100644 --- a/web/app/auth/session.py +++ b/web/app/auth/session.py @@ -14,7 +14,7 @@ from sqlalchemy.orm import selectinload from app.deps import get_db from app.models.session import Session -SESSION_COOKIE = "myst_session" +SESSION_COOKIE = "firebreak_session" SESSION_DURATION_DAYS = 7 @@ -48,19 +48,15 @@ async def create_session( ) -async def _lookup_session( +async def lookup_session( db: AsyncSession, - myst_session: str | None, + firebreak_session: str | None, ) -> Session | None: """Return the active session for a raw cookie token, if one exists.""" - # Missing cookie means anonymous request. Callers decide whether anonymous is - # acceptable with get_optional_session or should become a 401. - if not myst_session: + if not firebreak_session: return None - # Match the incoming cookie by hashing it the same way create_session did. - # Only active, non-expired sessions are accepted. - token_hash = hashlib.sha256(myst_session.encode()).hexdigest() + token_hash = hashlib.sha256(firebreak_session.encode()).hexdigest() now = datetime.now(UTC) stmt = ( select(Session) @@ -85,12 +81,11 @@ async def _lookup_session( async def get_current_session( db: Annotated[AsyncSession, Depends(get_db)], - myst_session: Annotated[str | None, Cookie()] = None, + firebreak_session: Annotated[str | None, Cookie()] = None, ) -> Session: """FastAPI dependency that requires a valid signed-in session.""" - # Use this dependency on routes that require a signed-in user. - sess = await _lookup_session(db, myst_session) + sess = await lookup_session(db, firebreak_session) if sess is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -101,37 +96,28 @@ async def get_current_session( async def get_optional_session( db: Annotated[AsyncSession, Depends(get_db)], - myst_session: Annotated[str | None, Cookie()] = None, + firebreak_session: Annotated[str | None, Cookie()] = None, ) -> Session | None: - """FastAPI dependency that returns the current session when available. Used on pages that can render differently for anonymous and signed-in users.""" + """FastAPI dependency that returns the current session when available.""" - return await _lookup_session(db, myst_session) + return await lookup_session(db, firebreak_session) -async def revoke_session(db: AsyncSession, response: Response, myst_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.""" - # Always ask the browser to delete its cookie, even if the DB row is already - # missing or revoked. response.delete_cookie( key=SESSION_COOKIE, path="/", samesite="lax", httponly=True, ) - if not myst_session: + if not firebreak_session: return - # Revoke by hash for the same reason we store sessions by hash: the raw - # cookie token should only exist in the browser. - token_hash = hashlib.sha256(myst_session.encode()).hexdigest() + token_hash = hashlib.sha256(firebreak_session.encode()).hexdigest() result = await db.execute( update(Session) .where(Session.token_hash == token_hash, Session.revoked_at.is_(None)) .values(revoked_at=datetime.now(UTC)) ) await db.commit() - - # Bypasses the strict static type checking check safely - rowcount = getattr(result, "rowcount", 0) - if rowcount == 0: - pass diff --git a/web/app/config.py b/web/app/config.py index aabe8f4..c0c622d 100644 --- a/web/app/config.py +++ b/web/app/config.py @@ -1,30 +1,37 @@ +from __future__ import annotations + from functools import lru_cache from pathlib import Path -from typing import ClassVar +from typing import TYPE_CHECKING -from pydantic import SecretStr +from fastapi import Request from pydantic_settings import BaseSettings, SettingsConfigDict +if TYPE_CHECKING: + from app.models.app_settings import AppSettings + env_file = Path(__file__).parent.parent / ".env" class Settings(BaseSettings): - """Application settings loaded from environment variables.""" + """Bootstrap settings loaded from environment variables. - app_name: str = "Myst" - database_url: str = "postgresql+asyncpg://myst:myst@db:5432/myst_db" # Default for Docker Compose; override with DATABASE_URL env var in production - forgejo_base_url: str = "" - forgejo_oauth_client_id: str = "" - forgejo_oauth_client_secret: SecretStr = SecretStr("") - # Public Myst base URL for OAuth redirect_uri (no trailing slash). If empty, Request.base_url is used. - myst_public_base_url: str = "" - # URL-safe base64 Fernet key (see `cryptography.fernet.Fernet.generate_key()`). Required to persist OAuth tokens and user PATs. - token_encryption_key: SecretStr = SecretStr("") + Only contains fields needed before the database is available. + Forgejo config lives in the AppSettings DB table after setup. + """ - model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(env_file=str(env_file)) + app_name: str = "Firebreak" + database_url: str = "postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db" + + model_config = SettingsConfigDict(env_file=str(env_file)) @lru_cache def get_settings() -> Settings: """Cached settings instance.""" return Settings() + + +def get_app_settings(request: Request) -> AppSettings: + """FastAPI dependency returning the AppSettings row from app state.""" + return request.app.state.app_settings diff --git a/web/app/main.py b/web/app/main.py index 5cc7385..78f929f 100644 --- a/web/app/main.py +++ b/web/app/main.py @@ -2,57 +2,68 @@ from contextlib import asynccontextmanager from pathlib import Path from typing import Annotated -from fastapi import Depends, FastAPI, Form, HTTPException, Request, status -from fastapi.responses import RedirectResponse +from fastapi import Depends, FastAPI, Request +from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles -from jinja2_fragments.fastapi import Jinja2Blocks +from sqlalchemy import 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.crypto import encrypt_optional, fernet_from_encryption_key from app.auth.session import get_current_session, get_optional_session -from app.config import Settings, get_settings +from app.config import get_settings from app.database import Base -from app.deps import get_db +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 - -TEMPLATES_DIR = Path(__file__).parent / "templates" +from app.routers import auth, links, settings, setup +from app.templating import templates @asynccontextmanager async def lifespan(app: FastAPI): - """Manage database engine lifecycle.""" - settings = get_settings() + """Manage database engine lifecycle and load app settings.""" + boot_settings = get_settings() engine = create_async_engine( - url=settings.database_url, + url=boot_settings.database_url, pool_pre_ping=True, - echo=settings.app_name != "Myst", + echo=boot_settings.app_name != "Firebreak", ) app.state.db_session = async_sessionmaker( engine, class_=AsyncSession, - expire_on_commit=False, # Prevents MissingGreenlet in async + expire_on_commit=False, ) async with engine.begin() as conn: - await conn.run_sync(Base.metadata.create_all) # Create all tables on startup + await conn.run_sync(Base.metadata.create_all) + + async with app.state.db_session() as db: + result = await db.execute(select(AppSettings).where(AppSettings.id == 1)) + row = result.scalar_one_or_none() + if row: + app.state.setup_complete = True + app.state.app_settings = row + else: + app.state.setup_complete = False + app.state.app_settings = None + yield - await engine.dispose() # Close all connections on shutdown + await engine.dispose() -templates = Jinja2Blocks(directory=str(TEMPLATES_DIR)) - app = FastAPI(lifespan=lifespan) +app.add_middleware(SetupRequiredMiddleware) app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static") app.include_router(auth.router) app.include_router(links.router) +app.include_router(settings.router) +app.include_router(setup.router) -@app.get("/") +@app.get("/", response_class=HTMLResponse) async def root( request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)] -): +) -> HTMLResponse: return templates.TemplateResponse( request, "index.html", @@ -60,38 +71,15 @@ async def root( ) -@app.get("/dashboard") +@app.get("/dashboard", response_class=HTMLResponse) async def dashboard( request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)] -): +) -> HTMLResponse: return templates.TemplateResponse( request, "dashboard.html", { "user": sess.user, - "pat_registered": request.query_params.get("pat") == "registered", + "pat_registered": sess.user.has_pat, }, ) - - -@app.post("/dashboard/pat") -async def register_pat( - pat: Annotated[str, Form()], - db: Annotated[AsyncSession, Depends(get_db)], - settings: Annotated[Settings, Depends(get_settings)], - sess: Annotated[UserBrowserSession, Depends(get_current_session)], -) -> RedirectResponse: - pat = pat.strip() - if not pat: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Forgejo access token is required." - ) - - fernet = fernet_from_encryption_key(settings.token_encryption_key) - sess.user.pat_encrypted = encrypt_optional(fernet, pat) - await db.commit() - - return RedirectResponse( - "/dashboard?pat=registered#forgejo-access-token", - status_code=status.HTTP_303_SEE_OTHER, - ) diff --git a/web/app/middleware.py b/web/app/middleware.py new file mode 100644 index 0000000..6a533df --- /dev/null +++ b/web/app/middleware.py @@ -0,0 +1,25 @@ +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import RedirectResponse, Response + + +class SetupRequiredMiddleware(BaseHTTPMiddleware): + """Redirect all requests to /setup when the app has not been configured yet.""" + + async def dispatch(self, request: Request, call_next) -> Response: + path = request.url.path + if ( + path.startswith("/setup") + or path.startswith("/static") + or path == "/favicon.ico" + ): + return await call_next(request) + + if not request.app.state.setup_complete: + if request.headers.get("HX-Request"): + response = Response(status_code=200) + response.headers["HX-Redirect"] = "/setup" + return response + return RedirectResponse("/setup", status_code=302) + + return await call_next(request) diff --git a/web/app/models/__init__.py b/web/app/models/__init__.py index 01acd7e..5237b9c 100644 --- a/web/app/models/__init__.py +++ b/web/app/models/__init__.py @@ -1,7 +1,8 @@ """Import ORM modules so ``Base.metadata`` is populated before ``create_all``.""" +from app.models.app_settings import AppSettings from app.models.grant import Grant from app.models.session import Session from app.models.user import LinkedIdentity, User -__all__ = ["Grant", "LinkedIdentity", "Session", "User"] +__all__ = ["AppSettings", "Grant", "LinkedIdentity", "Session", "User"] diff --git a/web/app/models/app_settings.py b/web/app/models/app_settings.py new file mode 100644 index 0000000..066ca17 --- /dev/null +++ b/web/app/models/app_settings.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import datetime + +from cryptography.fernet import Fernet +from pydantic import SecretStr +from sqlalchemy import CheckConstraint, DateTime, String, Text, func +from sqlalchemy.orm import Mapped, mapped_column + +from app.auth.crypto import fernet_from_encryption_key +from app.database import Base + + +class AppSettings(Base): + __tablename__ = "app_settings" + __table_args__ = (CheckConstraint("id = 1", name="single_row"),) + + id: Mapped[int] = mapped_column(primary_key=True, default=1) + forgejo_base_url: Mapped[str] = mapped_column(String, nullable=False) + forgejo_oauth_client_id: Mapped[str] = mapped_column(String, nullable=False) + forgejo_oauth_client_secret_encrypted: Mapped[str] = mapped_column(Text, nullable=False) + firebreak_public_base_url: Mapped[str] = mapped_column(String, nullable=False, default="") + token_encryption_key: Mapped[str] = mapped_column(Text, nullable=False) + setup_completed_at: Mapped[datetime.datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + __allow_unmapped__ = True + _fernet: Fernet | None = None + + def get_fernet(self) -> Fernet: + """Return a cached Fernet cipher from the stored encryption key.""" + if self._fernet is None: + fernet = fernet_from_encryption_key(SecretStr(self.token_encryption_key)) + if fernet is None: + raise ValueError("Token encryption key is missing or empty in app settings.") + self._fernet = fernet + return self._fernet diff --git a/web/app/models/user.py b/web/app/models/user.py index 297d1b7..ac707f4 100644 --- a/web/app/models/user.py +++ b/web/app/models/user.py @@ -23,8 +23,13 @@ class User(Base): display_name: Mapped[str | None] = mapped_column(String, nullable=True) email: Mapped[str | None] = mapped_column(String, nullable=True, index=True) pat_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True) + pat_registered_at: Mapped[datetime | None] = mapped_column(nullable=True) created_at: Mapped[datetime] = mapped_column(server_default=func.now()) + @property + def has_pat(self) -> bool: + return self.pat_encrypted is not None + identities: Mapped[list[LinkedIdentity]] = relationship( back_populates="user", cascade="all, delete-orphan", diff --git a/web/app/routers/auth.py b/web/app/routers/auth.py index 6525140..88a8607 100644 --- a/web/app/routers/auth.py +++ b/web/app/routers/auth.py @@ -6,14 +6,16 @@ from typing import Annotated from urllib.parse import urlencode import httpx -from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, Response, status +from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, status from fastapi.responses import RedirectResponse from sqlalchemy.ext.asyncio import AsyncSession +from app.auth.crypto import decrypt_token from app.auth.identity import find_or_create_user from app.auth.session import create_session, revoke_session -from app.config import Settings, get_settings +from app.config import get_app_settings from app.deps import get_db +from app.models.app_settings import AppSettings router = APIRouter(prefix="/auth", tags=["auth"]) @@ -21,44 +23,38 @@ router = APIRouter(prefix="/auth", tags=["auth"]) # ── Forgejo API client ── -async def _forgejo_post(settings: Settings, path: str, data: dict) -> dict: - """POST form data to a Forgejo API path and return the JSON response.""" - - # Keep Forgejo HTTP calls in small helpers so route handlers read as the - # OAuth flow instead of low-level request/response plumbing. - url = f"{settings.forgejo_base_url.rstrip('/')}{path}" +async def _forgejo_post(app_settings: AppSettings, path: str, data: dict) -> dict: + url = f"{app_settings.forgejo_base_url}{path}" try: async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post(url, data=data, headers={"Accept": "application/json"}) - except httpx.RequestError as exc: + except httpx.RequestError: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, - detail=f"Cannot reach Forgejo: {exc}", - ) from exc + detail="Cannot reach Forgejo. Check your connection settings.", + ) if resp.status_code != 200: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, - detail=(f"Forgejo API error {resp.status_code} at {path}: {resp.text[:500]}"), + detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.", ) return resp.json() -async def _forgejo_get(settings: Settings, path: str, token: str) -> dict: - """GET a Forgejo API path with a provider access token.""" - - url = f"{settings.forgejo_base_url.rstrip('/')}{path}" +async def _forgejo_get(app_settings: AppSettings, path: str, token: str) -> dict: + url = f"{app_settings.forgejo_base_url}{path}" try: async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.get(url, headers={"Authorization": f"token {token}"}) - except httpx.RequestError as exc: + except httpx.RequestError: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, - detail=f"Cannot reach Forgejo: {exc}", - ) from exc + detail="Cannot reach Forgejo. Check your connection settings.", + ) if resp.status_code != 200: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, - detail=(f"Forgejo API error {resp.status_code} at {path}: {resp.text[:500]}"), + detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.", ) return resp.json() @@ -66,11 +62,7 @@ async def _forgejo_get(settings: Settings, path: str, token: str) -> dict: # ── OAuth CSRF helpers ── -def _set_oauth_state_cookie(response: Response, state: str) -> None: - """Set the short-lived OAuth state cookie used to verify the callback.""" - - # Store the OAuth state server-to-browser only. The callback must echo this - # value back, which ties the callback to the login request we initiated. +def _set_oauth_state_cookie(response: RedirectResponse, state: str) -> None: response.set_cookie( key="oauth_state", value=state, @@ -82,10 +74,6 @@ def _set_oauth_state_cookie(response: Response, state: str) -> None: def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None: - """Validate the OAuth state query parameter against the stored cookie.""" - - # Use constant-time comparison because this value is part of the CSRF - # defense for the OAuth redirect flow. if not state or not oauth_state or not secrets.compare_digest(state, oauth_state): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, @@ -97,10 +85,6 @@ def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None: def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None]: - """Extract access token, refresh token, and expiry from Forgejo OAuth data.""" - - # Forgejo's token response is external input, so normalize it before the - # rest of the app stores or relies on any values. access_token = data.get("access_token") if not access_token or not isinstance(access_token, str): raise HTTPException( @@ -118,10 +102,6 @@ def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None] def _parse_user_response(data: dict) -> tuple[str, str, str | None]: - """Extract the Forgejo identity fields needed for local user linking.""" - - # Provider id and username are the stable link between Forgejo and our local - # user record. Email is optional because providers may omit or hide it. provider_user_id = str(data.get("id", "")).strip() provider_username = str(data.get("username", "")).strip() if not provider_user_id or not provider_username: @@ -137,37 +117,20 @@ def _parse_user_response(data: dict) -> tuple[str, str, str | None]: # ── OAuth config helpers ── -def _forgejo_oauth_redirect_uri(request: Request, settings: Settings) -> str: - """Return the callback URL registered with Forgejo for this request.""" - - # In production, prefer the configured public base URL so Forgejo sees the - # same callback URL users do. Locally, fall back to FastAPI's generated URL. - base_url = settings.myst_public_base_url.strip().rstrip("/") +def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) -> str: + base_url = app_settings.firebreak_public_base_url.strip().rstrip("/") if base_url: return f"{base_url}/auth/callback/forgejo" return str(request.url_for("forgejo_oauth_callback")) -def _require_forgejo_oauth_config(settings: Settings) -> None: - """Raise a setup error when the Forgejo OAuth settings are incomplete.""" - - # Fail before redirecting when OAuth is only partially configured. This gives - # a clearer setup error than a failed request after the user leaves the app. - if not settings.forgejo_base_url.strip(): +def _get_oauth_client_secret(app_settings: AppSettings) -> str: + try: + return decrypt_token(app_settings.get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted) + except ValueError: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Forgejo is not configured: set FORGEJO_BASE_URL in the environment.", - ) - if not settings.forgejo_oauth_client_id.strip(): - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Forgejo OAuth is not configured: set FORGEJO_OAUTH_CLIENT_ID in the environment.", - ) - secret = settings.forgejo_oauth_client_secret.get_secret_value().strip() - if not secret: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Forgejo OAuth is not configured: set FORGEJO_OAUTH_CLIENT_SECRET in the environment.", + detail="Forgejo OAuth credentials could not be decrypted. Reconfigure at /setup.", ) @@ -176,25 +139,21 @@ def _require_forgejo_oauth_config(settings: Settings) -> None: @router.get("/login/forgejo") async def login_forgejo( - request: Request, settings: Annotated[Settings, Depends(get_settings)] + request: Request, app_settings: Annotated[AppSettings, Depends(get_app_settings)] ) -> RedirectResponse: """Redirect the browser to Forgejo to begin OAuth sign-in.""" - _require_forgejo_oauth_config(settings) - - # Start the OAuth authorization-code flow. Forgejo receives our callback URL - # and the random state value; the user's browser is redirected there next. - redirect_uri = _forgejo_oauth_redirect_uri(request, settings) + redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings) state = secrets.token_urlsafe(32) query = urlencode( { - "client_id": settings.forgejo_oauth_client_id, + "client_id": app_settings.forgejo_oauth_client_id, "response_type": "code", "redirect_uri": redirect_uri, "state": state, } ) - authorization_url = f"{settings.forgejo_base_url.rstrip('/')}/login/oauth/authorize?{query}" + authorization_url = f"{app_settings.forgejo_base_url}/login/oauth/authorize?{query}" response = RedirectResponse(authorization_url, status_code=status.HTTP_302_FOUND) _set_oauth_state_cookie(response, state) return response @@ -204,16 +163,13 @@ async def login_forgejo( async def callback_forgejo( request: Request, db: Annotated[AsyncSession, Depends(get_db)], - settings: Annotated[Settings, Depends(get_settings)], + app_settings: Annotated[AppSettings, Depends(get_app_settings)], code: str | None = None, state: str | None = None, oauth_state: Annotated[str | None, Cookie()] = None, ) -> RedirectResponse: """Handle Forgejo's OAuth callback and create a local app session.""" - _require_forgejo_oauth_config(settings) - # The callback must include the same state value we put in the cookie during - # login, otherwise this could be an unsolicited OAuth response. _verify_oauth_state(state, oauth_state) if not code: @@ -222,37 +178,28 @@ async def callback_forgejo( detail="Forgejo did not return an authorization code. The user may have denied consent.", ) - # Build the response before session creation so the session cookie is set on - # the exact RedirectResponse returned to the browser. - redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND) - redirect.delete_cookie("oauth_state") + client_secret = _get_oauth_client_secret(app_settings) + redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings) - # Exchange Forgejo's short-lived authorization code for provider tokens. - # These tokens identify the Forgejo account, but they are not our app - # session cookie. token_data = await _forgejo_post( - settings, + app_settings, "/login/oauth/access_token", { "grant_type": "authorization_code", - "client_id": settings.forgejo_oauth_client_id, - "client_secret": settings.forgejo_oauth_client_secret.get_secret_value(), + "client_id": app_settings.forgejo_oauth_client_id, + "client_secret": client_secret, "code": code, - "redirect_uri": _forgejo_oauth_redirect_uri(request, settings), + "redirect_uri": redirect_uri, }, ) access_token, refresh_plain, expires_at = _parse_token_response(token_data) - # Use the provider access token once to fetch the Forgejo account profile we - # link to our local users table. - user_data = await _forgejo_get(settings, "/api/v1/user", access_token) + user_data = await _forgejo_get(app_settings, "/api/v1/user", access_token) provider_user_id, provider_username, email = _parse_user_response(user_data) - # Upsert the local user and linked identity. Provider tokens are encrypted - # before they are stored by find_or_create_user. user = await find_or_create_user( db, - settings, + app_settings, provider="forgejo", provider_user_id=provider_user_id, provider_username=provider_username, @@ -262,8 +209,10 @@ async def callback_forgejo( refresh_token_raw=refresh_plain, ) - # After OAuth succeeds, use our own session cookie for normal app requests. - # The raw cookie value is sent to the browser; only its hash is stored. + target = "/dashboard" if user.has_pat else "/settings" + redirect = RedirectResponse(target, status_code=status.HTTP_302_FOUND) + redirect.delete_cookie("oauth_state") + await create_session(db, redirect, user.id, secure=request.url.scheme == "https") return redirect @@ -271,12 +220,10 @@ async def callback_forgejo( @router.get("/logout") async def logout( db: Annotated[AsyncSession, Depends(get_db)], - myst_session: Annotated[str | None, Cookie()] = None, + firebreak_session: Annotated[str | None, Cookie()] = None, ) -> RedirectResponse: """Revoke the current app session and redirect back to the home page.""" - # revoke_session must receive this redirect response, otherwise the - # Set-Cookie delete header would be written to an unused Response object. redirect = RedirectResponse("/", status_code=status.HTTP_302_FOUND) - await revoke_session(db, redirect, myst_session) + await revoke_session(db, redirect, firebreak_session) return redirect diff --git a/web/app/routers/links.py b/web/app/routers/links.py index deade03..48cb8bf 100644 --- a/web/app/routers/links.py +++ b/web/app/routers/links.py @@ -25,6 +25,7 @@ class CreateLinkResponse(BaseModel): share_url: str -@router.post("/", response_model=CreateLinkResponse) -async def create_link(request: CreateLinkRequest): - pass +@router.post("/", status_code=501) +async def create_link(request: CreateLinkRequest) -> dict: + """Stub — link creation not yet implemented.""" + return {"detail": "Link creation is not yet implemented."} diff --git a/web/app/routers/settings.py b/web/app/routers/settings.py new file mode 100644 index 0000000..ba95a8a --- /dev/null +++ b/web/app/routers/settings.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, Depends, Form, HTTPException, Request, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.crypto import encrypt_optional +from app.auth.session import get_current_session +from app.config import get_app_settings +from app.deps import get_db +from app.models.app_settings import AppSettings +from app.models.session import Session as UserBrowserSession +from app.templating import templates + +router = APIRouter(prefix="/settings", tags=["settings"]) + + +@router.get("", response_class=HTMLResponse) +async def settings_page( + request: Request, + sess: Annotated[UserBrowserSession, Depends(get_current_session)], + app_settings: Annotated[AppSettings, Depends(get_app_settings)], +) -> HTMLResponse: + return templates.TemplateResponse( + request, + "settings.html", + { + "user": sess.user, + "pat_registered": sess.user.has_pat, + "pat_registered_at": sess.user.pat_registered_at, + "pat_deleted": request.query_params.get("pat") == "deleted", + }, + ) + + +@router.post("/pat") +async def register_pat( + pat: Annotated[str, Form()], + db: Annotated[AsyncSession, Depends(get_db)], + app_settings: Annotated[AppSettings, Depends(get_app_settings)], + sess: Annotated[UserBrowserSession, Depends(get_current_session)], +) -> RedirectResponse: + pat = pat.strip() + if not pat: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Forgejo access token is required.", + ) + + fernet = app_settings.get_fernet() + sess.user.pat_encrypted = encrypt_optional(fernet, pat) + sess.user.pat_registered_at = datetime.now(UTC) + await db.commit() + + return RedirectResponse( + "/settings?pat=registered", + status_code=status.HTTP_303_SEE_OTHER, + ) + + +@router.post("/pat/delete") +async def delete_pat( + db: Annotated[AsyncSession, Depends(get_db)], + sess: Annotated[UserBrowserSession, Depends(get_current_session)], +) -> RedirectResponse: + sess.user.pat_encrypted = None + sess.user.pat_registered_at = None + await db.commit() + + return RedirectResponse( + "/settings?pat=deleted", + status_code=status.HTTP_303_SEE_OTHER, + ) diff --git a/web/app/routers/setup.py b/web/app/routers/setup.py new file mode 100644 index 0000000..e465ff3 --- /dev/null +++ b/web/app/routers/setup.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +from typing import Annotated + +from cryptography.fernet import Fernet +from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status +from fastapi.responses import HTMLResponse, RedirectResponse +from pydantic import SecretStr +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.crypto import encrypt_token, fernet_from_encryption_key +from app.auth.session import lookup_session +from app.deps import get_db +from app.models.app_settings import AppSettings +from app.templating import templates + +router = APIRouter(prefix="/setup", tags=["setup"]) + + +async def _require_auth_if_configured( + request: Request, + db: Annotated[AsyncSession, Depends(get_db)], + firebreak_session: Annotated[str | None, Cookie()] = None, +) -> None: + """Block anonymous access to /setup after initial configuration.""" + if not request.app.state.setup_complete: + return + sess = await lookup_session(db, firebreak_session) + if sess is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Sign in to reconfigure Firebreak.", + ) + + +@router.get("", dependencies=[Depends(_require_auth_if_configured)], response_class=HTMLResponse) +async def setup_page(request: Request) -> HTMLResponse: + """Render the setup wizard. Pre-fills fields when reconfiguring.""" + existing = request.app.state.app_settings + ctx = { + "reconfiguring": existing is not None, + "forgejo_base_url": existing.forgejo_base_url if existing else "", + "forgejo_oauth_client_id": existing.forgejo_oauth_client_id if existing else "", + "firebreak_public_base_url": existing.firebreak_public_base_url if existing else "", + } + return templates.TemplateResponse(request, "setup.html", ctx) + + +@router.post("", dependencies=[Depends(_require_auth_if_configured)]) +async def setup_submit( + request: Request, + db: Annotated[AsyncSession, Depends(get_db)], + forgejo_base_url: Annotated[str, Form()], + forgejo_oauth_client_id: Annotated[str, Form()], + forgejo_oauth_client_secret: Annotated[str, Form()] = "", + firebreak_public_base_url: Annotated[str, Form()] = "", +) -> RedirectResponse: + """Process the setup wizard — creates or updates Forgejo settings.""" + is_reconfiguring = request.app.state.setup_complete + + forgejo_base_url = forgejo_base_url.strip().rstrip("/") + forgejo_oauth_client_id = forgejo_oauth_client_id.strip() + forgejo_oauth_client_secret = forgejo_oauth_client_secret.strip() + firebreak_public_base_url = firebreak_public_base_url.strip().rstrip("/") + + if not forgejo_base_url or not forgejo_oauth_client_id: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Forgejo URL and Client ID are required.", + ) + + if is_reconfiguring: + result = await db.execute(select(AppSettings).where(AppSettings.id == 1)) + row = result.scalar_one_or_none() + if row is None: + raise HTTPException( + status_code=500, detail="Settings row missing during reconfiguration." + ) + row.forgejo_base_url = forgejo_base_url + row.forgejo_oauth_client_id = forgejo_oauth_client_id + row.firebreak_public_base_url = firebreak_public_base_url + if forgejo_oauth_client_secret: + row.forgejo_oauth_client_secret_encrypted = encrypt_token( + row.get_fernet(), forgejo_oauth_client_secret + ) + await db.commit() + await db.refresh(row) + request.app.state.app_settings = row + return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER) + + # First-time setup — no auth required (no users exist yet) + if not forgejo_oauth_client_secret: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Client Secret is required during initial setup.", + ) + + encryption_key = Fernet.generate_key().decode() + fernet = fernet_from_encryption_key(SecretStr(encryption_key)) + encrypted_secret = encrypt_token(fernet, forgejo_oauth_client_secret) + + row = AppSettings( + id=1, + forgejo_base_url=forgejo_base_url, + forgejo_oauth_client_id=forgejo_oauth_client_id, + forgejo_oauth_client_secret_encrypted=encrypted_secret, + firebreak_public_base_url=firebreak_public_base_url, + token_encryption_key=encryption_key, + ) + db.add(row) + await db.commit() + await db.refresh(row) + request.app.state.setup_complete = True + request.app.state.app_settings = row + + return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER) diff --git a/web/app/static/css/input.css b/web/app/static/css/input.css index 647ab2a..1de83ec 100644 --- a/web/app/static/css/input.css +++ b/web/app/static/css/input.css @@ -204,6 +204,10 @@ color: #fffdf8; } + .landing-page .app-header { + display: none; + } + .landing-page { background: #17191c; } diff --git a/web/app/templates/base.html b/web/app/templates/base.html index 56cb6be..65a7dec 100644 --- a/web/app/templates/base.html +++ b/web/app/templates/base.html @@ -4,7 +4,7 @@ - {% block title %}Myst{% endblock %} + {% block title %}Firebreak{% endblock %} @@ -56,6 +56,7 @@ -
+
{% block content %}{% endblock %}
diff --git a/web/app/templates/dashboard.html b/web/app/templates/dashboard.html index 80f50a1..9066a45 100644 --- a/web/app/templates/dashboard.html +++ b/web/app/templates/dashboard.html @@ -1,5 +1,5 @@ {% extends "base.html" %} -{% block title %}Dashboard — Myst{% endblock %} +{% block title %}Dashboard — Firebreak{% endblock %} {% block content %}
@@ -26,29 +26,15 @@

Viewer activity will appear here.

-
- {% if pat_registered %} -
Forgejo access token registered.
- {% else %} -

Forgejo access token

-

- Register a read:repository-scoped PAT - to enable share link viewing. + {% if not pat_registered %} +

+ {% endif %}

Share links

@@ -76,34 +62,4 @@
- {% endblock %} \ No newline at end of file diff --git a/web/app/templates/index.html b/web/app/templates/index.html index 8b75aa6..18ca715 100644 --- a/web/app/templates/index.html +++ b/web/app/templates/index.html @@ -1,8 +1,9 @@ {% extends "base.html" %} {% block title %}Firebreak — protect your code from scraping{% endblock %} {% block body_class %}landing-page{% endblock %} +{% block main_class %}{% endblock %} {% block content %} -
+
+ + Reconfigure Forgejo connection + {% endblock %} diff --git a/web/app/templates/settings.html b/web/app/templates/settings.html new file mode 100644 index 0000000..3f98d08 --- /dev/null +++ b/web/app/templates/settings.html @@ -0,0 +1,134 @@ +{% extends "base.html" %} +{% block title %}Settings — Firebreak{% endblock %} +{% block content %} +
+
+

Settings

+

Manage your Firebreak configuration.

+
+ {% if pat_deleted %} +
Access token removed.
+ {% endif %} +
+

Forgejo access token

+

+ A read:repository-scoped + Personal Access Token is required for share link viewing. +

+ {% if pat_registered %} +
+
+
+
+ + + +
+
+

Access token

+

+ {% if pat_registered_at %} + Registered {{ pat_registered_at.strftime("%b %d, %Y") }} + {% else %} + Registered + {% endif %} +

+
+
+
+ +
+
+
+
+ + Update token + +
+
+ + +
+
+ +
+
+
+ {% else %} +
+
+ + +
+
+ +
+
+ {% endif %} +
+
+ +{% endblock %} diff --git a/web/app/templates/setup.html b/web/app/templates/setup.html new file mode 100644 index 0000000..213c93d --- /dev/null +++ b/web/app/templates/setup.html @@ -0,0 +1,118 @@ +{% extends "base.html" %} +{% block title %}{{ "Reconfigure" if reconfiguring else "Setup" }} — Firebreak{% endblock %} +{% block body_class %}landing-page{% endblock %} +{% block main_class %}{% endblock %} +{% block content %} +
+
+
+ Firebreak +

+ {{ "Reconfigure" if reconfiguring else "Setup" }} +

+ {% if reconfiguring %} +

+ Update your Forgejo OAuth connection. Make sure the OAuth application + is registered in your Forgejo instance before continuing. +

+ {% else %} +

+ Connect Firebreak to your Forgejo instance. You'll need to + register an OAuth application + in Forgejo first. +

+ {% endif %} +
+ {% if not reconfiguring %} +
+

How to get your OAuth credentials:

+
    +
  1. + In Forgejo, go to Settings → Applications +
  2. +
  3. + Under Manage OAuth2 Applications, create a new app +
  4. +
  5. + Set the redirect URI to +
    + http://localhost:8000/auth/callback/forgejo +
  6. +
  7. + Copy the Client ID and Client Secret into the form below +
  8. +
+
+ {% endif %} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +

+ Your production domain for OAuth redirects. Leave blank on localhost — Firebreak will use http://localhost:8000 automatically. +

+
+ +
+
+
+{% endblock %} diff --git a/web/app/templating.py b/web/app/templating.py new file mode 100644 index 0000000..730f468 --- /dev/null +++ b/web/app/templating.py @@ -0,0 +1,9 @@ +"""Shared Jinja2 template engine — importable without circular deps.""" + +from pathlib import Path + +from jinja2_fragments.fastapi import Jinja2Blocks + +TEMPLATES_DIR = Path(__file__).parent / "templates" + +templates = Jinja2Blocks(directory=str(TEMPLATES_DIR))