Download app.py from ezzygame/xs: direct link, hf CLI and curl.
- Browser
- Download file 6.98 kB
-
https://huggingface.co/spaces/ezzygame/xs/resolve/main/app.py
- Command line
-
hf download hf://spaces/ezzygame/xs/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ezzygame/xs/resolve/main/app.py
6.98 kB
| import asyncio | |
| import ipaddress | |
| import os | |
| import secrets | |
| import socket | |
| import time | |
| from contextlib import asynccontextmanager | |
| from urllib.parse import urlparse | |
| from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect | |
| from fastapi.responses import FileResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel, Field | |
| from playwright.async_api import async_playwright | |
| ACCESS_KEY = os.environ.get("ACCESS_KEY", "") | |
| MAX_SESSIONS = int(os.environ.get("MAX_SESSIONS", "2")) | |
| IDLE_SECONDS = int(os.environ.get("IDLE_SECONDS", "900")) | |
| playwright = None | |
| browser = None | |
| sessions = {} | |
| session_lock = asyncio.Lock() | |
| def valid_public_url(raw: str) -> str: | |
| """Basic URL check only; not a complete SSRF defense.""" | |
| parsed = urlparse(raw) | |
| if parsed.scheme not in ("http", "https") or not parsed.hostname: | |
| raise HTTPException(400, "Only http:// and https:// URLs are allowed.") | |
| host = parsed.hostname.lower() | |
| if host in ("localhost", "localhost.localdomain") or host.endswith(".localhost"): | |
| raise HTTPException(400, "Local destinations are blocked.") | |
| try: | |
| addresses = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) | |
| for item in addresses: | |
| ip = ipaddress.ip_address(item[4][0]) | |
| if not ip.is_global: | |
| raise HTTPException(400, "Private or non-public destinations are blocked.") | |
| except socket.gaierror: | |
| raise HTTPException(400, "Could not resolve destination host.") | |
| return raw | |
| async def lifespan(app: FastAPI): | |
| global playwright, browser | |
| playwright = await async_playwright().start() | |
| browser = await playwright.chromium.launch(headless=True, args=["--no-sandbox"]) | |
| yield | |
| for item in list(sessions.values()): | |
| try: | |
| await item["context"].close() | |
| except Exception: | |
| pass | |
| if browser: | |
| await browser.close() | |
| if playwright: | |
| await playwright.stop() | |
| app = FastAPI(title="Cloud Browser", lifespan=lifespan) | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| class CreateSession(BaseModel): | |
| access_key: str | |
| class NavigateRequest(BaseModel): | |
| session_id: str | |
| url: str | |
| class ActionRequest(BaseModel): | |
| session_id: str | |
| action: str | |
| x: float | None = None | |
| y: float | None = None | |
| text: str | None = Field(default=None, max_length=2000) | |
| delta_y: int | None = None | |
| async def get_session(session_id: str): | |
| item = sessions.get(session_id) | |
| if not item: | |
| raise HTTPException(404, "Session not found or expired.") | |
| item["last_seen"] = time.time() | |
| return item | |
| async def home(): | |
| return FileResponse("static/index.html") | |
| async def create_session(data: CreateSession): | |
| if not ACCESS_KEY or not secrets.compare_digest(data.access_key, ACCESS_KEY): | |
| raise HTTPException(401, "Invalid access key.") | |
| async with session_lock: | |
| now = time.time() | |
| expired = [sid for sid, item in sessions.items() if now - item["last_seen"] > IDLE_SECONDS] | |
| for sid in expired: | |
| try: | |
| await sessions.pop(sid)["context"].close() | |
| except Exception: | |
| pass | |
| if len(sessions) >= MAX_SESSIONS: | |
| raise HTTPException(429, "Browser capacity reached. Try again later.") | |
| context = await browser.new_context( | |
| viewport={"width": 1280, "height": 800}, | |
| device_scale_factor=1, | |
| accept_downloads=False, | |
| ) | |
| page = await context.new_page() | |
| await page.goto("https://example.com", wait_until="domcontentloaded", timeout=30000) | |
| sid = secrets.token_urlsafe(32) | |
| sessions[sid] = {"context": context, "page": page, "last_seen": time.time()} | |
| return {"session_id": sid, "url": page.url, "title": await page.title()} | |
| async def navigate(data: NavigateRequest): | |
| item = await get_session(data.session_id) | |
| url = valid_public_url(data.url.strip()) | |
| try: | |
| await item["page"].goto(url, wait_until="domcontentloaded", timeout=45000) | |
| except Exception as exc: | |
| # A timeout may still leave a usable page loaded. | |
| if not item["page"].url or item["page"].url == "about:blank": | |
| raise HTTPException(502, f"Navigation failed: {str(exc)[:180]}") | |
| return {"url": item["page"].url, "title": await item["page"].title()} | |
| async def action(data: ActionRequest): | |
| item = await get_session(data.session_id) | |
| page = item["page"] | |
| try: | |
| if data.action == "click": | |
| await page.mouse.click(data.x or 0, data.y or 0) | |
| elif data.action == "type": | |
| await page.keyboard.insert_text(data.text or "") | |
| elif data.action == "key": | |
| key = data.text or "" | |
| allowed = {"Enter", "Escape", "Backspace", "Tab", "ArrowUp", "ArrowDown", | |
| "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", | |
| "Control+A", "Control+L"} | |
| if key not in allowed: | |
| raise HTTPException(400, "Unsupported key.") | |
| await page.keyboard.press(key) | |
| elif data.action == "scroll": | |
| await page.mouse.wheel(0, max(-1200, min(1200, data.delta_y or 0))) | |
| elif data.action == "back": | |
| await page.go_back(wait_until="domcontentloaded", timeout=15000) | |
| elif data.action == "forward": | |
| await page.go_forward(wait_until="domcontentloaded", timeout=15000) | |
| elif data.action == "reload": | |
| await page.reload(wait_until="domcontentloaded", timeout=30000) | |
| else: | |
| raise HTTPException(400, "Unsupported action.") | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException(502, f"Browser action failed: {str(exc)[:180]}") | |
| return {"url": page.url, "title": await page.title()} | |
| async def stream(websocket: WebSocket, session_id: str): | |
| item = sessions.get(session_id) | |
| if not item: | |
| await websocket.close(code=4404) | |
| return | |
| await websocket.accept() | |
| page = item["page"] | |
| try: | |
| while True: | |
| item["last_seen"] = time.time() | |
| if page.is_closed(): | |
| break | |
| image = await page.screenshot(type="jpeg", quality=55, timeout=10000) | |
| await websocket.send_bytes(image) | |
| await asyncio.sleep(0.20) | |
| except (WebSocketDisconnect, RuntimeError, asyncio.CancelledError): | |
| pass | |
| except Exception: | |
| try: | |
| await websocket.close(code=1011) | |
| except Exception: | |
| pass | |
| async def close_session(session_id: str): | |
| item = sessions.pop(session_id, None) | |
| if item: | |
| await item["context"].close() | |
| return {"closed": True} | |