Skip to content

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.

studio: configurable HuggingFace endpoint via HF_ENDPOINT env var (#4989)

AdamPlatin12320f184664254
diff --git a/studio/backend/core/data_recipe/huggingface.py b/studio/backend/core/data_recipe/huggingface.py
index 395ae69bae8..624b92a48bb 100644
--- a/studio/backend/core/data_recipe/huggingface.py
+++ b/studio/backend/core/data_recipe/huggingface.py
@@ -55,6 +55,7 @@ def publish_recipe_dataset(
description: str,
hf_token: str | None = None,
private: bool = False,
+ link_endpoint: str | None = None,
) -> str:
hf_token = account_hf_token(hf_token)
dataset_path = _resolve_recipe_artifact_path(artifact_path)
@@ -124,6 +125,11 @@ def publish_recipe_dataset(
builder_config_path = builder_config_path,
)
- return f"https://huggingface.co/datasets/{repo_id}"
+ from utils.hf_endpoint import get_hf_endpoint
+
+ # The upload went to get_hf_endpoint(); this URL is for the browser, where
+ # a loopback mirror is not the same host. The caller passes what its client
+ # can reach.
+ return f"{link_endpoint or get_hf_endpoint()}/datasets/{repo_id}"
except HuggingFaceHubClientUploadError as exc:
raise RecipeDatasetPublishError(str(exc)) from exc
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 9f374b00c6d..77300568bcd 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2546,10 +2546,24 @@ def _resolve_swa_pattern(
def _hf_repo_from_url(url: Optional[str]) -> Optional[str]:
- """Strip `https://huggingface.co/owner/name(/...)` -> `owner/name`."""
- if not url or "huggingface.co/" not in url:
+ """Strip `https://huggingface.co/owner/name(/...)` -> `owner/name`.
+
+ A mirrored HF_ENDPOINT is recognised too, so a URL recorded on a mirror
+ still resolves to its repo id. huggingface.co stays accepted either way:
+ the same install can hold entries written before the mirror was set.
+ """
+ if not url:
return None
- tail = url.split("huggingface.co/", 1)[1].rstrip("/")
+ from utils.hf_endpoint import get_hf_endpoint
+
+ marker = "huggingface.co/"
+ if marker not in url:
+ mirror = get_hf_endpoint().split("://", 1)[-1].rstrip("/") + "/"
+ if mirror in url:
+ marker = mirror
+ else:
+ return None
+ tail = url.split(marker, 1)[1].rstrip("/")
parts = tail.split("/")
if len(parts) < 2:
return None
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index eda2749ee59..09bbd9a9ebe 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -360,8 +360,10 @@ class InferenceOrchestrator:
"""Fetch top GGUF and non-GGUF repos from unsloth by downloads."""
try:
import httpx
+ from utils.hf_endpoint import get_hf_endpoint
+
resp = httpx.get(
- "https://huggingface.co/api/models",
+ f"{get_hf_endpoint()}/api/models",
params = {
"author": "unsloth",
"sort": "downloads",
diff --git a/studio/backend/core/training/provenance.py b/studio/backend/core/training/provenance.py
index b29444c28e7..59efc910dee 100644
--- a/studio/backend/core/training/provenance.py
+++ b/studio/backend/core/training/provenance.py
@@ -416,7 +416,10 @@ def _hf_dataset_source_ref(path_value: str) -> Optional[tuple[str, str, str]]:
try:
parsed = urlsplit(path_value)
- endpoint = urlsplit(os.environ.get("HF_ENDPOINT", "https://huggingface.co"))
+ # The shared helper, not a third private parse: a blank or scheme-less
+ # value yielded an empty netloc here and matched no URL at all.
+ from utils.hf_endpoint import get_hf_endpoint
+ endpoint = urlsplit(get_hf_endpoint())
except ValueError:
return None
if (
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 3dd780de1a7..6c9946d7bed 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -218,6 +218,13 @@ if _STUDIO_ROOT_RESOLVED != _LEGACY_STUDIO_ROOT:
mark_managed_llama_cpp_path(_MANAGED_LLAMA_CPP_PATH)
+# huggingface_hub reads HF_ENDPOINT itself, at import, unnormalised and unvalidated.
+# Rewrite it first, before anything imports the library.
+from utils.hf_endpoint import normalize_hf_endpoint_env as _normalize_hf_endpoint_env
+
+_normalize_hf_endpoint_env()
+del _normalize_hf_endpoint_env
+
# The studio bundles unsloth_zoo; declare unsloth present (as `import unsloth` does) so its
# lazy submodule imports and the DiffusionGemma runner don't trip the install guard.
os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
@@ -350,6 +357,16 @@ from utils.cache_cleanup import (
)
from utils.lifespan_shutdown import run_lifespan_shutdown
from utils.native_path_leases import native_path_leases_supported
+
+from utils.client_ip import client_ip
+from utils.hf_endpoint import (
+ DEFAULTS_BY_HEALTH_KEY as _HF_ENDPOINT_DEFAULTS,
+ endpoint_is_reachable_by as _endpoint_is_reachable_by,
+ csp_asset_sources,
+ csp_connect_sources,
+ get_hf_endpoint,
+ get_hf_datasets_server,
+)
from utils.update_status import (
get_studio_install_source_status,
get_studio_update_status,
@@ -921,6 +938,32 @@ _IS_COLAB = os.path.isdir("/content") and (
)
+def _reportable_hf_endpoints(request) -> dict:
+ """The endpoints to hand the browser, which are not always the ones we use.
+
+ A loopback endpoint names a proxy on the MACHINE THE BACKEND RUNS ON, and a
+ private-network one an address on the backend's LAN. Handing either to a
+ browser elsewhere makes it fetch its OWN localhost or its OWN 10.0.0.5: the
+ calls either fail, or hit an unrelated service that, if it answers the CORS
+ preflight, is handed the user's Hub bearer token. endpoint_is_reachable_by
+ holds the rule; the backend keeps using its own value either way.
+
+ The client comes from client_ip(), not the socket peer: through the managed
+ Cloudflare tunnel the peer IS loopback, being the local cloudflared process
+ rather than the visitor, and an address it cannot determine reads as remote.
+ """
+ reported = {}
+ for key, value in (
+ ("hf_endpoint", get_hf_endpoint()),
+ ("hf_datasets_server", get_hf_datasets_server()),
+ ):
+ if _endpoint_is_reachable_by(value, client_ip(request)):
+ reported[key] = value
+ else:
+ reported[key] = _HF_ENDPOINT_DEFAULTS[key]
+ return reported
+
+
def _build_csp(script_nonce: "str | None" = None, *, docs: bool = False) -> str:
script_src = "script-src 'self'"
style_src = "style-src 'self' 'unsafe-inline'"
@@ -939,23 +982,38 @@ def _build_csp(script_nonce: "str | None" = None, *, docs: bool = False) -> str:
# one level) and null-origin iframes; '*' is safe as Colab is a sandboxed single user.
frame_ancestors = "*" if _IS_COLAB else "'none'"
+ # A mirror has to reach connect-src, or the browser blocks the Hub calls routed
+ # there. img/media carry a bare https:, so only a loopback HTTP one needs those.
+ # Origins only: a host-source with a path is matched exactly unless it ends
+ # in "/", so a path-prefixed mirror would block every request under it.
+ hf_connect_src = " ".join(
+ dict.fromkeys(
+ (
+ "https://huggingface.co",
+ "https://datasets-server.huggingface.co",
+ *csp_connect_sources(),
+ )
+ )
+ )
+ asset_sources = csp_asset_sources()
+ hf_asset_src = (" " + " ".join(asset_sources)) if asset_sources else ""
+
# In Colab the kernel scaffolding injects scripts and fetch/WS from *.prod.colab.dev and
# *.googleusercontent.com, so widen script-src/connect-src. Scripts still use a nonce.
if _IS_COLAB:
script_src += " https://*.prod.colab.dev https://*.googleusercontent.com"
connect_src = (
- "'self' blob: data: "
- "https://huggingface.co https://datasets-server.huggingface.co "
+ f"'self' blob: data: {hf_connect_src} "
"https://*.prod.colab.dev wss://*.prod.colab.dev "
"https://*.googleusercontent.com wss://*.googleusercontent.com"
)
else:
- connect_src = "'self' https://huggingface.co https://datasets-server.huggingface.co"
+ connect_src = f"'self' {hf_connect_src}"
return (
"default-src 'self'; "
- "img-src 'self' data: blob: https:; "
- "media-src 'self' data: blob: https:; "
+ f"img-src 'self' data: blob: https:{hf_asset_src}; "
+ f"media-src 'self' data: blob: https:{hf_asset_src}; "
f"connect-src {connect_src}; "
f"{style_src}; "
f"{script_src}; "
@@ -1745,6 +1803,9 @@ async def health_check(request: Request):
# Opaque per-install id; launchers reject sibling Unsloth instances on the same port.
"studio_root_id": _studio_root_id(),
"native_path_leases_supported": native_path_leases_supported(),
+ # Unauthenticated on purpose: an endpoint URL is not a host fingerprint,
+ # and the frontend needs it before a token exists.
+ **_reportable_hf_endpoints(request),
**({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),
}
# Lockstep with /api/liveness: the launcher falls back to this route on a backend too old
diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.py
index 88197e866f4..c778f7feea7 100644
--- a/studio/backend/routes/data_recipe/jobs.py
+++ b/studio/backend/routes/data_recipe/jobs.py
@@ -53,6 +53,8 @@ from models.data_recipe import (
PublishDatasetResponse,
RecipePayload,
)
+from utils.client_ip import client_ip
+from utils.hf_endpoint import client_reachable_endpoint, get_hf_endpoint
from utils.host_policy import dial_host, self_request_host
from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_error
@@ -445,6 +447,26 @@ def _normalize_run_name(value: Any) -> str | None:
return trimmed[:120]
+def _resolve_seed_endpoint(recipe: dict[str, Any]) -> None:
+ """Fill in the HF endpoint for a backend-executed seed fetch, in place.
+
+ Data Designer fetches the seed in this process, so the endpoint must be the
+ one THIS machine can reach. A client that sends none (the normal case) gets
+ HF_ENDPOINT resolved here, which matters for a remote browser: /api/health
+ reports the public default to it for a loopback mirror, and shipping that
+ back would bypass the mirror on the deployments that need it most. An
+ endpoint the user typed into the seed node is left alone.
+ """
+ seed_config = recipe.get("seed_config")
+ if not isinstance(seed_config, dict):
+ return
+ source = seed_config.get("source")
+ if not isinstance(source, dict) or source.get("seed_type") != "hf":
+ return
+ if not str(source.get("endpoint") or "").strip():
+ source["endpoint"] = get_hf_endpoint()
+
+
@router.post("/jobs", response_class = JSONResponse, response_model = JobCreateResponse)
def create_job(
payload: RecipePayload,
@@ -483,6 +505,8 @@ def create_job(
log = logger,
) from exc
+ _resolve_seed_endpoint(recipe)
+
try:
internal_api_key_id = _inject_local_providers(recipe, request, credential[1])
except CredentialRotated as exc:
@@ -808,6 +832,7 @@ def download_job_dataset(
response_model = PublishDatasetResponse,
)
def publish_job_dataset(
+ request: Request,
job_id: str,
payload: PublishDatasetRequest,
allow_ambient: bool = Depends(allow_ambient_hf_token),
@@ -856,6 +881,9 @@ def publish_job_dataset(
description = description,
hf_token = hf_token or None,
private = payload.private,
+ # client_ip, not the socket peer: through the managed tunnel the peer
+ # is the local cloudflared process, not the visitor.
+ link_endpoint = client_reachable_endpoint(client_ip(request)),
)
except RecipeDatasetPublishError as exc:
raise log_and_http_error(
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index c60c4e5fff9..0f396ce131e 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2855,7 +2855,9 @@ def _preflight_gated_base(base_model: str, hf_token: Optional[str]) -> None:
or _is_local_path(repo)
):
return
- url = f"https://huggingface.co/{repo}/resolve/main/model_index.json"
+ from utils.hf_endpoint import get_hf_endpoint
+
+ url = f"{get_hf_endpoint()}/{repo}/resolve/main/model_index.json"
headers = {"Authorization": f"Bearer {hf_token}"} if hf_token else {}
req = urllib.request.Request(url, method = "HEAD", headers = headers)
try:
diff --git a/studio/backend/tests/test_data_recipe_seed.py b/studio/backend/tests/test_data_recipe_seed.py
index 6c514e95f0c..316527c2845 100644
--- a/studio/backend/tests/test_data_recipe_seed.py
+++ b/studio/backend/tests/test_data_recipe_seed.py
@@ -391,3 +391,42 @@ def test_plugin_resolution_survives_a_reload_and_normalizes(monkeypatch, tmp_pat
source = tmp_path / "notes.txt"
source.write_text("a\n\n\n\nb", encoding = "utf-8")
assert seed_route._extract_text_from_file(source, ".txt") == "a\n\nb"
+
+
+def test_a_backend_executed_seed_resolves_the_endpoint_on_the_backend(monkeypatch):
+ """The seed is fetched in THIS process, so the endpoint must be ours.
+
+ A remote browser is told the public default for a loopback mirror (it cannot
+ reach the backend's localhost), so letting the client's value through would
+ bypass the mirror on exactly the deployments that need it. A value the user
+ typed into the seed node is still honoured.
+ """
+ pytest.importorskip("fastapi")
+ backend_root = Path(__file__).resolve().parent.parent
+ monkeypatch.syspath_prepend(str(backend_root))
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+
+ from routes.data_recipe.jobs import _resolve_seed_endpoint
+
+ recipe = {"seed_config": {"source": {"seed_type": "hf", "path": "a/b", "endpoint": None}}}
+ _resolve_seed_endpoint(recipe)
+ assert recipe["seed_config"]["source"]["endpoint"] == "http://127.0.0.1:9700"
+
+ recipe = {"seed_config": {"source": {"seed_type": "hf", "path": "a/b"}}}
+ _resolve_seed_endpoint(recipe)
+ assert recipe["seed_config"]["source"]["endpoint"] == "http://127.0.0.1:9700"
+
+ explicit = {
+ "seed_config": {
+ "source": {"seed_type": "hf", "path": "a/b", "endpoint": "https://hub.internal"}
+ }
+ }
+ _resolve_seed_endpoint(explicit)
+ assert explicit["seed_config"]["source"]["endpoint"] == "https://hub.internal"
+
+ # Nothing to resolve for the other seed types, and no crash on a malformed recipe.
+ other = {"seed_config": {"source": {"seed_type": "local", "paths": []}}}
+ _resolve_seed_endpoint(other)
+ assert "endpoint" not in other["seed_config"]["source"]
+ _resolve_seed_endpoint({})
+ _resolve_seed_endpoint({"seed_config": "nope"})
diff --git a/studio/backend/tests/test_hf_endpoint.py b/studio/backend/tests/test_hf_endpoint.py
new file mode 100644
index 00000000000..f3f77216a06
--- /dev/null
+++ b/studio/backend/tests/test_hf_endpoint.py
@@ -0,0 +1,388 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for HF_ENDPOINT / HF_DATASETS_SERVER env var handling in utils.hf_endpoint.
+
+Both getters read the environment on every call (no import-time freezing), so
+the tests just monkeypatch the environment and call them directly.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+
+import pytest
+
+from utils import hf_endpoint
+from utils.hf_endpoint import (
+ client_reachable_endpoint,
+ get_hf_datasets_server,
+ get_hf_endpoint,
+)
+
+OFFICIAL_HF = "https://huggingface.co"
+OFFICIAL_DS = "https://datasets-server.huggingface.co"
+
+
[email protected](autouse = True)
+def _isolate_env(monkeypatch):
+ """Start every test from both vars unset, and reset the once-only warn flag."""
+ monkeypatch.delenv("HF_ENDPOINT", raising = False)
+ monkeypatch.delenv("HF_DATASETS_SERVER", raising = False)
+ import utils.hf_endpoint as _mod
+
+ monkeypatch.setattr(_mod, "_ds_mirror_warned", False)
+ monkeypatch.setattr(_mod, "_rejected_warned", set())
+ monkeypatch.setattr(_mod, "_unreachable_warned", set())
+ yield
+
+
+class TestGetHfEndpoint:
+ def test_default_when_unset(self):
+ assert get_hf_endpoint() == OFFICIAL_HF
+
+ @pytest.mark.parametrize("blank", ["", " ", "\t"])
+ def test_blank_falls_back_to_default(self, monkeypatch, blank):
+ monkeypatch.setenv("HF_ENDPOINT", blank)
+ assert get_hf_endpoint() == OFFICIAL_HF
+
+ @pytest.mark.parametrize(
+ "mirror",
+ [
+ "https://hf-mirror.com",
+ "https://hf-mirror.com/", # trailing slash stripped
+ "hf-mirror.com", # scheme-less gets https://
+ "hf-mirror.com/", # scheme-less + trailing slash
+ ],
+ )
+ def test_mirror_forms_normalised(self, monkeypatch, mirror):
+ monkeypatch.setenv("HF_ENDPOINT", mirror)
+ assert get_hf_endpoint() == "https://hf-mirror.com"
+
+ def test_reads_env_per_call(self, monkeypatch):
+ """The getter must pick up env changes without a re-import."""
+ assert get_hf_endpoint() == OFFICIAL_HF
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ assert get_hf_endpoint() == "https://hf-mirror.com"
+
+
+class TestGetHfDatasetsServer:
+ def test_default_when_unset(self):
+ assert get_hf_datasets_server() == OFFICIAL_DS
+
+ def test_explicit_override(self, monkeypatch):
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://ds.example.com")
+ assert get_hf_datasets_server() == "https://ds.example.com"
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_blank_falls_back_to_default(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_DATASETS_SERVER", raw)
+ assert get_hf_datasets_server() == OFFICIAL_DS
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "https://ds.example.com/",
+ "ds.example.com", # scheme-less gets https://
+ "ds.example.com/", # scheme-less + trailing slash
+ ],
+ )
+ def test_forms_normalised(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_DATASETS_SERVER", raw)
+ assert get_hf_datasets_server() == "https://ds.example.com"
+
+ def test_mirror_hub_does_not_redirect_datasets_server(self, monkeypatch, caplog):
+ """A mirrored HF_ENDPOINT alone must not point datasets-server at the mirror."""
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ assert get_hf_datasets_server() == OFFICIAL_DS
+ assert any("HF_DATASETS_SERVER" in r.message for r in caplog.records)
+
+ def test_mirror_warning_emitted_once(self, monkeypatch, caplog):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ get_hf_datasets_server()
+ get_hf_datasets_server()
+ warnings = [r for r in caplog.records if "HF_DATASETS_SERVER" in r.message]
+ assert len(warnings) == 1
+
+ def test_no_warning_on_default_endpoint(self, caplog):
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ get_hf_datasets_server()
+ assert not [r for r in caplog.records if "HF_DATASETS_SERVER" in r.message]
+
+ def test_no_warning_when_datasets_server_explicit(self, monkeypatch, caplog):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://ds.example.com")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ get_hf_datasets_server()
+ assert not [r for r in caplog.records if "HF_DATASETS_SERVER" in r.message]
+
+
+# These values reach the CSP connect-src built in main.py, and a source list is
+# whitespace-separated and semicolon-delimited.
+HOSTILE_ENDPOINTS = [
+ "https://hf-mirror.com; script-src *",
+ "https://hf-mirror.com *",
+ "https://hf-mirror.com\nscript-src *",
+ "https://hf-mirror.com\r\nscript-src *",
+ "https://hf-mirror.com\tfoo",
+ "https://hf-mirror.com,https://evil.com",
+ "https://hf-mirror.com'",
+ 'https://hf-mirror.com"',
+ # No NUL case: os.environ rejects it before we see it.
+]
+
+MALFORMED_ENDPOINTS = [
+ "javascript:alert(1)",
+ "file:///etc/passwd",
+ "data:text/html,x",
+ "ftp://hf-mirror.com",
+ "https://",
+ "https://user:[email protected]",
+ "https://hf-mirror.com?x=1",
+ "https://hf-mirror.com#frag",
+ "https://hf-mirror.com:",
+ "https://hf-mirror.com:not-a-port",
+ # An IPv6 literal written without its brackets, and the other authorities that
+ # make SplitResult.port raise. The rejection has to come from this module, not
+ # from an exception out of main.py's startup call to normalize_hf_endpoint_env.
+ "https://::1",
+ "https://a:b:c",
+ "https://hf-mirror.com:99999",
+ "https://[::1",
+ # "https://*" as a CSP source allows every https origin.
+ "*",
+ "https://*",
+ "https://*.evil.com",
+]
+
+
+class TestRejectsUnusableEndpoints:
+ @pytest.mark.parametrize("raw", HOSTILE_ENDPOINTS + MALFORMED_ENDPOINTS)
+ def test_hub_endpoint_falls_back_to_official(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == OFFICIAL_HF
+
+ @pytest.mark.parametrize("raw", HOSTILE_ENDPOINTS + MALFORMED_ENDPOINTS)
+ def test_datasets_server_falls_back_to_official(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_DATASETS_SERVER", raw)
+ assert get_hf_datasets_server() == OFFICIAL_DS
+
+ def test_rejection_is_logged(self, monkeypatch, caplog):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com; script-src *")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ get_hf_endpoint()
+ assert any("HF_ENDPOINT" in r.getMessage() for r in caplog.records)
+
+ def test_rejection_logged_once_not_per_call(self, monkeypatch, caplog):
+ """_build_csp runs per response, so a per-call warning would flood the log."""
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com; script-src *")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ for _ in range(5):
+ get_hf_endpoint()
+ assert len([r for r in caplog.records if "HF_ENDPOINT" in r.getMessage()]) == 1
+
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("https://hub.internal:8443", "https://hub.internal:8443"),
+ ("http://localhost:8080", "http://localhost:8080"),
+ ("https://hub.internal/hf", "https://hub.internal/hf"),
+ ("https://hub.internal/hf/", "https://hub.internal/hf"),
+ ("hub.internal:8443", "https://hub.internal:8443"),
+ ],
+ )
+ def test_legitimate_forms_survive(self, monkeypatch, raw, expected):
+ """Ports, http for a LAN mirror, and a path prefix are all valid mirrors."""
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == expected
+
+
+class TestMalformedUrlDoesNotCrash:
+ """`_build_csp` runs on every response, so a raise here is a 500 for every request."""
+
+ @pytest.mark.parametrize(
+ "raw", ["https://[", "https://[::1", "https://[bad]", "http://[", "https://a[b"]
+ )
+ def test_bracketed_host_falls_back_instead_of_raising(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == OFFICIAL_HF
+ monkeypatch.delenv("HF_ENDPOINT")
+ monkeypatch.setenv("HF_DATASETS_SERVER", raw)
+ assert get_hf_datasets_server() == OFFICIAL_DS
+
+
+class TestPlainHttpIsLoopbackOnly:
+ """The frontend attaches the Hub token to these requests, so off-box HTTP
+ would put a bearer token on the wire in cleartext."""
+
+ @pytest.mark.parametrize(
+ "raw",
+ ["http://127.0.0.1:9700", "http://localhost:8080", "http://127.1.2.3", "http://[::1]:9000"],
+ )
+ def test_loopback_http_is_kept(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == raw
+
+ @pytest.mark.parametrize(
+ "raw", ["http://192.168.1.10:8080", "http://hf-mirror.com", "http://10.0.0.5:8080"]
+ )
+ def test_off_box_http_is_refused(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == OFFICIAL_HF
+
+ @pytest.mark.parametrize("raw", ["https://192.168.1.10:8080", "https://hf-mirror.com"])
+ def test_https_to_the_same_hosts_is_fine(self, monkeypatch, raw):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == raw
+
+
+class TestAssetSources:
+ def test_no_asset_sources_without_a_mirror(self):
+ from utils.hf_endpoint import csp_asset_sources
+ assert csp_asset_sources() == ()
+
+ def test_an_https_mirror_needs_none(self, monkeypatch):
+ """img-src/media-src already carry a bare https:."""
+ from utils.hf_endpoint import csp_asset_sources
+
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ assert csp_asset_sources() == ()
+
+ def test_a_loopback_http_mirror_needs_one(self, monkeypatch):
+ from utils.hf_endpoint import csp_asset_sources
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+ assert csp_asset_sources() == ("http://127.0.0.1:9700",)
+
+
+def test_an_uppercase_scheme_is_accepted_and_folded(monkeypatch):
+ """RFC 3986 3.1: HTTPS://mirror is a real mirror, and the frontend keys its
+ cache on the folded form."""
+ monkeypatch.setenv("HF_ENDPOINT", "HTTPS://hf-mirror.com")
+ assert get_hf_endpoint() == "https://hf-mirror.com"
+ monkeypatch.setenv("HF_ENDPOINT", "HTTP://127.0.0.1:9700")
+ assert get_hf_endpoint() == "http://127.0.0.1:9700"
+ monkeypatch.setenv("HF_ENDPOINT", "HTTP://hf-mirror.com")
+ assert get_hf_endpoint() == "https://huggingface.co"
+
+
+def test_a_loopback_endpoint_is_not_handed_to_a_remote_browser(monkeypatch):
+ """A remote browser handed http://127.0.0.1:9700 opens its OWN localhost, so
+ the publish link would be dead where before the feature it worked."""
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+ assert client_reachable_endpoint("127.0.0.1") == "http://127.0.0.1:9700"
+ assert client_reachable_endpoint("::1") == "http://127.0.0.1:9700"
+ assert client_reachable_endpoint("192.168.1.50") == "https://huggingface.co"
+ assert client_reachable_endpoint(None) == "https://huggingface.co"
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ assert client_reachable_endpoint("192.168.1.50") == "https://hf-mirror.com"
+
+
+def test_the_reachable_endpoint_follows_the_tunnel_aware_client_ip(monkeypatch):
+ """Every caller pairs this with client_ip(): through the managed tunnel the
+ socket peer is the local cloudflared process, not the visitor."""
+ from types import SimpleNamespace
+
+ from utils.client_ip import client_ip
+
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+
+ def request(peer: str, headers: dict | None = None):
+ return SimpleNamespace(client = SimpleNamespace(host = peer), headers = headers or {})
+
+ local = request("127.0.0.1")
+ assert client_reachable_endpoint(client_ip(local)) == "http://127.0.0.1:9700"
+
+ tunneled = request("127.0.0.1", {"cf-connecting-ip": "203.0.113.7"})
+ assert client_reachable_endpoint(client_ip(tunneled)) == "https://huggingface.co"
+
+ lan = request("192.168.1.50")
+ assert client_reachable_endpoint(client_ip(lan)) == "https://huggingface.co"
+
+
+def test_a_unicode_host_cannot_reach_the_csp_header(monkeypatch):
+ """Starlette encodes header values as latin-1, so a Unicode host in connect-src
+ turns EVERY response into a 500. All three sides take the punycode form."""
+ monkeypatch.setenv("HF_ENDPOINT", "https://例子.测试")
+ assert get_hf_endpoint() == "https://huggingface.co"
+ monkeypatch.setenv("HF_ENDPOINT", "https://xn--fsqu00a.xn--0zwm56d")
+ assert get_hf_endpoint() == "https://xn--fsqu00a.xn--0zwm56d"
+
+
+def test_an_ipv6_loopback_mirror_is_compressed_the_way_the_browser_sends_it(monkeypatch):
+ """A host-source is matched as a string (CSP3 6.7.2.5) and the browser sends
+ http://[::1]:9700 whichever spelling was configured."""
+ for raw in ("http://[0:0:0:0:0:0:0:1]:9700", "http://[::1]:9700"):
+ monkeypatch.setenv("HF_ENDPOINT", raw)
+ assert get_hf_endpoint() == "http://[::1]:9700", raw
+ monkeypatch.setenv("HF_ENDPOINT", "http://[0:0:0:0:0:0:0:1]")
+ assert get_hf_endpoint() == "http://[::1]"
+ monkeypatch.setenv("HF_ENDPOINT", "http://[2001:db8::1]:9700")
+ assert get_hf_endpoint() == "https://huggingface.co"
+
+
+def test_the_environment_is_normalised_for_huggingface_hub(monkeypatch):
+ """huggingface_hub reads HF_ENDPOINT itself, at import, unvalidated: a
+ scheme-less value breaks every HfApi call and a rejected one would still be
+ handed the user's token. Rewriting the variable first settles both."""
+ monkeypatch.setenv("HF_ENDPOINT", "hf-mirror.com")
+ hf_endpoint.normalize_hf_endpoint_env()
+ assert os.environ["HF_ENDPOINT"] == "https://hf-mirror.com"
+
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com/")
+ hf_endpoint.normalize_hf_endpoint_env()
+ assert os.environ["HF_ENDPOINT"] == "https://hf-mirror.com"
+
+ # Removed, so the library falls back rather than using a host we refused.
+ for rejected in (
+ "http://192.168.1.10:8080",
+ "https://hf-mirror.com; script-src *",
+ "https://例子.测试",
+ "*",
+ ):
+ monkeypatch.setenv("HF_ENDPOINT", rejected)
+ hf_endpoint.normalize_hf_endpoint_env()
+ assert "HF_ENDPOINT" not in os.environ, rejected
+
+ monkeypatch.delenv("HF_ENDPOINT", raising = False)
+ hf_endpoint.normalize_hf_endpoint_env()
+ assert "HF_ENDPOINT" not in os.environ
+
+
+def test_a_private_endpoint_reaches_only_a_client_on_a_local_network(monkeypatch):
+ """A private address means the VISITOR's network when the visitor is
+ elsewhere, so it is handed out only to a client that is itself local."""
+ monkeypatch.setenv("HF_ENDPOINT", "https://10.0.0.5:8443")
+ assert client_reachable_endpoint("192.168.1.50") == "https://10.0.0.5:8443"
+ assert client_reachable_endpoint("127.0.0.1") == "https://10.0.0.5:8443"
+ assert client_reachable_endpoint("8.8.8.8") == "https://huggingface.co"
+ assert client_reachable_endpoint(None) == "https://huggingface.co"
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+ assert client_reachable_endpoint("192.168.1.50") == "https://huggingface.co"
+ assert client_reachable_endpoint("127.0.0.1") == "http://127.0.0.1:9700"
+ monkeypatch.setenv("HF_ENDPOINT", "https://hub.internal")
+ assert client_reachable_endpoint("8.8.8.8") == "https://hub.internal"
+
+
+def test_the_per_client_fallback_is_logged_once_per_endpoint(monkeypatch, caplog):
+ """Both /api/health and the publish link call this on every request."""
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ for _ in range(3):
+ assert client_reachable_endpoint("8.8.8.8") == OFFICIAL_HF
+ assert len([r for r in caplog.records if "not reachable" in r.getMessage()]) == 1
+
+ # A different endpoint is a different configuration, so it warns on its own.
+ caplog.clear()
+ monkeypatch.setenv("HF_ENDPOINT", "https://10.0.0.5:8443")
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ assert client_reachable_endpoint("8.8.8.8") == OFFICIAL_HF
+ assert len([r for r in caplog.records if "not reachable" in r.getMessage()]) == 1
+
+ # A client that CAN reach it is not a fallback and must not warn.
+ caplog.clear()
+ with caplog.at_level(logging.WARNING, logger = "utils.hf_endpoint"):
+ assert client_reachable_endpoint("192.168.1.50") == "https://10.0.0.5:8443"
+ assert not [r for r in caplog.records if "not reachable" in r.getMessage()]
diff --git a/studio/backend/tests/test_hub_write_ambient_token.py b/studio/backend/tests/test_hub_write_ambient_token.py
index d9b8af27fb8..54d222a9871 100644
--- a/studio/backend/tests/test_hub_write_ambient_token.py
+++ b/studio/backend/tests/test_hub_write_ambient_token.py
@@ -23,6 +23,8 @@ from auth.authentication import (
from routes import export as export_routes
from routes.data_recipe import jobs as data_recipe_jobs_routes
+OFFICIAL_HF = "https://huggingface.co"
+
async def _fake_ensure_export_supported():
pass
@@ -49,8 +51,11 @@ def _publish_manager(monkeypatch, seen):
monkeypatch.setattr(
data_recipe_jobs_routes,
"publish_recipe_dataset",
- lambda artifact_path, repo_id, description, hf_token, private: (
- seen.update(token = hf_token) or f"https://huggingface.co/datasets/{repo_id}"
+ # link_endpoint is keyword-only at the real call site, so **kwargs here keeps
+ # the stub from going stale the next time the route grows an argument.
+ lambda *, artifact_path, repo_id, description, hf_token, private, **kwargs: (
+ seen.update(token = hf_token, **kwargs)
+ or f"{kwargs.get('link_endpoint') or OFFICIAL_HF}/datasets/{repo_id}"
),
)
@@ -85,6 +90,8 @@ def test_publish_allows_a_token_bearing_key_and_a_ui_session(
)
assert response.status_code == 200
assert seen["token"] == expected
+ # The published link is built for the caller, not for the host running Studio.
+ assert seen["link_endpoint"] == OFFICIAL_HF
# ------------------------------------------------------------------------ export routes
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 2aa66c5e8ef..0eba6df5b11 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -531,6 +531,33 @@ class TestSecurityHeadersMiddleware:
assert "geolocation=()" in permissions_policy
assert r.headers["server"] == "unsloth-studio"
+ def test_mirror_endpoints_in_connect_src(self, main_module, monkeypatch):
+ # A mirror must reach connect-src or the browser blocks the Hub calls.
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://ds.example.com")
+ app = _make_csp_app(main_module)
+ r = TestClient(app).get("/plain")
+ csp = r.headers["content-security-policy"]
+ directives = {
+ chunk.strip().split(" ", 1)[0]: chunk.strip()
+ for chunk in csp.split(";")
+ if chunk.strip()
+ }
+ assert "https://hf-mirror.com" in directives["connect-src"]
+ assert "https://ds.example.com" in directives["connect-src"]
+
+ def test_connect_src_unchanged_without_mirror(self, main_module, monkeypatch):
+ monkeypatch.delenv("HF_ENDPOINT", raising = False)
+ monkeypatch.delenv("HF_DATASETS_SERVER", raising = False)
+ app = _make_csp_app(main_module)
+ r = TestClient(app).get("/plain")
+ csp = r.headers["content-security-policy"]
+ assert "hf-mirror.com" not in csp
+ assert (
+ "connect-src 'self' https://huggingface.co "
+ "https://datasets-server.huggingface.co;" in csp
+ )
+
def test_internal_nonce_header_is_spliced_into_csp_and_stripped(self, main_module):
nonce = "test-nonce-abc"
app = _make_csp_app(main_module, attach_nonce = nonce)
@@ -1112,3 +1139,232 @@ class TestHealthAuthGate:
assert body["status"] == "healthy"
for field in self.LAUNCHER_BITS + self.FINGERPRINT_FIELDS:
assert field in body, f"missing: {field}"
+
+
+# Captured from origin/main (pre-PR), both vars unset, nonce fixed. The feature must
+# be invisible to a default deployment, which a substring assertion cannot show.
+_MAIN_CSP_DEFAULT = (
+ "default-src 'self'; img-src 'self' data: blob: https:; "
+ "media-src 'self' data: blob: https:; "
+ "connect-src 'self' https://huggingface.co https://datasets-server.huggingface.co; "
+ "style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-NONCE'; "
+ "worker-src 'self'; font-src 'self' data:; frame-src 'self'; "
+ "frame-ancestors 'none'; form-action 'self'; base-uri 'self'"
+)
+_MAIN_CSP_DOCS = (
+ "default-src 'self'; img-src 'self' data: blob: https:; "
+ "media-src 'self' data: blob: https:; "
+ "connect-src 'self' https://huggingface.co https://datasets-server.huggingface.co; "
+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "script-src 'self' 'nonce-NONCE'; worker-src 'self' blob:; "
+ "font-src 'self' data: https://fonts.gstatic.com; frame-src 'self'; "
+ "frame-ancestors 'none'; form-action 'self'; base-uri 'self'"
+)
+_MAIN_CSP_COLAB = (
+ "default-src 'self'; img-src 'self' data: blob: https:; "
+ "media-src 'self' data: blob: https:; "
+ "connect-src 'self' blob: data: https://huggingface.co "
+ "https://datasets-server.huggingface.co https://*.prod.colab.dev "
+ "wss://*.prod.colab.dev https://*.googleusercontent.com "
+ "wss://*.googleusercontent.com; style-src 'self' 'unsafe-inline'; "
+ "script-src 'self' 'nonce-NONCE' https://*.prod.colab.dev "
+ "https://*.googleusercontent.com; worker-src 'self'; font-src 'self' data:; "
+ "frame-src 'self'; frame-ancestors *; form-action 'self'; base-uri 'self'"
+)
+
+
+def _connect_src(policy: str) -> list[str]:
+ """Exact source tokens of connect-src. Substring checks pass on a prefix."""
+ for chunk in policy.split(";"):
+ tokens = chunk.strip().split()
+ if tokens and tokens[0] == "connect-src":
+ return tokens[1:]
+ raise AssertionError(f"no connect-src in {policy!r}")
+
+
+class TestCspHfEndpoints:
+ @pytest.fixture(autouse = True)
+ def _clean_env(self, monkeypatch):
+ monkeypatch.delenv("HF_ENDPOINT", raising = False)
+ monkeypatch.delenv("HF_DATASETS_SERVER", raising = False)
+ import utils.hf_endpoint as _mod
+
+ monkeypatch.setattr(_mod, "_ds_mirror_warned", False)
+ monkeypatch.setattr(_mod, "_rejected_warned", set())
+ yield
+
+ @pytest.mark.parametrize(
+ "kwargs, expected",
+ [
+ ({}, _MAIN_CSP_DEFAULT),
+ ({"docs": True}, _MAIN_CSP_DOCS),
+ ],
+ )
+ def test_unmirrored_policy_is_byte_identical_to_pre_pr(self, main_module, kwargs, expected):
+ assert main_module._build_csp("NONCE", **kwargs) == expected
+
+ def test_unmirrored_colab_policy_is_byte_identical_to_pre_pr(self, main_module, monkeypatch):
+ monkeypatch.setattr(main_module, "_IS_COLAB", True)
+ assert main_module._build_csp("NONCE") == _MAIN_CSP_COLAB
+
+ @pytest.mark.parametrize("blank", ["", " ", "\t"])
+ def test_blank_env_vars_leave_the_policy_identical(self, main_module, monkeypatch, blank):
+ monkeypatch.setenv("HF_ENDPOINT", blank)
+ monkeypatch.setenv("HF_DATASETS_SERVER", blank)
+ assert main_module._build_csp("NONCE") == _MAIN_CSP_DEFAULT
+
+ def test_endpoints_set_to_the_official_hosts_do_not_duplicate_sources(
+ self, main_module, monkeypatch
+ ):
+ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://datasets-server.huggingface.co")
+ assert main_module._build_csp("NONCE") == _MAIN_CSP_DEFAULT
+
+ def test_a_mirror_adds_exactly_its_two_origins(self, main_module, monkeypatch):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://ds.example.com")
+ policy = main_module._build_csp("NONCE")
+ assert _connect_src(policy) == [
+ "'self'",
+ "https://huggingface.co",
+ "https://datasets-server.huggingface.co",
+ "https://hf-mirror.com",
+ "https://ds.example.com",
+ ]
+ baseline = dict(
+ chunk.strip().split(" ", 1)
+ for chunk in _MAIN_CSP_DEFAULT.split(";")
+ if chunk.strip() and " " in chunk.strip()
+ )
+ actual = dict(
+ chunk.strip().split(" ", 1)
+ for chunk in policy.split(";")
+ if chunk.strip() and " " in chunk.strip()
+ )
+ for directive, value in baseline.items():
+ if directive == "connect-src":
+ continue
+ assert actual[directive] == value, directive
+
+ def test_a_mirrored_colab_policy_keeps_every_colab_source(self, main_module, monkeypatch):
+ monkeypatch.setattr(main_module, "_IS_COLAB", True)
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ sources = _connect_src(main_module._build_csp("NONCE"))
+ for required in _connect_src(_MAIN_CSP_COLAB):
+ assert required in sources, required
+ assert "https://hf-mirror.com" in sources
+
+ def test_a_mirror_is_listed_once_even_if_both_vars_name_it(self, main_module, monkeypatch):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://hf-mirror.com")
+ sources = _connect_src(main_module._build_csp("NONCE"))
+ assert sources.count("https://hf-mirror.com") == 1
+
+ @pytest.mark.parametrize(
+ "hostile",
+ [
+ "https://hf-mirror.com; script-src *",
+ "https://hf-mirror.com *",
+ "https://hf-mirror.com\nscript-src *",
+ "https://hf-mirror.com,https://evil.com",
+ "javascript:alert(1)",
+ "https://user:[email protected]",
+ ],
+ )
+ def test_an_endpoint_cannot_forge_a_directive(self, main_module, monkeypatch, hostile):
+ """A bad env var must not widen the policy -- it falls back to the default."""
+ monkeypatch.setenv("HF_ENDPOINT", hostile)
+ policy = main_module._build_csp("NONCE")
+ assert policy == _MAIN_CSP_DEFAULT
+ assert policy.count(";") == _MAIN_CSP_DEFAULT.count(";")
+
+ def test_the_header_on_a_real_response_carries_the_mirror(self, main_module, monkeypatch):
+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")
+ monkeypatch.setenv("HF_DATASETS_SERVER", "https://ds.example.com")
+ app = _make_csp_app(main_module)
+ r = TestClient(app).get("/plain")
+ sources = _connect_src(r.headers["content-security-policy"])
+ assert "https://hf-mirror.com" in sources
+ assert "https://ds.example.com" in sources
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_source",
+ [
+ ("https://hub.internal/hf", "https://hub.internal"),
+ ("https://hub.internal:8443/hf/v2", "https://hub.internal:8443"),
+ ("https://hf-mirror.com", "https://hf-mirror.com"),
+ ("http://localhost:8080", "http://localhost:8080"),
+ ],
+ )
+ def test_a_path_prefixed_mirror_is_listed_as_an_origin(
+ self, main_module, monkeypatch, endpoint, expected_source
+ ):
+ """CSP3 6.7.2.7: a host-source with a path that does not end in "/" matches
+ that path EXACTLY. Listing "https://hub.internal/hf" would therefore allow
+ exactly that one URL and block every /hf/api/... request under it, in
+ Chrome, Edge, Firefox and Safari alike. The path belongs in the request
+ URL; the policy gets the origin.
+ """
+ monkeypatch.setenv("HF_ENDPOINT", endpoint)
+ sources = _connect_src(main_module._build_csp("NONCE"))
+ assert expected_source in sources
+ assert not any(
+ s.count("/") > 2 for s in sources if s.startswith(("http://", "https://"))
+ ), sources
+
+ @pytest.mark.parametrize(
+ "endpoint, loopback_sees, remote_sees",
+ [
+ ("http://127.0.0.1:9700", "http://127.0.0.1:9700", "https://huggingface.co"),
+ ("http://localhost:8080", "http://localhost:8080", "https://huggingface.co"),
+ ("https://hf-mirror.com", "https://hf-mirror.com", "https://hf-mirror.com"),
+ ],
+ )
+ def test_a_loopback_endpoint_is_only_reported_to_a_loopback_client(
+ self, main_module, monkeypatch, endpoint, loopback_sees, remote_sees
+ ):
+ """A loopback endpoint means the BROWSER's localhost anywhere else: dead,
+ or an unrelated service that would be handed the user's Hub token."""
+ monkeypatch.setenv("HF_ENDPOINT", endpoint)
+ local = TestClient(main_module.app, client = ("127.0.0.1", 40000))
+ assert local.get("/api/health").json()["hf_endpoint"] == loopback_sees
+ remote = TestClient(main_module.app, client = ("192.168.1.50", 40000))
+ assert remote.get("/api/health").json()["hf_endpoint"] == remote_sees
+
+ def test_a_tunneled_client_is_not_mistaken_for_a_local_one(self, main_module, monkeypatch):
+ """Through the managed tunnel the socket peer IS loopback: it is the local
+ cloudflared process, not the visitor."""
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9700")
+ c = TestClient(main_module.app, client = ("127.0.0.1", 40000))
+ tunneled = c.get("/api/health", headers = {"CF-Connecting-IP": "8.8.8.8"})
+ assert tunneled.json()["hf_endpoint"] == "https://huggingface.co"
+ assert c.get("/api/health").json()["hf_endpoint"] == "http://127.0.0.1:9700"
+ # A forged header from a non-loopback peer is ignored (client_ip's rule).
+ remote = TestClient(main_module.app, client = ("192.168.1.50", 40000))
+ forged = remote.get("/api/health", headers = {"CF-Connecting-IP": "127.0.0.1"})
+ assert forged.json()["hf_endpoint"] == "https://huggingface.co"
+
+ @pytest.mark.parametrize(
+ "endpoint, remote_sees",
+ [
+ ("http://127.0.0.1:9700", "https://huggingface.co"),
+ ("https://10.0.0.5:8443", "https://huggingface.co"),
+ ("https://192.168.1.9", "https://huggingface.co"),
+ ("https://[fd00::1]", "https://huggingface.co"),
+ ("https://hf-mirror.com", "https://hf-mirror.com"),
+ ],
+ )
+ def test_a_private_network_endpoint_is_not_reported_to_a_remote_browser(
+ self, main_module, monkeypatch, endpoint, remote_sees
+ ):
+ """10.0.0.5 means the VISITOR's 10.0.0.5, one step out from localhost. A
+ LAN client is on the backend's network and still gets the real value."""
+ monkeypatch.setenv("HF_ENDPOINT", endpoint)
+ tunneled = TestClient(main_module.app, client = ("127.0.0.1", 40000))
+ seen = tunneled.get("/api/health", headers = {"CF-Connecting-IP": "8.8.8.8"}).json()[
+ "hf_endpoint"
+ ]
+ assert seen == remote_sees
+ lan = TestClient(main_module.app, client = ("192.168.1.50", 40000))
+ lan_expected = "https://huggingface.co" if "127.0.0.1" in endpoint else endpoint
+ assert lan.get("/api/health").json()["hf_endpoint"] == lan_expected
diff --git a/studio/backend/utils/hf_endpoint.py b/studio/backend/utils/hf_endpoint.py
new file mode 100644
index 00000000000..6608dba213a
--- /dev/null
+++ b/studio/backend/utils/hf_endpoint.py
@@ -0,0 +1,315 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Centralised HuggingFace endpoint configuration.
+
+Backend code that constructs HF URLs directly (i.e. *outside* of
+``huggingface_hub`` calls) should use :func:`get_hf_endpoint` instead of
+hard-coding ``https://huggingface.co``. The value is read through
+:func:`utils.utils.hf_endpoint_url` — the single source of truth for
+``HF_ENDPOINT`` parsing — so both entry points stay in lockstep.
+
+The datasets-server base URL is independent from the Hub mirror: most Hub
+mirrors do not proxy the datasets-server API, so a mirrored ``HF_ENDPOINT``
+never implicitly redirects datasets-server traffic. Operators who do run a
+mirrored datasets-server must set ``HF_DATASETS_SERVER`` explicitly.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import os
+from urllib.parse import urlsplit, urlunsplit
+
+from utils.utils import hf_endpoint_url
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_HF_ENDPOINT = "https://huggingface.co"
+_DEFAULT_DATASETS_SERVER = "https://datasets-server.huggingface.co"
+
+# Reported when the configured value is not reachable by this client.
+DEFAULTS_BY_HEALTH_KEY = {
+ "hf_endpoint": _DEFAULT_HF_ENDPOINT,
+ "hf_datasets_server": _DEFAULT_DATASETS_SERVER,
+}
+
+_ds_mirror_warned = False
+# The CSP builder runs on every response, so each bad value is logged once.
+_rejected_warned: set[str] = set()
+# client_reachable_endpoint() runs per request too, so each configured endpoint
+# logs its per-client fallback once instead of on every /api/health call.
+_unreachable_warned: set[str] = set()
+
+# A source list is whitespace-separated and semicolon-delimited: any of these in an
+# endpoint would add sources or whole directives rather than one origin.
+_FORBIDDEN_CHARS = frozenset(" \t\r\n\f\v;,'\"\\")
+
+
+def _split(candidate: str):
+ """``urlsplit`` that answers None instead of raising on a malformed host."""
+ try:
+ return urlsplit(candidate)
+ except ValueError:
+ return None
+
+
+def is_loopback_host(hostname: str | None) -> bool:
+ if not hostname:
+ return False
+ host = hostname.strip("[]").lower()
+ if host == "localhost" or host.endswith(".localhost"):
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+def _port_is_valid(parts) -> bool:
+ """``SplitResult.port`` raises rather than returning None on a bad port."""
+ try:
+ parts.port
+ except ValueError:
+ return False
+ return True
+
+
+def _sanitize(candidate: str, default: str, var_name: str) -> str:
+ """Return ``candidate`` when it is a plain http(s) origin, else ``default``.
+
+ These values are interpolated into request URLs *and* into the
+ ``connect-src`` directive of the Content-Security-Policy header, so a value
+ carrying whitespace, a semicolon or a control character would inject extra
+ CSP sources or directives. Operators set these env vars themselves, so this
+ is a configuration guard rather than a defence against hostile input, but a
+ silently broken policy is the worst way to find that out.
+ """
+ if not candidate:
+ return default
+ if any(ch in _FORBIDDEN_CHARS for ch in candidate) or any(
+ ord(ch) < 0x20 or ord(ch) == 0x7F for ch in candidate
+ ):
+ reason = "contains whitespace, a separator or a control character"
+ elif not candidate.isascii():
+ # Starlette headers are latin-1, so an IDN host in the CSP 500s every
+ # response, and the Tauri builder has no IDNA encoder either.
+ reason = "contains non-ASCII characters; use the punycode (xn--) form of the host"
+ elif (parts := _split(candidate)) is None:
+ # urlsplit RAISES on "https://[", and _build_csp runs on every response.
+ reason = "is not a parseable URL"
+ else:
+ if parts.scheme not in ("http", "https"):
+ reason = "is not an http(s) URL"
+ elif not parts.hostname:
+ reason = "has no host"
+ elif parts.username or parts.password:
+ reason = "carries credentials"
+ elif parts.query or parts.fragment:
+ reason = "carries a query string or fragment"
+ elif not _port_is_valid(parts):
+ # "javascript:alert(1)" becomes a fine URL with a nonsense port.
+ reason = "has an invalid port"
+ elif parts.netloc.endswith(":"):
+ reason = "has an empty port"
+ elif "*" in parts.netloc:
+ reason = "contains a wildcard host"
+ elif parts.scheme == "http" and not is_loopback_host(parts.hostname):
+ # Hub calls carry the user's token, so http off-box puts it on the wire.
+ reason = (
+ "is plain HTTP to a non-loopback host, which would put the Hub token on the wire"
+ )
+ else:
+ # Folded: RFC 3986 3.1, and the frontend keys its cache on this string.
+ return _canonical(parts, parts.scheme + candidate[len(parts.scheme) :])
+ if candidate not in _rejected_warned:
+ _rejected_warned.add(candidate)
+ logger.warning(
+ "%s=%r %s; ignoring it and using %s instead.",
+ var_name,
+ candidate,
+ reason,
+ default,
+ )
+ return default
+
+
+def is_private_host(hostname: str | None) -> bool:
+ """Is this an address literal that is only meaningful on some local network?
+
+ RFC 1918 and friends, plus link-local and unique-local IPv6. Reserved and
+ documentation ranges count too, which is the conservative direction: an
+ address that is not routable on the internet is one whose meaning depends on
+ where you stand. A NAME is not private by this test even if it resolves to
+ such an address: there is nothing here to resolve it with, and a name at
+ least means the same thing to both ends when their DNS agrees.
+ """
+ if not hostname:
+ return False
+ try:
+ address = ipaddress.ip_address(hostname.strip("[]").lower())
+ except ValueError:
+ return False
+ return address.is_private or address.is_link_local
+
+
+def endpoint_is_reachable_by(endpoint: str, client_host: str | None) -> bool:
+ """Would a browser at ``client_host`` reach the SAME host this endpoint names?
+
+ A loopback endpoint names a proxy on the machine the BACKEND runs on, so it
+ means the browser's own localhost anywhere else. A private-network address
+ has the same problem one step out: through the managed tunnel, or from the
+ internet, ``https://10.0.0.5:8443`` is an address on the VISITOR's network,
+ where it is either dead or some unrelated service that would be offered the
+ user's Hub token. A private address is therefore reported only to a client
+ that is itself local, which keeps the ordinary LAN deployment working, and a
+ loopback one only to a loopback client.
+ """
+ parts = _split(endpoint)
+ if parts is None:
+ return True
+ host = parts.hostname
+ if is_loopback_host(host):
+ return is_loopback_host(client_host)
+ if is_private_host(host):
+ return is_loopback_host(client_host) or is_private_host(client_host)
+ return True
+
+
+def client_reachable_endpoint(client_host: str | None) -> str:
+ """The hub endpoint to hand to a browser at ``client_host``.
+
+ Everything the backend does itself keeps using ``get_hf_endpoint()``; this is
+ only for values that leave for a browser (``/api/health``, the publish link).
+ A remote client that cannot reach the configured endpoint gets the official
+ one instead, and the fallback is logged once per configured endpoint so the
+ operator can see why a tunnelled browser is not using the mirror.
+ """
+ endpoint = get_hf_endpoint()
+ if endpoint_is_reachable_by(endpoint, client_host):
+ return endpoint
+ if endpoint not in _unreachable_warned:
+ _unreachable_warned.add(endpoint)
+ logger.warning(
+ "HF_ENDPOINT %s is not reachable from this client (%s); serving %s to "
+ "that browser instead. The backend itself keeps using the configured "
+ "endpoint.",
+ endpoint,
+ client_host or "client address unknown",
+ _DEFAULT_HF_ENDPOINT,
+ )
+ return _DEFAULT_HF_ENDPOINT
+
+
+def _canonical(parts, folded: str) -> str:
+ """Compress an IPv6 literal host, leaving everything else untouched.
+
+ ``http://[0:0:0:0:0:0:0:1]`` and ``http://[::1]`` are the same host, but a
+ CSP host-source is matched as a string (CSP3 6.7.2.5), and the browser sends
+ the compressed form: the uncompressed source would not match its own request
+ and the policy would block the very mirror it names.
+ """
+ host = parts.hostname
+ if not host or ":" not in host:
+ return folded
+ try:
+ compressed = ipaddress.ip_address(host).compressed
+ except ValueError:
+ return folded
+ if compressed == host:
+ return folded
+ netloc = f"[{compressed}]"
+ if parts.port is not None:
+ netloc += f":{parts.port}"
+ return urlunsplit((parts.scheme.lower(), netloc, parts.path, "", ""))
+
+
+def normalize_hf_endpoint_env() -> None:
+ """Make HF_ENDPOINT mean the same thing to huggingface_hub as it does here.
+
+ The library reads the variable itself, at import, with no normalisation and
+ no validation. A scheme-less ``hf-mirror.com`` therefore reaches it verbatim
+ and every ``HfApi`` / ``snapshot_download`` call fails on a missing scheme
+ while Studio's own requests work, and a value this module REJECTS -- a
+ plain-HTTP mirror off the machine, say -- would still be handed the user's
+ Hub token by the library while Studio itself fell back to huggingface.co.
+ Rewriting the variable before huggingface_hub is imported gives the whole
+ process, and the subprocesses that inherit this environment, one endpoint.
+ """
+ if not (os.environ.get("HF_ENDPOINT") or "").strip():
+ return
+ endpoint = get_hf_endpoint()
+ if endpoint == _DEFAULT_HF_ENDPOINT:
+ # Rejected, or the official host: either way, unset asks for the default.
+ os.environ.pop("HF_ENDPOINT", None)
+ else:
+ os.environ["HF_ENDPOINT"] = endpoint
+
+
+def csp_connect_sources() -> tuple[str, str]:
+ """The two endpoints as CSP ``connect-src`` sources, i.e. origins only.
+
+ A CSP host-source carrying a path is matched *exactly* unless the path ends
+ in a solidus (CSP3 6.7.2.7), so listing a path-prefixed mirror verbatim --
+ ``https://hub.internal/hf`` -- allows exactly that one URL and blocks every
+ ``/hf/api/models`` request under it, in Chrome, Edge, Firefox and Safari
+ alike. The path belongs in the request URL, not in the policy, so the source
+ is reduced to scheme://host[:port].
+ """
+ return (_origin_of(get_hf_endpoint()), _origin_of(get_hf_datasets_server()))
+
+
+def csp_asset_sources() -> tuple[str, ...]:
+ """Configured origins that ``img-src``/``media-src`` do not already cover.
+
+ Those directives carry a bare ``https:``, so an https mirror needs nothing
+ added. A loopback HTTP mirror does: its avatars (hf-owner-avatar.ts) and
+ README images (hf-readme.ts) are same-origin-relative to the endpoint, and
+ without this they are blocked while the API calls beside them succeed.
+
+ Returning only the http origins is what keeps an unconfigured deployment's
+ policy byte-identical to the pre-PR one.
+ """
+ return tuple(
+ dict.fromkeys(source for source in csp_connect_sources() if source.startswith("http://"))
+ )
+
+
+def _origin_of(endpoint: str) -> str:
+ parts = urlsplit(endpoint)
+ return f"{parts.scheme}://{parts.netloc}" if parts.netloc else endpoint
+
+
+def get_hf_endpoint() -> str:
+ """Return the configured HuggingFace hub endpoint (no trailing slash).
+
+ Wraps :func:`utils.utils.hf_endpoint_url` so callers get a value that is
+ safe for ``f"{endpoint}/path"`` concatenation.
+ """
+ return _sanitize(hf_endpoint_url().rstrip("/"), _DEFAULT_HF_ENDPOINT, "HF_ENDPOINT")
+
+
+def get_hf_datasets_server() -> str:
+ """Return the datasets-server base URL (no trailing slash).
+
+ Returns ``HF_DATASETS_SERVER`` when set, otherwise the official
+ ``datasets-server.huggingface.co``. A mirrored ``HF_ENDPOINT`` does
+ **not** implicitly apply here — Hub mirrors rarely proxy the
+ datasets-server API, so operators must opt in explicitly.
+ """
+ raw = (os.environ.get("HF_DATASETS_SERVER") or "").strip()
+ if raw:
+ endpoint = raw if "://" in raw else "https://" + raw
+ return _sanitize(endpoint.rstrip("/"), _DEFAULT_DATASETS_SERVER, "HF_DATASETS_SERVER")
+ global _ds_mirror_warned
+ if not _ds_mirror_warned and get_hf_endpoint() != _DEFAULT_HF_ENDPOINT:
+ _ds_mirror_warned = True
+ logger.warning(
+ "HF_ENDPOINT is set to %s but HF_DATASETS_SERVER is unset; "
+ "datasets-server calls will still go to %s. "
+ "Set HF_DATASETS_SERVER to override.",
+ get_hf_endpoint(),
+ _DEFAULT_DATASETS_SERVER,
+ )
+ return _DEFAULT_DATASETS_SERVER
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 447614f2a21..f01bd265271 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1724,8 +1724,11 @@ def _detect_audio_from_tokenizer(
from urllib.parse import quote
revision_path = "main" if revision is None else quote(revision, safe = "")
+ from utils.hf_endpoint import get_hf_endpoint
+
+ hf_endpoint = get_hf_endpoint()
for tok_path in _AUDIO_TOKENIZER_CONFIG_PATHS:
- url = f"https://huggingface.co/{model_name}/resolve/{revision_path}/{tok_path}"
+ url = f"{hf_endpoint}/{model_name}/resolve/{revision_path}/{tok_path}"
try:
resp = requests.get(url, headers = headers, timeout = 15)
except Exception as e:
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 6b6cd735ae0..23e8125ff88 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -834,6 +834,7 @@ def _check_tokenizer_config_needs_v5(model_name: str, hf_token: str | None = Non
return False
# --- Fall back to fetching from HuggingFace ---
+ import urllib.error
import urllib.request
url = _hf_raw_url(model_name, "tokenizer_config.json")
@@ -854,6 +855,34 @@ def _check_tokenizer_config_needs_v5(model_name: str, hf_token: str | None = Non
)
_tokenizer_class_cache[cache_key] = result
return result
+ except urllib.error.HTTPError as exc:
+ # 401/403/404 are legitimate misses: a gated repo read without a token is
+ # normal, not a mirror fault. Anything else means the endpoint answered but
+ # failed, the signature of a mirror that does not proxy /resolve/ paths.
+ if exc.code in (401, 403, 404):
+ logger.debug(
+ "tokenizer_config.json not readable for '%s' at %s: %s", model_name, url, exc
+ )
+ else:
+ logger.warning(
+ "HTTP %s fetching tokenizer_config.json for '%s' from %s; "
+ "if HF_ENDPOINT is set to a mirror, verify it proxies /resolve/ paths",
+ exc.code,
+ model_name,
+ url,
+ )
+ _tokenizer_class_cache[cache_key] = False
+ return False
+ except urllib.error.URLError as exc:
+ logger.warning(
+ "Connection error fetching tokenizer_config.json for '%s' from %s: %s; "
+ "if HF_ENDPOINT is set to a mirror, verify it is reachable",
+ model_name,
+ url,
+ exc,
+ )
+ _tokenizer_class_cache[cache_key] = False
+ return False
except Exception as exc:
logger.debug("Could not fetch tokenizer_config.json for '%s': %s", model_name, exc)
_tokenizer_class_cache[cache_key] = False
@@ -978,7 +1007,16 @@ def _load_config_json(model_name: str, hf_token: str | None = None) -> dict | No
if exc.code in (401, 403, 404):
logger.debug("config.json access denied for '%s': %s", model_name, exc)
return None
- logger.debug("Could not fetch config.json for '%s': %s", model_name, exc)
+ # 5xx: debug here hides a broken mirror behind a later transformers crash.
+ logger.warning(
+ "HTTP %s fetching config.json for '%s' from %s; "
+ "if HF_ENDPOINT is set to a mirror, verify it proxies /resolve/ paths",
+ exc.code,
+ model_name,
+ url,
+ )
+ # Transient: serve the hub cache uncached so the next call retries the network,
+ # but never another caller's cached private metadata.
return None if cache_denied else _config_json_from_hf_cache(model_name)
except Exception as exc:
logger.debug("Could not fetch config.json for '%s': %s", model_name, exc)
diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.ts
index 5ed4259e7ff..efb79670233 100644
--- a/studio/frontend/src/config/env.ts
+++ b/studio/frontend/src/config/env.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { apiUrl } from "@/lib/api-base";
+import { setHfEndpoints } from "@/lib/hf-endpoint";
import {
isDetectionDeferred,
isProvisionalVerdict,
@@ -165,12 +166,18 @@ export async function fetchDeviceType(options?: {
cloudflare_url?: string | null;
server_url?: string | null;
secure?: boolean;
+ hf_endpoint?: string;
+ hf_datasets_server?: string;
};
// Once the store holds an authoritative (server-reported) platform, a non-forced response
// must not overwrite it. It may be an unauthenticated fallback, or an earlier authenticated
// request that resolved after a later forced refresh already picked up device_type and the
// tunnel fields; writing either would reset device type or null the tunnel fields. Forced
// refreshes are explicit re-reads, so they still write.
+ // Before the authoritative-platform guard below: unauthenticated and
+ // idempotent, and a mirror whose first authoritative reply already landed
+ // would otherwise never route its Hub calls.
+ setHfEndpoints(data.hf_endpoint, data.hf_datasets_server);
if (shouldKeepAuthoritativePlatform(options?.force)) {
return usePlatformStore.getState().deviceType;
}
diff --git a/studio/frontend/src/features/data-recipes/learning-recipes/instruction-from-answer.json b/studio/frontend/src/features/data-recipes/learning-recipes/instruction-from-answer.json
index 51af88b2680..6e52d184711 100644
--- a/studio/frontend/src/features/data-recipes/learning-recipes/instruction-from-answer.json
+++ b/studio/frontend/src/features/data-recipes/learning-recipes/instruction-from-answer.json
@@ -24,8 +24,7 @@
"seed_config": {
"source": {
"seed_type": "hf",
- "path": "unsloth/alpaca-cleaned",
- "endpoint": "https://huggingface.co"
+ "path": "unsloth/alpaca-cleaned"
},
"sampling_strategy": "ordered",
"selection_strategy": {
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
index b725de9e3df..abea18abf0b 100644
--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
Popover,
@@ -127,6 +128,8 @@ function BaseModelReference({
baseModelSummary?: string | null;
}) {
const canOpenHub = baseModelSource === "huggingface" && !!baseModelHubId;
+ const hfEndpoint = useHfEndpoint();
+ const hubUrl = `${hfEndpoint}/${baseModelHubId}`;
return (
<div className="flex min-w-0 items-center gap-2 rounded-[10px] border border-border/55 bg-muted/35 px-3 py-2">
<div className="flex size-7 shrink-0 items-center justify-center rounded-[8px] bg-background/70 text-muted-foreground">
@@ -155,18 +158,14 @@ function BaseModelReference({
<Tooltip>
<TooltipTrigger asChild={true}>
<a
- href={`https://huggingface.co/${baseModelHubId}`}
+ href={hubUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Open ${baseModelHubId} on Hugging Face`}
className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
onClick={(event) => {
event.stopPropagation();
- if (
- confirmExternalLink(
- `https://huggingface.co/${baseModelHubId}`,
- )
- ) {
+ if (confirmExternalLink(hubUrl)) {
event.preventDefault();
}
}}
diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
index e46203b0b03..0c7eb7bcc0f 100644
--- a/studio/frontend/src/features/hub/catalog/model-inspector.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import {
Tooltip,
TooltipContent,
@@ -74,7 +75,8 @@ function ViewRepositoryButton({
isDataset: boolean;
}) {
const online = useOnlineStatus();
- const url = `https://huggingface.co/${isDataset ? "datasets/" : ""}${repoId}`;
+ const hfEndpoint = useHfEndpoint();
+ const url = `${hfEndpoint}/${isDataset ? "datasets/" : ""}${repoId}`;
const baseClass =
"inline-flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors";
const icon = (
diff --git a/studio/frontend/src/features/hub/catalog/model-readme.tsx b/studio/frontend/src/features/hub/catalog/model-readme.tsx
index 140abe3bf64..e249bf542ed 100644
--- a/studio/frontend/src/features/hub/catalog/model-readme.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-readme.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import { Spinner } from "@/components/ui/spinner";
import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
import { LruMap } from "@/features/hub/lib/lru-map";
@@ -355,9 +356,10 @@ export function ModelReadme({
const hfToken = useHfTokenStore((s) => s.token);
const online = useOnlineStatus();
const tokenFingerprint = useMemo(() => fingerprintToken(hfToken), [hfToken]);
+ const hfEndpoint = useHfEndpoint();
const stateKey = useMemo(
- () => `${kind}::${repoId}::${tokenFingerprint}`,
- [kind, repoId, tokenFingerprint],
+ () => `${hfEndpoint}::${kind}::${repoId}::${tokenFingerprint}`,
+ [hfEndpoint, kind, repoId, tokenFingerprint],
);
const [state, setState] = useState<ReadmeState>(() => {
const cached = readResolvedReadmeCache(stateKey);
diff --git a/studio/frontend/src/features/hub/catalog/models-table.tsx b/studio/frontend/src/features/hub/catalog/models-table.tsx
index ebfc6880b5c..f5bc3b160bb 100644
--- a/studio/frontend/src/features/hub/catalog/models-table.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-table.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import {
DropdownMenu,
DropdownMenuContent,
@@ -477,7 +478,8 @@ function RowActions({
isDataset: boolean;
onSelect: (id: string) => void;
}) {
- const hfUrl = `https://huggingface.co/${isDataset ? "datasets/" : ""}${row.result.id}`;
+ const hfEndpoint = useHfEndpoint();
+ const hfUrl = `${hfEndpoint}/${isDataset ? "datasets/" : ""}${row.result.id}`;
const actionClass =
"pointer-events-auto inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground/70 transition-colors hover:bg-foreground/[0.07] hover:text-foreground focus-visible:text-foreground data-[state=open]:bg-foreground/[0.07] data-[state=open]:text-foreground";
return (
diff --git a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
index d3685ca266b..46fa9ba9c50 100644
--- a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import {
Tooltip,
TooltipContent,
@@ -73,7 +74,8 @@ export function SafetensorsDownloadCard({
}) {
const hfToken = useHfTokenStore((s) => s.token);
const online = useOnlineStatus();
- const sizeKey = `${repoId}::${fingerprintToken(hfToken)}`;
+ const hfEndpoint = useHfEndpoint();
+ const sizeKey = `${hfEndpoint}::${repoId}::${fingerprintToken(hfToken)}`;
const [modelSize, setModelSize] = useState<{
key: string;
bytes: number | null;
diff --git a/studio/frontend/src/features/hub/hooks/use-dataset-size.ts b/studio/frontend/src/features/hub/hooks/use-dataset-size.ts
index db4623da47d..4d3fb78aaac 100644
--- a/studio/frontend/src/features/hub/hooks/use-dataset-size.ts
+++ b/studio/frontend/src/features/hub/hooks/use-dataset-size.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useHfDatasetsServer } from "@/lib/hf-endpoint";
import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
import { useEffect, useState } from "react";
@@ -17,7 +18,10 @@ export function useDatasetSize(
const enabled = options.enabled ?? true;
const token = options.token || undefined;
const repoKey = repoId ?? "";
- const key = repoKey ? `${repoKey}::${fingerprintToken(token)}` : "";
+ const hfDatasetsServer = useHfDatasetsServer();
+ const key = repoKey
+ ? `${hfDatasetsServer}::${repoKey}::${fingerprintToken(token)}`
+ : "";
const [state, setState] = useState<{
key: string;
value: DatasetSizeInfo | null;
diff --git a/studio/frontend/src/features/hub/hooks/use-feed-write-back.ts b/studio/frontend/src/features/hub/hooks/use-feed-write-back.ts
index 815a17edd66..510d922fb04 100644
--- a/studio/frontend/src/features/hub/hooks/use-feed-write-back.ts
+++ b/studio/frontend/src/features/hub/hooks/use-feed-write-back.ts
@@ -2,9 +2,9 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useEffect, useMemo, useRef } from "react";
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import type { ChannelId } from "../lib/channels";
-import { fingerprintToken } from "../lib/token-fingerprint";
-import { useHubFeedStore } from "../stores/hub-feed-store";
+import { feedIdentity, useHubFeedStore } from "../stores/hub-feed-store";
import type { HfModelResult } from "./use-hub-model-search";
export function useFeedWriteBack(opts: {
@@ -15,9 +15,10 @@ export function useFeedWriteBack(opts: {
}): void {
const { channelId, results, isLoading, accessToken } = opts;
const setChannelEntry = useHubFeedStore((s) => s.setChannelEntry);
+ const hfEndpoint = useHfEndpoint();
const tokenFingerprint = useMemo(
- () => fingerprintToken(accessToken),
- [accessToken],
+ () => feedIdentity(hfEndpoint, accessToken),
+ [hfEndpoint, accessToken],
);
const writtenKeyRef = useRef<string | null>(null);
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
index b3f363ee818..729b6aa1ac5 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
@@ -1,10 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { getHfEndpoint, useHfEndpoint } from "@/lib/hf-endpoint";
import { fetchWithTimeout } from "../lib/network";
import type { HubModelType } from "../types";
import { listDatasets } from "@huggingface/hub";
import { useCallback, useMemo } from "react";
+
import { useHubPaginatedSearch } from "./use-hub-paginated-search";
interface DatasetInfoSplit {
@@ -418,6 +420,7 @@ export function useHubDatasetSearch(
} = options ?? {};
const hasQuery = query.trim().length > 0;
const useCuratedOnly = !hasQuery && !!modelType;
+ const hfEndpoint = useHfEndpoint();
const createIter = useCallback(
(signal: AbortSignal) => {
if (useCuratedOnly) {
@@ -427,10 +430,11 @@ export function useHubDatasetSearch(
search: hasQuery ? { query } : {},
additionalFields: ["cardData", "tags", "createdAt", "downloadsAllTime"],
fetch: makeDatasetSortFetch(sortBy, sortDirection, signal),
+ hubUrl: getHfEndpoint(),
...(accessToken ? { credentials: { accessToken } } : {}),
}) as AsyncGenerator<unknown>;
},
- [useCuratedOnly, hasQuery, query, accessToken, sortBy, sortDirection],
+ [useCuratedOnly, hasQuery, query, accessToken, sortBy, sortDirection, hfEndpoint],
);
const search = useHubPaginatedSearch(createIter, mapDataset, {
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-feed.ts b/studio/frontend/src/features/hub/hooks/use-hub-feed.ts
index 353685baaf8..c4823e6f986 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-feed.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-feed.ts
@@ -2,9 +2,13 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import { type ChannelId, findChannel } from "../lib/channels";
-import { fingerprintToken } from "../lib/token-fingerprint";
-import { isChannelEntryFresh, useHubFeedStore } from "../stores/hub-feed-store";
+import {
+ feedIdentity,
+ isChannelEntryFresh,
+ useHubFeedStore,
+} from "../stores/hub-feed-store";
import {
type HfModelResult,
fetchChannelFirstPage,
@@ -58,9 +62,10 @@ export function useHubFeed(opts: {
deviceType: string | null;
}): UseHubFeedResult {
const { accessToken, online, enabled, deviceType } = opts;
+ const hfEndpoint = useHfEndpoint();
const tokenFingerprint = useMemo(
- () => fingerprintToken(accessToken),
- [accessToken],
+ () => feedIdentity(hfEndpoint, accessToken),
+ [hfEndpoint, accessToken],
);
const channels = useHubFeedStore((s) => s.channels);
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
index ec7b2a53594..d9015685193 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { usePlatformStore } from "@/config/env";
+import { getHfEndpoint, useHfEndpoint } from "@/lib/hf-endpoint";
import type { PipelineType } from "@huggingface/hub";
import { listModels } from "@huggingface/hub";
import {
@@ -304,6 +305,7 @@ async function* mergedModelIterator(
tasks,
(task, taskSignal) =>
listModels({
+ hubUrl: getHfEndpoint(),
search: { query, owner: "unsloth", ...(task ? { task } : {}) },
fetch: makeSortFetch(sortBy, direction, taskSignal),
...common,
@@ -314,6 +316,7 @@ async function* mergedModelIterator(
tasks,
(task, taskSignal) =>
listModels({
+ hubUrl: getHfEndpoint(),
search: { query, ...(task ? { task } : {}) },
fetch: makeSortFetch(sortBy, direction, taskSignal),
...common,
@@ -324,6 +327,7 @@ async function* mergedModelIterator(
// Start the pinned lookup now so it runs in parallel with Phase 1 instead of blocking Phase 2.
const pinnedPromise = pinnedId
? cachedModelInfo({
+ hubUrl: getHfEndpoint(),
name: pinnedId,
additionalFields: ALL_FIELDS,
fetch: makeHfFetch(signal),
@@ -396,6 +400,7 @@ async function* priorityThenListingIterator(
const settled = await Promise.allSettled(
priorityIds.map((id) =>
cachedModelInfo({
+ hubUrl: getHfEndpoint(),
name: id,
additionalFields: ALL_FIELDS,
fetch: makeHfFetch(signal),
@@ -416,6 +421,7 @@ async function* priorityThenListingIterator(
tasks,
(task, taskSignal) =>
listModels({
+ hubUrl: getHfEndpoint(),
search: { owner: "unsloth", ...(task ? { task } : {}) },
fetch: makeSortFetch(sortBy, direction, taskSignal),
...common,
@@ -455,6 +461,7 @@ function createChannelIterator(
channel.tags && channel.tags.length ? [...channel.tags] : undefined;
const queryString = opts.query || channel.query || undefined;
return listModels({
+ hubUrl: getHfEndpoint(),
search: {
...(queryString ? { query: queryString } : {}),
...(channel.owner ? { owner: channel.owner } : {}),
@@ -491,6 +498,7 @@ async function* channelUnslothFirstIterator(
const seen = new Set<string>();
const unslothIter = listModels({
+ hubUrl: getHfEndpoint(),
search: {
...(queryString ? { query: queryString } : {}),
owner: "unsloth",
@@ -510,6 +518,7 @@ async function* channelUnslothFirstIterator(
}
const generalIter = listModels({
+ hubUrl: getHfEndpoint(),
search: {
...(queryString ? { query: queryString } : {}),
...(channel.tags ? { tags: channel.tags } : {}),
@@ -643,6 +652,7 @@ export function useHubModelSearch(
};
}, [query]);
+ const hfEndpoint = useHfEndpoint();
const createIter = useCallback(
(signal: AbortSignal) => {
// Channel scoping bypasses the unsloth-merge iterator: a hard owner/tag filter shows that slice.
@@ -712,6 +722,7 @@ export function useHubModelSearch(
normalizeTaskFilter(task),
(task, taskSignal) =>
listModels({
+ hubUrl: getHfEndpoint(),
// Unsloth-only scope restricts the plain sort browse to the org.
search: {
...(unslothOnly ? { owner: "unsloth" } : {}),
@@ -728,6 +739,7 @@ export function useHubModelSearch(
// Unsloth-only typed query: search within the org rather than floating a few hits globally.
if (unslothOnly) {
return listModels({
+ hubUrl: getHfEndpoint(),
search: { query: searchQuery, owner: "unsloth" },
additionalFields: ALL_FIELDS,
fetch: makeSortFetch(sortBy, sortDirection, signal),
@@ -762,6 +774,7 @@ export function useHubModelSearch(
channelQuery,
pinUnslothFirst,
unslothOnly,
+ hfEndpoint,
],
);
diff --git a/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts b/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts
index 2072f37d557..2f51e945ca2 100644
--- a/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts
+++ b/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { HfModelResult } from "@/features/hub/hooks/use-hub-model-search";
+import { getHfEndpoint, useHfEndpoint } from "@/lib/hf-endpoint";
import { cachedModelInfo } from "../lib/hf-cache";
import { useEffect, useState } from "react";
import { toHfModelResult } from "../lib/view-models";
@@ -26,6 +27,8 @@ export function useSelectedModelMetadata(
error: boolean;
}>(() => ({ repoId: "", result: null, error: false }));
+ const hfEndpoint = useHfEndpoint();
+
useEffect(() => {
if (!(repoId && enabled && online)) {
return;
@@ -37,6 +40,7 @@ export function useSelectedModelMetadata(
let cancelled = false;
cachedModelInfo({
+ hubUrl: getHfEndpoint(),
name: repoId,
...(accessToken ? { accessToken } : {}),
})
@@ -64,7 +68,7 @@ export function useSelectedModelMetadata(
return () => {
cancelled = true;
};
- }, [repoId, accessToken, enabled, online]);
+ }, [repoId, accessToken, enabled, online, hfEndpoint]);
if (state.repoId !== repoId) {
return { result: null, error: false };
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 571b18cfbde..966f568d697 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useAppShellReadySignal } from "@/components/app-readiness";
+import { useHfEndpoint } from "@/lib/hf-endpoint";
import { usePlatformStore } from "@/config/env";
import {
applyActiveModelStatusToStore,
@@ -107,7 +108,6 @@ import {
registerRefresh,
supersedingRefresh,
} from "./lib/superseded-refresh";
-import { fingerprintToken } from "./lib/token-fingerprint";
import { studioPageForTask } from "./lib/unsloth-support";
import {
buildDiscoverRows,
@@ -117,7 +117,11 @@ import {
matchesFormat,
} from "./lib/view-models";
import { hfApiToken, useHfTokenStore } from "./stores/hf-token-store";
-import { isChannelEntryFresh, useHubFeedStore } from "./stores/hub-feed-store";
+import {
+ feedIdentity,
+ isChannelEntryFresh,
+ useHubFeedStore,
+} from "./stores/hub-feed-store";
import type {
CachedInventoryRow,
CapabilityFilter,
@@ -760,9 +764,10 @@ export function ModelsPage() {
const hfToken = useHfTokenStore((s) => s.token);
const debouncedHfToken = useDebouncedValue(hfToken, 500);
const apiHfToken = hfApiToken(debouncedHfToken);
+ const hubHfEndpoint = useHfEndpoint();
const tokenFingerprint = useMemo(
- () => fingerprintToken(apiHfToken),
- [apiHfToken],
+ () => feedIdentity(hubHfEndpoint, apiHfToken),
+ [hubHfEndpoint, apiHfToken],
);
const deferredFormatFilter = useDeferredValue(formatFilter);
const deferredCapabilityFilter = useDeferredValue(capabilityFilter);
diff --git a/studio/frontend/src/features/hub/lib/dataset-size.ts b/studio/frontend/src/features/hub/lib/dataset-size.ts
index dbfe3206912..ef76deb5d6e 100644
--- a/studio/frontend/src/features/hub/lib/dataset-size.ts
+++ b/studio/frontend/src/features/hub/lib/dataset-size.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { getHfDatasetsServerBase, getHfEndpoint } from "@/lib/hf-endpoint";
import { LruMap } from "./lru-map";
import { fetchWithTimeout } from "./network";
import { fingerprintToken } from "./token-fingerprint";
@@ -212,14 +213,15 @@ export function fetchDatasetSize(
typeof tokenOrSignal === "string" ? tokenOrSignal : undefined;
const resolvedSignal =
signal ?? (typeof tokenOrSignal === "string" ? undefined : tokenOrSignal);
- const cacheKey = `${repoId}::${fingerprintToken(resolvedToken)}`;
+ // Server in the key: a 404 here is cached for 24 hours.
+ const cacheKey = `${getHfDatasetsServerBase()}::${repoId}::${fingerprintToken(resolvedToken)}`;
return fetchCachedSize<DatasetSizeInfo>(
cacheKey,
datasetCache,
datasetInflight,
async (signal) => {
const res = await fetchWithTimeout(
- `https://datasets-server.huggingface.co/size?dataset=${encodeURIComponent(repoId)}`,
+ `${getHfDatasetsServerBase()}/size?dataset=${encodeURIComponent(repoId)}`,
{
signal,
headers: resolvedToken
@@ -310,7 +312,8 @@ export function fetchModelSize(
token?: string,
signal?: AbortSignal,
): Promise<ModelSizeInfo | null> {
- const cacheKey = `${repoId}::${fingerprintToken(token)}`;
+ // Endpoint in the key: a model 404 is cached for the whole session.
+ const cacheKey = `${getHfEndpoint()}::${repoId}::${fingerprintToken(token)}`;
return fetchCachedSize<ModelSizeInfo>(
cacheKey,
modelCache,
@@ -318,7 +321,7 @@ export function fetchModelSize(
async (signal) => {
const path = repoId.split("/").map(encodeURIComponent).join("/");
const res = await fetchWithTimeout(
- `https://huggingface.co/api/models/${path}?blobs=true`,
+ `${getHfEndpoint()}/api/models/${path}?blobs=true`,
{
signal,
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
diff --git a/studio/frontend/src/features/hub/lib/hf-cache.ts b/studio/frontend/src/features/hub/lib/hf-cache.ts
index 8860d430ea1..58b091d780b 100644
--- a/studio/frontend/src/features/hub/lib/hf-cache.ts
+++ b/studio/frontend/src/features/hub/lib/hf-cache.ts
@@ -3,6 +3,7 @@
import { type ModelEntry, modelInfo } from "@huggingface/hub";
+import { getHfEndpoint } from "@/lib/hf-endpoint";
import { LruMap } from "./lru-map";
import { fingerprintToken } from "./token-fingerprint";
@@ -69,8 +70,13 @@ function isStale(key: string): boolean {
return !hit || Date.now() - hit.ts >= CACHE_TTL_MS;
}
-function cacheKey(name: string, token: string | undefined): string {
- return `${name}::${fingerprintToken(token)}`;
+// Endpoint in the key: the same repo id names a different repo on a mirror, so a repo-and-token key would serve the old host's answer for the rest of the TTL.
+function cacheKey(
+ name: string,
+ token: string | undefined,
+ hubUrl?: string,
+): string {
+ return `${hubUrl || getHfEndpoint()}::${name}::${fingerprintToken(token)}`;
}
function extractToken(
@@ -98,7 +104,7 @@ export async function cachedModelInfo(
params: Parameters<typeof modelInfo>[0],
): Promise<CachedResult> {
const token = extractToken(params);
- const key = cacheKey(params.name, token);
+ const key = cacheKey(params.name, token, params.hubUrl);
if (!isStale(key)) return cache.get(key)!.data;
const flying = inflight.get(key);
@@ -124,7 +130,7 @@ export async function cachedModelInfo(
private?: boolean;
};
if (token && !typed.private && !typed.gated) {
- const anonKey = cacheKey(params.name, undefined);
+ const anonKey = cacheKey(params.name, undefined, params.hubUrl);
if (isStale(anonKey)) cache.set(anonKey, entry);
}
return result as CachedResult;
diff --git a/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts b/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts
index 6e83cfe3c50..6751ff95346 100644
--- a/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts
+++ b/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useEffect, useState } from "react";
+import { getHfEndpoint, useHfEndpoint } from "@/lib/hf-endpoint";
import { LruMap } from "@/features/hub/lib/lru-map";
import { fetchWithTimeout } from "@/features/hub/lib/network";
import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
@@ -58,10 +59,15 @@ function release(): void {
waiting.shift()?.();
}
+// Keyed by endpoint too: a hit is held 24 hours and a 404 permanently, so a default-host entry would outlive a late mirror.
+function avatarKey(name: string): string {
+ return `${getHfEndpoint()}::${name}`;
+}
+
// Expired transient misses report "no entry" so the caller refetches, but the
// entry is kept so its failure count can escalate the next backoff.
function readCache(name: string): AvatarCacheEntry | null {
- const entry = cache.get(name);
+ const entry = cache.get(avatarKey(name));
if (!entry) return null;
if (entry.kind === "miss-transient" && Date.now() >= entry.until) {
return null;
@@ -76,7 +82,7 @@ function readCachedUrl(name: string): string | null {
}
function transientMiss(name: string): AvatarCacheEntry {
- const prev = cache.get(name);
+ const prev = cache.get(avatarKey(name));
const failures = prev?.kind === "miss-transient" ? prev.failures + 1 : 1;
const ttl = Math.min(
TRANSIENT_MISS_BASE_TTL_MS * 2 ** (failures - 1),
@@ -89,8 +95,8 @@ async function fetchAvatarUrl(
name: string,
): Promise<{ url: string | null; transient: boolean }> {
const candidates = [
- `https://huggingface.co/api/organizations/${encodeURIComponent(name)}/overview`,
- `https://huggingface.co/api/users/${encodeURIComponent(name)}/overview`,
+ `${getHfEndpoint()}/api/organizations/${encodeURIComponent(name)}/overview`,
+ `${getHfEndpoint()}/api/users/${encodeURIComponent(name)}/overview`,
];
let sawTransient = false;
@@ -108,7 +114,7 @@ async function fetchAvatarUrl(
if (data.avatarUrl) {
const resolved = data.avatarUrl.startsWith("http")
? data.avatarUrl
- : `https://huggingface.co${data.avatarUrl}`;
+ : `${getHfEndpoint()}${data.avatarUrl}`;
return { url: resolved, transient: false };
}
continue;
@@ -125,7 +131,8 @@ async function fetchAvatarUrl(
}
function loadAvatar(name: string): Promise<string | null> {
- const existing = inflight.get(name);
+ const key = avatarKey(name);
+ const existing = inflight.get(key);
if (existing) return existing;
const promise = acquire()
.then(() => fetchAvatarUrl(name))
@@ -133,22 +140,22 @@ function loadAvatar(name: string): Promise<string | null> {
.then(
({ url, transient }) => {
if (url) {
- cache.set(name, { kind: "url", url, expiresAt: Date.now() + URL_TTL_MS });
+ cache.set(key, { kind: "url", url, expiresAt: Date.now() + URL_TTL_MS });
} else if (transient) {
- cache.set(name, transientMiss(name));
+ cache.set(key, transientMiss(name));
} else {
- cache.set(name, { kind: "miss-permanent" });
+ cache.set(key, { kind: "miss-permanent" });
}
- inflight.delete(name);
+ inflight.delete(key);
return url;
},
() => {
- cache.set(name, transientMiss(name));
- inflight.delete(name);
+ cache.set(key, transientMiss(name));
+ inflight.delete(key);
return null;
},
);
- inflight.set(name, promise);
+ inflight.set(key, promise);
return promise;
}
@@ -158,6 +165,7 @@ export function useHfOwnerAvatar(
): string | null {
const key = owner?.trim() ?? "";
const online = useOnlineStatus();
+ const hfEndpoint = useHfEndpoint();
const [state, setState] = useState<{ key: string; url: string | null }>(() => {
return { key, url: readCachedUrl(key) };
});
@@ -224,7 +232,7 @@ export function useHfOwnerAvatar(
if (retryTimer != null) clearTimeout(retryTimer);
if (fetchTimer != null) clearTimeout(fetchTimer);
};
- }, [key, online, enabled]);
+ }, [key, online, enabled, hfEndpoint]);
return url;
}
diff --git a/studio/frontend/src/features/hub/lib/hf-readme.ts b/studio/frontend/src/features/hub/lib/hf-readme.ts
index d68df2b808e..70ae348b615 100644
--- a/studio/frontend/src/features/hub/lib/hf-readme.ts
+++ b/studio/frontend/src/features/hub/lib/hf-readme.ts
@@ -4,6 +4,7 @@
import { LruMap } from "@/features/hub/lib/lru-map";
import { fetchWithTimeout } from "@/features/hub/lib/network";
import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
+import { getHfEndpoint } from "@/lib/hf-endpoint";
import { defaultUrlTransform, type UrlTransform } from "streamdown";
export type ReadmeKind = "model" | "dataset";
@@ -38,7 +39,7 @@ export function readmeBaseUrl(
kind: ReadmeKind,
branch: "main" | "master" = "main",
): string {
- return `https://huggingface.co/${readmePrefix(kind)}${repoId}/resolve/${branch}/`;
+ return `${getHfEndpoint()}/${readmePrefix(kind)}${repoId}/resolve/${branch}/`;
}
async function fetchReadmeOnce(
@@ -52,7 +53,9 @@ async function fetchReadmeOnce(
let transient = false;
for (const branch of ["main", "master"] as const) {
try {
- const url = `https://huggingface.co/${prefix}${repoId}/raw/${branch}/README.md`;
+ // /resolve, not /raw: /raw is a huggingface.co web route a mirror need not
+ // serve, and README.md is never LFS.
+ const url = `${getHfEndpoint()}/${prefix}${repoId}/resolve/${branch}/README.md`;
const res = await fetchWithTimeout(
url,
{
@@ -80,7 +83,9 @@ export function fetchReadme(
kind: ReadmeKind = "model",
token: string | null = null,
): Promise<FetchedReadme | null> {
- const key = `${kind}::${repoId}::${fingerprintToken(token)}`;
+ // Endpoint in the key: a card is cached with no expiry, so one from the default
+ // host would be shown all session without the mirror being asked.
+ const key = `${getHfEndpoint()}::${kind}::${repoId}::${fingerprintToken(token)}`;
const cached = cache.get(key);
if (cached && Date.now() < cached.staleAt) return cached.promise;
diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.ts
index 9c3cec6244e..c299fdebe15 100644
--- a/studio/frontend/src/features/hub/lib/network.ts
+++ b/studio/frontend/src/features/hub/lib/network.ts
@@ -1,11 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { getHfEndpoint } from "@/lib/hf-endpoint";
+
const NETWORK_STATUS_EVENT = "unsloth-network-status";
const REMOTE_OFFLINE_TTL_MS = 30_000;
const HUGGING_FACE_ORIGIN = "https://huggingface.co";
const noopUnsubscribe = () => undefined;
+/**
+ * Origin the Hub traffic actually goes to. The backoff maps key on the request
+ * origin, so this has to follow HF_ENDPOINT too: keying a mirror deployment on
+ * huggingface.co would probe an origin nothing ever talks to.
+ */
+function defaultHubOrigin(): string {
+ try {
+ return new URL(getHfEndpoint()).origin;
+ } catch {
+ return HUGGING_FACE_ORIGIN;
+ }
+}
+
type RemoteNetworkScope = string | readonly string[];
/**
@@ -111,7 +126,7 @@ function getEarliestRemoteOfflineUntil(): number {
}
export function isRemoteNetworkOffline(
- scope: RemoteNetworkScope = HUGGING_FACE_ORIGIN,
+ scope: RemoteNetworkScope = defaultHubOrigin(),
): boolean {
return getRemoteOfflineUntil(scope) > Date.now();
}
@@ -120,7 +135,7 @@ export function isHuggingFaceOffline(): boolean {
// navigator.onLine is advisory only (false-reports offline on WSL2 / some WebKitGTK/Tauri
// webviews). The authoritative signal is the empirical remote-offline TTL, set when a real fetch
// fails and cleared on next success; navigator's online/offline events still drive re-evaluation.
- return isRemoteNetworkOffline(HUGGING_FACE_ORIGIN);
+ return isRemoteNetworkOffline(defaultHubOrigin());
}
/**
@@ -129,7 +144,7 @@ export function isHuggingFaceOffline(): boolean {
*/
export type HubPhase = "available" | "probing" | "unavailable";
-export function getHubPhase(origin: string = HUGGING_FACE_ORIGIN): HubPhase {
+export function getHubPhase(origin: string = defaultHubOrigin()): HubPhase {
if (!lastFailureByOrigin.has(origin)) {
return "available";
}
@@ -137,7 +152,7 @@ export function getHubPhase(origin: string = HUGGING_FACE_ORIGIN): HubPhase {
}
export function getLastHubFailure(
- origin: string = HUGGING_FACE_ORIGIN,
+ origin: string = defaultHubOrigin(),
): HubFailure | null {
return lastFailureByOrigin.get(origin) ?? null;
}
@@ -165,12 +180,12 @@ export function markRemoteNetworkOnline(origin?: string): void {
}
export function markRemoteNetworkOffline(
- originOrTtl: string | number = HUGGING_FACE_ORIGIN,
+ originOrTtl: string | number = defaultHubOrigin(),
ttlMs = REMOTE_OFFLINE_TTL_MS,
failure?: HubFailure,
): void {
const origin =
- typeof originOrTtl === "string" ? originOrTtl : HUGGING_FACE_ORIGIN;
+ typeof originOrTtl === "string" ? originOrTtl : defaultHubOrigin();
const ttl = typeof originOrTtl === "number" ? originOrTtl : ttlMs;
const nextUntil = Date.now() + ttl;
const previousUntil = remoteOfflineUntilByOrigin.get(origin) ?? 0;
@@ -197,7 +212,7 @@ export function markRemoteNetworkOffline(
/** Let Retry re-probe now. The failure stays until a request succeeds. */
export function clearRemoteBackoff(
- origin: string = HUGGING_FACE_ORIGIN,
+ origin: string = defaultHubOrigin(),
): void {
if (!remoteOfflineUntilByOrigin.delete(origin)) {
return;
diff --git a/studio/frontend/src/features/hub/stores/hub-feed-store.ts b/studio/frontend/src/features/hub/stores/hub-feed-store.ts
index 1a57c09b7c5..bde575bd7f8 100644
--- a/studio/frontend/src/features/hub/stores/hub-feed-store.ts
+++ b/studio/frontend/src/features/hub/stores/hub-feed-store.ts
@@ -5,6 +5,7 @@ import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import type { HfModelResult } from "../hooks/use-hub-model-search";
import { type ChannelId, findChannel } from "../lib/channels";
+import { fingerprintToken } from "../lib/token-fingerprint";
import { createThrottledStorage, noopStorage } from "./persist-storage";
export interface ChannelFeedEntry {
@@ -24,6 +25,19 @@ export interface HubFeedState {
clearForToken: (tokenFingerprint: string) => void;
}
+/**
+ * What a persisted feed entry belongs to: the endpoint AND the token. Freshness
+ * is an equality check on this, so folding the endpoint in stops a huggingface.co
+ * feed being rendered after Studio restarts against a mirror. Entries from an
+ * older build hold a bare fingerprint and are refetched once.
+ */
+export function feedIdentity(
+ endpoint: string,
+ token: string | null | undefined,
+): string {
+ return `${endpoint}::${fingerprintToken(token)}`;
+}
+
export const FEED_CACHE_CAP = 24;
export const FEED_TTL_MS: Record<ChannelId, number> = {
diff --git a/studio/frontend/src/features/images/train/example-dataset-cards.tsx b/studio/frontend/src/features/images/train/example-dataset-cards.tsx
index 612a45d9c47..6b269ad447d 100644
--- a/studio/frontend/src/features/images/train/example-dataset-cards.tsx
+++ b/studio/frontend/src/features/images/train/example-dataset-cards.tsx
@@ -9,6 +9,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import { getHfDatasetsServerBase, useHfDatasetsServer } from "@/lib/hf-endpoint";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
@@ -24,12 +25,16 @@ import {
const _previewCache = new Map<string, Promise<string[]>>();
async function fetchPreviews(repo: string): Promise<string[]> {
- const cached = _previewCache.get(repo);
+ // Keyed by server too: an empty result cached against the default would
+ // otherwise never be retried against a mirror that arrives later.
+ const base = getHfDatasetsServerBase();
+ const cacheKey = `${base}::${repo}`;
+ const cached = _previewCache.get(cacheKey);
if (cached) return cached;
const p = (async () => {
try {
const res = await fetch(
- `https://datasets-server.huggingface.co/first-rows?dataset=${encodeURIComponent(
+ `${base}/first-rows?dataset=${encodeURIComponent(
repo,
)}&config=default&split=train`,
);
@@ -51,7 +56,7 @@ async function fetchPreviews(repo: string): Promise<string[]> {
return [];
}
})();
- _previewCache.set(repo, p);
+ _previewCache.set(cacheKey, p);
return p;
}
@@ -62,6 +67,7 @@ export function shortExampleLabel(label: string): string {
function ExamplePreviews({ repo }: { repo: string }) {
const [urls, setUrls] = useState<string[] | null>(null);
+ const hfDatasetsServer = useHfDatasetsServer();
useEffect(() => {
let cancelled = false;
void fetchPreviews(repo).then((u) => {
@@ -70,7 +76,7 @@ function ExamplePreviews({ repo }: { repo: string }) {
return () => {
cancelled = true;
};
- }, [repo]);
+ }, [repo, hfDatasetsServer]);
if (!urls || urls.length === 0) return null;
return (
diff --git a/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts b/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts
index 4ba704d21c3..2ccad7207a2 100644
--- a/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts
+++ b/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts
@@ -450,7 +450,8 @@ export const useRecipeStudioStore = create<RecipeStudioState>((set, get) => ({
hf_split: "",
hf_path: "",
hf_token: "",
- hf_endpoint: "https://huggingface.co",
+ // Blank so buildSeedConfig resolves the endpoint at build time.
+ hf_endpoint: "",
local_file_name: "",
unstructured_upload_uid:
nextSourceType === "unstructured" ? makeUnstructuredUploadUid() : "",
diff --git a/studio/frontend/src/features/recipe-studio/utils/config-factories.ts b/studio/frontend/src/features/recipe-studio/utils/config-factories.ts
index d47bac88583..74e95643e7f 100644
--- a/studio/frontend/src/features/recipe-studio/utils/config-factories.ts
+++ b/studio/frontend/src/features/recipe-studio/utils/config-factories.ts
@@ -406,7 +406,10 @@ export function makeSeedConfig(
hf_split: "",
hf_path: "",
hf_token: "",
- hf_endpoint: "https://huggingface.co",
+ // Empty, not getHfEndpoint(): a seed created before /api/health reports the
+ // mirror would pin the official host into the recipe, and the field is not
+ // user-editable. buildSeedConfig resolves a blank one at build time.
+ hf_endpoint: "",
local_file_name: "",
...(seedSourceType === "unstructured"
? { unstructured_upload_uid: makeUnstructuredUploadUid() }
diff --git a/studio/frontend/src/features/recipe-studio/utils/import/parsers/seed-config-parser.ts b/studio/frontend/src/features/recipe-studio/utils/import/parsers/seed-config-parser.ts
index 467d77b0f84..c9717ba1d42 100644
--- a/studio/frontend/src/features/recipe-studio/utils/import/parsers/seed-config-parser.ts
+++ b/studio/frontend/src/features/recipe-studio/utils/import/parsers/seed-config-parser.ts
@@ -28,7 +28,7 @@ function makeDefaultSeedConfig(id: string): SeedConfig {
hf_split: "",
hf_path: "",
hf_token: "",
- hf_endpoint: "https://huggingface.co",
+ hf_endpoint: "",
local_file_name: "",
unstructured_file_ids: [],
unstructured_file_names: [],
@@ -71,7 +71,9 @@ function parseSeedSettings(seedConfigRaw: unknown): Partial<SeedConfig> {
let seed_source_type: SeedSourceType = "hf";
let hf_path = "";
let hf_token = "";
- let hf_endpoint = "https://huggingface.co";
+ // Blank unless the imported recipe names one, so an endpoint that arrives
+ // later is still picked up when the payload is built.
+ let hf_endpoint = "";
let hf_repo_id = "";
let local_file_name = "";
let unstructuredFileIds: string[] = [];
diff --git a/studio/frontend/src/features/recipe-studio/utils/payload/builders-seed.ts b/studio/frontend/src/features/recipe-studio/utils/payload/builders-seed.ts
index eaa185021aa..333e0c1cea7 100644
--- a/studio/frontend/src/features/recipe-studio/utils/payload/builders-seed.ts
+++ b/studio/frontend/src/features/recipe-studio/utils/payload/builders-seed.ts
@@ -34,7 +34,10 @@ export function buildSeedConfig(
const seedSourceType = config.seed_source_type ?? "hf";
const path = config.hf_path.trim();
- const endpoint = config.hf_endpoint?.trim() || "https://huggingface.co";
+ // Only an endpoint the user set. The seed is fetched BY THE BACKEND, which
+ // resolves its own HF_ENDPOINT when this is absent; sending the browser's value
+ // would ship a remote client's substitute into a backend-side fetch.
+ const endpoint = config.hf_endpoint?.trim() || null;
const token = config.hf_token?.trim() || null;
let selectionStrategy: Record<string, unknown> | null = null;
diff --git a/studio/frontend/src/hooks/use-hf-dataset-splits.ts b/studio/frontend/src/hooks/use-hf-dataset-splits.ts
index c5fcff3f15e..9128321559a 100644
--- a/studio/frontend/src/hooks/use-hf-dataset-splits.ts
+++ b/studio/frontend/src/hooks/use-hf-dataset-splits.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { authFetch } from "@/features/auth";
+import { getHfDatasetsServerBase, useHfDatasetsServer } from "@/lib/hf-endpoint";
import { useEffect, useState } from "react";
import {
type DatasetSplitFetchers,
@@ -41,7 +42,11 @@ export interface HfDatasetSplitsResult {
requiresManualEntry: boolean;
}
-const HF_SPLITS_API = "https://datasets-server.huggingface.co/splits";
+// Datasets-server base is independent of the Hub mirror: HF_ENDPOINT does not
+// redirect it, only HF_DATASETS_SERVER (surfaced via /api/health) does.
+function getHfSplitsApi(): string {
+ return `${getHfDatasetsServerBase()}/splits`;
+}
const MAX_SPLIT_ENTRIES = 2048;
function validatedEntries(value: unknown): HfSplitEntry[] {
@@ -100,7 +105,7 @@ async function fetchRemoteSplits({
datasetName,
signal,
}: LoadHfDatasetSplitsArgs): Promise<HfSplitEntry[]> {
- const url = `${HF_SPLITS_API}?dataset=${encodeURIComponent(datasetName)}`;
+ const url = `${getHfSplitsApi()}?dataset=${encodeURIComponent(datasetName)}`;
const headers: Record<string, string> = {};
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
@@ -138,11 +143,15 @@ export function useHfDatasetSplits(
const [entries, setEntries] = useState<HfSplitEntry[]>([]);
const [isLoading, setIsLoading] = useState(datasetName !== null);
const [error, setError] = useState<string | null>(null);
+ // In the request identity, or a server arriving later leaves the selector on
+ // the official one, or on the failure it reached there.
+ const hfDatasetsServer = useHfDatasetsServer();
const requestKey = JSON.stringify([
datasetName,
options?.preferLocalCache === true,
options?.localPath ?? null,
options?.online !== false,
+ hfDatasetsServer,
]);
const [previousRequestKey, setPreviousRequestKey] = useState(requestKey);
if (requestKey !== previousRequestKey) {
@@ -210,7 +219,7 @@ export function useHfDatasetSplits(
});
return () => controller.abort();
- }, [accessToken, datasetName, localPath, online, preferLocalCache]);
+ }, [accessToken, datasetName, localPath, online, preferLocalCache, hfDatasetsServer]);
// Derive unique subsets
const subsets = Array.from(new Set(entries.map((e) => e.config)));
diff --git a/studio/frontend/src/lib/hf-endpoint.ts b/studio/frontend/src/lib/hf-endpoint.ts
new file mode 100644
index 00000000000..38336f394e4
--- /dev/null
+++ b/studio/frontend/src/lib/hf-endpoint.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The frontend's HuggingFace endpoints, held in one place. `config/env.ts` pushes
+ * the values in when `/api/health` answers.
+ *
+ * A store, not plain module state, so React sees it change. Imports only zustand,
+ * deliberately: `network.ts` imports this and the unit tests import that under bare
+ * node, which cannot evaluate what `config/env.ts` would bring.
+ */
+
+import { useStore } from "zustand";
+import { createStore } from "zustand/vanilla";
+
+export const DEFAULT_HF_ENDPOINT = "https://huggingface.co";
+export const DEFAULT_DATASETS_SERVER = "https://datasets-server.huggingface.co";
+
+const store = createStore<{ endpoint: string; datasetsServer: string }>(() => ({
+ endpoint: DEFAULT_HF_ENDPOINT,
+ datasetsServer: DEFAULT_DATASETS_SERVER,
+}));
+
+/**
+ * Accept a value from `/api/health` only if it parses as an http(s) URL. Not a
+ * second copy of the backend's policy: `utils/hf_endpoint.py` is the only
+ * producer and has already sanitised and canonicalised it. Deciding the rules
+ * twice is what made the two disagree about an IDN host and an IPv6 literal.
+ */
+function usableEndpoint(raw: string | null | undefined): string | null {
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ try {
+ const { protocol } = new URL(trimmed);
+ if (protocol !== "https:" && protocol !== "http:") return null;
+ } catch {
+ return null;
+ }
+ return trimmed.replace(/\/+$/, "");
+}
+
+/**
+ * Apply the endpoints reported by `/api/health`. A blank, absent or unparseable
+ * value leaves the current one alone: older backends report neither field, and
+ * resetting would strand a mirror-only deployment on huggingface.co.
+ */
+export function setHfEndpoints(
+ endpoint?: string | null,
+ datasetsServer?: string | null,
+): void {
+ const next = {
+ endpoint: usableEndpoint(endpoint),
+ datasetsServer: usableEndpoint(datasetsServer),
+ };
+ store.setState((prev) => ({
+ endpoint: next.endpoint ?? prev.endpoint,
+ datasetsServer: next.datasetsServer ?? prev.datasetsServer,
+ }));
+}
+
+export function resetHfEndpoints(): void {
+ store.setState({
+ endpoint: DEFAULT_HF_ENDPOINT,
+ datasetsServer: DEFAULT_DATASETS_SERVER,
+ });
+}
+
+export function getHfEndpoint(): string {
+ return store.getState().endpoint;
+}
+
+export function getHfDatasetsServerBase(): string {
+ return store.getState().datasetsServer;
+}
+
+/** Subscribed, so a mirror arriving after the first render re-runs the caller. */
+export function useHfEndpoint(): string {
+ return useStore(store, (s) => s.endpoint);
+}
+
+export function useHfDatasetsServer(): string {
+ return useStore(store, (s) => s.datasetsServer);
+}
diff --git a/studio/frontend/tests/hf-endpoint.test.ts b/studio/frontend/tests/hf-endpoint.test.ts
new file mode 100644
index 00000000000..765bef27922
--- /dev/null
+++ b/studio/frontend/tests/hf-endpoint.test.ts
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Two things here are easy to get wrong: the module must stay importable under
+ * bare node (network.ts imports it, and the tests import that directly), and a
+ * reply omitting the fields must not reset a configured mirror.
+ */
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./bundler-resolver.mjs", import.meta.url);
+
+const {
+ DEFAULT_DATASETS_SERVER,
+ DEFAULT_HF_ENDPOINT,
+ getHfDatasetsServerBase,
+ getHfEndpoint,
+ resetHfEndpoints,
+ setHfEndpoints,
+ useHfDatasetsServer,
+ useHfEndpoint,
+} = await import("../src/lib/hf-endpoint.ts");
+
+const { isHuggingFaceOffline, markRemoteNetworkOffline, clearRemoteBackoff } =
+ await import("../src/features/hub/lib/network.ts");
+
+test("before /api/health answers, both endpoints are the official ones", () => {
+ resetHfEndpoints();
+ assert.equal(getHfEndpoint(), "https://huggingface.co");
+ assert.equal(
+ getHfDatasetsServerBase(),
+ "https://datasets-server.huggingface.co",
+ );
+ assert.equal(DEFAULT_HF_ENDPOINT, "https://huggingface.co");
+ assert.equal(
+ DEFAULT_DATASETS_SERVER,
+ "https://datasets-server.huggingface.co",
+ );
+});
+
+test("the hooks React subscribes to are the same state the getters read", () => {
+ // The hooks are thin useStore wrappers, so what matters is that they read the
+ // one store the setter writes, not a second copy kept in sync by hand.
+ resetHfEndpoints();
+ assert.equal(typeof useHfEndpoint, "function");
+ assert.equal(typeof useHfDatasetsServer, "function");
+ setHfEndpoints("https://hf-mirror.com", "https://ds.example.com");
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ assert.equal(getHfDatasetsServerBase(), "https://ds.example.com");
+});
+
+test("a mirror reported by the backend is applied to both getters", () => {
+ resetHfEndpoints();
+ setHfEndpoints("https://hf-mirror.com", "https://ds.example.com");
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ assert.equal(getHfDatasetsServerBase(), "https://ds.example.com");
+});
+
+test("a reported endpoint is stored as sent, minus trailing slashes", () => {
+ // Already sanitised and canonicalised by the backend; only the trailing slash
+ // is dropped, since every consumer builds `${getHfEndpoint()}/path`.
+ for (const [raw, expected] of [
+ ["https://hf-mirror.com", "https://hf-mirror.com"],
+ ["https://hf-mirror.com/", "https://hf-mirror.com"],
+ ["https://hf-mirror.com///", "https://hf-mirror.com"],
+ [" https://hf-mirror.com ", "https://hf-mirror.com"],
+ ["http://127.0.0.1:9700", "http://127.0.0.1:9700"],
+ ["http://[::1]:9700", "http://[::1]:9700"],
+ ["https://hub.internal:8443/hf/", "https://hub.internal:8443/hf"],
+ ["https://xn--fsqu00a.xn--0zwm56d", "https://xn--fsqu00a.xn--0zwm56d"],
+ ] as const) {
+ resetHfEndpoints();
+ setHfEndpoints(raw, null);
+ assert.equal(getHfEndpoint(), expected, `for ${raw}`);
+ }
+});
+
+test("an older backend that reports neither field keeps the configured mirror", () => {
+ // An older Studio carries no hf_endpoint: resetting would strand a mirror-only
+ // deployment on a host it cannot reach.
+ resetHfEndpoints();
+ setHfEndpoints("https://hf-mirror.com", "https://ds.example.com");
+ setHfEndpoints(undefined, undefined);
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ assert.equal(getHfDatasetsServerBase(), "https://ds.example.com");
+ setHfEndpoints(null, null);
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ setHfEndpoints("", " ");
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ assert.equal(getHfDatasetsServerBase(), "https://ds.example.com");
+});
+
+test("a value that does not parse as an http(s) URL is ignored", () => {
+ // Not a second copy of the policy: only a value that would throw inside
+ // `new URL(getHfEndpoint())` is kept out.
+ for (const junk of [
+ "javascript:alert(1)",
+ "file:///etc/passwd",
+ "data:text/html,x",
+ "ftp://hf-mirror.com",
+ "https://",
+ "hf-mirror.com",
+ "not a url",
+ ]) {
+ resetHfEndpoints();
+ setHfEndpoints(junk, junk);
+ assert.equal(getHfEndpoint(), DEFAULT_HF_ENDPOINT, `for ${junk}`);
+ assert.equal(getHfDatasetsServerBase(), DEFAULT_DATASETS_SERVER, `for ${junk}`);
+ }
+});
+
+test("a non-string value cannot crash the getter", () => {
+ resetHfEndpoints();
+ for (const junk of [42, {}, [], true, () => undefined]) {
+ setHfEndpoints(junk as unknown as string, junk as unknown as string);
+ }
+ assert.equal(getHfEndpoint(), "https://huggingface.co");
+});
+
+test("the datasets server stays independent of the hub mirror", () => {
+ // Most mirrors do not proxy /splits, so HF_ENDPOINT alone must not redirect it.
+ resetHfEndpoints();
+ setHfEndpoints("https://hf-mirror.com", undefined);
+ assert.equal(getHfEndpoint(), "https://hf-mirror.com");
+ assert.equal(
+ getHfDatasetsServerBase(),
+ "https://datasets-server.huggingface.co",
+ );
+});
+
+test("the Hub offline backoff keys on the configured mirror, not huggingface.co", () => {
+ // The backoff maps key on the request origin: keying a mirror deployment on
+ // huggingface.co would report the Hub healthy while every request failed.
+ resetHfEndpoints();
+ setHfEndpoints("https://hf-mirror.com", undefined);
+ clearRemoteBackoff("https://hf-mirror.com");
+ assert.equal(isHuggingFaceOffline(), false);
+ markRemoteNetworkOffline("https://hf-mirror.com", 60_000, {
+ kind: "network-opaque",
+ message: "the mirror could not be reached",
+ origin: "https://hf-mirror.com",
+ retryable: true,
+ });
+ assert.equal(isHuggingFaceOffline(), true);
+ clearRemoteBackoff("https://hf-mirror.com");
+ assert.equal(isHuggingFaceOffline(), false);
+ resetHfEndpoints();
+});
diff --git a/studio/frontend/tests/hub-network-availability.test.ts b/studio/frontend/tests/hub-network-availability.test.ts
index 6e766c63b6a..e81efd43f51 100644
--- a/studio/frontend/tests/hub-network-availability.test.ts
+++ b/studio/frontend/tests/hub-network-availability.test.ts
@@ -2,9 +2,14 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
+import { register } from "node:module";
import test from "node:test";
-import {
+// network.ts resolves the Hub origin through "@/lib/hf-endpoint", the way vite
+// resolves the alias. Bare node does not, so the import has to go through the
+// resolver, which in turn means a dynamic import after register().
+register("./bundler-resolver.mjs", import.meta.url);
+const {
classifyFetchFailure,
clearRemoteBackoff,
fetchWithTimeout,
@@ -17,7 +22,7 @@ import {
markRemoteNetworkOffline,
markRemoteNetworkOnline,
sanitizeHubErrorMessage,
-} from "../src/features/hub/lib/network.ts";
+} = await import("../src/features/hub/lib/network.ts");
import { readSrcAsync } from "./helpers/kit.ts";
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
index 949eed29d59..bf513e1ecc4 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -54,6 +54,13 @@ struct DesktopBackendMetadata {
studio_root_id: String,
started_at_ms: u64,
updated_at_ms: u64,
+ // The endpoints this backend was launched with. A process that adopts it may
+ // have a different environment, and builds its CSP before it can ask
+ // /api/health. Absent in older files, hence the defaults.
+ #[serde(default)]
+ hf_endpoint: Option<String>,
+ #[serde(default)]
+ hf_datasets_server: Option<String>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -470,6 +477,29 @@ fn metadata_path() -> Option<PathBuf> {
dirs::home_dir().map(|home| metadata_path_for_home(&home))
}
+fn non_empty_env(key: &str) -> Option<String> {
+ std::env::var(key)
+ .ok()
+ .map(|value| value.trim().to_string())
+ .filter(|value| !value.is_empty())
+}
+
+/// The endpoints recorded by whichever process started the backend still
+/// running, so this one can allow them in its CSP. Best effort: a missing,
+/// unreadable or older file yields nothing.
+pub(crate) fn recorded_hf_endpoints() -> Vec<String> {
+ let Some(path) = metadata_path() else {
+ return Vec::new();
+ };
+ let Ok(Some(metadata)) = read_metadata(&path) else {
+ return Vec::new();
+ };
+ [metadata.hf_endpoint, metadata.hf_datasets_server]
+ .into_iter()
+ .flatten()
+ .collect()
+}
+
pub(crate) fn token_sha256(token: &str) -> String {
hex_bytes(&Sha256::digest(token.as_bytes()))
}
@@ -530,6 +560,8 @@ pub(crate) fn activate_owner(
studio_root_id: pending.studio_root_id,
started_at_ms: now,
updated_at_ms: now,
+ hf_endpoint: non_empty_env("HF_ENDPOINT"),
+ hf_datasets_server: non_empty_env("HF_DATASETS_SERVER"),
};
let state = BackendOwnerState { path, metadata };
state.write().map_err(|error| {
@@ -769,6 +801,8 @@ pub(crate) fn install_test_owner(root_id: &str, token: &str) {
studio_root_id: root_id.to_string(),
started_at_ms: 1,
updated_at_ms: 1,
+ hf_endpoint: None,
+ hf_datasets_server: None,
};
*TEST_EXPECTED_STUDIO_ROOT_ID.lock().unwrap() = Some(root_id.to_string());
*TEST_METADATA.lock().unwrap() = Some(metadata);
@@ -789,6 +823,8 @@ pub(crate) fn test_owner_state(root_id: &str, token: &str, port: u16) -> Backend
studio_root_id: root_id.to_string(),
started_at_ms: 1,
updated_at_ms: 1,
+ hf_endpoint: None,
+ hf_datasets_server: None,
};
BackendOwnerState {
path: std::env::temp_dir().join(format!(
@@ -1401,6 +1437,8 @@ mod tests {
studio_root_id: ROOT_ID.to_string(),
started_at_ms: 1,
updated_at_ms: 1,
+ hf_endpoint: None,
+ hf_datasets_server: None,
}
}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index b1b329ba5a4..8a1910c691e 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1838,6 +1838,195 @@ fn webview_cache_plugin<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
.build()
}
+/// Mirror endpoints for the webview CSP: this process, plus any backend it adopts.
+fn configured_hf_endpoints() -> Vec<String> {
+ let mut raw: Vec<String> = ["HF_ENDPOINT", "HF_DATASETS_SERVER"]
+ .into_iter()
+ .filter_map(|key| std::env::var(key).ok())
+ .collect();
+ // An adopted backend may have been started from a shell that set HF_ENDPOINT
+ // while this process was not; /api/health sends the frontend to that mirror.
+ raw.extend(desktop_backend_owner::recorded_hf_endpoints());
+ csp_sources_from(raw)
+}
+
+fn csp_sources_from(raw: Vec<String>) -> Vec<String> {
+ let mut sources: Vec<String> = Vec::new();
+ for value in raw {
+ let value = value.trim().to_string();
+ if value.is_empty() {
+ continue;
+ }
+ let with_scheme =
+ if value.contains("://") { value } else { format!("https://{value}") };
+ let trimmed = with_scheme.trim_end_matches('/');
+ let normalised = match split_scheme(trimmed) {
+ Some((scheme, rest)) => format!("{scheme}://{rest}"),
+ None => trimmed.to_string(),
+ };
+ if !is_usable_csp_source(&normalised) {
+ continue;
+ }
+ let source = csp_origin_of(&normalised);
+ if !sources.contains(&source) {
+ sources.push(source);
+ }
+ }
+ sources
+}
+
+/// Split "scheme://rest", scheme lowercased (RFC 3986 3.1).
+fn split_scheme(endpoint: &str) -> Option<(String, &str)> {
+ endpoint
+ .split_once("://")
+ .map(|(scheme, rest)| (scheme.to_ascii_lowercase(), rest))
+}
+
+/// Mirrors `utils/hf_endpoint.py::is_loopback_host`.
+fn is_loopback_host(authority: &str) -> bool {
+ let host = match authority.rsplit_once(':') {
+ Some((h, port)) if !authority.ends_with(']') && port.chars().all(|c| c.is_ascii_digit()) => h,
+ _ => authority,
+ };
+ let host = host.trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase();
+ if host == "localhost" || host.ends_with(".localhost") {
+ return true;
+ }
+ // Parsed, not string-matched: 0:0:0:0:0:0:0:1 is ::1, and 127.x.y.z all count.
+ matches!(host.parse::<std::net::IpAddr>(), Ok(ip) if ip.is_loopback())
+}
+
+/// Compress an IPv6 literal: a host-source is matched as a string (CSP3 6.7.2.5)
+/// and the browser sends the compressed form.
+fn canonical_authority(authority: &str) -> String {
+ let (host, port) = match authority.strip_prefix('[') {
+ Some(rest) => match rest.split_once(']') {
+ Some((host, tail)) => (host, tail),
+ None => return authority.to_string(),
+ },
+ None => return authority.to_string(),
+ };
+ match host.parse::<std::net::Ipv6Addr>() {
+ Ok(ip) => format!("[{ip}]{port}"),
+ Err(_) => authority.to_string(),
+ }
+}
+
+/// Reduce to scheme://host[:port]: a host-source with a path is matched EXACTLY
+/// unless the path ends in a solidus (CSP3 6.7.2.7).
+fn csp_origin_of(endpoint: &str) -> String {
+ match split_scheme(endpoint) {
+ Some((scheme, rest)) => {
+ let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
+ format!("{scheme}://{}", canonical_authority(authority))
+ }
+ None => endpoint.to_string(),
+ }
+}
+
+/// Mirrors `utils/hf_endpoint.py::_sanitize`, so the webview policy and
+/// /api/health never disagree about what counts as configured.
+fn is_usable_csp_source(endpoint: &str) -> bool {
+ let (scheme, authority) = match split_scheme(endpoint) {
+ Some((scheme, rest)) if scheme == "http" || scheme == "https" => (scheme, rest),
+ _ => return false,
+ };
+ if endpoint
+ .chars()
+ .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ';' | ',' | '\'' | '"' | '\\'))
+ {
+ return false;
+ }
+ // No IDNA encoder here, and latin-1 CSP headers on the backend.
+ if !endpoint.is_ascii() {
+ return false;
+ }
+ let host = authority
+ .split(['/', '?', '#'])
+ .next()
+ .unwrap_or_default();
+ if host.is_empty() || host.contains('@') || authority.contains('?') || authority.contains('#') {
+ return false;
+ }
+ if host.contains('*') {
+ return false;
+ }
+ // Hub calls carry the user's token: http off-box puts it on the wire.
+ if scheme == "http" && !is_loopback_host(host) {
+ return false;
+ }
+ // "javascript:alert(1)" arrives as "https://javascript:alert(1)".
+ match host.rsplit_once(':') {
+ Some((_, port)) if !host.ends_with(']') => {
+ !port.is_empty() && port.chars().all(|c| c.is_ascii_digit())
+ }
+ _ => true,
+ }
+}
+
+/// Append to `connect-src`, skipping sources already listed. Matched on the
+/// directive's first token, so a hostname containing it cannot match.
+fn append_connect_sources(policy: &mut String, sources: &[String]) -> bool {
+ append_sources_to(policy, "connect-src", sources)
+}
+
+/// The same, for any directive. img-src and media-src carry a bare `https:`,
+/// which does not cover a plain-HTTP loopback mirror.
+fn append_sources_to(policy: &mut String, directive_name: &str, sources: &[String]) -> bool {
+ let mut appended = false;
+ let rebuilt: Vec<String> = policy
+ .split(';')
+ .map(|directive| directive.trim())
+ .filter(|directive| !directive.is_empty())
+ .map(|directive| {
+ let is_target = directive
+ .split_whitespace()
+ .next()
+ .is_some_and(|name| name.eq_ignore_ascii_case(directive_name));
+ if !is_target || appended {
+ return directive.to_string();
+ }
+ let existing: Vec<&str> = directive.split_whitespace().collect();
+ let mut tokens = existing.clone();
+ for source in sources {
+ if !existing.iter().any(|token| *token == source.as_str()) {
+ tokens.push(source);
+ }
+ }
+ appended = true;
+ tokens.join(" ")
+ })
+ .collect();
+ if appended {
+ *policy = rebuilt.join("; ");
+ }
+ appended
+}
+
+/// tauri.conf.json's static CSP allows only the official Hub hosts. Tauri builds
+/// the header from the Context config on every asset request, so appending here
+/// covers the statically declared window too.
+fn extend_csp_with_hf_endpoints<R: tauri::Runtime>(context: &mut tauri::Context<R>) {
+ let endpoints = configured_hf_endpoints();
+ if endpoints.is_empty() {
+ return;
+ }
+ if let Some(tauri::utils::config::Csp::Policy(policy)) =
+ context.config_mut().app.security.csp.as_mut()
+ {
+ append_connect_sources(policy, &endpoints);
+ let assets: Vec<String> = endpoints
+ .iter()
+ .filter(|e| e.starts_with("http://"))
+ .cloned()
+ .collect();
+ if !assets.is_empty() {
+ append_sources_to(policy, "img-src", &assets);
+ append_sources_to(policy, "media-src", &assets);
+ }
+ }
+}
+
fn main() {
// Must precede any Xlib call: GTK3 never calls XInitThreads and this
// process drives X from several threads. See x11_threads for the crash.
@@ -1867,7 +2056,8 @@ fn main() {
}
windows_job::initialize();
- let context = tauri::generate_context!();
+ let mut context = tauri::generate_context!();
+ extend_csp_with_hf_endpoints(&mut context);
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
@@ -2086,6 +2276,160 @@ mod tests {
assert_eq!(fs::read_to_string(&log_path).unwrap(), "dddd");
}
+ #[test]
+ fn connect_sources_appended_after_existing_directive() {
+ let mut policy = "default-src 'self'; connect-src 'self' https://huggingface.co; img-src 'self' data:".to_string();
+ assert!(append_connect_sources(
+ &mut policy,
+ &["https://hf-mirror.com".to_string(), "https://ds.example.com".to_string()],
+ ));
+ assert_eq!(
+ policy,
+ "default-src 'self'; connect-src 'self' https://huggingface.co https://hf-mirror.com https://ds.example.com; img-src 'self' data:",
+ );
+ }
+
+ #[test]
+ fn already_listed_sources_are_not_duplicated() {
+ let mut policy = "connect-src 'self' https://huggingface.co".to_string();
+ assert!(append_connect_sources(&mut policy, &["https://huggingface.co".to_string()]));
+ assert_eq!(policy, "connect-src 'self' https://huggingface.co");
+ }
+
+ #[test]
+ fn policy_without_connect_src_is_left_untouched() {
+ let mut policy = "default-src 'self'; img-src 'self' data:".to_string();
+ assert!(!append_connect_sources(&mut policy, &["https://hf-mirror.com".to_string()]));
+ assert_eq!(policy, "default-src 'self'; img-src 'self' data:");
+ }
+
+ #[test]
+ fn hostname_containing_directive_name_cannot_match() {
+ let mut policy = "connect-src 'self'; img-src connect-src.evil.com".to_string();
+ assert!(append_connect_sources(&mut policy, &["https://hf-mirror.com".to_string()]));
+ assert_eq!(policy, "connect-src 'self' https://hf-mirror.com; img-src connect-src.evil.com");
+ }
+
+ #[test]
+ fn a_path_prefixed_mirror_is_reduced_to_its_origin() {
+ assert_eq!(csp_origin_of("https://hub.internal/hf"), "https://hub.internal");
+ assert_eq!(
+ csp_origin_of("https://hub.internal:8443/hf/v2"),
+ "https://hub.internal:8443"
+ );
+ assert_eq!(csp_origin_of("https://hf-mirror.com"), "https://hf-mirror.com");
+ assert_eq!(csp_origin_of("http://localhost:8080"), "http://localhost:8080");
+ }
+
+ #[test]
+ fn a_plain_https_origin_is_a_usable_csp_source() {
+ assert!(is_usable_csp_source("https://hf-mirror.com"));
+ assert!(is_usable_csp_source("http://localhost:8080"));
+ assert!(is_usable_csp_source("https://hub.internal:8443/hf"));
+ }
+
+ #[test]
+ fn an_endpoint_that_could_forge_a_directive_is_rejected() {
+ for hostile in [
+ "https://hf-mirror.com; script-src *",
+ "https://hf-mirror.com *",
+ "https://hf-mirror.com\nscript-src *",
+ "https://hf-mirror.com\r\nscript-src *",
+ "https://hf-mirror.com\tfoo",
+ "https://hf-mirror.com,https://evil.com",
+ "https://hf-mirror.com'",
+ ] {
+ assert!(!is_usable_csp_source(hostile), "should reject {hostile:?}");
+ }
+ }
+
+ #[test]
+ fn a_non_http_or_hostless_endpoint_is_rejected() {
+ for bad in [
+ "javascript:alert(1)",
+ "file:///etc/passwd",
+ "data:text/html,x",
+ "ftp://hf-mirror.com",
+ "https://",
+ "https://user:[email protected]",
+ "https://hf-mirror.com?x=1",
+ "https://hf-mirror.com#f",
+ "https://javascript:alert(1)",
+ "https://hf-mirror.com:",
+ "https://hf-mirror.com:80x",
+ "https://*",
+ "https://*.evil.com",
+ ] {
+ assert!(!is_usable_csp_source(bad), "should reject {bad:?}");
+ }
+ }
+
+ #[test]
+ fn plain_http_is_loopback_only() {
+ assert!(is_usable_csp_source("http://127.0.0.1:9700"));
+ assert!(is_usable_csp_source("http://localhost:8080"));
+ assert!(is_usable_csp_source("http://127.1.2.3"));
+ assert!(!is_usable_csp_source("http://192.168.1.10:8080"));
+ assert!(!is_usable_csp_source("http://hf-mirror.com"));
+ assert!(!is_usable_csp_source("http://10.0.0.5:8080"));
+ assert!(is_usable_csp_source("https://192.168.1.10:8080"));
+ assert!(is_usable_csp_source("https://hf-mirror.com"));
+ }
+
+ #[test]
+ fn csp_sources_are_normalised_and_deduplicated() {
+ let sources = csp_sources_from(vec![
+ "https://hf-mirror.com".to_string(),
+ "HTTPS://hf-mirror.com/".to_string(),
+ "hf-mirror.com".to_string(),
+ " ".to_string(),
+ "http://192.168.1.10".to_string(),
+ "https://ds.internal/hf".to_string(),
+ ]);
+ assert_eq!(sources, vec!["https://hf-mirror.com", "https://ds.internal"]);
+ }
+
+ #[test]
+ fn a_unicode_host_is_refused_and_its_punycode_form_is_not() {
+ assert!(!is_usable_csp_source("https://例子.测试"));
+ assert!(is_usable_csp_source("https://xn--fsqu00a.xn--0zwm56d"));
+ }
+
+ #[test]
+ fn every_ipv6_loopback_spelling_is_recognised_and_compressed() {
+ assert!(is_usable_csp_source("http://[0:0:0:0:0:0:0:1]:9700"));
+ assert!(is_usable_csp_source("http://[::1]:9700"));
+ assert!(is_usable_csp_source("http://127.9.9.9"));
+ assert!(!is_usable_csp_source("http://[2001:db8::1]:9700"));
+ assert_eq!(
+ csp_origin_of("http://[0:0:0:0:0:0:0:1]:9700"),
+ "http://[::1]:9700"
+ );
+ assert_eq!(csp_origin_of("http://[0:0:0:0:0:0:0:1]"), "http://[::1]");
+ }
+
+ #[test]
+ fn the_scheme_is_matched_case_insensitively() {
+ assert!(is_usable_csp_source("HTTPS://hf-mirror.com"));
+ assert!(is_usable_csp_source("Https://hf-mirror.com"));
+ assert!(is_usable_csp_source("HTTP://127.0.0.1:9700"));
+ assert!(!is_usable_csp_source("HTTP://hf-mirror.com"));
+ assert_eq!(csp_origin_of("HTTPS://hf-mirror.com/hf"), "https://hf-mirror.com");
+ }
+
+ #[test]
+ fn a_loopback_http_mirror_reaches_the_asset_directives_too() {
+ let mut policy = "connect-src 'self'; img-src 'self' data: https:; \
+media-src 'self' https:"
+ .to_string();
+ let assets = ["http://127.0.0.1:9700".to_string()];
+ assert!(append_sources_to(&mut policy, "img-src", &assets));
+ assert!(append_sources_to(&mut policy, "media-src", &assets));
+ assert!(policy.contains("img-src 'self' data: https: http://127.0.0.1:9700"));
+ assert!(policy.contains("media-src 'self' https: http://127.0.0.1:9700"));
+ assert!(policy.contains("connect-src 'self';"));
+ }
+
#[test]
fn an_oversized_log_from_a_previous_session_rotates_on_the_first_write() {
let directory = tempfile::tempdir().unwrap();