Aynkhn's picture
Deploy FaceVision to Hugging Face Spaces
0fd3d47 verified
Raw History Blame Contribute Delete
1.82 kB
"""Cross-origin isolation headers for the served frontend.
``next.config.ts`` declares these headers, but ``headers()`` is a no-op under
``output: 'export'`` -- there is no Next server in the container to apply them, and
``next build`` says so explicitly. MediaPipe's threaded WASM backend needs cross-origin
isolation, so the headers have to come from whatever actually serves the bundle, which
is this application.
Because the WASM and model files are self-hosted under the exported bundle rather than
fetched from a CDN, ``require-corp`` is safe here: there is no cross-origin subresource
left to be blocked.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
SECURITY_HEADERS = {
# Required together to make the page cross-origin isolated, which is what
# unlocks SharedArrayBuffer for MediaPipe's threaded backend.
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
}
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Apply the isolation and hardening headers to every response."""
async def dispatch(
self,
request: Request,
call_next: Callable[[Request], Awaitable[Response]],
) -> Response:
response = await call_next(request)
for header, value in SECURITY_HEADERS.items():
response.headers.setdefault(header, value)
# Same-origin subresources must opt in explicitly once COEP is on.
response.headers.setdefault("Cross-Origin-Resource-Policy", "same-origin")
return response