Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio desktop: serve the web UI behind an allowlisted reverse proxy (fixes #17420) (#17435)
Debojyoti Banerjeecc655b19fbaa
diff --git a/README.md b/README.mdindex 615c98fec1e..72742f5d849 100644--- a/README.md+++ b/README.md@@ -229,6 +229,14 @@ unsloth studio -H 0.0.0.0 -p 8888```**LAN Access (home network)**: `Settings > API keys > LAN access`+**Your own reverse proxy or custom domain** (Cloudflare Named Tunnel, nginx, Caddy) running on the same computer: Unsloth Desktop only serves its web UI to a proxy for hostnames you list (comma separated), so set them, then quit and reopen it:+```bash+export UNSLOTH_STUDIO_PROXY_HOSTS=studio.example.com # Linux: start Unsloth Desktop from this shell+launchctl setenv UNSLOTH_STUDIO_PROXY_HOSTS studio.example.com # macOS+setx UNSLOTH_STUDIO_PROXY_HOSTS studio.example.com # Windows+```+The proxy must send that hostname as `Host` (cloudflared's default, so leave its HTTP Host Header override unset) or as `X-Forwarded-Host`. Sign in with the password from `Settings > Remote access > Remote password`.+#### Password management & headless startsExposing Unsloth (`--secure`, `--cloudflare`, or a non-loopback `-H`) asks once at the terminal for a new admin password. Ctrl+C there aborts the launch rather than exposing the auto-generated one; set a password non-interactively instead, or use `-H 127.0.0.1` to stay off the network.diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 4b25e9a0ed1..a86dcfde9d0 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -3530,13 +3530,17 @@ def _is_direct_loopback_frontend_request(scope) -> bool:def _is_remote_frontend_request(scope, app_state) -> bool:"""True for a request the desktop backend may answer with its packaged web UI: Cloudflare's own edge, one- of the sockets the runtime LAN listener bound (both keyed on the connection, not a client header), or a- direct unproxied browser on the loopback listener."""+ of the sockets the runtime LAN listener bound (both keyed on the connection, not a client header), a+ direct unproxied browser on the loopback listener, or a local reverse proxy for a hostname the user+ allowlisted in ``UNSLOTH_STUDIO_PROXY_HOSTS``."""from lan_access import request_on_lan_listener+ from utils.client_ip import request_via_trusted_proxy+return (_is_live_cloudflare_frontend_request(scope, app_state)or request_on_lan_listener(scope)or _is_direct_loopback_frontend_request(scope)+ or request_via_trusted_proxy(scope))diff --git a/studio/backend/tests/test_trusted_proxy_hosts.py b/studio/backend/tests/test_trusted_proxy_hosts.pynew file mode 100644index 00000000000..f2a5c02efc8--- /dev/null+++ b/studio/backend/tests/test_trusted_proxy_hosts.py@@ -0,0 +1,172 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""UNSLOTH_STUDIO_PROXY_HOSTS: the desktop web UI behind the user's own reverse proxy (#17420)."""++import asyncio+from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI++from utils.client_ip import request_via_trusted_proxy, trusted_proxy_hosts++_ENV = "UNSLOTH_STUDIO_PROXY_HOSTS"+++def _scope(+ headers,+ client = "127.0.0.1",+ server = "127.0.0.1",+):+ return {+ "type": "http",+ "client": (client, 50000) if client else None,+ "server": (server, 8888) if server else None,+ "headers": [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers],+ }+++def allow_studio(monkeypatch):+ monkeypatch.setenv(_ENV, "studio.example.com")+++def test_the_setting_parses_names_and_drops_everything_else(monkeypatch):+ monkeypatch.setenv(+ _ENV,+ "Studio.Example.com, https://ai.example.org/ other.example.net:443 * localhost 127.0.0.1 [::1] bad_name",+ )+ assert trusted_proxy_hosts() == {"studio.example.com", "ai.example.org", "other.example.net"}+++def test_nothing_is_admitted_without_the_setting(monkeypatch):+ monkeypatch.delenv(_ENV, raising = False)+ assert not request_via_trusted_proxy(_scope([("host", "studio.example.com")]))+ assert not request_via_trusted_proxy(+ _scope([("host", "127.0.0.1:8888"), ("x-forwarded-host", "studio.example.com")])+ )+++ "headers",+ [+ # cloudflared's default: the public hostname as Host+ [+ ("host", "studio.example.com"),+ ("cf-connecting-ip", "203.0.113.7"),+ ("x-forwarded-proto", "https"),+ ],+ # a proxy that keeps the origin Host and names the public one in X-Forwarded-Host+ [+ ("host", "127.0.0.1:8888"),+ ("x-forwarded-host", "studio.example.com"),+ ("x-forwarded-proto", "https"),+ ],+ [("host", "localhost:8888"), ("x-forwarded-host", "Studio.Example.com:443")],+ [("host", "studio.example.com"), ("x-forwarded-host", "studio.example.com")],+ ],+)+def test_a_local_proxy_for_an_allowlisted_name_is_admitted(allow_studio, headers):+ assert request_via_trusted_proxy(_scope(headers))+++ "headers",+ [+ [("host", "evil.example")],+ # DNS rebinding: the page's own name is the Host, a header it sets cannot borrow the allowlist+ [("host", "evil.example:8888"), ("x-forwarded-host", "studio.example.com")],+ [("host", "studio.example.com"), ("x-forwarded-host", "evil.example")],+ [("host", "127.0.0.1:8888"), ("x-forwarded-host", "studio.example.com, evil.example")],+ [("host", "studio.example.com.evil.example")],+ [("host", "studio.example.com"), ("host", "studio.example.com")],+ [],+ # a plain loopback request is the existing direct-browser gate's to judge+ [("host", "127.0.0.1:8888")],+ ],+)+def test_other_names_are_refused(allow_studio, headers):+ assert not request_via_trusted_proxy(_scope(headers))+++ "client, server",+ [+ ("192.168.1.20", "127.0.0.1"),+ ("127.0.0.1", "192.168.1.5"),+ (None, "127.0.0.1"),+ ("127.0.0.1", None),+ ],+)+def test_only_the_loopback_listener_honours_the_allowlist(allow_studio, client, server):+ assert not request_via_trusted_proxy(_scope([("host", "studio.example.com")], client, server))+++def test_trust_forwarded_keeps_the_allowlist_working(allow_studio, monkeypatch):+ # uvicorn's proxy_headers rewrites the loopback peer to the X-Forwarded-For visitor+ monkeypatch.delenv("UNSLOTH_STUDIO_TRUST_FORWARDED", raising = False)+ proxied = _scope([("host", "studio.example.com")], client = "203.0.113.7")+ assert not request_via_trusted_proxy(proxied)+ monkeypatch.setenv("UNSLOTH_STUDIO_TRUST_FORWARDED", "1")+ assert request_via_trusted_proxy(proxied)+ assert not request_via_trusted_proxy(_scope([("host", "evil.example")], client = "203.0.113.7"))+ assert not request_via_trusted_proxy(+ _scope([("host", "studio.example.com")], client = "203.0.113.7", server = "192.168.1.5")+ )+++def _desktop_frontend(tmp_path):+ import main++ dist = tmp_path / "dist"+ (dist / "assets").mkdir(parents = True)+ (dist / "index.html").write_text(+ "<html><head></head><body>studio</body></html>", encoding = "utf-8"+ )+ (dist / "assets" / "app.js").write_text("console.log(1)", encoding = "utf-8")+ app = FastAPI()+ assert main.setup_frontend(app, dist, tunnel_only = True)+ return app+++def _get(app, path, headers):+ async def run():+ transport = httpx.ASGITransport(app = app, client = ("127.0.0.1", 50000))+ async with httpx.AsyncClient(+ transport = transport, base_url = "http://127.0.0.1:8888"+ ) as client:+ return await client.get(path, headers = headers)++ return asyncio.run(run())++[email protected]("path", ["/", "/chat", "/assets/app.js"])+def test_the_desktop_web_ui_is_served_through_an_allowlisted_proxy(tmp_path, monkeypatch, path):+ app = _desktop_frontend(tmp_path)+ proxied = {+ "host": "studio.example.com",+ "x-forwarded-proto": "https",+ "cf-connecting-ip": "203.0.113.7",+ }++ monkeypatch.delenv(_ENV, raising = False)+ assert _get(app, path, proxied).status_code == 404++ monkeypatch.setenv(_ENV, "studio.example.com")+ assert _get(app, path, proxied).status_code == 200+ assert _get(app, path, {**proxied, "host": "evil.example"}).status_code == 404+ # a direct local browser keeps working either way+ assert _get(app, path, {}).status_code == 200+++def test_a_proxied_request_still_never_counts_as_local_for_the_bootstrap_password(monkeypatch):+ import main+ monkeypatch.setenv(_ENV, "studio.example.com")+ for headers in (+ {"host": "studio.example.com"},+ {"host": "127.0.0.1", "x-forwarded-host": "studio.example.com"},+ ):+ request = SimpleNamespace(client = SimpleNamespace(host = "127.0.0.1"), headers = headers)+ assert main._is_local_bootstrap_request(request) is False, headersdiff --git a/studio/backend/utils/client_ip.py b/studio/backend/utils/client_ip.pyindex dc75c7e7b7f..16da3961d89 100644--- a/studio/backend/utils/client_ip.py+++ b/studio/backend/utils/client_ip.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport ipaddressimport os+import refrom urllib.parse import urlparse_TRUST_FORWARDED_ENV = "UNSLOTH_STUDIO_TRUST_FORWARDED"@@ -154,6 +155,65 @@ def _host_header_is_loopback(host_header: str | None) -> bool:return host == "localhost" or _is_loopback_ip(host)+_PROXY_HOSTS_ENV = "UNSLOTH_STUDIO_PROXY_HOSTS"+_DNS_NAME = re.compile(r"[a-z0-9-]+(\.[a-z0-9-]+)*")+++def _authority_hostname(value: str | None) -> str | None:+ host = (value or "").strip().lower()+ if "://" in host: # tolerate a pasted URL in the setting+ host = host.split("://", 1)[1].split("/", 1)[0]+ if host.count(":") == 1:+ host, port = host.split(":", 1)+ if not port.isdigit():+ return None+ host = host.rstrip(".")+ # Names only: a wildcard would admit any rebound name.+ if host == "localhost" or not _DNS_NAME.fullmatch(host):+ return None+ try:+ ipaddress.ip_address(host)+ except ValueError:+ return host+ return None+++def trusted_proxy_hosts() -> frozenset[str]:+ raw = os.environ.get(_PROXY_HOSTS_ENV, "")+ names = (_authority_hostname(entry) for entry in raw.replace(",", " ").split())+ return frozenset(name for name in names if name)+++def request_via_trusted_proxy(scope) -> bool:+ """Local reverse proxy for an allowlisted name. Host must be loopback or allowlisted: a DNS-rebound page+ sends its own name as Host, so it cannot borrow the allowlist via X-Forwarded-Host."""+ allowed = trusted_proxy_hosts()+ if not allowed or not isinstance(scope, dict):+ return False+ server = scope.get("server")+ client = scope.get("client")+ if not server or not client or not _is_loopback_ip(server[0]):+ return False+ # UNSLOTH_STUDIO_TRUST_FORWARDED makes uvicorn replace the loopback peer with X-Forwarded-For.+ if not _is_loopback_ip(client[0]) and not trust_forwarded_headers():+ return False+ host_values = []+ forwarded_hosts = []+ for name, value in scope.get("headers") or ():+ if name == b"host":+ host_values.append(value.decode("latin-1"))+ elif name == b"x-forwarded-host":+ forwarded_hosts.extend(p for p in value.decode("latin-1").split(",") if p.strip())+ if len(host_values) != 1:+ return False+ host_allowed = _authority_hostname(host_values[0]) in allowed+ if not host_allowed and not _host_header_is_loopback(host_values[0]):+ return False+ if any(_authority_hostname(part) not in allowed for part in forwarded_hosts):+ return False+ return host_allowed or bool(forwarded_hosts)++# Hop headers a proxy adds without naming the client (Apache's X-Forwarded-Server, an nginx block that# only sets X-Forwarded-Proto). Kept apart because Colab's tolerated-header check walks the tuple above._PROXY_HOP_HEADERS = ("via", "x-forwarded-port", "x-forwarded-proto", "x-forwarded-server")