feat(web): setup wizard, settings page, and Myst → Firebreak rename
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 <noreply@anthropic.com>
This commit is contained in:
parent
fda444b808
commit
8e56a5bb1c
22 changed files with 702 additions and 322 deletions
97
README.md
97
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
|
## 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.
|
||||||
|
|
||||||
[](docs/diagrams/system-routing.svg)
|
[](docs/diagrams/system-routing.svg)
|
||||||
|
|
||||||
Click the diagram to open the full-size 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 |
|
| Purpose | Method |
|
||||||
|---------|--------|
|
|---------|--------|
|
||||||
| User Identity | Forgejo Sessions |
|
| User Identity | Forgejo OAuth |
|
||||||
| Data Access | Dedicated Forgejo User PAT |
|
| Data Access | User's Forgejo PAT |
|
||||||
|
|
||||||
### Tech Stack
|
### Tech Stack
|
||||||
|
|
||||||
|
|
@ -46,91 +46,50 @@ HTMX provides interactivity (filtering, form submissions) with minimal JavaScrip
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### 1. Run `myst config init`
|
### 1. Deploy with Docker Compose
|
||||||
|
|
||||||
```bash
|
```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
|
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.
|
The setup wizard auto-generates an encryption key for token storage.
|
||||||
- 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.
|
|
||||||
|
|
||||||
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
|
For non-Docker deployments, supply `DATABASE_URL` yourself:
|
||||||
# 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
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
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.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## Phase 1 Progress
|
## Phase 1 Progress
|
||||||
|
|
||||||
- [x] Project renamed from Embargo to Myst
|
- [x] Project renamed from Embargo to Firebreak
|
||||||
- [x] CLI scaffold (`myst config init`)
|
- [x] CLI scaffold (`firebreak config init`)
|
||||||
- [x] Config generation (`.env`)
|
- [x] Config generation (`.env`)
|
||||||
- [ ] Service foundation (FastAPI + PostgreSQL)
|
- [ ] Service foundation (FastAPI + PostgreSQL)
|
||||||
- [x] `myst config verify` — verify Forgejo connectivity
|
- [x] `firebreak config verify` — verify Forgejo connectivity
|
||||||
- [x] `myst config verify --diagnostic` — comprehensive diagnostics
|
- [x] `firebreak config verify --diagnostic` — comprehensive diagnostics
|
||||||
- [x] `myst config view` — show current config
|
- [x] `firebreak config view` — show current config
|
||||||
- [ ] Forgejo session authentication
|
- [x] Forgejo OAuth authentication
|
||||||
- [ ] Repo ownership verification
|
- [ ] Repo ownership verification
|
||||||
- [ ] Private link creation (email-verified)
|
- [ ] Private link creation (email-verified)
|
||||||
- [ ] Public link creation (time-expired)
|
- [ ] Public link creation (time-expired)
|
||||||
- [ ] Web-based code viewer
|
- [ ] Web-based code viewer
|
||||||
- [ ] User dashboard
|
- [x] User dashboard
|
||||||
- [ ] SMTP configuration UI
|
- [ ] SMTP configuration UI
|
||||||
- [ ] Access logs
|
- [ ] Access logs
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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.
|
**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 `<img>` and use a frame still for video loading states.
|
**Preference:** Keep logo sizing in the logo `<img>` 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
|
### Firebreak UI is currently dark-only
|
||||||
**Area:** web/app/templates/base.html, web/app/static/css/input.css
|
**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.
|
**Obstacle:** Theme switching and persisted localStorage theme state conflicted with the current Firebreak brand pass, especially on the cinematic landing page.
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ services:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
env_file: ./web/.env
|
env_file: ./web/.env
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgresql+asyncpg://myst:myst@db:5432/myst_db
|
- DATABASE_URL=postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|
@ -17,13 +17,13 @@ services:
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: myst
|
POSTGRES_USER: firebreak
|
||||||
POSTGRES_PASSWORD: myst
|
POSTGRES_PASSWORD: firebreak
|
||||||
POSTGRES_DB: myst_db
|
POSTGRES_DB: firebreak_db
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U myst -d myst_db"]
|
test: ["CMD-SHELL", "pg_isready -U firebreak -d firebreak_db"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,14 @@ from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.orm import selectinload
|
from sqlalchemy.orm import selectinload
|
||||||
|
|
||||||
from app.auth.crypto import encrypt_optional, fernet_from_encryption_key
|
from app.auth.crypto import encrypt_optional
|
||||||
from app.config import Settings
|
from app.models.app_settings import AppSettings
|
||||||
from app.models.user import LinkedIdentity, User
|
from app.models.user import LinkedIdentity, User
|
||||||
|
|
||||||
|
|
||||||
async def find_or_create_user(
|
async def find_or_create_user(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
settings: Settings,
|
app_settings: AppSettings,
|
||||||
*,
|
*,
|
||||||
provider: str,
|
provider: str,
|
||||||
provider_user_id: str,
|
provider_user_id: str,
|
||||||
|
|
@ -25,10 +25,8 @@ async def find_or_create_user(
|
||||||
) -> User:
|
) -> User:
|
||||||
"""Find or create a user based on the given provider and identity details."""
|
"""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 = app_settings.get_fernet()
|
||||||
fernet = fernet_from_encryption_key(settings.token_encryption_key)
|
|
||||||
|
|
||||||
# Query the database for an existing identity
|
|
||||||
result = await db.execute(
|
result = await db.execute(
|
||||||
select(LinkedIdentity)
|
select(LinkedIdentity)
|
||||||
.options(selectinload(LinkedIdentity.user))
|
.options(selectinload(LinkedIdentity.user))
|
||||||
|
|
@ -39,7 +37,6 @@ async def find_or_create_user(
|
||||||
)
|
)
|
||||||
identity = result.scalar_one_or_none()
|
identity = result.scalar_one_or_none()
|
||||||
|
|
||||||
# Update the identity and user if identity exists
|
|
||||||
if identity:
|
if identity:
|
||||||
identity.provider_username = provider_username
|
identity.provider_username = provider_username
|
||||||
if access_token_raw is not None:
|
if access_token_raw is not None:
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ from sqlalchemy.orm import selectinload
|
||||||
from app.deps import get_db
|
from app.deps import get_db
|
||||||
from app.models.session import Session
|
from app.models.session import Session
|
||||||
|
|
||||||
SESSION_COOKIE = "myst_session"
|
SESSION_COOKIE = "firebreak_session"
|
||||||
SESSION_DURATION_DAYS = 7
|
SESSION_DURATION_DAYS = 7
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -48,19 +48,15 @@ async def create_session(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _lookup_session(
|
async def lookup_session(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
myst_session: str | None,
|
firebreak_session: str | None,
|
||||||
) -> Session | None:
|
) -> Session | None:
|
||||||
"""Return the active session for a raw cookie token, if one exists."""
|
"""Return the active session for a raw cookie token, if one exists."""
|
||||||
|
|
||||||
# Missing cookie means anonymous request. Callers decide whether anonymous is
|
if not firebreak_session:
|
||||||
# acceptable with get_optional_session or should become a 401.
|
|
||||||
if not myst_session:
|
|
||||||
return None
|
return None
|
||||||
# Match the incoming cookie by hashing it the same way create_session did.
|
token_hash = hashlib.sha256(firebreak_session.encode()).hexdigest()
|
||||||
# Only active, non-expired sessions are accepted.
|
|
||||||
token_hash = hashlib.sha256(myst_session.encode()).hexdigest()
|
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
stmt = (
|
stmt = (
|
||||||
select(Session)
|
select(Session)
|
||||||
|
|
@ -85,12 +81,11 @@ async def _lookup_session(
|
||||||
|
|
||||||
async def get_current_session(
|
async def get_current_session(
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
myst_session: Annotated[str | None, Cookie()] = None,
|
firebreak_session: Annotated[str | None, Cookie()] = None,
|
||||||
) -> Session:
|
) -> Session:
|
||||||
"""FastAPI dependency that requires a valid signed-in 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, firebreak_session)
|
||||||
sess = await _lookup_session(db, myst_session)
|
|
||||||
if sess is None:
|
if sess is None:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
|
@ -101,37 +96,28 @@ async def get_current_session(
|
||||||
|
|
||||||
async def get_optional_session(
|
async def get_optional_session(
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
myst_session: Annotated[str | None, Cookie()] = None,
|
firebreak_session: Annotated[str | None, Cookie()] = None,
|
||||||
) -> Session | 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."""
|
"""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(
|
response.delete_cookie(
|
||||||
key=SESSION_COOKIE,
|
key=SESSION_COOKIE,
|
||||||
path="/",
|
path="/",
|
||||||
samesite="lax",
|
samesite="lax",
|
||||||
httponly=True,
|
httponly=True,
|
||||||
)
|
)
|
||||||
if not myst_session:
|
if not firebreak_session:
|
||||||
return
|
return
|
||||||
# Revoke by hash for the same reason we store sessions by hash: the raw
|
token_hash = hashlib.sha256(firebreak_session.encode()).hexdigest()
|
||||||
# cookie token should only exist in the browser.
|
|
||||||
token_hash = hashlib.sha256(myst_session.encode()).hexdigest()
|
|
||||||
result = await db.execute(
|
result = await db.execute(
|
||||||
update(Session)
|
update(Session)
|
||||||
.where(Session.token_hash == token_hash, Session.revoked_at.is_(None))
|
.where(Session.token_hash == token_hash, Session.revoked_at.is_(None))
|
||||||
.values(revoked_at=datetime.now(UTC))
|
.values(revoked_at=datetime.now(UTC))
|
||||||
)
|
)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
||||||
# Bypasses the strict static type checking check safely
|
|
||||||
rowcount = getattr(result, "rowcount", 0)
|
|
||||||
if rowcount == 0:
|
|
||||||
pass
|
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,37 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from pathlib import Path
|
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
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from app.models.app_settings import AppSettings
|
||||||
|
|
||||||
env_file = Path(__file__).parent.parent / ".env"
|
env_file = Path(__file__).parent.parent / ".env"
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
"""Application settings loaded from environment variables."""
|
"""Bootstrap settings loaded from environment variables.
|
||||||
|
|
||||||
app_name: str = "Myst"
|
Only contains fields needed before the database is available.
|
||||||
database_url: str = "postgresql+asyncpg://myst:myst@db:5432/myst_db" # Default for Docker Compose; override with DATABASE_URL env var in production
|
Forgejo config lives in the AppSettings DB table after setup.
|
||||||
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("")
|
|
||||||
|
|
||||||
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
|
@lru_cache
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
"""Cached settings instance."""
|
"""Cached settings instance."""
|
||||||
return Settings()
|
return Settings()
|
||||||
|
|
||||||
|
|
||||||
|
def get_app_settings(request: Request) -> AppSettings:
|
||||||
|
"""FastAPI dependency returning the AppSettings row from app state."""
|
||||||
|
return request.app.state.app_settings
|
||||||
|
|
|
||||||
|
|
@ -2,57 +2,68 @@ 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, Form, HTTPException, Request, status
|
from fastapi import Depends, FastAPI, Request
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import HTMLResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
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 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 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.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.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.models.session import Session as UserBrowserSession
|
||||||
from app.routers import auth, links
|
from app.routers import auth, links, settings, setup
|
||||||
|
from app.templating import templates
|
||||||
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
"""Manage database engine lifecycle."""
|
"""Manage database engine lifecycle and load app settings."""
|
||||||
settings = get_settings()
|
boot_settings = get_settings()
|
||||||
engine = create_async_engine(
|
engine = create_async_engine(
|
||||||
url=settings.database_url,
|
url=boot_settings.database_url,
|
||||||
pool_pre_ping=True,
|
pool_pre_ping=True,
|
||||||
echo=settings.app_name != "Myst",
|
echo=boot_settings.app_name != "Firebreak",
|
||||||
)
|
)
|
||||||
app.state.db_session = async_sessionmaker(
|
app.state.db_session = async_sessionmaker(
|
||||||
engine,
|
engine,
|
||||||
class_=AsyncSession,
|
class_=AsyncSession,
|
||||||
expire_on_commit=False, # Prevents MissingGreenlet in async
|
expire_on_commit=False,
|
||||||
)
|
)
|
||||||
async with engine.begin() as conn:
|
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
|
yield
|
||||||
await engine.dispose() # Close all connections on shutdown
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
templates = Jinja2Blocks(directory=str(TEMPLATES_DIR))
|
|
||||||
|
|
||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
app.add_middleware(SetupRequiredMiddleware)
|
||||||
|
|
||||||
app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")
|
app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(links.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(
|
async def root(
|
||||||
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
|
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
|
||||||
):
|
) -> HTMLResponse:
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"index.html",
|
"index.html",
|
||||||
|
|
@ -60,38 +71,15 @@ async def root(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/dashboard")
|
@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:
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"dashboard.html",
|
"dashboard.html",
|
||||||
{
|
{
|
||||||
"user": sess.user,
|
"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,
|
|
||||||
)
|
|
||||||
|
|
|
||||||
25
web/app/middleware.py
Normal file
25
web/app/middleware.py
Normal file
|
|
@ -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)
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
"""Import ORM modules so ``Base.metadata`` is populated before ``create_all``."""
|
"""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.grant import Grant
|
||||||
from app.models.session import Session
|
from app.models.session import Session
|
||||||
from app.models.user import LinkedIdentity, User
|
from app.models.user import LinkedIdentity, User
|
||||||
|
|
||||||
__all__ = ["Grant", "LinkedIdentity", "Session", "User"]
|
__all__ = ["AppSettings", "Grant", "LinkedIdentity", "Session", "User"]
|
||||||
|
|
|
||||||
38
web/app/models/app_settings.py
Normal file
38
web/app/models/app_settings.py
Normal file
|
|
@ -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
|
||||||
|
|
@ -23,8 +23,13 @@ class User(Base):
|
||||||
display_name: Mapped[str | None] = mapped_column(String, nullable=True)
|
display_name: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||||
email: Mapped[str | None] = mapped_column(String, nullable=True, index=True)
|
email: Mapped[str | None] = mapped_column(String, nullable=True, index=True)
|
||||||
pat_encrypted: Mapped[str | None] = mapped_column(Text, nullable=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())
|
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(
|
identities: Mapped[list[LinkedIdentity]] = relationship(
|
||||||
back_populates="user",
|
back_populates="user",
|
||||||
cascade="all, delete-orphan",
|
cascade="all, delete-orphan",
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,16 @@ from typing import Annotated
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
import httpx
|
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 fastapi.responses import RedirectResponse
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
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.identity import find_or_create_user
|
||||||
from app.auth.session import create_session, revoke_session
|
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.deps import get_db
|
||||||
|
from app.models.app_settings import AppSettings
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
@ -21,44 +23,38 @@ router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
# ── Forgejo API client ──
|
# ── Forgejo API client ──
|
||||||
|
|
||||||
|
|
||||||
async def _forgejo_post(settings: Settings, path: str, data: dict) -> dict:
|
async def _forgejo_post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
||||||
"""POST form data to a Forgejo API path and return the JSON response."""
|
url = f"{app_settings.forgejo_base_url}{path}"
|
||||||
|
|
||||||
# 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}"
|
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
resp = await client.post(url, data=data, headers={"Accept": "application/json"})
|
resp = await client.post(url, data=data, headers={"Accept": "application/json"})
|
||||||
except httpx.RequestError as exc:
|
except httpx.RequestError:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
detail=f"Cannot reach Forgejo: {exc}",
|
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||||
) from exc
|
)
|
||||||
if resp.status_code != 200:
|
if resp.status_code != 200:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
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()
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
async def _forgejo_get(settings: Settings, path: str, token: str) -> dict:
|
async def _forgejo_get(app_settings: AppSettings, path: str, token: str) -> dict:
|
||||||
"""GET a Forgejo API path with a provider access token."""
|
url = f"{app_settings.forgejo_base_url}{path}"
|
||||||
|
|
||||||
url = f"{settings.forgejo_base_url.rstrip('/')}{path}"
|
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
resp = await client.get(url, headers={"Authorization": f"token {token}"})
|
resp = await client.get(url, headers={"Authorization": f"token {token}"})
|
||||||
except httpx.RequestError as exc:
|
except httpx.RequestError:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
detail=f"Cannot reach Forgejo: {exc}",
|
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||||
) from exc
|
)
|
||||||
if resp.status_code != 200:
|
if resp.status_code != 200:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
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()
|
return resp.json()
|
||||||
|
|
||||||
|
|
@ -66,11 +62,7 @@ async def _forgejo_get(settings: Settings, path: str, token: str) -> dict:
|
||||||
# ── OAuth CSRF helpers ──
|
# ── OAuth CSRF helpers ──
|
||||||
|
|
||||||
|
|
||||||
def _set_oauth_state_cookie(response: Response, state: str) -> None:
|
def _set_oauth_state_cookie(response: RedirectResponse, 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.
|
|
||||||
response.set_cookie(
|
response.set_cookie(
|
||||||
key="oauth_state",
|
key="oauth_state",
|
||||||
value=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:
|
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):
|
if not state or not oauth_state or not secrets.compare_digest(state, oauth_state):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
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]:
|
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")
|
access_token = data.get("access_token")
|
||||||
if not access_token or not isinstance(access_token, str):
|
if not access_token or not isinstance(access_token, str):
|
||||||
raise HTTPException(
|
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]:
|
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_user_id = str(data.get("id", "")).strip()
|
||||||
provider_username = str(data.get("username", "")).strip()
|
provider_username = str(data.get("username", "")).strip()
|
||||||
if not provider_user_id or not provider_username:
|
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 ──
|
# ── OAuth config helpers ──
|
||||||
|
|
||||||
|
|
||||||
def _forgejo_oauth_redirect_uri(request: Request, settings: Settings) -> str:
|
def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) -> str:
|
||||||
"""Return the callback URL registered with Forgejo for this request."""
|
base_url = app_settings.firebreak_public_base_url.strip().rstrip("/")
|
||||||
|
|
||||||
# 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("/")
|
|
||||||
if base_url:
|
if base_url:
|
||||||
return f"{base_url}/auth/callback/forgejo"
|
return f"{base_url}/auth/callback/forgejo"
|
||||||
return str(request.url_for("forgejo_oauth_callback"))
|
return str(request.url_for("forgejo_oauth_callback"))
|
||||||
|
|
||||||
|
|
||||||
def _require_forgejo_oauth_config(settings: Settings) -> None:
|
def _get_oauth_client_secret(app_settings: AppSettings) -> str:
|
||||||
"""Raise a setup error when the Forgejo OAuth settings are incomplete."""
|
try:
|
||||||
|
return decrypt_token(app_settings.get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)
|
||||||
# Fail before redirecting when OAuth is only partially configured. This gives
|
except ValueError:
|
||||||
# a clearer setup error than a failed request after the user leaves the app.
|
|
||||||
if not settings.forgejo_base_url.strip():
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
detail="Forgejo is not configured: set FORGEJO_BASE_URL in the environment.",
|
detail="Forgejo OAuth credentials could not be decrypted. Reconfigure at /setup.",
|
||||||
)
|
|
||||||
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.",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -176,25 +139,21 @@ def _require_forgejo_oauth_config(settings: Settings) -> None:
|
||||||
|
|
||||||
@router.get("/login/forgejo")
|
@router.get("/login/forgejo")
|
||||||
async def 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:
|
) -> RedirectResponse:
|
||||||
"""Redirect the browser to Forgejo to begin OAuth sign-in."""
|
"""Redirect the browser to Forgejo to begin OAuth sign-in."""
|
||||||
|
|
||||||
_require_forgejo_oauth_config(settings)
|
redirect_uri = _forgejo_oauth_redirect_uri(request, app_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)
|
|
||||||
state = secrets.token_urlsafe(32)
|
state = secrets.token_urlsafe(32)
|
||||||
query = urlencode(
|
query = urlencode(
|
||||||
{
|
{
|
||||||
"client_id": settings.forgejo_oauth_client_id,
|
"client_id": app_settings.forgejo_oauth_client_id,
|
||||||
"response_type": "code",
|
"response_type": "code",
|
||||||
"redirect_uri": redirect_uri,
|
"redirect_uri": redirect_uri,
|
||||||
"state": state,
|
"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)
|
response = RedirectResponse(authorization_url, status_code=status.HTTP_302_FOUND)
|
||||||
_set_oauth_state_cookie(response, state)
|
_set_oauth_state_cookie(response, state)
|
||||||
return response
|
return response
|
||||||
|
|
@ -204,16 +163,13 @@ async def login_forgejo(
|
||||||
async def callback_forgejo(
|
async def callback_forgejo(
|
||||||
request: Request,
|
request: Request,
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
settings: Annotated[Settings, Depends(get_settings)],
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
code: str | None = None,
|
code: str | None = None,
|
||||||
state: str | None = None,
|
state: str | None = None,
|
||||||
oauth_state: Annotated[str | None, Cookie()] = None,
|
oauth_state: Annotated[str | None, Cookie()] = None,
|
||||||
) -> RedirectResponse:
|
) -> RedirectResponse:
|
||||||
"""Handle Forgejo's OAuth callback and create a local app session."""
|
"""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)
|
_verify_oauth_state(state, oauth_state)
|
||||||
|
|
||||||
if not code:
|
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.",
|
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
|
client_secret = _get_oauth_client_secret(app_settings)
|
||||||
# the exact RedirectResponse returned to the browser.
|
redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings)
|
||||||
redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
|
||||||
redirect.delete_cookie("oauth_state")
|
|
||||||
|
|
||||||
# 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(
|
token_data = await _forgejo_post(
|
||||||
settings,
|
app_settings,
|
||||||
"/login/oauth/access_token",
|
"/login/oauth/access_token",
|
||||||
{
|
{
|
||||||
"grant_type": "authorization_code",
|
"grant_type": "authorization_code",
|
||||||
"client_id": settings.forgejo_oauth_client_id,
|
"client_id": app_settings.forgejo_oauth_client_id,
|
||||||
"client_secret": settings.forgejo_oauth_client_secret.get_secret_value(),
|
"client_secret": client_secret,
|
||||||
"code": code,
|
"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)
|
access_token, refresh_plain, expires_at = _parse_token_response(token_data)
|
||||||
|
|
||||||
# Use the provider access token once to fetch the Forgejo account profile we
|
user_data = await _forgejo_get(app_settings, "/api/v1/user", access_token)
|
||||||
# link to our local users table.
|
|
||||||
user_data = await _forgejo_get(settings, "/api/v1/user", access_token)
|
|
||||||
provider_user_id, provider_username, email = _parse_user_response(user_data)
|
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(
|
user = await find_or_create_user(
|
||||||
db,
|
db,
|
||||||
settings,
|
app_settings,
|
||||||
provider="forgejo",
|
provider="forgejo",
|
||||||
provider_user_id=provider_user_id,
|
provider_user_id=provider_user_id,
|
||||||
provider_username=provider_username,
|
provider_username=provider_username,
|
||||||
|
|
@ -262,8 +209,10 @@ async def callback_forgejo(
|
||||||
refresh_token_raw=refresh_plain,
|
refresh_token_raw=refresh_plain,
|
||||||
)
|
)
|
||||||
|
|
||||||
# After OAuth succeeds, use our own session cookie for normal app requests.
|
target = "/dashboard" if user.has_pat else "/settings"
|
||||||
# The raw cookie value is sent to the browser; only its hash is stored.
|
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")
|
await create_session(db, redirect, user.id, secure=request.url.scheme == "https")
|
||||||
return redirect
|
return redirect
|
||||||
|
|
||||||
|
|
@ -271,12 +220,10 @@ async def callback_forgejo(
|
||||||
@router.get("/logout")
|
@router.get("/logout")
|
||||||
async def logout(
|
async def logout(
|
||||||
db: Annotated[AsyncSession, Depends(get_db)],
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
myst_session: Annotated[str | None, Cookie()] = None,
|
firebreak_session: Annotated[str | None, Cookie()] = None,
|
||||||
) -> RedirectResponse:
|
) -> RedirectResponse:
|
||||||
"""Revoke the current app session and redirect back to the home page."""
|
"""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)
|
redirect = RedirectResponse("/", status_code=status.HTTP_302_FOUND)
|
||||||
await revoke_session(db, redirect, myst_session)
|
await revoke_session(db, redirect, firebreak_session)
|
||||||
return redirect
|
return redirect
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ class CreateLinkResponse(BaseModel):
|
||||||
share_url: str
|
share_url: str
|
||||||
|
|
||||||
|
|
||||||
@router.post("/", response_model=CreateLinkResponse)
|
@router.post("/", status_code=501)
|
||||||
async def create_link(request: CreateLinkRequest):
|
async def create_link(request: CreateLinkRequest) -> dict:
|
||||||
pass
|
"""Stub — link creation not yet implemented."""
|
||||||
|
return {"detail": "Link creation is not yet implemented."}
|
||||||
|
|
|
||||||
76
web/app/routers/settings.py
Normal file
76
web/app/routers/settings.py
Normal file
|
|
@ -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,
|
||||||
|
)
|
||||||
117
web/app/routers/setup.py
Normal file
117
web/app/routers/setup.py
Normal file
|
|
@ -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)
|
||||||
|
|
@ -204,6 +204,10 @@
|
||||||
color: #fffdf8;
|
color: #fffdf8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.landing-page .app-header {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.landing-page {
|
.landing-page {
|
||||||
background: #17191c;
|
background: #17191c;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>
|
<title>
|
||||||
{% block title %}Myst{% endblock %}
|
{% block title %}Firebreak{% endblock %}
|
||||||
</title>
|
</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
|
@ -56,6 +56,7 @@
|
||||||
<nav class="flex items-center gap-2">
|
<nav class="flex items-center gap-2">
|
||||||
{% if user %}
|
{% if user %}
|
||||||
<a href="/dashboard" class="btn btn-sm btn-borderless">Dashboard</a>
|
<a href="/dashboard" class="btn btn-sm btn-borderless">Dashboard</a>
|
||||||
|
<a href="/settings" class="btn btn-sm btn-borderless">Settings</a>
|
||||||
<a href="/auth/logout" class="btn btn-sm btn-secondary">Logout</a>
|
<a href="/auth/logout" class="btn btn-sm btn-secondary">Logout</a>
|
||||||
{% else %}
|
{% else %}
|
||||||
<a href="/auth/login/forgejo" class="btn btn-sm btn-primary">
|
<a href="/auth/login/forgejo" class="btn btn-sm btn-primary">
|
||||||
|
|
@ -71,7 +72,7 @@
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<main class="px-4 py-8 mx-auto max-w-7xl sm:px-8">
|
<main class="{% block main_class %}px-4 py-8 mx-auto max-w-7xl sm:px-8{% endblock %}">
|
||||||
{% block content %}{% endblock %}
|
{% block content %}{% endblock %}
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block title %}Dashboard — Myst{% 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">
|
||||||
|
|
@ -26,29 +26,15 @@
|
||||||
<p class="mt-2 text-xs text-muted-foreground">Viewer activity will appear here.</p>
|
<p class="mt-2 text-xs text-muted-foreground">Viewer activity will appear here.</p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<div id="forgejo-access-token">
|
{% if not pat_registered %}
|
||||||
{% if pat_registered %}
|
<div class="rounded-lg border border-warning-muted bg-warning-muted/40 px-5 py-4">
|
||||||
<div
|
<p class="text-sm font-semibold text-warning-foreground">Access token required</p>
|
||||||
class="mt-3 rounded-md border-l-4 border-success bg-success-muted px-4 py-3 text-sm font-semibold text-success-foreground"
|
<p class="mt-1 text-sm text-muted-foreground">
|
||||||
role="status">Forgejo access token registered.</div>
|
Register a Forgejo access token to create share links.
|
||||||
{% else %}
|
|
||||||
<h2 class="text-base font-semibold">Forgejo access token</h2>
|
|
||||||
<p class="mt-2 text-sm text-muted-foreground">
|
|
||||||
Register a <code class="rounded-sm bg-secondary px-1.5 py-0.5 text-primary">read:repository</code>-scoped PAT
|
|
||||||
to enable share link viewing.
|
|
||||||
</p>
|
</p>
|
||||||
<form id="pat-form" class="mt-4" method="post" action="/dashboard/pat" novalidate>
|
<a href="/settings" class="btn btn-sm btn-primary mt-3 w-fit">Go to Settings</a>
|
||||||
<div class="grid gap-2 sm:gap-4 sm:grid-cols-[1fr_auto] sm:items-end">
|
|
||||||
<input type="text" id="pat" name="pat" class="block w-full input-mono" placeholder="ad8j3..."
|
|
||||||
aria-describedby="pat-error" aria-invalid="false" required />
|
|
||||||
<button type="submit" class="btn btn-sm btn-primary self-center">Register</button>
|
|
||||||
</div>
|
|
||||||
<div class="mt-2">
|
|
||||||
<p id="pat-error" class="input-error hidden">A Forgejo token is required.</p>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
<div class="space-y-3">
|
<div class="space-y-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-base font-semibold">Share links</h2>
|
<h2 class="text-base font-semibold">Share links</h2>
|
||||||
|
|
@ -76,34 +62,4 @@
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
const form = document.getElementById("pat-form");
|
|
||||||
const input = document.getElementById("pat");
|
|
||||||
const error = document.getElementById("pat-error");
|
|
||||||
|
|
||||||
if (!form || !input || !error) return;
|
|
||||||
|
|
||||||
const showError = () => {
|
|
||||||
input.setAttribute("aria-invalid", "true");
|
|
||||||
input.classList.add("border-danger", "focus:border-danger", "focus:ring-danger-muted");
|
|
||||||
error.classList.remove("hidden");
|
|
||||||
input.focus();
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearError = () => {
|
|
||||||
input.setAttribute("aria-invalid", "false");
|
|
||||||
input.classList.remove("border-danger", "focus:border-danger", "focus:ring-danger-muted");
|
|
||||||
error.classList.add("hidden");
|
|
||||||
};
|
|
||||||
|
|
||||||
form.addEventListener("submit", (event) => {
|
|
||||||
if (input.value.trim()) return;
|
|
||||||
event.preventDefault();
|
|
||||||
showError();
|
|
||||||
});
|
|
||||||
|
|
||||||
input.addEventListener("input", clearError);
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block title %}Firebreak — protect your code from scraping{% endblock %}
|
{% block title %}Firebreak — protect your code from scraping{% endblock %}
|
||||||
{% block body_class %}landing-page{% endblock %}
|
{% block body_class %}landing-page{% endblock %}
|
||||||
|
{% block main_class %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="relative left-1/2 right-1/2 -mx-[50vw] -mt-8 -mb-8 flex min-h-[calc(100dvh-4.25rem)] w-screen items-center justify-center overflow-hidden bg-[#17191c] px-6 py-20 text-center text-[#f7f2e8]">
|
<section class="relative flex min-h-dvh w-full items-center justify-center overflow-hidden bg-[#17191c] px-6 py-20 text-center text-[#f7f2e8]">
|
||||||
<video class="absolute inset-0 h-full w-full object-cover"
|
<video class="absolute inset-0 h-full w-full object-cover"
|
||||||
autoplay
|
autoplay
|
||||||
muted
|
muted
|
||||||
|
|
@ -45,6 +46,10 @@
|
||||||
</a>
|
</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
<a href="/setup"
|
||||||
|
class="mt-5 text-xs text-[#f7f2e8]/30 hover:text-[#f7f2e8]/60 hover:underline decoration-1 underline-offset-4 transition">
|
||||||
|
Reconfigure Forgejo connection
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
|
||||||
134
web/app/templates/settings.html
Normal file
134
web/app/templates/settings.html
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Settings — Firebreak{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<div class="flex flex-col gap-6">
|
||||||
|
<section class="pb-6 border-b border-border">
|
||||||
|
<h1 class="text-2xl font-semibold">Settings</h1>
|
||||||
|
<p class="mt-2 text-sm text-muted-foreground">Manage your Firebreak configuration.</p>
|
||||||
|
</section>
|
||||||
|
{% if pat_deleted %}
|
||||||
|
<div class="rounded-md border-l-4 border-warning bg-warning-muted px-4 py-3 text-sm font-semibold text-warning-foreground"
|
||||||
|
role="status">Access token removed.</div>
|
||||||
|
{% endif %}
|
||||||
|
<div id="forgejo-access-token">
|
||||||
|
<h2 class="text-base font-semibold">Forgejo access token</h2>
|
||||||
|
<p class="mt-2 text-sm text-muted-foreground">
|
||||||
|
A <code class="rounded-sm bg-secondary px-1.5 py-0.5 text-foreground">read:repository</code>-scoped
|
||||||
|
Personal Access Token is required for share link viewing.
|
||||||
|
</p>
|
||||||
|
{% if pat_registered %}
|
||||||
|
<div class="mt-4 card">
|
||||||
|
<div class="flex items-center justify-between px-4 py-3.5">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div class="flex size-8 items-center justify-center rounded-md bg-success-muted text-success-foreground">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="16"
|
||||||
|
height="16"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round">
|
||||||
|
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-foreground">Access token</p>
|
||||||
|
<p class="mt-0.5 text-xs text-muted-foreground">
|
||||||
|
{% if pat_registered_at %}
|
||||||
|
Registered {{ pat_registered_at.strftime("%b %d, %Y") }}
|
||||||
|
{% else %}
|
||||||
|
Registered
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form method="post" action="/settings/pat/delete">
|
||||||
|
<button type="submit"
|
||||||
|
class="btn btn-xs btn-secondary text-danger-foreground hover:bg-danger-muted hover:border-danger-muted">
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<details class="mt-4">
|
||||||
|
<summary class="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
|
||||||
|
Update token
|
||||||
|
</summary>
|
||||||
|
<form id="pat-form"
|
||||||
|
class="mt-3"
|
||||||
|
method="post"
|
||||||
|
action="/settings/pat"
|
||||||
|
novalidate>
|
||||||
|
<div class="grid gap-2 sm:gap-4 sm:grid-cols-[1fr_auto] sm:items-end">
|
||||||
|
<input type="password"
|
||||||
|
id="pat"
|
||||||
|
name="pat"
|
||||||
|
class="block w-full input-mono"
|
||||||
|
placeholder="Paste new token..."
|
||||||
|
aria-describedby="pat-error"
|
||||||
|
aria-invalid="false"
|
||||||
|
required />
|
||||||
|
<button type="submit" class="btn btn-sm btn-primary self-center">Update</button>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2">
|
||||||
|
<p id="pat-error" class="input-error hidden">A Forgejo token is required.</p>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
{% else %}
|
||||||
|
<form id="pat-form"
|
||||||
|
class="mt-4"
|
||||||
|
method="post"
|
||||||
|
action="/settings/pat"
|
||||||
|
novalidate>
|
||||||
|
<div class="grid gap-2 sm:gap-4 sm:grid-cols-[1fr_auto] sm:items-end">
|
||||||
|
<input type="password"
|
||||||
|
id="pat"
|
||||||
|
name="pat"
|
||||||
|
class="block w-full input-mono"
|
||||||
|
placeholder="ad8j3..."
|
||||||
|
aria-describedby="pat-error"
|
||||||
|
aria-invalid="false"
|
||||||
|
required />
|
||||||
|
<button type="submit" class="btn btn-sm btn-primary self-center">Register</button>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2">
|
||||||
|
<p id="pat-error" class="input-error hidden">A Forgejo token is required.</p>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const form = document.getElementById("pat-form");
|
||||||
|
const input = document.getElementById("pat");
|
||||||
|
const error = document.getElementById("pat-error");
|
||||||
|
|
||||||
|
if (!form || !input || !error) return;
|
||||||
|
|
||||||
|
const showError = () => {
|
||||||
|
input.setAttribute("aria-invalid", "true");
|
||||||
|
input.classList.add("border-danger", "focus:border-danger", "focus:ring-danger-muted");
|
||||||
|
error.classList.remove("hidden");
|
||||||
|
input.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearError = () => {
|
||||||
|
input.setAttribute("aria-invalid", "false");
|
||||||
|
input.classList.remove("border-danger", "focus:border-danger", "focus:ring-danger-muted");
|
||||||
|
error.classList.add("hidden");
|
||||||
|
};
|
||||||
|
|
||||||
|
form.addEventListener("submit", (event) => {
|
||||||
|
if (input.value.trim()) return;
|
||||||
|
event.preventDefault();
|
||||||
|
showError();
|
||||||
|
});
|
||||||
|
|
||||||
|
input.addEventListener("input", clearError);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
118
web/app/templates/setup.html
Normal file
118
web/app/templates/setup.html
Normal file
|
|
@ -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 %}
|
||||||
|
<section class="flex min-h-dvh items-center justify-center px-6 py-20">
|
||||||
|
<div class="w-full max-w-lg">
|
||||||
|
<div class="mb-8 text-center">
|
||||||
|
<img src="/static/img/firebreak-brand.svg"
|
||||||
|
alt="Firebreak"
|
||||||
|
width="240"
|
||||||
|
height="268"
|
||||||
|
class="mx-auto h-auto w-full max-w-24" />
|
||||||
|
<h1 class="mt-6 text-2xl font-semibold text-[#f7f2e8]">
|
||||||
|
{{ "Reconfigure" if reconfiguring else "Setup" }}
|
||||||
|
</h1>
|
||||||
|
{% if reconfiguring %}
|
||||||
|
<p class="mt-2 text-sm leading-6 text-[#f7f2e8]/60">
|
||||||
|
Update your Forgejo OAuth connection. Make sure the OAuth application
|
||||||
|
is registered in your Forgejo instance before continuing.
|
||||||
|
</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="mt-2 text-sm leading-6 text-[#f7f2e8]/60">
|
||||||
|
Connect Firebreak to your Forgejo instance. You'll need to
|
||||||
|
<a href="https://forgejo.org/docs/latest/user/oauth2-provider/"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
class="underline underline-offset-2 text-[#f7f2e8]/80 hover:text-[#f7f2e8]">register an OAuth application</a>
|
||||||
|
in Forgejo first.
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if not reconfiguring %}
|
||||||
|
<div class="mb-8 rounded-lg border border-[#f7f2e8]/10 bg-[#1f2226]/60 px-5 py-4 text-xs leading-5 text-[#f7f2e8]/50">
|
||||||
|
<p class="font-medium text-[#f7f2e8]/70 mb-2.5">How to get your OAuth credentials:</p>
|
||||||
|
<ol class="list-decimal list-inside space-y-1.5">
|
||||||
|
<li>
|
||||||
|
In Forgejo, go to <strong class="text-[#f7f2e8]/70">Settings → Applications</strong>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Under <strong class="text-[#f7f2e8]/70">Manage OAuth2 Applications</strong>, create a new app
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Set the redirect URI to
|
||||||
|
<br />
|
||||||
|
<code class="mt-1 inline-block rounded bg-[#f7f2e8]/8 px-1.5 py-0.5 font-mono text-[10px] text-[#f7f2e8]/60">http://localhost:8000/auth/callback/forgejo</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Copy the <strong class="text-[#f7f2e8]/70">Client ID</strong> and <strong class="text-[#f7f2e8]/70">Client Secret</strong> into the form below
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<form method="post" action="/setup" class="space-y-5">
|
||||||
|
<div>
|
||||||
|
<label for="forgejo_base_url"
|
||||||
|
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||||
|
Forgejo Instance URL
|
||||||
|
</label>
|
||||||
|
<input type="url"
|
||||||
|
id="forgejo_base_url"
|
||||||
|
name="forgejo_base_url"
|
||||||
|
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
|
||||||
|
placeholder="https://git.example.com"
|
||||||
|
value="{{ forgejo_base_url }}"
|
||||||
|
required />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="forgejo_oauth_client_id"
|
||||||
|
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||||
|
OAuth Client ID
|
||||||
|
</label>
|
||||||
|
<input type="text"
|
||||||
|
id="forgejo_oauth_client_id"
|
||||||
|
name="forgejo_oauth_client_id"
|
||||||
|
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="c8ab3315-537d-44f3-..."
|
||||||
|
value="{{ forgejo_oauth_client_id }}"
|
||||||
|
required />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="forgejo_oauth_client_secret"
|
||||||
|
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||||
|
OAuth Client Secret
|
||||||
|
{% if reconfiguring %}
|
||||||
|
<span class="ml-1 normal-case tracking-normal font-normal text-[#f7f2e8]/30">(leave blank to keep current)</span>
|
||||||
|
{% endif %}
|
||||||
|
</label>
|
||||||
|
<input type="password"
|
||||||
|
id="forgejo_oauth_client_secret"
|
||||||
|
name="forgejo_oauth_client_secret"
|
||||||
|
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="gto_wkxxnv4ewa..."
|
||||||
|
{{ "" if reconfiguring else "required" }} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="firebreak_public_base_url"
|
||||||
|
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||||
|
Public Base URL
|
||||||
|
<span class="ml-1 normal-case tracking-normal font-normal text-[#f7f2e8]/30">(optional)</span>
|
||||||
|
</label>
|
||||||
|
<input type="url"
|
||||||
|
id="firebreak_public_base_url"
|
||||||
|
name="firebreak_public_base_url"
|
||||||
|
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
|
||||||
|
placeholder="https://share.example.com"
|
||||||
|
value="{{ firebreak_public_base_url }}" />
|
||||||
|
<p class="mt-1.5 text-xs text-[#f7f2e8]/30">
|
||||||
|
Your production domain for OAuth redirects. Leave blank on localhost — Firebreak will use <code class="font-mono text-[#f7f2e8]/40">http://localhost:8000</code> automatically.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary w-full mt-2">
|
||||||
|
{{ "Save Forgejo settings" if reconfiguring else "Complete Setup" }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
9
web/app/templating.py
Normal file
9
web/app/templating.py
Normal file
|
|
@ -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))
|
||||||
Loading…
Add table
Reference in a new issue