"""Reverse-proxy /s/{session_id}/… to the sandboxed preview port."""
from __future__ import annotations
import re
import httpx
from fastapi import Request, Response
from backend.app.models.session import SessionStatus
from backend.app.services.sessions import session_manager
_HOP_BY_HOP = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
"content-encoding",
"content-length",
}
_FRAME_BLOCK_HEADERS = {
"x-frame-options",
"content-security-policy",
"content-security-policy-report-only",
}
_BASE_TAG_RE = re.compile(rb"
]*)>", re.IGNORECASE)
def preview_base_href(session_id: str, path: str) -> str:
"""Directory URL for an injected .
Relative links must resolve against the *current document* directory, not
the session root. unscripted's overlays/popover.html uses
href="../css/style.css" and href="overlays.css". A root base of
/s/{id}/ turns those into /s/css/style.css (404) and /s/{id}/overlays.css
(404), so nested pages render as unstyled white documents. Root
index.html still gets /s/{id}/ so css/style.css keeps working.
"""
suffix = (path or "").lstrip("/")
if not suffix or suffix.endswith("/"):
directory = suffix
elif "/" in suffix:
directory = suffix.rsplit("/", 1)[0] + "/"
else:
directory = ""
return f"/s/{session_id}/{directory}"
def inject_preview_base(content: bytes, session_id: str, path: str) -> bytes:
if b"'
m = _BASE_TAG_RE.search(content)
if m:
insert_at = m.end()
return content[:insert_at] + base + content[insert_at:]
return base + content
async def proxy_request(session_id: str, path: str, request: Request) -> Response:
sess = session_manager.get(session_id)
if not sess or sess.status != SessionStatus.running or not sess.port:
return Response(
content="Session not running or expired",
status_code=404,
media_type="text/plain",
)
session_manager.touch(session_id)
# Normalize path
suffix = path.lstrip("/")
target = f"http://127.0.0.1:{sess.port}/{suffix}"
if request.url.query:
target = f"{target}?{request.url.query}"
headers = {
k: v
for k, v in request.headers.items()
if k.lower() not in _HOP_BY_HOP and k.lower() != "host"
}
headers["host"] = f"127.0.0.1:{sess.port}"
# Upstream SimpleHTTP often returns Content-Length: 0 on HEAD — use GET for body
method = request.method
body = await request.body()
try:
async with httpx.AsyncClient(timeout=60.0, follow_redirects=False) as client:
upstream = await client.request(
method,
target,
headers=headers,
content=body if body else None,
)
except httpx.RequestError as e:
return Response(content=f"Upstream error: {type(e).__name__}", status_code=502)
out_headers = {
k: v
for k, v in upstream.headers.items()
if k.lower() not in _HOP_BY_HOP and k.lower() not in _FRAME_BLOCK_HEADERS
}
# Allow embedding in our SPA iframe (same-origin /s/… under the Space)
out_headers["Content-Security-Policy"] = (
f"frame-ancestors 'self' https://*.hf.space https://huggingface.co; "
"base-uri 'self'"
)
# Rewrite absolute Location to stay under our proxy prefix
loc = out_headers.get("location") or out_headers.get("Location")
if loc:
if loc.startswith("/"):
out_headers["location"] = f"/s/{session_id}{loc}"
elif loc.startswith(f"http://127.0.0.1:{sess.port}"):
rest = loc.split(f"http://127.0.0.1:{sess.port}", 1)[-1] or "/"
out_headers["location"] = f"/s/{session_id}{rest}"
content = upstream.content
ctype = (upstream.headers.get("content-type") or "").lower()
# Inject for the current directory so nested relative assets
# (../css/style.css, ./overlays.css) stay inside /s/{id}/.
if method != "HEAD" and "text/html" in ctype and content:
content = inject_preview_base(content, session_id, suffix)
return Response(
content=content if method != "HEAD" else b"",
status_code=upstream.status_code,
headers=out_headers,
media_type=upstream.headers.get("content-type"),
)