fix(web): security hardening, rename cleanup, and error pages
- Move TOKEN_ENCRYPTION_KEY from DB to env var (no longer stored alongside encrypted data) - Add one-time setup token printed to server logs to prevent anonymous setup takeover - Setup token persists until first successful login, allowing config retries - Remove setup_complete flag in favor of app_settings nullability check - Fix stale Myst→Firebreak references in crypto.py, dev.sh, pyproject.toml - Add dynamic OAuth callback URL in setup wizard - Fix global heading color override to use foreground instead of danger - Add aria-label to brand link for accessibility - Remove forced redirect to /settings after first login - Remove reconfigure link from landing page - Add styled error page with HTML/JSON content negotiation - Add 401 guard dog easter egg Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
8e56a5bb1c
commit
18897362df
18 changed files with 420 additions and 84 deletions
22
README.md
22
README.md
|
|
@ -52,7 +52,21 @@ HTMX provides interactivity (filtering, form submissions) with minimal JavaScrip
|
|||
docker compose up -d
|
||||
```
|
||||
|
||||
### 2. Run the Setup Wizard
|
||||
### 2. Generate an Encryption Key
|
||||
|
||||
Firebreak encrypts OAuth tokens and PATs at rest using a Fernet key. Generate one and add it to your environment before running the setup wizard:
|
||||
|
||||
```bash
|
||||
uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'
|
||||
```
|
||||
|
||||
Add the output to your `.env` file (or your deployment platform's environment variables):
|
||||
|
||||
```
|
||||
TOKEN_ENCRYPTION_KEY=your-generated-key-here
|
||||
```
|
||||
|
||||
### 3. Run the Setup Wizard
|
||||
|
||||
Open `http://localhost:8000` in your browser. On first boot, Firebreak redirects to a setup wizard where you configure:
|
||||
|
||||
|
|
@ -60,13 +74,11 @@ Open `http://localhost:8000` in your browser. On first boot, Firebreak redirects
|
|||
- **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
|
||||
|
||||
The setup wizard auto-generates an encryption key for token storage.
|
||||
|
||||
### 3. Sign In and Register Your Token
|
||||
### 4. Sign In and Register Your Token
|
||||
|
||||
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.
|
||||
|
||||
### 4. Alternative Deployments
|
||||
### 5. Alternative Deployments
|
||||
|
||||
For non-Docker deployments, supply `DATABASE_URL` yourself:
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ def fernet_from_encryption_key(key: SecretStr) -> Fernet | None:
|
|||
except Exception as e:
|
||||
msg = (
|
||||
f"Invalid TOKEN_ENCRYPTION_KEY: {e}. "
|
||||
"Generate a valid key with cryptography.fernet.Fernet.generate_key().decode()"
|
||||
"Generate a valid key with: uv run python -c "
|
||||
"'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
|
||||
)
|
||||
raise ValueError(msg) from e
|
||||
|
||||
|
|
@ -29,8 +30,8 @@ def encrypt_optional(fernet: Fernet | None, raw_token: str | None) -> str | None
|
|||
return None
|
||||
if fernet is None:
|
||||
msg = (
|
||||
"Token encryption is not configured: set TOKEN_ENCRYPTION_KEY "
|
||||
"to the output of cryptography.fernet.Fernet.generate_key().decode()"
|
||||
"Token encryption is not configured. "
|
||||
"Set TOKEN_ENCRYPTION_KEY in your .env file or deployment environment."
|
||||
)
|
||||
raise ValueError(msg)
|
||||
return encrypt_token(fernet, raw_token)
|
||||
|
|
@ -51,8 +52,8 @@ def decrypt_optional(fernet: Fernet | None, encrypted_token: str | None) -> str
|
|||
return None
|
||||
if fernet is None:
|
||||
msg = (
|
||||
"Token encryption is not configured: set TOKEN_ENCRYPTION_KEY "
|
||||
"to the output of cryptography.fernet.Fernet.generate_key().decode()"
|
||||
"Token encryption is not configured. "
|
||||
"Set TOKEN_ENCRYPTION_KEY in your .env file or deployment environment."
|
||||
)
|
||||
raise ValueError(msg)
|
||||
return decrypt_token(fernet, encrypted_token)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.auth.crypto import encrypt_optional
|
||||
from app.config import get_fernet
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.models.user import LinkedIdentity, User
|
||||
|
||||
|
|
@ -25,7 +26,7 @@ async def find_or_create_user(
|
|||
) -> User:
|
||||
"""Find or create a user based on the given provider and identity details."""
|
||||
|
||||
fernet = app_settings.get_fernet()
|
||||
fernet = get_fernet()
|
||||
|
||||
result = await db.execute(
|
||||
select(LinkedIdentity)
|
||||
|
|
|
|||
|
|
@ -4,13 +4,17 @@ from functools import lru_cache
|
|||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
from fastapi import Request
|
||||
from pydantic import SecretStr
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from app.auth.crypto import fernet_from_encryption_key
|
||||
|
||||
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):
|
||||
|
|
@ -22,8 +26,9 @@ class Settings(BaseSettings):
|
|||
|
||||
app_name: str = "Firebreak"
|
||||
database_url: str = "postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db"
|
||||
token_encryption_key: str = ""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=str(env_file))
|
||||
model_config = SettingsConfigDict(env_file=str(_env_file))
|
||||
|
||||
|
||||
@lru_cache
|
||||
|
|
@ -32,6 +37,25 @@ def get_settings() -> Settings:
|
|||
return Settings()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_fernet() -> Fernet:
|
||||
"""Return a cached Fernet cipher from the TOKEN_ENCRYPTION_KEY env var."""
|
||||
key = get_settings().token_encryption_key
|
||||
if not key:
|
||||
raise ValueError(
|
||||
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
|
||||
"environment. Generate one with: uv run python -c "
|
||||
"'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
|
||||
)
|
||||
fernet = fernet_from_encryption_key(SecretStr(key))
|
||||
if fernet is None:
|
||||
raise ValueError(
|
||||
"TOKEN_ENCRYPTION_KEY is invalid. Generate a valid key with: uv run python -c "
|
||||
"'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
|
||||
)
|
||||
return fernet
|
||||
|
||||
|
||||
def get_app_settings(request: Request) -> AppSettings:
|
||||
"""FastAPI dependency returning the AppSettings row from app state."""
|
||||
return request.app.state.app_settings
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import logging
|
||||
import secrets
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func as sql_func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from app import models as _models # noqa: F401 - register ORM tables on metadata
|
||||
|
|
@ -37,14 +39,29 @@ async def lifespan(app: FastAPI):
|
|||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
async with app.state.db_session() as db:
|
||||
from app.models.user import User
|
||||
|
||||
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
|
||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
||||
|
||||
app.state.app_settings = row
|
||||
|
||||
# Generate a setup token whenever no users exist yet — whether it's
|
||||
# a fresh install or a retry after bad OAuth config.
|
||||
if not user_count:
|
||||
app.state.setup_token = secrets.token_urlsafe(32)
|
||||
logger = logging.getLogger("firebreak")
|
||||
logger.warning(
|
||||
"\n"
|
||||
"╔══════════════════════════════════════════════════════════╗\n"
|
||||
"║ SETUP TOKEN (paste this into the setup wizard): ║\n"
|
||||
"║ %-54s ║\n"
|
||||
"╚══════════════════════════════════════════════════════════╝",
|
||||
app.state.setup_token,
|
||||
)
|
||||
else:
|
||||
app.state.setup_complete = False
|
||||
app.state.app_settings = None
|
||||
app.state.setup_token = None
|
||||
|
||||
yield
|
||||
await engine.dispose()
|
||||
|
|
@ -59,6 +76,33 @@ app.include_router(links.router)
|
|||
app.include_router(settings.router)
|
||||
app.include_router(setup.router)
|
||||
|
||||
ERROR_TITLES = {
|
||||
400: "Bad Request",
|
||||
401: "Unauthorized",
|
||||
403: "Forbidden",
|
||||
404: "Not Found",
|
||||
500: "Internal Server Error",
|
||||
503: "Service Unavailable",
|
||||
}
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) -> HTMLResponse | JSONResponse:
|
||||
"""Render a styled error page for browser requests, JSON for API clients."""
|
||||
accept = request.headers.get("accept", "")
|
||||
if "text/html" in accept:
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
"error.html",
|
||||
{
|
||||
"status_code": exc.status_code,
|
||||
"title": ERROR_TITLES.get(exc.status_code, "Error"),
|
||||
"detail": exc.detail,
|
||||
},
|
||||
status_code=exc.status_code,
|
||||
)
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def root(
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class SetupRequiredMiddleware(BaseHTTPMiddleware):
|
|||
):
|
||||
return await call_next(request)
|
||||
|
||||
if not request.app.state.setup_complete:
|
||||
if request.app.state.app_settings is None:
|
||||
if request.headers.get("HX-Request"):
|
||||
response = Response(status_code=200)
|
||||
response.headers["HX-Redirect"] = "/setup"
|
||||
|
|
|
|||
|
|
@ -2,12 +2,9 @@ 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
|
||||
|
||||
|
||||
|
|
@ -20,19 +17,6 @@ class AppSettings(Base):
|
|||
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
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ 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 get_app_settings
|
||||
from app.config import get_app_settings, get_fernet
|
||||
from app.deps import get_db
|
||||
from app.models.app_settings import AppSettings
|
||||
|
||||
|
|
@ -126,7 +126,7 @@ def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) ->
|
|||
|
||||
def _get_oauth_client_secret(app_settings: AppSettings) -> str:
|
||||
try:
|
||||
return decrypt_token(app_settings.get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)
|
||||
return decrypt_token(get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
|
|
@ -209,8 +209,11 @@ async def callback_forgejo(
|
|||
refresh_token_raw=refresh_plain,
|
||||
)
|
||||
|
||||
target = "/dashboard" if user.has_pat else "/settings"
|
||||
redirect = RedirectResponse(target, status_code=status.HTTP_302_FOUND)
|
||||
# Clear setup token on first successful login — setup is proven to work
|
||||
if request.app.state.setup_token is not None:
|
||||
request.app.state.setup_token = None
|
||||
|
||||
redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
||||
redirect.delete_cookie("oauth_state")
|
||||
|
||||
await create_session(db, redirect, user.id, secure=request.url.scheme == "https")
|
||||
|
|
|
|||
|
|
@ -9,9 +9,8 @@ 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.config import get_fernet
|
||||
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
|
||||
|
||||
|
|
@ -22,7 +21,6 @@ router = APIRouter(prefix="/settings", tags=["settings"])
|
|||
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,
|
||||
|
|
@ -40,7 +38,6 @@ async def settings_page(
|
|||
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()
|
||||
|
|
@ -50,7 +47,7 @@ async def register_pat(
|
|||
detail="Forgejo access token is required.",
|
||||
)
|
||||
|
||||
fernet = app_settings.get_fernet()
|
||||
fernet = get_fernet()
|
||||
sess.user.pat_encrypted = encrypt_optional(fernet, pat)
|
||||
sess.user.pat_registered_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
|
|
|||
|
|
@ -2,17 +2,17 @@ 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 import func as sql_func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.crypto import encrypt_token, fernet_from_encryption_key
|
||||
from app.auth.crypto import encrypt_token
|
||||
from app.auth.session import lookup_session
|
||||
from app.config import get_fernet
|
||||
from app.deps import get_db
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.models.user import User
|
||||
from app.templating import templates
|
||||
|
||||
router = APIRouter(prefix="/setup", tags=["setup"])
|
||||
|
|
@ -23,9 +23,19 @@ async def _require_auth_if_configured(
|
|||
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:
|
||||
"""Block anonymous access to /setup after initial configuration.
|
||||
|
||||
If no users exist yet (e.g. bad OAuth config on first setup), the setup
|
||||
token is still required but login is not — there's nobody to log in as.
|
||||
"""
|
||||
if request.app.state.app_settings is None:
|
||||
return
|
||||
|
||||
# If no users exist, allow access — the setup token still protects POST
|
||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
||||
if user_count == 0:
|
||||
return
|
||||
|
||||
sess = await lookup_session(db, firebreak_session)
|
||||
if sess is None:
|
||||
raise HTTPException(
|
||||
|
|
@ -35,14 +45,21 @@ async def _require_auth_if_configured(
|
|||
|
||||
|
||||
@router.get("", dependencies=[Depends(_require_auth_if_configured)], response_class=HTMLResponse)
|
||||
async def setup_page(request: Request) -> HTMLResponse:
|
||||
async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_db)]) -> HTMLResponse:
|
||||
"""Render the setup wizard. Pre-fills fields when reconfiguring."""
|
||||
existing = request.app.state.app_settings
|
||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
||||
has_users = user_count > 0
|
||||
public_base = (
|
||||
(existing.firebreak_public_base_url if existing else "")
|
||||
or str(request.base_url).rstrip("/")
|
||||
)
|
||||
ctx = {
|
||||
"reconfiguring": existing is not None,
|
||||
"reconfiguring": existing is not None and has_users,
|
||||
"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 "",
|
||||
"oauth_callback_url": f"{public_base}/auth/callback/forgejo",
|
||||
}
|
||||
return templates.TemplateResponse(request, "setup.html", ctx)
|
||||
|
||||
|
|
@ -55,9 +72,21 @@ async def setup_submit(
|
|||
forgejo_oauth_client_id: Annotated[str, Form()],
|
||||
forgejo_oauth_client_secret: Annotated[str, Form()] = "",
|
||||
firebreak_public_base_url: Annotated[str, Form()] = "",
|
||||
setup_token: Annotated[str, Form()] = "",
|
||||
) -> RedirectResponse:
|
||||
"""Process the setup wizard — creates or updates Forgejo settings."""
|
||||
is_reconfiguring = request.app.state.setup_complete
|
||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
||||
has_users = user_count > 0
|
||||
is_reconfiguring = request.app.state.app_settings is not None and has_users
|
||||
|
||||
# Require setup token when no users exist (first-time or fixing bad config)
|
||||
if not has_users:
|
||||
expected = request.app.state.setup_token
|
||||
if not expected or setup_token.strip() != expected:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid setup token. Check your server logs for the correct token.",
|
||||
)
|
||||
|
||||
forgejo_base_url = forgejo_base_url.strip().rstrip("/")
|
||||
forgejo_oauth_client_id = forgejo_oauth_client_id.strip()
|
||||
|
|
@ -81,37 +110,64 @@ async def setup_submit(
|
|||
row.forgejo_oauth_client_id = forgejo_oauth_client_id
|
||||
row.firebreak_public_base_url = firebreak_public_base_url
|
||||
if forgejo_oauth_client_secret:
|
||||
try:
|
||||
fernet = get_fernet()
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=(
|
||||
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
|
||||
"environment. Generate one with: "
|
||||
"uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
|
||||
),
|
||||
)
|
||||
row.forgejo_oauth_client_secret_encrypted = encrypt_token(
|
||||
row.get_fernet(), forgejo_oauth_client_secret
|
||||
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)
|
||||
# First-time setup (or retry after bad config) — 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))
|
||||
try:
|
||||
fernet = get_fernet()
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=(
|
||||
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
|
||||
"environment. Generate one with: "
|
||||
"uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
|
||||
),
|
||||
)
|
||||
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)
|
||||
# Update existing row if retrying after bad config, otherwise create
|
||||
result = await db.execute(select(AppSettings).where(AppSettings.id == 1))
|
||||
row = result.scalar_one_or_none()
|
||||
if row:
|
||||
row.forgejo_base_url = forgejo_base_url
|
||||
row.forgejo_oauth_client_id = forgejo_oauth_client_id
|
||||
row.forgejo_oauth_client_secret_encrypted = encrypted_secret
|
||||
row.firebreak_public_base_url = firebreak_public_base_url
|
||||
else:
|
||||
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,
|
||||
)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@
|
|||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
@apply text-danger-foreground;
|
||||
@apply text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
BIN
web/app/static/img/mark_cuckerberg.png
Normal file
BIN
web/app/static/img/mark_cuckerberg.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
|
|
@ -17,7 +17,8 @@
|
|||
<header class="app-header">
|
||||
<div class="flex items-center justify-between px-4 py-3 mx-auto max-w-7xl sm:px-8">
|
||||
<a href="/"
|
||||
class="brand-link flex items-center gap-2 text-base text-foreground hover:text-primary">
|
||||
class="brand-link flex items-center gap-2 text-base text-foreground hover:text-primary"
|
||||
aria-label="Firebreak home">
|
||||
<svg width="28"
|
||||
height="30"
|
||||
viewBox="0 0 28 30"
|
||||
|
|
|
|||
200
web/app/templates/error.html
Normal file
200
web/app/templates/error.html
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}{{ status_code }} — Firebreak{% endblock %}
|
||||
{% block body_class %}landing-page{% endblock %}
|
||||
{% block main_class %}{% endblock %}
|
||||
{% block content %}
|
||||
{% if status_code == 401 %}
|
||||
<style>
|
||||
@keyframes creep-in {
|
||||
from { transform: translateX(100%); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
@keyframes trot {
|
||||
0%, 100% { transform: translateY(0) rotate(0deg); }
|
||||
25% { transform: translateY(-3px) rotate(-0.6deg); }
|
||||
75% { transform: translateY(-3px) rotate(0.6deg); }
|
||||
}
|
||||
@keyframes look-up {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(3deg); }
|
||||
}
|
||||
@keyframes laser-pulse {
|
||||
0%, 100% { opacity: 0.8; box-shadow: 0 0 6px 2px #ff0000, 0 0 16px 4px #ff000066; }
|
||||
50% { opacity: 1; box-shadow: 0 0 10px 4px #ff0000, 0 0 30px 8px #ff000088; }
|
||||
}
|
||||
@keyframes btn-hit {
|
||||
0% { filter: brightness(1); }
|
||||
20% { filter: brightness(3) drop-shadow(0 0 12px #ff0000); }
|
||||
100% { filter: brightness(1); }
|
||||
}
|
||||
.guard-dog-wrap {
|
||||
animation: creep-in 6s ease-out both;
|
||||
animation-delay: 1.5s;
|
||||
}
|
||||
.guard-dog-trot {
|
||||
animation: trot 0.4s ease-in-out 15;
|
||||
animation-delay: 1.5s;
|
||||
}
|
||||
.guard-dog-look {
|
||||
animation: look-up 0.8s ease-out both;
|
||||
animation-delay: 7.5s;
|
||||
transform-origin: bottom center;
|
||||
}
|
||||
.laser-eye {
|
||||
position: absolute;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #ff0000;
|
||||
animation: laser-pulse 2s ease-in-out infinite;
|
||||
animation-delay: 7.5s;
|
||||
opacity: 0;
|
||||
animation-fill-mode: both;
|
||||
}
|
||||
.laser-eye-left { top: 22%; left: 40%; }
|
||||
.laser-eye-right { top: 22%; left: 52%; }
|
||||
.laser-beam {
|
||||
position: fixed;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, #ff0000, #ff000000);
|
||||
transform-origin: left center;
|
||||
pointer-events: none;
|
||||
z-index: 100;
|
||||
opacity: 0;
|
||||
box-shadow: 0 0 8px 2px #ff0000aa, 0 0 20px 4px #ff000044;
|
||||
}
|
||||
.laser-beam.fire { opacity: 1; transition: opacity 0.05s; }
|
||||
.laser-beam.fade { opacity: 0; transition: opacity 0.4s; }
|
||||
@keyframes rattle {
|
||||
0%, 100% { transform: translate(0, 0); }
|
||||
10% { transform: translate(-1px, 1px); }
|
||||
20% { transform: translate(1px, -1px); }
|
||||
30% { transform: translate(-2px, 0px); }
|
||||
40% { transform: translate(2px, 1px); }
|
||||
50% { transform: translate(-1px, -2px); }
|
||||
60% { transform: translate(2px, 2px); }
|
||||
70% { transform: translate(-3px, 1px); }
|
||||
80% { transform: translate(3px, -1px); }
|
||||
90% { transform: translate(-2px, 2px); }
|
||||
}
|
||||
.btn-zapped {
|
||||
background: #c62030 !important;
|
||||
color: #f7f2e8 !important;
|
||||
box-shadow: 0 0 12px 4px rgba(198, 32, 48, 0.5), 0 0 30px 8px rgba(198, 32, 48, 0.25);
|
||||
animation: rattle 0.15s linear infinite;
|
||||
}
|
||||
#go-home-btn:hover {
|
||||
background: #c62030;
|
||||
color: #f7f2e8;
|
||||
}
|
||||
</style>
|
||||
{% endif %}
|
||||
<section class="relative flex min-h-dvh items-center justify-center overflow-hidden px-6 py-20">
|
||||
<div class="relative z-10 w-full max-w-md text-center">
|
||||
<img src="/static/img/firebreak-brand.svg"
|
||||
alt="Firebreak"
|
||||
width="240"
|
||||
height="268"
|
||||
class="mx-auto mb-8 h-auto w-full max-w-24" />
|
||||
{% if status_code == 401 %}
|
||||
<p class="text-8xl font-bold text-[#c62030]/60 sm:text-9xl">{{ status_code }}</p>
|
||||
<h1 class="mt-4 text-xl font-semibold text-[#f7f2e8]">{{ title }}</h1>
|
||||
{% else %}
|
||||
<p class="text-8xl font-bold text-[#f7f2e8]/20 sm:text-9xl">{{ status_code }}</p>
|
||||
<h1 class="mt-4 text-xl font-semibold text-[#f7f2e8]">{{ title }}</h1>
|
||||
{% endif %}
|
||||
<p class="mt-3 text-sm leading-6 text-[#f7f2e8]/60">{{ detail }}</p>
|
||||
{% if status_code == 401 %}
|
||||
{% set quips = [
|
||||
"This area is protected by Big Tech's finest.",
|
||||
"Your data is safe. His isn't.",
|
||||
"He doesn't bite. He just harvests.",
|
||||
"Move along. Nothing to scrape here.",
|
||||
"Unauthorized. The Zuck abides.",
|
||||
"ACCESS DENIED. Deploying Cuckerberg.",
|
||||
] %}
|
||||
<p class="mt-2 text-xs italic text-[#f7f2e8]/30">{{ quips | random }}</p>
|
||||
{% endif %}
|
||||
<div class="mt-8">
|
||||
<a href="/" class="btn btn-primary" id="go-home-btn">Go home</a>
|
||||
</div>
|
||||
</div>
|
||||
{% if status_code == 401 %}
|
||||
<div class="guard-dog-wrap pointer-events-none absolute -bottom-4 -right-8 w-44 sm:w-56"
|
||||
aria-hidden="true">
|
||||
<div class="guard-dog-trot">
|
||||
<div class="guard-dog-look">
|
||||
<div class="relative">
|
||||
<img src="/static/img/mark_cuckerberg.png"
|
||||
alt=""
|
||||
class="w-full opacity-20 grayscale" />
|
||||
<div class="laser-eye laser-eye-left"></div>
|
||||
<div class="laser-eye laser-eye-right"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% if status_code == 401 %}
|
||||
<script>
|
||||
console.log('%cUnauthorized access detected. Deploying Cuckerberg.', 'font-size: 16px; color: red;');
|
||||
|
||||
function fireBeam(eye, target) {
|
||||
const eyeRect = eye.getBoundingClientRect();
|
||||
const btnRect = target.getBoundingClientRect();
|
||||
const x1 = eyeRect.left + eyeRect.width / 2;
|
||||
const y1 = eyeRect.top + eyeRect.height / 2;
|
||||
const x2 = btnRect.left + btnRect.width / 2;
|
||||
const y2 = btnRect.top + btnRect.height / 2;
|
||||
const dx = x2 - x1;
|
||||
const dy = y2 - y1;
|
||||
const length = Math.hypot(dx, dy);
|
||||
const angle = Math.atan2(dy, dx) * (180 / Math.PI);
|
||||
|
||||
const beam = document.createElement('div');
|
||||
beam.className = 'laser-beam';
|
||||
beam.style.left = x1 + 'px';
|
||||
beam.style.top = y1 + 'px';
|
||||
beam.style.width = length + 'px';
|
||||
beam.style.transform = 'rotate(' + angle + 'deg)';
|
||||
document.body.appendChild(beam);
|
||||
|
||||
requestAnimationFrame(() => beam.classList.add('fire'));
|
||||
return beam;
|
||||
}
|
||||
|
||||
const btn = document.getElementById('go-home-btn');
|
||||
let armed = false;
|
||||
if (btn) {
|
||||
setTimeout(() => { armed = true; }, 7500);
|
||||
|
||||
btn.addEventListener('click', (e) => {
|
||||
if (!armed) return;
|
||||
e.preventDefault();
|
||||
const eyes = document.querySelectorAll('.laser-eye');
|
||||
const beams = [];
|
||||
eyes.forEach((eye) => beams.push(fireBeam(eye, btn)));
|
||||
btn.classList.add('btn-zapped');
|
||||
|
||||
// Intensify glow over 2 seconds
|
||||
let start = performance.now();
|
||||
function intensify(now) {
|
||||
const t = Math.min((now - start) / 2000, 1);
|
||||
const spread = 12 + t * 20;
|
||||
const blur = 30 + t * 40;
|
||||
const opacity = 0.5 + t * 0.4;
|
||||
const scale = 1 + t * 0.06;
|
||||
btn.style.boxShadow = `0 0 ${spread}px ${spread/3}px rgba(198,32,48,${opacity}), 0 0 ${blur}px ${blur/3}px rgba(198,32,48,${opacity * 0.5})`;
|
||||
btn.style.scale = scale;
|
||||
if (t < 1) requestAnimationFrame(intensify);
|
||||
}
|
||||
requestAnimationFrame(intensify);
|
||||
|
||||
// Redirect right at peak intensity
|
||||
setTimeout(() => { window.location.href = '/'; }, 2000);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
|
@ -25,7 +25,7 @@
|
|||
class="h-auto w-full max-w-36 drop-shadow-[0_14px_34px_rgb(0_0_0_/0.55)] sm:max-w-48 lg:max-w-60" />
|
||||
<p class="mt-8 max-w-2xl text-balance text-base font-medium leading-8 tracking-normal text-[#f7f2e8]/90 drop-shadow-[0_4px_18px_rgb(0_0_0_/0.72)] sm:text-lg sm:leading-9">
|
||||
<span class="block">Fight Fire with Fire.</span>
|
||||
<span class="mt-2 block">Your code. Your rules. Let them look, but don't let them scrape.</span>
|
||||
<span class="mt-2 block">Keep your code yours. Let them look, but don't let them scrape.</span>
|
||||
</p>
|
||||
<p class="mt-7 max-w-xl rounded-lg border border-[#f7f2e8]/14 bg-[#17191c]/42 px-5 py-4 text-sm leading-6 text-[#f7f2e8]/76 shadow-[0_18px_50px_rgb(0_0_0_/0.24)] backdrop-blur-sm sm:text-[0.9375rem]">
|
||||
Firebreak creates temporary, read-only links to private Forgejo repository snapshots.
|
||||
|
|
@ -46,10 +46,6 @@
|
|||
</a>
|
||||
{% endif %}
|
||||
</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>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@
|
|||
<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>
|
||||
<code class="mt-1 inline-block rounded bg-[#f7f2e8]/8 px-1.5 py-0.5 font-mono text-[10px] text-[#f7f2e8]/60">{{ oauth_callback_url }}</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
|
||||
|
|
@ -52,6 +52,23 @@
|
|||
</div>
|
||||
{% endif %}
|
||||
<form method="post" action="/setup" class="space-y-5">
|
||||
{% if not reconfiguring %}
|
||||
<div>
|
||||
<label for="setup_token"
|
||||
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||
Setup Token
|
||||
</label>
|
||||
<input type="password"
|
||||
id="setup_token"
|
||||
name="setup_token"
|
||||
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 font-mono text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
|
||||
placeholder="Paste the token from your server logs"
|
||||
required />
|
||||
<p class="mt-1.5 text-xs text-[#f7f2e8]/30">
|
||||
Printed to the server console on first boot.
|
||||
</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div>
|
||||
<label for="forgejo_base_url"
|
||||
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ set -euo pipefail
|
|||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
export DATABASE_URL="postgresql+asyncpg://myst:myst@localhost:5432/myst_db"
|
||||
export MYST_PUBLIC_BASE_URL="http://localhost:8000"
|
||||
export DATABASE_URL="postgresql+asyncpg://firebreak:firebreak@localhost:5432/firebreak_db"
|
||||
export FIREBREAK_PUBLIC_BASE_URL="http://localhost:8000"
|
||||
|
||||
echo "Starting local Postgres and Adminer..."
|
||||
docker compose -f ../docker-compose.yml up -d db adminer
|
||||
|
|
@ -12,10 +12,10 @@ docker compose -f ../docker-compose.yml up -d db adminer
|
|||
echo "Building Tailwind CSS..."
|
||||
./tailwindcss -i ./app/static/css/input.css -o ./app/static/css/output.css
|
||||
|
||||
echo "Starting Myst dev server..."
|
||||
echo "Starting Firebreak dev server..."
|
||||
echo " FastAPI: http://localhost:8000"
|
||||
echo " Adminer: http://localhost:8080"
|
||||
echo " PostgreSQL / db / myst / myst / myst_db"
|
||||
echo " PostgreSQL / db / firebreak / firebreak / firebreak_db"
|
||||
echo " CSS: watching app/static/css/input.css"
|
||||
|
||||
./tailwindcss -i ./app/static/css/input.css -o ./app/static/css/output.css --watch &
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ target-version = "py313"
|
|||
line-length = 100
|
||||
|
||||
[project]
|
||||
name = "myst-web"
|
||||
name = "firebreak-web"
|
||||
version = "0.1.0"
|
||||
description = "Myst: FastAPI + HTMX web interface for managing Forgejo repositories"
|
||||
description = "Firebreak: FastAPI + HTMX web interface for managing Forgejo repositories"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"aiofiles>=24.1.0",
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue