fix: replace TrustedHostMiddleware with proper HSTS middleware

TrustedHostMiddleware blocked Vite proxied requests (Host: localhost:5173
vs allowed_hosts list). Replaced with simple HSTSMiddleware that adds
Strict-Transport-Security header without blocking any requests.
This commit is contained in:
2026-05-26 15:24:40 +03:00
parent a2786ad713
commit 10cdb8a81a

View File

@@ -19,9 +19,9 @@ import asyncio
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
from .api import auth
@@ -190,11 +190,15 @@ app.add_middleware(
allow_headers=["*"],
)
# HSTS — force HTTPS in production (see [SEC:L-2])
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=_allowed_origins if _allowed_origins else ["*"],
)
# HSTS — Strict-Transport-Security header (see [SEC:L-2])
class HSTSMiddleware(BaseHTTPMiddleware):
"""Add Strict-Transport-Security header to every response."""
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
return response
app.add_middleware(HSTSMiddleware)
# #endregion app_middleware
# #region network_error_handler [C:1] [TYPE Function]
# @BRIEF Global exception handler for NetworkError.