ezzygame commited on
Commit
c30b1cb
·
verified ·
1 Parent(s): a1bd801

Upload 5 files

Browse files
cloud-browser-hf/Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM mcr.microsoft.com/playwright/python:v1.52.0-noble
2
+
3
+ ENV PYTHONUNBUFFERED=1 \
4
+ PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
5
+ PORT=7860
6
+
7
+ WORKDIR /app
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+ COPY app.py .
11
+ COPY static ./static
12
+
13
+ EXPOSE 7860
14
+ CMD ["sh", "-c", "uvicorn app:app --host 0.0.0.0 --port ${PORT}"]
cloud-browser-hf/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cloud Browser — Hugging Face Docker Space starter
2
+
3
+ A prototype for a website-embedded remote Chromium browser. FastAPI launches Chromium with Playwright, creates an isolated browser context per session, and streams page screenshots over a WebSocket. The user can navigate, click, type, scroll, and go back/forward.
4
+
5
+ ## Important scope
6
+
7
+ This is a **starter / proof of concept**, not a hardened public service. It uses a shared `ACCESS_KEY` for demonstration. For a public multi-user website, replace this with your website's real authentication and verify each user's identity server-side before creating a session. Do not expose the shared key in frontend JavaScript on a public site.
8
+
9
+ This implementation streams screenshots rather than a full desktop video stream. It is simpler to deploy, but can be slower and less fluid than WebRTC/noVNC for video-heavy sites. Audio, downloads, clipboard, browser extensions, and multiple tabs are not implemented.
10
+
11
+ ## Files
12
+
13
+ - `app.py` — FastAPI API, session lifecycle, WebSocket screenshot/input loop
14
+ - `static/index.html` — browser UI
15
+ - `requirements.txt` — Python dependencies
16
+ - `Dockerfile` — Chromium + app container
17
+ - `README.md` — deployment and limitations
18
+
19
+ ## Deploy to Hugging Face
20
+
21
+ 1. Create a **Docker Space**: https://huggingface.co/new-space
22
+ 2. Set the Space repository files to the files in this folder.
23
+ 3. In Space **Settings → Variables and secrets**, add a secret:
24
+ - `ACCESS_KEY` = a long random value (at least 32 random characters)
25
+ 4. Keep the Space private/protected if your plan supports it, but remember that private Space access rules may prevent public visitors from opening the app. Protected Spaces hide source code, but the running app URL can still be reachable.
26
+ 5. Push the files to the Space repository. Hugging Face builds the Docker image automatically.
27
+ 6. Open the Space URL and enter the access key to start a session.
28
+ 7. For website embedding, test the Space URL in an iframe. If browser security headers or your deployment settings prevent framing, use a link/new tab or configure the appropriate embedding policy.
29
+
30
+ ## Local run
31
+
32
+ ```bash
33
+ docker build -t cloud-browser .
34
+ docker run --rm -p 7860:7860 -e ACCESS_KEY='replace-with-a-long-random-secret' cloud-browser
35
+ ```
36
+
37
+ Open http://localhost:7860.
38
+
39
+ ## API overview
40
+
41
+ - `POST /api/session` with JSON `{"access_key":"..."}` creates an isolated session and returns a random session ID.
42
+ - `POST /api/navigate` with `{"session_id":"...","url":"https://example.com"}` navigates.
43
+ - `POST /api/action` with `{"session_id":"...","action":"click","x":100,"y":100}` sends input.
44
+ - `WS /ws/{session_id}` streams JPEG screenshots.
45
+ - `DELETE /api/session/{session_id}` closes the browser context.
46
+
47
+ The demo uses an access key for simple testing. In production, authenticate users through your website backend, bind every session to the authenticated user, enforce per-user quotas, and never trust a client-supplied session ID by itself.
48
+
49
+ ## Security requirements before public launch
50
+
51
+ A public remote browser is a high-risk network proxy. At minimum:
52
+ - Add real login/session authentication and CSRF/origin protections.
53
+ - Add rate limits, concurrent-session limits, idle timeouts, and quotas.
54
+ - Block requests to localhost, private, link-local, and cloud metadata IP ranges, including DNS rebinding cases. URL checks in this demo are **not** a complete SSRF defense.
55
+ - Consider restricting navigation to HTTP/HTTPS only and applying outbound network controls.
56
+ - Run browsers with least privilege, sandboxing where supported, and a regularly patched image.
57
+ - Keep browser contexts isolated; never share cookies, storage, or profiles between users.
58
+ - Do not persist browsing data unless explicitly required and disclosed.
59
+ - Add abuse reporting, logging that avoids collecting sensitive page contents, and a clear acceptable-use policy.
60
+
61
+ ## Hugging Face limits
62
+
63
+ Docker Spaces are one container/compute environment, not an automatic browser farm. Each active Chromium context consumes RAM and CPU, and screenshot streaming adds load. Start with one or two concurrent sessions, measure actual resource use, then add limits. For substantial traffic, you will likely need multiple Space replicas or a dedicated browser-session service, which may conflict with the requirement to host everything on Spaces only.
64
+
65
+ Space local disk is ephemeral across restarts unless persistent storage is configured. Free compute may sleep when idle; confirm current plan and hardware limits in Hugging Face documentation.
cloud-browser-hf/app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import ipaddress
3
+ import os
4
+ import secrets
5
+ import socket
6
+ import time
7
+ from contextlib import asynccontextmanager
8
+ from urllib.parse import urlparse
9
+
10
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
11
+ from fastapi.responses import FileResponse
12
+ from fastapi.staticfiles import StaticFiles
13
+ from pydantic import BaseModel, Field
14
+ from playwright.async_api import async_playwright
15
+
16
+ ACCESS_KEY = os.environ.get("ACCESS_KEY", "")
17
+ MAX_SESSIONS = int(os.environ.get("MAX_SESSIONS", "2"))
18
+ IDLE_SECONDS = int(os.environ.get("IDLE_SECONDS", "900"))
19
+
20
+ playwright = None
21
+ browser = None
22
+ sessions = {}
23
+ session_lock = asyncio.Lock()
24
+
25
+
26
+ def valid_public_url(raw: str) -> str:
27
+ """Basic URL check only; not a complete SSRF defense."""
28
+ parsed = urlparse(raw)
29
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
30
+ raise HTTPException(400, "Only http:// and https:// URLs are allowed.")
31
+ host = parsed.hostname.lower()
32
+ if host in ("localhost", "localhost.localdomain") or host.endswith(".localhost"):
33
+ raise HTTPException(400, "Local destinations are blocked.")
34
+ try:
35
+ addresses = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80))
36
+ for item in addresses:
37
+ ip = ipaddress.ip_address(item[4][0])
38
+ if not ip.is_global:
39
+ raise HTTPException(400, "Private or non-public destinations are blocked.")
40
+ except socket.gaierror:
41
+ raise HTTPException(400, "Could not resolve destination host.")
42
+ return raw
43
+
44
+
45
+ @asynccontextmanager
46
+ async def lifespan(app: FastAPI):
47
+ global playwright, browser
48
+ playwright = await async_playwright().start()
49
+ browser = await playwright.chromium.launch(headless=True, args=["--no-sandbox"])
50
+ yield
51
+ for item in list(sessions.values()):
52
+ try:
53
+ await item["context"].close()
54
+ except Exception:
55
+ pass
56
+ if browser:
57
+ await browser.close()
58
+ if playwright:
59
+ await playwright.stop()
60
+
61
+
62
+ app = FastAPI(title="Cloud Browser", lifespan=lifespan)
63
+ app.mount("/static", StaticFiles(directory="static"), name="static")
64
+
65
+
66
+ class CreateSession(BaseModel):
67
+ access_key: str
68
+
69
+
70
+ class NavigateRequest(BaseModel):
71
+ session_id: str
72
+ url: str
73
+
74
+
75
+ class ActionRequest(BaseModel):
76
+ session_id: str
77
+ action: str
78
+ x: float | None = None
79
+ y: float | None = None
80
+ text: str | None = Field(default=None, max_length=2000)
81
+ delta_y: int | None = None
82
+
83
+
84
+ async def get_session(session_id: str):
85
+ item = sessions.get(session_id)
86
+ if not item:
87
+ raise HTTPException(404, "Session not found or expired.")
88
+ item["last_seen"] = time.time()
89
+ return item
90
+
91
+
92
+ @app.get("/")
93
+ async def home():
94
+ return FileResponse("static/index.html")
95
+
96
+
97
+ @app.post("/api/session")
98
+ async def create_session(data: CreateSession):
99
+ if not ACCESS_KEY or not secrets.compare_digest(data.access_key, ACCESS_KEY):
100
+ raise HTTPException(401, "Invalid access key.")
101
+ async with session_lock:
102
+ now = time.time()
103
+ expired = [sid for sid, item in sessions.items() if now - item["last_seen"] > IDLE_SECONDS]
104
+ for sid in expired:
105
+ try:
106
+ await sessions.pop(sid)["context"].close()
107
+ except Exception:
108
+ pass
109
+ if len(sessions) >= MAX_SESSIONS:
110
+ raise HTTPException(429, "Browser capacity reached. Try again later.")
111
+ context = await browser.new_context(
112
+ viewport={"width": 1280, "height": 800},
113
+ device_scale_factor=1,
114
+ accept_downloads=False,
115
+ )
116
+ page = await context.new_page()
117
+ await page.goto("https://example.com", wait_until="domcontentloaded", timeout=30000)
118
+ sid = secrets.token_urlsafe(32)
119
+ sessions[sid] = {"context": context, "page": page, "last_seen": time.time()}
120
+ return {"session_id": sid, "url": page.url, "title": await page.title()}
121
+
122
+
123
+ @app.post("/api/navigate")
124
+ async def navigate(data: NavigateRequest):
125
+ item = await get_session(data.session_id)
126
+ url = valid_public_url(data.url.strip())
127
+ try:
128
+ await item["page"].goto(url, wait_until="domcontentloaded", timeout=45000)
129
+ except Exception as exc:
130
+ # A timeout may still leave a usable page loaded.
131
+ if not item["page"].url or item["page"].url == "about:blank":
132
+ raise HTTPException(502, f"Navigation failed: {str(exc)[:180]}")
133
+ return {"url": item["page"].url, "title": await item["page"].title()}
134
+
135
+
136
+ @app.post("/api/action")
137
+ async def action(data: ActionRequest):
138
+ item = await get_session(data.session_id)
139
+ page = item["page"]
140
+ try:
141
+ if data.action == "click":
142
+ await page.mouse.click(data.x or 0, data.y or 0)
143
+ elif data.action == "type":
144
+ await page.keyboard.insert_text(data.text or "")
145
+ elif data.action == "key":
146
+ key = data.text or ""
147
+ allowed = {"Enter", "Escape", "Backspace", "Tab", "ArrowUp", "ArrowDown",
148
+ "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown",
149
+ "Control+A", "Control+L"}
150
+ if key not in allowed:
151
+ raise HTTPException(400, "Unsupported key.")
152
+ await page.keyboard.press(key)
153
+ elif data.action == "scroll":
154
+ await page.mouse.wheel(0, max(-1200, min(1200, data.delta_y or 0)))
155
+ elif data.action == "back":
156
+ await page.go_back(wait_until="domcontentloaded", timeout=15000)
157
+ elif data.action == "forward":
158
+ await page.go_forward(wait_until="domcontentloaded", timeout=15000)
159
+ elif data.action == "reload":
160
+ await page.reload(wait_until="domcontentloaded", timeout=30000)
161
+ else:
162
+ raise HTTPException(400, "Unsupported action.")
163
+ except HTTPException:
164
+ raise
165
+ except Exception as exc:
166
+ raise HTTPException(502, f"Browser action failed: {str(exc)[:180]}")
167
+ return {"url": page.url, "title": await page.title()}
168
+
169
+
170
+ @app.websocket("/ws/{session_id}")
171
+ async def stream(websocket: WebSocket, session_id: str):
172
+ item = sessions.get(session_id)
173
+ if not item:
174
+ await websocket.close(code=4404)
175
+ return
176
+ await websocket.accept()
177
+ page = item["page"]
178
+ try:
179
+ while True:
180
+ item["last_seen"] = time.time()
181
+ if page.is_closed():
182
+ break
183
+ image = await page.screenshot(type="jpeg", quality=55, timeout=10000)
184
+ await websocket.send_bytes(image)
185
+ await asyncio.sleep(0.20)
186
+ except (WebSocketDisconnect, RuntimeError, asyncio.CancelledError):
187
+ pass
188
+ except Exception:
189
+ try:
190
+ await websocket.close(code=1011)
191
+ except Exception:
192
+ pass
193
+
194
+
195
+ @app.delete("/api/session/{session_id}")
196
+ async def close_session(session_id: str):
197
+ item = sessions.pop(session_id, None)
198
+ if item:
199
+ await item["context"].close()
200
+ return {"closed": True}
cloud-browser-hf/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi>=0.115,<1.0
2
+ uvicorn[standard]>=0.30,<1.0
3
+ playwright>=1.50,<2.0
cloud-browser-hf/static/index.html ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Cloud Browser</title>
7
+ <style>
8
+ :root{color-scheme:dark;font:15px system-ui,sans-serif;background:#101319;color:#edf0f7}
9
+ *{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;flex-direction:column}
10
+ header{padding:12px 16px;background:#191e28;border-bottom:1px solid #303746;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
11
+ .brand{font-weight:700;margin-right:10px}.address{display:flex;gap:8px;flex:1;min-width:240px}
12
+ input{background:#0d1118;border:1px solid #3b4352;border-radius:9px;color:#fff;padding:10px 12px;min-width:0;flex:1}
13
+ button{border:1px solid #414a5b;background:#272e3b;color:#fff;border-radius:9px;padding:9px 12px;cursor:pointer}
14
+ button:hover{background:#353e4f}button:disabled{opacity:.5;cursor:wait}
15
+ main{padding:14px;display:flex;flex-direction:column;gap:10px;flex:1}
16
+ #status{color:#aeb9cc;font-size:13px;min-height:18px}
17
+ #viewport{background:#080a0e;border:1px solid #303746;border-radius:12px;overflow:auto;display:flex;align-items:flex-start;justify-content:center;min-height:300px;flex:1}
18
+ #screen{display:block;width:100%;height:auto;cursor:crosshair;outline:none;image-rendering:auto}
19
+ .hint{color:#8d98aa;font-size:12px}
20
+ @media(min-width:1000px){main{padding:20px}#viewport{min-height:calc(100vh - 150px)}}
21
+ </style>
22
+ </head>
23
+ <body>
24
+ <header>
25
+ <span class="brand">☁ Cloud Browser</span>
26
+ <button id="back" title="Back">←</button><button id="forward" title="Forward">→</button><button id="reload" title="Reload">⟳</button>
27
+ <form class="address" id="navform"><input id="url" value="https://example.com" aria-label="Website URL"><button type="submit">Go</button></form>
28
+ </header>
29
+ <main>
30
+ <div id="status">Enter the access key to start a private browser session.</div>
31
+ <div id="viewport"><img id="screen" alt="Remote Chromium screen" tabindex="0"></div>
32
+ <div class="hint">Click the page to focus it. Typing and scrolling are sent to the remote browser. This prototype does not support audio or downloads.</div>
33
+ </main>
34
+ <script>
35
+ let sessionId=null, ws=null, naturalW=1280, naturalH=800;
36
+ const $=id=>document.getElementById(id), status=$('status');
37
+ async function api(path,body,method='POST'){
38
+ const r=await fetch(path,{method,headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});
39
+ const d=await r.json(); if(!r.ok)throw Error(d.detail||'Request failed'); return d;
40
+ }
41
+ async function start(){
42
+ const key=prompt('Access key');
43
+ if(!key)return;
44
+ try{
45
+ status.textContent='Starting isolated Chromium session…';
46
+ const d=await api('/api/session',{access_key:key});sessionId=d.session_id;
47
+ $('url').value=d.url;status.textContent='Connected · '+d.title;
48
+ ws=new WebSocket(`${location.protocol==='https:'?'wss':'ws'}://${location.host}/ws/${sessionId}`);
49
+ ws.binaryType='blob';
50
+ ws.onmessage=e=>{const img=$('screen');const old=img.dataset.blob;if(old)URL.revokeObjectURL(old);const u=URL.createObjectURL(e.data);img.dataset.blob=u;img.src=u;};
51
+ ws.onclose=()=>{status.textContent='Stream disconnected. Reload to start a new session.'};
52
+ }catch(e){status.textContent=e.message}
53
+ }
54
+ async function navigate(raw){
55
+ if(!sessionId) return;
56
+ let value=raw.trim();if(!/^https?:\/\//i.test(value))value='https://'+value;
57
+ try{status.textContent='Loading…';const d=await api('/api/navigate',{session_id:sessionId,url:value});$('url').value=d.url;status.textContent=d.title+' · '+d.url;}
58
+ catch(e){status.textContent=e.message}
59
+ }
60
+ $('navform').addEventListener('submit',e=>{e.preventDefault();navigate($('url').value)});
61
+ async function action(a,extra={}){if(!sessionId)return;try{const d=await api('/api/action',{session_id:sessionId,action:a,...extra});if(d.url)$('url').value=d.url;status.textContent=d.title+' · '+d.url;}catch(e){status.textContent=e.message}}
62
+ $('back').onclick=()=>action('back');$('forward').onclick=()=>action('forward');$('reload').onclick=()=>action('reload');
63
+ const screen=$('screen');
64
+ screen.addEventListener('click',e=>{
65
+ const r=screen.getBoundingClientRect();
66
+ const x=(e.clientX-r.left)*naturalW/r.width, y=(e.clientY-r.top)*naturalH/r.height;
67
+ action('click',{x,y});screen.focus();
68
+ });
69
+ screen.addEventListener('keydown',e=>{
70
+ if(e.key.length===1&&!e.ctrlKey&&!e.metaKey){e.preventDefault();action('type',{text:e.key});}
71
+ else {const map={Enter:'Enter',Escape:'Escape',Backspace:'Backspace',Tab:'Tab',ArrowUp:'ArrowUp',ArrowDown:'ArrowDown',ArrowLeft:'ArrowLeft',ArrowRight:'ArrowRight',Home:'Home',End:'End',PageUp:'PageUp',PageDown:'PageDown'};
72
+ if(map[e.key]){e.preventDefault();action('key',{text:map[e.key]});}
73
+ else if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='a'){e.preventDefault();action('key',{text:'Control+A'});}
74
+ }
75
+ });
76
+ $('viewport').addEventListener('wheel',e=>{e.preventDefault();action('scroll',{delta_y:Math.round(e.deltaY)});},{passive:false});
77
+ window.addEventListener('beforeunload',()=>{if(sessionId)navigator.sendBeacon(`/api/session/${sessionId}`);});
78
+ start();
79
+ </script>
80
+ </body>
81
+ </html>