Spaces:
Sleeping
Sleeping
CSP fix: explicit script-src unsafe-eval + allow HF iframe (serve.py)
Browse files
serve.py
CHANGED
|
@@ -88,6 +88,39 @@ except Exception as exc: # noqa: BLE001
|
|
| 88 |
log.warning("Could not adjust TrustedHostMiddleware: %s", exc)
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def _strip_root_routes() -> None:
|
| 92 |
"""main_api_app registers GET / — remove so frontend can own the landing page."""
|
| 93 |
kept = []
|
|
|
|
| 88 |
log.warning("Could not adjust TrustedHostMiddleware: %s", exc)
|
| 89 |
|
| 90 |
|
| 91 |
+
# Final response headers for HF iframe + CSP (runs outermost when added last)
|
| 92 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 93 |
+
from starlette.requests import Request as StarletteRequest
|
| 94 |
+
from starlette.responses import Response as StarletteResponse
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class HfBrowserCompatMiddleware(BaseHTTPMiddleware):
|
| 98 |
+
CSP = (
|
| 99 |
+
"default-src 'self'; "
|
| 100 |
+
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net blob:; "
|
| 101 |
+
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
|
| 102 |
+
"font-src 'self' https://fonts.gstatic.com data:; "
|
| 103 |
+
"img-src 'self' data: https: blob:; "
|
| 104 |
+
"connect-src 'self' https: wss: ws:; "
|
| 105 |
+
"worker-src 'self' blob:; "
|
| 106 |
+
"frame-ancestors 'self' https://huggingface.co https://*.huggingface.co https://*.hf.space; "
|
| 107 |
+
"base-uri 'self'; "
|
| 108 |
+
"object-src 'none'"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
async def dispatch(self, request: StarletteRequest, call_next):
|
| 112 |
+
response: StarletteResponse = await call_next(request)
|
| 113 |
+
# Remove frame deny so Space can load in HF shell iframe
|
| 114 |
+
if "x-frame-options" in response.headers:
|
| 115 |
+
del response.headers["x-frame-options"]
|
| 116 |
+
response.headers["Content-Security-Policy"] = self.CSP
|
| 117 |
+
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
| 118 |
+
return response
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
app.add_middleware(HfBrowserCompatMiddleware)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
def _strip_root_routes() -> None:
|
| 125 |
"""main_api_app registers GET / — remove so frontend can own the landing page."""
|
| 126 |
kept = []
|