Files
BadNote/server/badnote_server/config.py

74 lines
2.8 KiB
Python
Raw Normal View History

Fix bugs across app + server, optimize UI/UX, add Gitea CI Bug fixes (Flutter): - Wrap multi-statement DB writes (insert/update/delete note, deleteDocument, deletePageData, OCR FTS merge, migrations) in transactions to prevent data loss on interruption and a read-modify-write FTS race. - Fix PdfDocument leaks on exception (try/finally dispose) and preserve image aspect ratio when stamping images onto PDF pages. - Guard file-picker against empty selection (was .single -> crash). - Fix eraser ConcurrentModificationError and unmodifiable-list crash on PDF pages; capture page synchronously on save to stop wrong-page data loss. - Fix Riverpod DB-not-ready races, broken pull-to-refresh, settings load race, and search N+1; transform stored annotations on PDF page rotation. - Normalize pen pressure for devices without a pressure range. - PPT: single source of truth for slide strokes so ink displays and exports. UI/UX: - Material 3 typography, theme-aware colors (dark-mode fixes), hover cursors and right-click/visible actions on desktop, keyboard shortcuts (undo/redo/ save/find), toolbar overflow handling, friendlier empty states, semantic OCR status badges, relative timestamps, 1-based page indicators, large-deck PPT navigation, and a scratchpad-scope label in split view. Server (optional backend): - Persist JWT secret (was per-process random), block path traversal in storage, fix CORS '*'+credentials, add OCR job ownership checks, last-writer-wins sync guard, constant-time login, and split out heavy OCR deps so the API/tests run without them. CI: Gitea workflows for format+analyze+test (Linux, system sqlite) and a Windows release build; pristine `flutter analyze`, all Flutter and server tests green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 03:18:00 +08:00
"""BadNote server configuration via environment variables."""
import os
import secrets
import warnings
def _resolve_jwt_secret() -> str:
"""Resolve the JWT signing secret.
Priority:
1. ``BADNOTE_JWT_SECRET`` environment variable (recommended for prod).
2. A persisted secret file (so the secret survives restarts and is shared
across worker processes).
3. A freshly generated secret, persisted to that file.
A per-process random secret (the previous behaviour) invalidated every
token on restart and gave each worker a different secret in multi-worker
deployments, so tokens were rejected at random. We persist instead.
"""
env_secret = os.environ.get("BADNOTE_JWT_SECRET")
if env_secret:
return env_secret
db_path = os.environ.get("BADNOTE_DB_PATH", "./data/badnote_server.db")
default_secret_file = os.path.join(os.path.dirname(db_path) or ".", ".jwt_secret")
secret_path = os.environ.get("BADNOTE_JWT_SECRET_FILE", default_secret_file)
try:
if os.path.exists(secret_path):
with open(secret_path, "r", encoding="utf-8") as f:
existing = f.read().strip()
if existing:
return existing
secret = secrets.token_urlsafe(48)
os.makedirs(os.path.dirname(secret_path) or ".", exist_ok=True)
# Restrictive permissions: only the owner may read the secret.
fd = os.open(secret_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(secret)
return secret
except OSError:
warnings.warn(
"Could not persist a JWT secret; using an ephemeral one. "
"Set BADNOTE_JWT_SECRET to keep tokens valid across restarts.",
RuntimeWarning,
)
return secrets.token_urlsafe(48)
def _resolve_cors_origins() -> list[str]:
"""Parse the allowed CORS origins from ``BADNOTE_CORS_ORIGINS``.
Comma-separated list of origins. Empty by default; the app falls back to a
permissive ``*`` (without credentials) when none are configured.
"""
raw = os.environ.get("BADNOTE_CORS_ORIGINS", "")
return [o.strip() for o in raw.split(",") if o.strip()]
class Settings:
host: str = os.environ.get("BADNOTE_HOST", "0.0.0.0")
port: int = int(os.environ.get("BADNOTE_PORT", "8080"))
db_path: str = os.environ.get("BADNOTE_DB_PATH", "./data/badnote_server.db")
storage_path: str = os.environ.get("BADNOTE_STORAGE_PATH", "./data/storage")
queue_path: str = os.environ.get("BADNOTE_QUEUE_PATH", "./data/queue")
jwt_secret: str = _resolve_jwt_secret()
jwt_expiry_hours: int = int(os.environ.get("BADNOTE_JWT_EXPIRY_HOURS", "720"))
cors_origins: list[str] = _resolve_cors_origins()
settings = Settings()