feat: add CORS configuration options to enhance API security

This commit is contained in:
2025-12-19 02:33:00 +09:00
parent ea5a0004da
commit 1806e0823f
3 changed files with 75 additions and 8 deletions
+47 -2
View File
@@ -1,4 +1,5 @@
import os
import json
from datetime import datetime
from typing import Sequence
@@ -21,6 +22,50 @@ from app.utils.auth import load_auth_config, issue_token, verify_token
app = FastAPI()
def _parse_cors_allowed_origins(raw: str | None) -> list[str]:
if not raw:
return []
value = raw.strip()
if not value:
return []
if value == "*":
return ["*"]
try:
if value.startswith("["):
parsed = json.loads(value)
if isinstance(parsed, list):
origins = [str(item).strip() for item in parsed]
else:
origins = [str(parsed).strip()]
else:
origins = [part.strip() for part in value.split(",")]
except Exception:
logger.warning(
"Invalid PLEXPLAYLISTSYNC_CORS_ALLOWED_ORIGINS; CORS will be disabled."
)
return []
return [origin for origin in origins if origin]
def _env_truthy(name: str, default: str = "0") -> bool:
value = os.getenv(name, default)
return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
_CORS_ALLOWED_ORIGINS = _parse_cors_allowed_origins(
os.getenv("PLEXPLAYLISTSYNC_CORS_ALLOWED_ORIGINS", "")
)
_CORS_ALLOW_CREDENTIALS = (
False
if "*" in _CORS_ALLOWED_ORIGINS
else _env_truthy("PLEXPLAYLISTSYNC_CORS_ALLOW_CREDENTIALS", "0")
)
# --- Optional API Authentication (username/password) ---
AUTH_CONFIG = load_auth_config()
@@ -107,8 +152,8 @@ async def startup_event():
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_origins=_CORS_ALLOWED_ORIGINS,
allow_credentials=_CORS_ALLOW_CREDENTIALS,
allow_methods=["*"],
allow_headers=["*"],
)