Spaces:
Running
Running
Download routers/proxy.py from Shadowfilebot/Bot: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/routers/proxy.py
- Command line
-
hf download hf://spaces/Shadowfilebot/Bot/routers/proxy.py
-
curl -L -o proxy.py https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/routers/proxy.py
6.63 kB
| """ | |
| Reverse proxy for virtual ports. | |
| Single Responsibility: only handles HTTP/WebSocket proxying. | |
| Port CRUD is in ports.py — separate concern. | |
| """ | |
| import asyncio | |
| import json | |
| import httpx | |
| from fastapi import APIRouter, Depends, Request, WebSocket, WebSocketDisconnect | |
| from fastapi.responses import Response, StreamingResponse | |
| from starlette.background import BackgroundTask | |
| from auth import AuthUser, get_current_user, get_ws_user, verify_token | |
| from config import MIN_PORT, MAX_PORT | |
| from storage import load_meta, check_zone_owner | |
| router = APIRouter(tags=["proxy"]) | |
| # ── Shared HTTP client ──────────────────────── | |
| _HOP_HEADERS = frozenset({ | |
| "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", | |
| "te", "trailers", "transfer-encoding", "upgrade", | |
| }) | |
| _client: httpx.AsyncClient | None = None | |
| def _get_client() -> httpx.AsyncClient: | |
| global _client | |
| if _client is None: | |
| _client = httpx.AsyncClient( | |
| timeout=httpx.Timeout(30.0, connect=5.0), | |
| follow_redirects=False, | |
| limits=httpx.Limits(max_connections=50), | |
| ) | |
| return _client | |
| def _validate_proxy_access(zone_name: str, port: int): | |
| """Validate port range and check it's registered for the zone.""" | |
| if not (MIN_PORT <= port <= MAX_PORT): | |
| raise ValueError(f"Port must be between {MIN_PORT} and {MAX_PORT}") | |
| meta = load_meta() | |
| if zone_name not in meta: | |
| raise ValueError(f"Zone '{zone_name}' does not exist") | |
| ports = meta[zone_name].get("ports", []) | |
| if not any(p["port"] == port for p in ports): | |
| raise ValueError("Port not mapped") | |
| # ── HTTP Reverse Proxy ──────────────────────── | |
| async def proxy_http(request: Request, zone_name: str, port: int, subpath: str = ""): | |
| try: | |
| _validate_proxy_access(zone_name, port) | |
| except ValueError as e: | |
| return Response(content=f"Port not mapped or invalid: {e}", status_code=404) | |
| clean_subpath = subpath.lstrip("/") | |
| target_url = f"http://127.0.0.1:{port}/{clean_subpath}" | |
| if request.url.query: | |
| target_url += f"?{request.url.query}" | |
| headers = {} | |
| for key, value in request.headers.items(): | |
| if key.lower() not in _HOP_HEADERS and key.lower() != "host": | |
| headers[key] = value | |
| headers["host"] = f"127.0.0.1:{port}" | |
| headers["x-forwarded-for"] = request.client.host if request.client else "127.0.0.1" | |
| headers["x-forwarded-proto"] = request.url.scheme | |
| headers["x-forwarded-prefix"] = f"/port/{zone_name}/{port}" | |
| client = _get_client() | |
| try: | |
| body = await request.body() | |
| upstream_req = client.build_request( | |
| method=request.method, | |
| url=target_url, | |
| headers=headers, | |
| content=body, | |
| ) | |
| resp = await client.send(upstream_req, stream=True) | |
| except httpx.ConnectError: | |
| return Response( | |
| content=f"Cannot connect to port {port}. Make sure your server is running in zone '{zone_name}'.", | |
| status_code=502, | |
| media_type="text/plain", | |
| ) | |
| except httpx.TimeoutException: | |
| return Response(content=f"Timeout connecting to port {port}", status_code=504, media_type="text/plain") | |
| resp_headers = {} | |
| for key, value in resp.headers.items(): | |
| if key.lower() not in _HOP_HEADERS and key.lower() != "content-encoding": | |
| resp_headers[key] = value | |
| # Rewrite Location redirect headers if needed | |
| if "location" in resp_headers: | |
| loc = resp_headers["location"] | |
| if loc.startswith("/"): | |
| resp_headers["location"] = f"/port/{zone_name}/{port}{loc}" | |
| elif f":{port}" in loc: | |
| parts = loc.split(f":{port}", 1) | |
| if len(parts) == 2: | |
| resp_headers["location"] = f"/port/{zone_name}/{port}{parts[1]}" | |
| return StreamingResponse( | |
| resp.aiter_raw(), | |
| status_code=resp.status_code, | |
| headers=resp_headers, | |
| background=BackgroundTask(resp.aclose), | |
| ) | |
| # ── WebSocket Reverse Proxy ────────────────── | |
| async def proxy_ws(websocket: WebSocket, zone_name: str, port: int, subpath: str = ""): | |
| try: | |
| _validate_proxy_access(zone_name, port) | |
| except ValueError as e: | |
| await websocket.close(code=4004, reason=str(e)) | |
| return | |
| await websocket.accept() | |
| clean_subpath = subpath.lstrip("/") | |
| target_url = f"ws://127.0.0.1:{port}/{clean_subpath}" | |
| if websocket.url.query: | |
| target_url += f"?{websocket.url.query}" | |
| import websockets as ws_lib | |
| try: | |
| async with ws_lib.connect(target_url) as backend_ws: | |
| async def client_to_backend(): | |
| try: | |
| while True: | |
| msg = await websocket.receive() | |
| if msg.get("type") == "websocket.disconnect": | |
| break | |
| if "text" in msg: | |
| await backend_ws.send(msg["text"]) | |
| elif "bytes" in msg: | |
| await backend_ws.send(msg["bytes"]) | |
| except (WebSocketDisconnect, Exception): | |
| pass | |
| async def backend_to_client(): | |
| try: | |
| async for message in backend_ws: | |
| if isinstance(message, str): | |
| await websocket.send_text(message) | |
| else: | |
| await websocket.send_bytes(message) | |
| except (WebSocketDisconnect, Exception): | |
| pass | |
| await asyncio.gather(client_to_backend(), backend_to_client()) | |
| except Exception: | |
| try: | |
| await websocket.send_text(json.dumps({"error": f"Cannot connect WebSocket to port {port}"})) | |
| except Exception: | |
| pass | |
| finally: | |
| try: | |
| await websocket.close() | |
| except Exception: | |
| pass | |