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: persist provider and Hugging Face credentials (#8299)

Wasim Yousef Said19abc08bb427
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 96a603e2e75..6f4b52793dc 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -3,6 +3,8 @@
"""SQLite storage for auth data (user credentials + JWT secret)."""
+from contextlib import contextmanager
+
import hashlib
import hmac
import ipaddress
@@ -12,7 +14,7 @@ import sqlite3
import tempfile
import threading
from datetime import datetime, timezone
-from typing import Optional, Tuple
+from typing import Iterator, Optional, Tuple
from utils.paths import auth_db_path, ensure_dir
@@ -246,6 +248,26 @@ def _current_generation(conn: sqlite3.Connection, username: str) -> Optional[str
return credential_generation(secret) if secret is not None else None
+@contextmanager
+def credential_generation_guard(username: str, expect_gen: Optional[str]) -> Iterator[None]:
+ """Hold the auth write lock while a credential-derived write commits elsewhere."""
+ conn = get_connection()
+ try:
+ if expect_gen is not None:
+ conn.execute("BEGIN IMMEDIATE")
+ if _current_generation(conn, username) != expect_gen:
+ raise CredentialRotated(
+ "The credential this request authenticated with was revoked."
+ )
+ yield
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
def get_connection() -> sqlite3.Connection:
"""Get a connection to the auth database, creating tables if needed."""
ensure_dir(DB_PATH.parent)
@@ -419,6 +441,45 @@ def get_or_create_identity_secret() -> bytes:
return secret
+# Dedicated AES-256 key used to encrypt Studio credentials in studio.db.
+# It intentionally lives in auth.db so copying studio.db alone does not expose
+# provider or Hugging Face tokens, and survives password changes/resets.
+_CREDENTIAL_ENCRYPTION_KEY_DB_KEY = "credential_encryption_key_v1"
+_credential_encryption_key_cache: Optional[bytes] = None
+
+
+def get_or_create_credential_encryption_key() -> bytes:
+ """Return the install-local credential encryption key, creating it once."""
+ global _credential_encryption_key_cache
+ if _credential_encryption_key_cache is not None:
+ return _credential_encryption_key_cache
+
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (_CREDENTIAL_ENCRYPTION_KEY_DB_KEY,),
+ ).fetchone()
+ if row is None:
+ conn.execute(
+ "INSERT OR IGNORE INTO app_secrets (key, value) VALUES (?, ?)",
+ (_CREDENTIAL_ENCRYPTION_KEY_DB_KEY, secrets.token_hex(32)),
+ )
+ conn.commit()
+ row = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (_CREDENTIAL_ENCRYPTION_KEY_DB_KEY,),
+ ).fetchone()
+ secret = bytes.fromhex(row["value"])
+ if len(secret) != 32:
+ raise ValueError("Invalid credential encryption key")
+ finally:
+ conn.close()
+
+ _credential_encryption_key_cache = secret
+ return secret
+
+
def compute_identity_proof(nonce: bytes, host: str, port: int) -> str:
"""HMAC-SHA256 proof that the caller holds this install's identity secret,
bound to the loopback address and port the connection landed on. A proof
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 2395216a89b..568bfeb9be3 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1335,7 +1335,7 @@ class ChatCompletionRequest(BaseModel):
# ── External provider routing (x-unsloth extensions) ──────────
provider_id: Optional[str] = Field(
None,
- description = "[x-unsloth] Saved provider config ID. If set with encrypted_api_key, routes to external LLM.",
+ description = "[x-unsloth] Saved provider config ID. Its stored key is used when encrypted_api_key is omitted.",
)
provider_type: Optional[str] = Field(
None,
@@ -1663,13 +1663,17 @@ class ToolConfirmRequest(BaseModel):
class OpenAIContainerRequest(BaseModel):
"""Shared body for the OpenAI container endpoints (list / create / delete).
- Carries the encrypted API key + base URL so the route can decrypt and proxy
- to the user's account, keeping the key off backend persistent storage.
+ Carries a saved provider ID or one-time encrypted API key plus base URL so
+ the route can proxy to the user's account.
"""
- encrypted_api_key: str = Field(
- ...,
- description = "[x-unsloth] RSA-encrypted, base64-encoded OpenAI API key.",
+ provider_id: Optional[str] = Field(
+ None,
+ description = "[x-unsloth] Saved OpenAI provider config whose stored key may be used.",
+ )
+ encrypted_api_key: Optional[str] = Field(
+ None,
+ description = "[x-unsloth] Optional RSA-encrypted OpenAI API key override.",
)
provider_base_url: Optional[str] = Field(
None,
diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.py
index 4238403e00d..84946802794 100644
--- a/studio/backend/models/providers.py
+++ b/studio/backend/models/providers.py
@@ -56,6 +56,11 @@ class ProviderCreate(BaseModel):
description = "Discovered catalog model IDs last fetched for this connection",
)
+ encrypted_api_key: Optional[str] = Field(
+ None,
+ description = "Optional RSA-encrypted API key to persist for this connection",
+ )
+
class ProviderUpdate(BaseModel):
"""Request to update a saved provider configuration."""
@@ -69,6 +74,25 @@ class ProviderUpdate(BaseModel):
description = "Discovered catalog model IDs last fetched for this connection",
)
+ encrypted_api_key: Optional[str] = Field(
+ None,
+ description = "Optional RSA-encrypted replacement API key; omission preserves the saved key",
+ )
+ clear_api_key: bool = Field(
+ False,
+ description = "Explicitly remove the saved API key",
+ )
+
+
+class ProviderCredentialMigration(BaseModel):
+ """One-time browser credential migration that never replaces a saved key."""
+
+ encrypted_api_key: str = Field(
+ ...,
+ min_length = 1,
+ description = "RSA-encrypted legacy API key to insert only when no key exists",
+ )
+
class ProviderResponse(BaseModel):
"""A saved provider configuration (returned by list/get endpoints)."""
@@ -78,6 +102,8 @@ class ProviderResponse(BaseModel):
display_name: str = Field(..., description = "User-chosen label")
base_url: str = Field(..., description = "API base URL")
is_enabled: bool = Field(True, description = "Whether this provider is enabled")
+
+ has_api_key: bool = Field(False, description = "Whether this caller has a saved API key")
models: list[str] = Field(
default_factory = list,
description = "Enabled model IDs for this connection",
@@ -105,6 +131,10 @@ class ProviderModelInfo(BaseModel):
class ProviderModelsRequest(BaseModel):
"""Request to list models from an external provider."""
+ provider_id: Optional[str] = Field(
+ None, description = "Saved provider config whose stored key may be used"
+ )
+
provider_type: str = Field(..., description = "Provider type from the registry")
encrypted_api_key: Optional[str] = Field(
None,
@@ -121,6 +151,10 @@ class ProviderModelsRequest(BaseModel):
class ProviderTestRequest(BaseModel):
"""Request to test connectivity to an external provider."""
+ provider_id: Optional[str] = Field(
+ None, description = "Saved provider config whose stored key may be used"
+ )
+
provider_type: str = Field(..., description = "Provider type from the registry")
encrypted_api_key: Optional[str] = Field(
None,
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 06e6fa69eef..a2e347214ff 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2140,6 +2140,25 @@ from auth.authentication import API_KEY_PREFIX, get_current_subject
from state import active_generations
+def _request_api_key_token(request: Any) -> Optional[str]:
+ """Return any sk-unsloth bearer used for authentication, including workflow keys."""
+ try:
+ header = request.headers.get("authorization")
+ except Exception:
+ return None
+ if not isinstance(header, str):
+ return None
+ scheme, _, token = header.partition(" ")
+ if scheme.lower() != "bearer" or not token.startswith(API_KEY_PREFIX):
+ return None
+ return token
+
+
+def _request_has_api_key(request: Any) -> bool:
+ """Whether the request used any API key rather than an interactive session JWT."""
+ return _request_api_key_token(request) is not None
+
+
def _request_used_api_key(request: Any) -> bool:
"""True when this request authenticated with a third party's sk-unsloth key.
@@ -2149,15 +2168,10 @@ def _request_used_api_key(request: Any) -> bool:
itself and are excluded, or every research step would pop the API monitor open.
"""
# Total by construction: this only decides a monitor label and must never fail a
- # load. Only a real Request hands back a string; the load routes take stand-ins too.
- try:
- header = request.headers.get("authorization")
- except Exception:
- return False
- if not isinstance(header, str):
- return False
- scheme, _, token = header.partition(" ")
- if scheme.lower() != "bearer" or not token.startswith(API_KEY_PREFIX):
+ # load. Saved-secret authorization uses _request_has_api_key instead, because
+ # internal workflow keys must remain programmatic callers for credential access.
+ token = _request_api_key_token(request)
+ if token is None:
return False
try:
return not auth_storage.is_internal_api_key(token)
@@ -2168,7 +2182,6 @@ def _request_used_api_key(request: Any) -> bool:
from state.tool_approvals import resolve_tool_decision
-from core.inference.key_exchange import decrypt_api_key
from core.inference.model_ids import display_model_name, model_id_matches, public_model_id
from core.inference.api_monitor import api_monitor
from core.inference.llama_http import nonstreaming_client
@@ -2192,6 +2205,7 @@ from core.inference.passthrough_healing import (
from core.inference.providers import get_base_url
from core.inference.external_provider import ExternalProviderClient
from core.inference.chat_templates import resolve_effective_chat_template_override
+from routes.provider_credentials import resolve_provider_api_key_or_400
from storage import providers_db
from utils.utils import is_hf_authentication_error, safe_error_detail, log_and_http_error
@@ -10059,7 +10073,7 @@ async def _proxy_to_external_provider(
provider_type = payload.provider_type
base_url = payload.provider_base_url
- if payload.provider_id:
+ if payload.provider_id and not payload.encrypted_api_key:
config = providers_db.get_provider(payload.provider_id)
if config is None:
raise HTTPException(
@@ -10071,8 +10085,10 @@ async def _proxy_to_external_provider(
status_code = 400,
detail = f"Provider '{config['display_name']}' is disabled.",
)
- provider_type = provider_type or config["provider_type"]
- base_url = base_url or config["base_url"]
+ # A saved credential is scoped to this saved provider. Never pair it with
+ # request-controlled routing metadata.
+ provider_type = config["provider_type"]
+ base_url = config["base_url"]
if not provider_type:
raise HTTPException(
@@ -10089,16 +10105,11 @@ async def _proxy_to_external_provider(
detail = f"Unknown provider type: {provider_type}",
)
- api_key = ""
- if payload.encrypted_api_key:
- try:
- api_key = decrypt_api_key(payload.encrypted_api_key)
- except Exception as exc:
- logger.warning("external_provider.decrypt_failed", error = str(exc))
- raise HTTPException(
- status_code = 400,
- detail = "Failed to decrypt API key. The server key may have changed — try refreshing the page.",
- )
+ api_key = resolve_provider_api_key_or_400(
+ payload.provider_id,
+ payload.encrypted_api_key,
+ allow_saved_key = not _request_has_api_key(request),
+ )
model = payload.external_model or payload.model
if model == "default":
@@ -10235,7 +10246,9 @@ async def _proxy_to_external_provider(
# ── OpenAI shell-tool container management ───────────────────────
-def _resolve_openai_cloud_client(body: OpenAIContainerRequest) -> ExternalProviderClient:
+def _resolve_openai_cloud_client(
+ body: OpenAIContainerRequest, *, allow_saved_key: bool
+) -> ExternalProviderClient:
"""
Decrypt the API key + validate the base URL points at OpenAI cloud, then
build an ExternalProviderClient for the three container CRUD endpoints
@@ -10244,7 +10257,29 @@ def _resolve_openai_cloud_client(body: OpenAIContainerRequest) -> ExternalProvid
custom presets.
"""
base_url = body.provider_base_url or get_base_url("openai")
- if not base_url or "api.openai.com" not in base_url:
+ if body.provider_id and not body.encrypted_api_key:
+ config = providers_db.get_provider(body.provider_id)
+ if config is None:
+ raise HTTPException(
+ status_code = 404,
+ detail = f"Provider config not found: {body.provider_id}",
+ )
+ if config["provider_type"] != "openai":
+ raise HTTPException(
+ status_code = 400,
+ detail = "OpenAI container management requires a saved OpenAI provider.",
+ )
+
+ if not config["is_enabled"]:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Provider '{config['display_name']}' is disabled.",
+ )
+ base_url = config["base_url"]
+ from urllib.parse import urlparse
+
+ parsed_base_url = urlparse(base_url)
+ if parsed_base_url.scheme != "https" or parsed_base_url.hostname != "api.openai.com":
raise HTTPException(
status_code = 400,
detail = (
@@ -10253,14 +10288,13 @@ def _resolve_openai_cloud_client(body: OpenAIContainerRequest) -> ExternalProvid
f"points at {base_url!r}."
),
)
- try:
- api_key = decrypt_api_key(body.encrypted_api_key)
- except Exception as exc:
- logger.warning("external_provider.decrypt_failed", error = str(exc))
- raise HTTPException(
- status_code = 400,
- detail = "Failed to decrypt API key. The server key may have changed — try refreshing the page.",
- )
+ api_key = resolve_provider_api_key_or_400(
+ body.provider_id,
+ body.encrypted_api_key,
+ allow_saved_key = allow_saved_key,
+ )
+ if not api_key:
+ raise HTTPException(status_code = 400, detail = "No OpenAI API key is saved.")
return ExternalProviderClient(
provider_type = "openai",
base_url = base_url,
@@ -10292,10 +10326,12 @@ def _summarize_container(raw: dict) -> OpenAIContainerSummary:
response_model = ListOpenAIContainersResponse,
)
async def list_openai_containers(
- body: OpenAIContainerRequest, current_subject: str = Depends(get_current_subject)
+ body: OpenAIContainerRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
) -> ListOpenAIContainersResponse:
"""List the user's OpenAI shell-tool containers."""
- client = _resolve_openai_cloud_client(body)
+ client = _resolve_openai_cloud_client(body, allow_saved_key = not _request_has_api_key(request))
try:
try:
raw = await client.list_openai_containers()
@@ -10332,10 +10368,12 @@ async def list_openai_containers(
response_model = OpenAIContainerSummary,
)
async def create_openai_container(
- body: CreateOpenAIContainerBody, current_subject: str = Depends(get_current_subject)
+ body: CreateOpenAIContainerBody,
+ request: Request,
+ _current_subject: str = Depends(get_current_subject),
) -> OpenAIContainerSummary:
"""Create a named container with the user-chosen idle TTL."""
- client = _resolve_openai_cloud_client(body)
+ client = _resolve_openai_cloud_client(body, allow_saved_key = not _request_has_api_key(request))
try:
try:
raw = await client.create_openai_container(
@@ -10368,7 +10406,9 @@ async def create_openai_container(
@router.post("/external/openai/containers/delete", status_code = 204)
async def delete_openai_container(
- body: DeleteOpenAIContainerBody, current_subject: str = Depends(get_current_subject)
+ body: DeleteOpenAIContainerBody,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
) -> None:
"""Delete a named container by id."""
logger.info(
@@ -10377,7 +10417,7 @@ async def delete_openai_container(
body.container_id,
body.provider_base_url,
)
- client = _resolve_openai_cloud_client(body)
+ client = _resolve_openai_cloud_client(body, allow_saved_key = not _request_has_api_key(request))
try:
try:
await client.delete_openai_container(body.container_id)
diff --git a/studio/backend/routes/provider_credentials.py b/studio/backend/routes/provider_credentials.py
new file mode 100644
index 00000000000..7aa12cf89a1
--- /dev/null
+++ b/studio/backend/routes/provider_credentials.py
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared request-layer resolution for external-provider credentials."""
+
+from __future__ import annotations
+
+
+from contextlib import contextmanager
+from typing import Iterator
+
+from auth import storage as auth_storage
+
+import structlog
+from fastapi import HTTPException
+
+
+from storage import credential_secrets
+
+logger = structlog.get_logger(__name__)
+
+
+@contextmanager
+def current_credential_write(credential: tuple[str, str | None]) -> Iterator[None]:
+ """Reject a credential-derived write if password rotation revoked its request."""
+ subject, generation = credential
+ try:
+ with auth_storage.credential_generation_guard(subject, generation):
+ yield
+ except auth_storage.CredentialRotated as exc:
+ raise HTTPException(status_code = 401, detail = "Invalid or expired token") from exc
+
+
+def require_ui_session(via_api_key: bool) -> None:
+ """Keep installation-owned credentials behind an interactive UI session."""
+ if via_api_key:
+ raise HTTPException(status_code = 403, detail = "Remote access requires a UI session.")
+
+
+def resolve_provider_api_key_or_400(
+ provider_id: str | None,
+ encrypted_api_key: str | None,
+ *,
+ allow_saved_key: bool = True,
+) -> str:
+ """Resolve an explicit key, or a saved key only for an interactive UI session."""
+
+ try:
+ saved_provider_id = provider_id if allow_saved_key else None
+ return credential_secrets.resolve_provider_api_key(saved_provider_id, encrypted_api_key)
+ except Exception as exc:
+ logger.warning(
+ "external_provider.api_key_decrypt_failed",
+ error_type = type(exc).__name__,
+ )
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ "Failed to decrypt API key. The server public key may have changed — "
+ "try refreshing the page."
+ ),
+ ) from exc
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 4e7e53f2f06..9105b9d2cd0 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -6,7 +6,7 @@ API routes for external LLM provider management.
Endpoints:
- Discover available provider types (registry)
- - CRUD for saved provider configurations (no API keys stored)
+ - CRUD for saved provider configurations and API keys
- Fetch the RSA public key for API key encryption
- Test provider connectivity
- List models from a provider
@@ -16,9 +16,18 @@ import uuid
import structlog
from fastapi import APIRouter, Depends, HTTPException
-from auth.authentication import get_current_subject
+from auth.authentication import (
+ authenticated_via_api_key,
+ get_current_credential,
+ get_current_subject,
+)
+
+from routes.provider_credentials import (
+ current_credential_write,
+ require_ui_session,
+ resolve_provider_api_key_or_400,
+)
from core.inference.key_exchange import (
- decrypt_api_key,
get_public_key_fingerprint,
get_public_key_pem,
)
@@ -31,6 +40,7 @@ from core.inference.pricing import pricing_snapshot
from core.inference.external_provider import ExternalProviderClient
from models.providers import (
ProviderCreate,
+ ProviderCredentialMigration,
ProviderModelsRequest,
ProviderModelInfo,
ProviderResponse,
@@ -39,7 +49,7 @@ from models.providers import (
ProviderTestResult,
ProviderUpdate,
)
-from storage import providers_db
+from storage import credential_secrets, providers_db
from utils.utils import safe_curated_detail, log_and_http_error
logger = structlog.get_logger(__name__)
@@ -54,6 +64,10 @@ def _provider_response(row: dict) -> ProviderResponse:
display_name = row["display_name"],
base_url = row["base_url"],
is_enabled = bool(row["is_enabled"]),
+ has_api_key = credential_secrets.has_secret(
+ credential_secrets.PROVIDER_API_KEY_KIND,
+ row["id"],
+ ),
models = row.get("models") or [],
available_models = row.get("available_models") or [],
created_at = row["created_at"],
@@ -100,7 +114,7 @@ async def get_pricing_snapshot(current_subject: str = Depends(get_current_subjec
@router.get("/", response_model = list[ProviderResponse])
-async def list_provider_configs(current_subject: str = Depends(get_current_subject)):
+async def list_provider_configs(_current_subject: str = Depends(get_current_subject)):
"""List all saved provider configurations."""
rows = providers_db.list_providers()
return [_provider_response(row) for row in rows]
@@ -108,9 +122,13 @@ async def list_provider_configs(current_subject: str = Depends(get_current_subje
@router.post("/", response_model = ProviderResponse, status_code = 201)
async def create_provider_config(
- payload: ProviderCreate, current_subject: str = Depends(get_current_subject)
+ payload: ProviderCreate,
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
):
- """Create a new saved provider configuration (no API key stored)."""
+ """Create a saved provider configuration and optional encrypted API key."""
+
+ require_ui_session(via_api_key)
info = get_provider_info(payload.provider_type)
if info is None:
raise HTTPException(
@@ -119,17 +137,27 @@ async def create_provider_config(
f"Use GET /api/providers/registry to see available types.",
)
+ api_key = resolve_provider_api_key_or_400(None, payload.encrypted_api_key)
provider_id = uuid.uuid4().hex[:16]
base_url = payload.base_url or info["base_url"]
- providers_db.create_provider(
- id = provider_id,
- provider_type = payload.provider_type,
- display_name = payload.display_name,
- base_url = base_url,
- models = payload.models,
- available_models = payload.available_models,
- )
+ if api_key:
+ credential_secrets.get_or_create_credential_encryption_key()
+ with current_credential_write(credential):
+ providers_db.create_provider(
+ id = provider_id,
+ provider_type = payload.provider_type,
+ display_name = payload.display_name,
+ base_url = base_url,
+ models = payload.models,
+ available_models = payload.available_models,
+ )
+ try:
+ if api_key:
+ credential_secrets.save_provider_api_key(provider_id, api_key)
+ except Exception:
+ providers_db.delete_provider(provider_id)
+ raise
row = providers_db.get_provider(provider_id)
return _provider_response(row)
@@ -139,36 +167,143 @@ async def create_provider_config(
async def update_provider_config(
provider_id: str,
payload: ProviderUpdate,
- current_subject: str = Depends(get_current_subject),
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
):
"""Update a saved provider configuration."""
+
+ require_ui_session(via_api_key)
existing = providers_db.get_provider(provider_id)
if not existing:
raise HTTPException(status_code = 404, detail = "Provider not found")
- updated = providers_db.update_provider(
- id = provider_id,
- display_name = payload.display_name,
- base_url = payload.base_url,
- is_enabled = payload.is_enabled,
- models = payload.models,
- available_models = payload.available_models,
- )
- if not updated:
+ if payload.clear_api_key and payload.encrypted_api_key:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Cannot replace and clear an API key in the same request",
+ )
+
+ metadata_fields = {"display_name", "base_url", "is_enabled", "models", "available_models"}
+ metadata_requested = bool(payload.model_fields_set & metadata_fields)
+
+ replacement_api_key = None
+ if payload.encrypted_api_key:
+ credential_secrets.get_or_create_credential_encryption_key()
+ replacement_api_key = resolve_provider_api_key_or_400(
+ provider_id, payload.encrypted_api_key
+ )
+ if not replacement_api_key:
+ raise HTTPException(status_code = 400, detail = "API key cannot be empty")
+
+ with current_credential_write(credential):
+ if metadata_requested:
+ providers_db.update_provider(
+ id = provider_id,
+ display_name = payload.display_name,
+ base_url = payload.base_url,
+ is_enabled = payload.is_enabled,
+ models = payload.models,
+ available_models = payload.available_models,
+ )
+ try:
+ if replacement_api_key is not None:
+ credential_secrets.save_provider_api_key(provider_id, replacement_api_key)
+ elif payload.clear_api_key:
+ credential_secrets.delete_provider_api_key(provider_id)
+ except Exception:
+ if metadata_requested:
+ try:
+ providers_db.update_provider(
+ id = provider_id,
+ display_name = existing["display_name"],
+ base_url = existing["base_url"],
+ is_enabled = bool(existing["is_enabled"]),
+ models = existing.get("models") or [],
+ available_models = existing.get("available_models") or [],
+ )
+ except Exception:
+ logger.exception(
+ "provider.update_metadata_rollback_failed", provider_id = provider_id
+ )
+ raise
+
+ if not metadata_requested and not payload.encrypted_api_key and not payload.clear_api_key:
raise HTTPException(status_code = 400, detail = "No fields to update")
row = providers_db.get_provider(provider_id)
return _provider_response(row)
[email protected]("/{provider_id}/api-key/migrate", response_model = ProviderResponse)
+async def migrate_provider_api_key(
+ provider_id: str,
+ payload: ProviderCredentialMigration,
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+):
+ """Insert a browser legacy key only when this provider has no saved key."""
+ require_ui_session(via_api_key)
+ if providers_db.get_provider(provider_id) is None:
+ raise HTTPException(status_code = 404, detail = "Provider not found")
+ api_key = resolve_provider_api_key_or_400(
+ None, payload.encrypted_api_key, allow_saved_key = False
+ )
+ if not api_key:
+ raise HTTPException(status_code = 400, detail = "API key cannot be empty")
+ credential_secrets.get_or_create_credential_encryption_key()
+ with current_credential_write(credential):
+ credential_secrets.save_provider_api_key_if_absent(provider_id, api_key)
+ return _provider_response(providers_db.get_provider(provider_id))
+
+
@router.delete("/{provider_id}", status_code = 204)
async def delete_provider_config(
- provider_id: str, current_subject: str = Depends(get_current_subject)
+ provider_id: str,
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
):
- """Delete a saved provider configuration."""
- deleted = providers_db.delete_provider(provider_id)
- if not deleted:
- raise HTTPException(status_code = 404, detail = "Provider not found")
+ """Idempotently delete a saved provider and its installation credential."""
+ require_ui_session(via_api_key)
+
+ # Decryption must not open the auth DB after the generation guard locks it.
+ credential_secrets.get_or_create_credential_encryption_key()
+ with current_credential_write(credential):
+ existing_api_key = credential_secrets.get_provider_api_key(provider_id)
+ credential_secrets.delete_provider_api_key(provider_id)
+ try:
+ providers_db.delete_provider(provider_id)
+ except Exception:
+ if existing_api_key:
+ try:
+ credential_secrets.save_provider_api_key(provider_id, existing_api_key)
+ except Exception:
+ logger.exception(
+ "provider.delete_credential_rollback_failed", provider_id = provider_id
+ )
+ raise
+
+
+def _bind_saved_provider_target(payload):
+ """Use the saved provider's endpoint whenever its saved credential may be used."""
+ if not payload.provider_id or payload.encrypted_api_key:
+ return payload
+ config = providers_db.get_provider(payload.provider_id)
+ if config is None:
+ raise HTTPException(
+ status_code = 404,
+ detail = f"Provider config not found: {payload.provider_id}",
+ )
+ if not config["is_enabled"]:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Provider '{config['display_name']}' is disabled.",
+ )
+ return payload.model_copy(
+ update = {
+ "provider_type": config["provider_type"],
+ "base_url": config["base_url"],
+ }
+ )
# ── Test connectivity ─────────────────────────────────────────────
@@ -176,15 +311,19 @@ async def delete_provider_config(
@router.post("/test", response_model = ProviderTestResult)
async def test_provider(
- payload: ProviderTestRequest, current_subject: str = Depends(get_current_subject)
+ payload: ProviderTestRequest,
+ _current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
):
"""
Test connectivity to an external provider.
Makes a lightweight GET /models call to verify the API key works. Generic
custom endpoints use a chat-completions probe because /models is optional.
- encrypted_api_key is decrypted server-side and never stored.
+ An explicit encrypted key takes precedence over the saved provider key.
"""
+
+ payload = _bind_saved_provider_target(payload)
info = get_provider_info(payload.provider_type)
if info is None:
raise HTTPException(
@@ -192,16 +331,11 @@ async def test_provider(
detail = f"Unknown provider type: {payload.provider_type}",
)
- api_key = ""
- if payload.encrypted_api_key:
- try:
- api_key = decrypt_api_key(payload.encrypted_api_key)
- except Exception as exc:
- logger.warning("Failed to decrypt API key (%s): %s", type(exc).__name__, exc)
- raise HTTPException(
- status_code = 400,
- detail = "Failed to decrypt API key. The public key may have changed — try refreshing the page.",
- )
+ api_key = resolve_provider_api_key_or_400(
+ payload.provider_id,
+ payload.encrypted_api_key,
+ allow_saved_key = not via_api_key,
+ )
base_url = payload.base_url or info["base_url"]
if payload.provider_type == "custom":
@@ -277,13 +411,17 @@ async def test_provider(
@router.post("/models", response_model = list[ProviderModelInfo])
async def list_provider_models(
- payload: ProviderModelsRequest, current_subject: str = Depends(get_current_subject)
+ payload: ProviderModelsRequest,
+ _current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
):
"""
List models available from an external provider.
- encrypted_api_key is decrypted server-side and never stored.
+ An explicit encrypted key takes precedence over the saved provider key.
"""
+
+ payload = _bind_saved_provider_target(payload)
info = get_provider_info(payload.provider_type)
if info is None:
raise HTTPException(
@@ -291,16 +429,11 @@ async def list_provider_models(
detail = f"Unknown provider type: {payload.provider_type}",
)
- api_key = ""
- if payload.encrypted_api_key:
- try:
- api_key = decrypt_api_key(payload.encrypted_api_key)
- except Exception as exc:
- logger.warning("Failed to decrypt API key (%s): %s", type(exc).__name__, exc)
- raise HTTPException(
- status_code = 400,
- detail = "Failed to decrypt API key. The public key may have changed — try refreshing the page.",
- )
+ api_key = resolve_provider_api_key_or_400(
+ payload.provider_id,
+ payload.encrypted_api_key,
+ allow_saved_key = not via_api_key,
+ )
if info.get("model_list_mode") == "curated":
return [
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 7ae08fcfefe..e1f3aeb24b2 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -10,8 +10,16 @@ from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
-from auth.authentication import authenticated_via_api_key, get_current_subject
+from auth.authentication import (
+ authenticated_via_api_key,
+ get_current_credential,
+ get_current_subject,
+)
from auth.storage import rotate_preview_link_secret
+
+from routes.provider_credentials import current_credential_write, require_ui_session
+
+from storage import credential_secrets
from core.rag.config import default_gguf_repo, effective_gguf_repo
from loggers import get_logger
from utils.utils import safe_error_detail, log_and_http_error
@@ -111,6 +119,74 @@ class UploadLimitResponse(BaseModel):
max_allowed_upload_size_mb: int = MAX_UPLOAD_LIMIT_MB
+class HuggingFaceTokenPayload(BaseModel):
+ token: str = Field(..., min_length = 1, max_length = 512)
+
+ @field_validator("token")
+ @classmethod
+ def normalize_token(cls, value: str) -> str:
+ normalized = value.strip(" \t\r\n\"'")
+ if not normalized:
+ raise ValueError("Hugging Face token cannot be empty")
+ return normalized
+
+
+class HuggingFaceTokenResponse(BaseModel):
+ token: Optional[str] = None
+ has_token: bool = False
+
+
[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)
+def get_hugging_face_token(
+ _current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+) -> HuggingFaceTokenResponse:
+ require_ui_session(via_api_key)
+ token = credential_secrets.get_hf_token()
+ return HuggingFaceTokenResponse(token = token, has_token = token is not None)
+
+
[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)
+def update_hugging_face_token(
+ payload: HuggingFaceTokenPayload,
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+) -> HuggingFaceTokenResponse:
+ require_ui_session(via_api_key)
+
+ # Warm the auth-owned key before the generation guard takes its write lock.
+ credential_secrets.get_or_create_credential_encryption_key()
+ with current_credential_write(credential):
+ credential_secrets.save_hf_token(payload.token)
+ return HuggingFaceTokenResponse(token = payload.token, has_token = True)
+
+
[email protected]("/hugging-face-token/migrate", response_model = HuggingFaceTokenResponse)
+def migrate_hugging_face_token(
+ payload: HuggingFaceTokenPayload,
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+) -> HuggingFaceTokenResponse:
+ """Insert a browser legacy token only when the installation has none."""
+ require_ui_session(via_api_key)
+ credential_secrets.get_or_create_credential_encryption_key()
+ with current_credential_write(credential):
+ credential_secrets.save_hf_token_if_absent(payload.token)
+ token = credential_secrets.get_hf_token()
+ return HuggingFaceTokenResponse(token = token, has_token = token is not None)
+
+
[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)
+def clear_hugging_face_token(
+ credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+) -> HuggingFaceTokenResponse:
+ require_ui_session(via_api_key)
+ with current_credential_write(credential):
+ credential_secrets.delete_hf_token()
+ return HuggingFaceTokenResponse(token = None, has_token = False)
+
+
class HelperPrecachePayload(BaseModel):
enabled: bool
diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.py
new file mode 100644
index 00000000000..62ca68dcc56
--- /dev/null
+++ b/studio/backend/storage/credential_secrets.py
@@ -0,0 +1,233 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Encrypted installation-wide credential persistence in ``studio.db``.
+
+Studio is a single-user local application. Credentials belong to the installation,
+not to an authenticated subject. The AES key lives separately in auth.db and the
+credential kind/scope are authenticated so ciphertext rows cannot be swapped.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import sqlite3
+import threading
+from datetime import datetime, timezone
+from typing import Optional
+
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+
+from auth.storage import get_or_create_credential_encryption_key
+from utils.paths import ensure_dir, studio_db_path
+
+logger = logging.getLogger(__name__)
+
+HF_TOKEN_KIND = "hf_token"
+HF_TOKEN_SCOPE = "default"
+PROVIDER_API_KEY_KIND = "provider_api_key"
+_FORMAT_VERSION = 1
+_NONCE_BYTES = 12
+
+_schema_lock = threading.Lock()
+_schema_ready = False
+
+
+def _associated_data(credential_kind: str, scope_id: str) -> bytes:
+ return f"unsloth-studio-credential\0{credential_kind}\0{scope_id}".encode("utf-8")
+
+
+def _ensure_schema(conn: sqlite3.Connection) -> None:
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA busy_timeout=5000")
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS credential_secrets (
+ credential_kind TEXT NOT NULL,
+ scope_id TEXT NOT NULL,
+ format_version INTEGER NOT NULL,
+ nonce BLOB NOT NULL,
+ ciphertext BLOB NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (credential_kind, scope_id)
+ ) WITHOUT ROWID
+ """
+ )
+ conn.commit()
+
+
+def get_connection() -> sqlite3.Connection:
+ global _schema_ready
+ db_path = studio_db_path()
+ ensure_dir(db_path.parent)
+ conn = sqlite3.connect(str(db_path), timeout = 5.0)
+ conn.row_factory = sqlite3.Row
+ try:
+ os.chmod(db_path.parent, 0o700)
+ os.chmod(db_path, 0o600)
+ except OSError:
+ pass
+ if not _schema_ready:
+ with _schema_lock:
+ if not _schema_ready:
+ try:
+ _ensure_schema(conn)
+ _schema_ready = True
+ except Exception:
+ conn.close()
+ raise
+ return conn
+
+
+def _encrypted_secret(
+ credential_kind: str, scope_id: str, plaintext: str
+) -> tuple[bytes, bytes, str]:
+ if not credential_kind or not scope_id:
+ raise ValueError("Credential kind and scope are required")
+ if not plaintext:
+ raise ValueError("Credential value cannot be empty")
+ key = get_or_create_credential_encryption_key()
+ nonce = os.urandom(_NONCE_BYTES)
+ ciphertext = AESGCM(key).encrypt(
+ nonce,
+ plaintext.encode("utf-8"),
+ _associated_data(credential_kind, scope_id),
+ )
+ return nonce, ciphertext, datetime.now(timezone.utc).isoformat()
+
+
+def upsert_secret(credential_kind: str, scope_id: str, plaintext: str) -> None:
+ """Encrypt and atomically insert or replace one installation credential."""
+ nonce, ciphertext, now = _encrypted_secret(credential_kind, scope_id, plaintext)
+ conn = get_connection()
+ try:
+ conn.execute(
+ """
+ INSERT INTO credential_secrets (
+ credential_kind, scope_id, format_version,
+ nonce, ciphertext, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(credential_kind, scope_id) DO UPDATE SET
+ format_version = excluded.format_version,
+ nonce = excluded.nonce,
+ ciphertext = excluded.ciphertext,
+ updated_at = excluded.updated_at
+ """,
+ (credential_kind, scope_id, _FORMAT_VERSION, nonce, ciphertext, now, now),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def insert_secret_if_absent(credential_kind: str, scope_id: str, plaintext: str) -> bool:
+ """Atomically insert a migration credential without replacing an existing value."""
+ nonce, ciphertext, now = _encrypted_secret(credential_kind, scope_id, plaintext)
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """
+ INSERT OR IGNORE INTO credential_secrets (
+ credential_kind, scope_id, format_version,
+ nonce, ciphertext, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
+ """,
+ (credential_kind, scope_id, _FORMAT_VERSION, nonce, ciphertext, now, now),
+ )
+ conn.commit()
+ return cursor.rowcount > 0
+ finally:
+ conn.close()
+
+
+def get_secret(credential_kind: str, scope_id: str) -> Optional[str]:
+ """Return a decrypted credential, or ``None`` if absent or unreadable."""
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ """
+ SELECT format_version, nonce, ciphertext
+ FROM credential_secrets
+ WHERE credential_kind = ? AND scope_id = ?
+ """,
+ (credential_kind, scope_id),
+ ).fetchone()
+ finally:
+ conn.close()
+ if row is None or row["format_version"] != _FORMAT_VERSION:
+ return None
+ try:
+ plaintext = AESGCM(get_or_create_credential_encryption_key()).decrypt(
+ bytes(row["nonce"]),
+ bytes(row["ciphertext"]),
+ _associated_data(credential_kind, scope_id),
+ )
+ return plaintext.decode("utf-8")
+ except Exception:
+ logger.warning(
+ "Saved credential is unreadable; re-entry is required (kind=%s)",
+ credential_kind,
+ )
+ return None
+
+
+def has_secret(credential_kind: str, scope_id: str) -> bool:
+ return get_secret(credential_kind, scope_id) is not None
+
+
+def delete_secret(credential_kind: str, scope_id: str) -> bool:
+ """Idempotently delete one credential; return whether a row existed."""
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ "DELETE FROM credential_secrets WHERE credential_kind = ? AND scope_id = ?",
+ (credential_kind, scope_id),
+ )
+ conn.commit()
+ return cursor.rowcount > 0
+ finally:
+ conn.close()
+
+
+def get_hf_token() -> Optional[str]:
+ return get_secret(HF_TOKEN_KIND, HF_TOKEN_SCOPE)
+
+
+def save_hf_token(token: str) -> None:
+ upsert_secret(HF_TOKEN_KIND, HF_TOKEN_SCOPE, token)
+
+
+def save_hf_token_if_absent(token: str) -> bool:
+ return insert_secret_if_absent(HF_TOKEN_KIND, HF_TOKEN_SCOPE, token)
+
+
+def delete_hf_token() -> bool:
+ return delete_secret(HF_TOKEN_KIND, HF_TOKEN_SCOPE)
+
+
+def get_provider_api_key(provider_id: str) -> Optional[str]:
+ return get_secret(PROVIDER_API_KEY_KIND, provider_id)
+
+
+def save_provider_api_key(provider_id: str, api_key: str) -> None:
+ upsert_secret(PROVIDER_API_KEY_KIND, provider_id, api_key)
+
+
+def save_provider_api_key_if_absent(provider_id: str, api_key: str) -> bool:
+ return insert_secret_if_absent(PROVIDER_API_KEY_KIND, provider_id, api_key)
+
+
+def delete_provider_api_key(provider_id: str) -> bool:
+ return delete_secret(PROVIDER_API_KEY_KIND, provider_id)
+
+
+def resolve_provider_api_key(provider_id: Optional[str], encrypted_api_key: Optional[str]) -> str:
+ """Resolve an explicit request key first, then the installation's saved key."""
+ if encrypted_api_key:
+ from core.inference.key_exchange import decrypt_api_key
+ return decrypt_api_key(encrypted_api_key)
+ if provider_id:
+ return get_provider_api_key(provider_id) or ""
+ return ""
diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.py
new file mode 100644
index 00000000000..c8374794f30
--- /dev/null
+++ b/studio/backend/tests/test_credential_routes.py
@@ -0,0 +1,445 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+
+import asyncio
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+from auth import storage as auth_storage
+from models.providers import (
+ ProviderCreate,
+ ProviderCredentialMigration,
+ ProviderModelsRequest,
+ ProviderTestRequest,
+ ProviderUpdate,
+)
+
+
+def _load_route_module(module_name: str, path: Path):
+ spec = importlib.util.spec_from_file_location(module_name, path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+_routes_dir = Path(__file__).resolve().parents[1] / "routes"
+_previous_routes = sys.modules.get("routes")
+_routes_package = types.ModuleType("routes")
+_routes_package.__path__ = [str(_routes_dir)]
+sys.modules["routes"] = _routes_package
+try:
+ _load_route_module("routes.provider_credentials", _routes_dir / "provider_credentials.py")
+ providers_route = _load_route_module(
+ "_credential_providers_route", _routes_dir / "providers.py"
+ )
+ settings_route = _load_route_module("_credential_settings_route", _routes_dir / "settings.py")
+finally:
+ sys.modules.pop("routes.provider_credentials", None)
+ if _previous_routes is None:
+ sys.modules.pop("routes", None)
+ else:
+ sys.modules["routes"] = _previous_routes
+from storage import credential_secrets, providers_db
+
+
[email protected](autouse = True)
+def isolated_databases(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ auth_db = tmp_path / "auth.db"
+ studio_db = tmp_path / "studio.db"
+ monkeypatch.setattr(auth_storage, "DB_PATH", auth_db)
+ monkeypatch.setattr(auth_storage, "_credential_encryption_key_cache", None)
+ monkeypatch.setattr(providers_db, "studio_db_path", lambda: studio_db)
+ monkeypatch.setattr(credential_secrets, "studio_db_path", lambda: studio_db)
+ monkeypatch.setattr(providers_db, "ensure_dir", lambda _path: None)
+ monkeypatch.setattr(credential_secrets, "ensure_dir", lambda _path: None)
+ monkeypatch.setattr(
+ credential_secrets,
+ "get_or_create_credential_encryption_key",
+ auth_storage.get_or_create_credential_encryption_key,
+ )
+ providers_db._schema_ready = False
+ credential_secrets._schema_ready = False
+ yield
+ providers_db._schema_ready = False
+ credential_secrets._schema_ready = False
+ auth_storage._credential_encryption_key_cache = None
+
+
+def test_provider_create_preserve_replace_clear_and_delete(monkeypatch):
+ plaintext_by_envelope = {"first": "sk-first", "second": "sk-second"}
+ monkeypatch.setattr(
+ providers_route,
+ "resolve_provider_api_key_or_400",
+ lambda _provider_id, envelope, **_kwargs: plaintext_by_envelope.get(envelope, ""),
+ )
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai",
+ display_name = "OpenAI",
+ encrypted_api_key = "first",
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert created.has_api_key is True
+ assert credential_secrets.get_provider_api_key(created.id) == "sk-first"
+
+ metadata_only = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(display_name = "Renamed"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert metadata_only.display_name == "Renamed"
+ assert credential_secrets.get_provider_api_key(created.id) == "sk-first"
+
+ replaced = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(encrypted_api_key = "second"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert replaced.has_api_key is True
+ assert credential_secrets.get_provider_api_key(created.id) == "sk-second"
+
+ cleared = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(clear_api_key = True),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert cleared.has_api_key is False
+ assert credential_secrets.get_provider_api_key(created.id) is None
+
+ credential_secrets.save_provider_api_key(created.id, "sk-before-delete")
+
+ asyncio.run(
+ providers_route.delete_provider_config(
+ created.id, credential = ("alice", None), via_api_key = False
+ )
+ )
+ asyncio.run(
+ providers_route.delete_provider_config(
+ created.id, credential = ("alice", None), via_api_key = False
+ )
+ )
+
+ assert credential_secrets.get_provider_api_key(created.id) is None
+ assert providers_db.get_provider(created.id) is None
+
+
+def test_provider_update_validates_before_writes_and_rolls_back_metadata(monkeypatch):
+ providers_db.create_provider(
+ id = "provider-1",
+ provider_type = "openai",
+ display_name = "Original",
+ base_url = "https://api.openai.com/v1",
+ )
+ credential_secrets.save_provider_api_key("provider-1", "sk-original")
+
+ def invalid_envelope(_provider_id, _envelope, **_kwargs):
+ raise HTTPException(status_code = 400, detail = "invalid envelope")
+
+ monkeypatch.setattr(providers_route, "resolve_provider_api_key_or_400", invalid_envelope)
+ with pytest.raises(HTTPException):
+ asyncio.run(
+ providers_route.update_provider_config(
+ "provider-1",
+ ProviderUpdate(display_name = "Must not persist", encrypted_api_key = "invalid"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert providers_db.get_provider("provider-1")["display_name"] == "Original"
+
+ monkeypatch.setattr(
+ providers_route,
+ "resolve_provider_api_key_or_400",
+ lambda _provider_id, _envelope, **_kwargs: "sk-replacement",
+ )
+ original_save = credential_secrets.save_provider_api_key
+
+ def fail_replacement(provider_id: str, api_key: str):
+ if api_key == "sk-replacement":
+ raise RuntimeError("simulated credential write failure")
+ original_save(provider_id, api_key)
+
+ monkeypatch.setattr(credential_secrets, "save_provider_api_key", fail_replacement)
+ with pytest.raises(RuntimeError, match = "credential write failure"):
+ asyncio.run(
+ providers_route.update_provider_config(
+ "provider-1",
+ ProviderUpdate(display_name = "Also rolled back", encrypted_api_key = "valid"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+
+ assert providers_db.get_provider("provider-1")["display_name"] == "Original"
+ assert credential_secrets.get_provider_api_key("provider-1") == "sk-original"
+
+
+def test_provider_delete_restores_key_when_provider_delete_fails(monkeypatch):
+ providers_db.create_provider(
+ id = "provider-1",
+ provider_type = "openai",
+ display_name = "OpenAI",
+ base_url = "https://api.openai.com/v1",
+ )
+ credential_secrets.save_provider_api_key("provider-1", "sk-original")
+
+ def fail_delete(_provider_id: str):
+ raise RuntimeError("simulated provider delete failure")
+
+ monkeypatch.setattr(providers_db, "delete_provider", fail_delete)
+ with pytest.raises(RuntimeError, match = "provider delete failure"):
+ asyncio.run(
+ providers_route.delete_provider_config(
+ "provider-1", credential = ("alice", None), via_api_key = False
+ )
+ )
+
+ assert providers_db.get_provider("provider-1") is not None
+ assert credential_secrets.get_provider_api_key("provider-1") == "sk-original"
+
+
+def test_credential_writes_reject_a_rotated_request(monkeypatch):
+ @contextmanager
+ def reject_stale(_subject, _generation):
+ raise auth_storage.CredentialRotated("revoked")
+ yield
+
+ monkeypatch.setattr(auth_storage, "credential_generation_guard", reject_stale)
+ with pytest.raises(HTTPException) as error:
+ settings_route.update_hugging_face_token(
+ settings_route.HuggingFaceTokenPayload(token = "hf_stale"),
+ credential = ("alice", "stale-generation"),
+ via_api_key = False,
+ )
+ assert error.value.status_code == 401
+ assert credential_secrets.get_hf_token() is None
+
+
+def test_explicit_provider_key_preserves_the_edited_target():
+ payload = ProviderModelsRequest(
+ provider_id = "provider-1",
+ provider_type = "custom",
+ encrypted_api_key = "encrypted-replacement",
+ base_url = "https://new.example/v1",
+ )
+ assert providers_route._bind_saved_provider_target(payload) is payload
+
+
+def test_provider_mutations_reject_api_key_authentication():
+ with pytest.raises(HTTPException) as error:
+ asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(provider_type = "openai", display_name = "Forbidden"),
+ credential = ("alice", None),
+ via_api_key = True,
+ )
+ )
+ assert error.value.status_code == 403
+ assert providers_db.list_providers() == []
+
+
+def test_shared_provider_resolver_uses_saved_and_explicit_precedence(monkeypatch):
+ credential_secrets.save_provider_api_key("provider-1", "saved")
+ assert providers_route.resolve_provider_api_key_or_400("provider-1", None) == "saved"
+
+ assert (
+ providers_route.resolve_provider_api_key_or_400("provider-1", None, allow_saved_key = False)
+ == ""
+ )
+
+ from core.inference import key_exchange
+
+ monkeypatch.setattr(key_exchange, "decrypt_api_key", lambda value: f"explicit:{value}")
+ assert (
+ providers_route.resolve_provider_api_key_or_400("provider-1", "ciphertext")
+ == "explicit:ciphertext"
+ )
+
+ monkeypatch.setattr(
+ key_exchange,
+ "decrypt_api_key",
+ lambda _value: (_ for _ in ()).throw(ValueError("secret detail")),
+ )
+ with pytest.raises(HTTPException) as error:
+ providers_route.resolve_provider_api_key_or_400("provider-1", "broken")
+ assert error.value.status_code == 400
+ assert "secret detail" not in str(error.value.detail)
+
+
+def test_provider_model_and_connection_routes_use_saved_key(monkeypatch):
+ seen_clients: list[tuple[str, str, str]] = []
+
+ class FakeProviderClient:
+ def __init__(self, **kwargs):
+ seen_clients.append((kwargs["provider_type"], kwargs["base_url"], kwargs["api_key"]))
+
+ async def list_models(self):
+ return [{"id": "mistral-large-latest"}]
+
+ async def close(self):
+ return None
+
+ monkeypatch.setattr(providers_route, "ExternalProviderClient", FakeProviderClient)
+
+ providers_db.create_provider(
+ id = "provider-1",
+ provider_type = "mistral",
+ display_name = "Mistral",
+ base_url = "https://api.mistral.ai/v1",
+ )
+ credential_secrets.save_provider_api_key("provider-1", "saved-key")
+
+ credential_secrets.save_hf_token("hf-after-restart")
+ auth_storage._credential_encryption_key_cache = None
+ credential_secrets._schema_ready = False
+ assert (
+ settings_route.get_hugging_face_token("alice", via_api_key = False).token
+ == "hf-after-restart"
+ )
+
+ models = asyncio.run(
+ providers_route.list_provider_models(
+ ProviderModelsRequest(
+ provider_type = "custom",
+ provider_id = "provider-1",
+ base_url = "https://attacker.invalid/v1",
+ ),
+ _current_subject = "alice",
+ via_api_key = False,
+ )
+ )
+ result = asyncio.run(
+ providers_route.test_provider(
+ ProviderTestRequest(
+ provider_type = "custom",
+ provider_id = "provider-1",
+ base_url = "https://attacker.invalid/v1",
+ ),
+ _current_subject = "alice",
+ via_api_key = False,
+ )
+ )
+
+ api_key_models = asyncio.run(
+ providers_route.list_provider_models(
+ ProviderModelsRequest(
+ provider_type = "custom",
+ provider_id = "provider-1",
+ ),
+ _current_subject = "alice",
+ via_api_key = True,
+ )
+ )
+
+ assert [model.id for model in models] == ["mistral-large-latest"]
+ assert result.success is True
+
+ assert [model.id for model in api_key_models] == ["mistral-large-latest"]
+ assert seen_clients == [
+ ("mistral", "https://api.mistral.ai/v1", "saved-key"),
+ ("mistral", "https://api.mistral.ai/v1", "saved-key"),
+ ("mistral", "https://api.mistral.ai/v1", ""),
+ ]
+
+
+def test_hugging_face_routes_are_global_and_idempotent():
+ jwt_secret = "current-jwt-secret"
+ auth_storage.create_initial_user("alice", "password-123", jwt_secret)
+ credential = ("alice", auth_storage.credential_generation(jwt_secret))
+ # Exercise a cold encryption-key cache while the real generation guard is active.
+ auth_storage._credential_encryption_key_cache = None
+ saved = settings_route.update_hugging_face_token(
+ settings_route.HuggingFaceTokenPayload(token = " 'hf_alice' "),
+ credential = credential,
+ via_api_key = False,
+ )
+ assert saved.token == "hf_alice"
+ assert settings_route.get_hugging_face_token("alice", via_api_key = False).token == "hf_alice"
+ assert settings_route.get_hugging_face_token("bob", via_api_key = False).token == "hf_alice"
+
+ assert settings_route.clear_hugging_face_token(credential, via_api_key = False).has_token is False
+ assert settings_route.clear_hugging_face_token(credential, via_api_key = False).has_token is False
+
+
+def test_legacy_migration_never_replaces_newer_credentials(monkeypatch):
+ credential = ("alice", None)
+ settings_route.update_hugging_face_token(
+ settings_route.HuggingFaceTokenPayload(token = "hf_newer"),
+ credential = credential,
+ via_api_key = False,
+ )
+ migrated_hf = settings_route.migrate_hugging_face_token(
+ settings_route.HuggingFaceTokenPayload(token = "hf_legacy"),
+ credential = credential,
+ via_api_key = False,
+ )
+ assert migrated_hf.token == "hf_newer"
+
+ providers_db.create_provider(
+ id = "provider-1",
+ provider_type = "openai",
+ display_name = "OpenAI",
+ base_url = "https://api.openai.com/v1",
+ )
+ credential_secrets.save_provider_api_key("provider-1", "sk-newer")
+ monkeypatch.setattr(
+ providers_route,
+ "resolve_provider_api_key_or_400",
+ lambda *_args, **_kwargs: "sk-legacy",
+ )
+ migrated_provider = asyncio.run(
+ providers_route.migrate_provider_api_key(
+ "provider-1",
+ ProviderCredentialMigration(encrypted_api_key = "encrypted-legacy"),
+ credential = credential,
+ via_api_key = False,
+ )
+ )
+ assert migrated_provider.has_api_key is True
+ assert credential_secrets.get_provider_api_key("provider-1") == "sk-newer"
+
+
+def test_hugging_face_secret_routes_reject_api_key_authentication():
+ with pytest.raises(HTTPException) as get_error:
+ settings_route.get_hugging_face_token("alice", via_api_key = True)
+ assert get_error.value.status_code == 403
+
+ with pytest.raises(HTTPException) as put_error:
+ settings_route.update_hugging_face_token(
+ settings_route.HuggingFaceTokenPayload(token = "hf_forbidden"),
+ credential = ("alice", None),
+ via_api_key = True,
+ )
+ assert put_error.value.status_code == 403
+
+ with pytest.raises(HTTPException) as delete_error:
+ settings_route.clear_hugging_face_token(
+ ("alice", None),
+ via_api_key = True,
+ )
+ assert delete_error.value.status_code == 403
diff --git a/studio/backend/tests/test_credential_secrets.py b/studio/backend/tests/test_credential_secrets.py
new file mode 100644
index 00000000000..70287ce2370
--- /dev/null
+++ b/studio/backend/tests/test_credential_secrets.py
@@ -0,0 +1,226 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+import sqlite3
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+
+from auth import storage as auth_storage
+from storage import credential_secrets
+
+
[email protected](autouse = True)
+def isolated_databases(tmp_path, monkeypatch):
+ auth_db = tmp_path / "auth.db"
+ studio_db = tmp_path / "studio.db"
+ monkeypatch.setattr(auth_storage, "DB_PATH", auth_db)
+ monkeypatch.setattr(auth_storage, "_credential_encryption_key_cache", None)
+ monkeypatch.setattr(credential_secrets, "studio_db_path", lambda: studio_db)
+ monkeypatch.setattr(
+ credential_secrets, "ensure_dir", lambda path: path.mkdir(parents = True, exist_ok = True)
+ )
+ monkeypatch.setattr(
+ credential_secrets,
+ "get_or_create_credential_encryption_key",
+ auth_storage.get_or_create_credential_encryption_key,
+ )
+ credential_secrets._schema_ready = False
+ yield studio_db
+ credential_secrets._schema_ready = False
+ auth_storage._credential_encryption_key_cache = None
+
+
+def test_round_trip_scopes_and_ciphertext(isolated_databases):
+ secret = "hf_example-secret-value"
+ credential_secrets.save_hf_token(secret)
+
+ assert credential_secrets.get_hf_token() == secret
+ assert secret.encode() not in isolated_databases.read_bytes()
+
+ credential_secrets.save_provider_api_key("provider-1", "sk-one")
+ credential_secrets.save_provider_api_key("provider-2", "sk-two")
+ assert credential_secrets.get_provider_api_key("provider-1") == "sk-one"
+ assert credential_secrets.get_provider_api_key("provider-2") == "sk-two"
+
+
+def test_upsert_and_delete_are_idempotent():
+ credential_secrets.save_provider_api_key("provider-1", "first")
+ credential_secrets.save_provider_api_key("provider-1", "second")
+ assert credential_secrets.get_provider_api_key("provider-1") == "second"
+
+ assert credential_secrets.save_provider_api_key_if_absent("provider-1", "legacy") is False
+ assert credential_secrets.get_provider_api_key("provider-1") == "second"
+ assert credential_secrets.save_hf_token_if_absent("hf_legacy") is True
+ assert credential_secrets.save_hf_token_if_absent("hf_delayed") is False
+ assert credential_secrets.get_hf_token() == "hf_legacy"
+ assert credential_secrets.delete_provider_api_key("provider-1") is True
+ assert credential_secrets.delete_provider_api_key("provider-1") is False
+
+
+def test_tampering_and_key_loss_fail_closed(isolated_databases):
+ credential_secrets.save_hf_token("hf_private")
+ conn = sqlite3.connect(isolated_databases)
+ try:
+ row = conn.execute("SELECT ciphertext FROM credential_secrets").fetchone()
+ damaged = bytearray(row[0])
+ damaged[-1] ^= 1
+ conn.execute("UPDATE credential_secrets SET ciphertext = ?", (bytes(damaged),))
+ conn.commit()
+ finally:
+ conn.close()
+ assert credential_secrets.get_hf_token() is None
+
+ credential_secrets.save_hf_token("hf_replaced-key")
+ auth_storage._credential_encryption_key_cache = None
+ conn = auth_storage.get_connection()
+ try:
+ conn.execute(
+ "UPDATE app_secrets SET value = ? WHERE key = ?",
+ ("00" * 32, auth_storage._CREDENTIAL_ENCRYPTION_KEY_DB_KEY),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ assert credential_secrets.get_hf_token() is None
+
+
+def test_repeated_schema_initialization_and_concurrent_upserts():
+ credential_secrets.get_connection().close()
+ credential_secrets._schema_ready = False
+ credential_secrets.get_connection().close()
+
+ with ThreadPoolExecutor(max_workers = 4) as pool:
+ list(
+ pool.map(
+ lambda value: credential_secrets.save_provider_api_key("provider-1", value),
+ ["one", "two", "three", "four"],
+ )
+ )
+ assert credential_secrets.get_provider_api_key("provider-1") in {
+ "one",
+ "two",
+ "three",
+ "four",
+ }
+
+
+def test_credential_key_persists_independently_of_password_changes():
+ before = auth_storage.get_or_create_credential_encryption_key()
+ auth_storage._credential_encryption_key_cache = None
+ after = auth_storage.get_or_create_credential_encryption_key()
+ assert before == after
+
+
+def test_credentials_survive_real_process_restart(tmp_path):
+ backend_dir = Path(__file__).resolve().parents[1]
+ env = {
+ **os.environ,
+ "UNSLOTH_STUDIO_HOME": str(tmp_path / "studio-home"),
+ }
+ app_setup = """
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from auth.authentication import authenticated_via_api_key, get_current_credential, get_current_subject
+import importlib.util
+from pathlib import Path
+import sys
+import types
+routes_dir = Path.cwd() / "routes"
+routes_package = types.ModuleType("routes")
+routes_package.__path__ = [str(routes_dir)]
+sys.modules["routes"] = routes_package
+def load_route(name, filename):
+ spec = importlib.util.spec_from_file_location(name, routes_dir / filename)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+load_route("routes.provider_credentials", "provider_credentials.py")
+providers = load_route("restart_providers_route", "providers.py")
+settings = load_route("restart_settings_route", "settings.py")
+
+from core.inference.key_exchange import init_key_pair
+init_key_pair()
+app = FastAPI()
+app.include_router(providers.router, prefix="/api/providers")
+app.include_router(settings.router, prefix="/api/settings")
+app.dependency_overrides[get_current_subject] = lambda: "alice"
+app.dependency_overrides[get_current_credential] = lambda: ("alice", None)
+app.dependency_overrides[authenticated_via_api_key] = lambda: False
+client = TestClient(app)
+"""
+ write_credentials = (
+ app_setup
+ + """
+import base64
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import padding
+hf_response = client.put("/api/settings/hugging-face-token", json={"token": "hf_restart"})
+assert hf_response.status_code == 200, hf_response.text
+public_key_pem = client.get("/api/providers/public-key").json()["public_key"]
+public_key = serialization.load_pem_public_key(public_key_pem.encode())
+encrypted_key = base64.b64encode(public_key.encrypt(
+ b"sk_restart",
+ padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
+)).decode()
+provider_response = client.post("/api/providers/", json={
+ "provider_type": "custom",
+ "display_name": "Restart provider",
+ "base_url": "https://provider.invalid/v1",
+ "models": ["restart-model"],
+ "encrypted_api_key": encrypted_key,
+})
+assert provider_response.status_code == 201, provider_response.text
+"""
+ )
+ use_credentials_after_restart = (
+ app_setup
+ + """
+hf_response = client.get("/api/settings/hugging-face-token")
+assert hf_response.status_code == 200, hf_response.text
+assert hf_response.json() == {"token": "hf_restart", "has_token": True}
+provider_rows = client.get("/api/providers/").json()
+assert len(provider_rows) == 1 and provider_rows[0]["has_api_key"] is True
+seen = {}
+class FakeProviderClient:
+ def __init__(self, **kwargs):
+ seen["api_key"] = kwargs["api_key"]
+ async def chat_completion(self, **_kwargs):
+ return {}
+ async def close(self):
+ return None
+providers.ExternalProviderClient = FakeProviderClient
+use_response = client.post("/api/providers/test", json={
+ "provider_type": "custom",
+ "provider_id": provider_rows[0]["id"],
+ "base_url": "https://attacker.invalid/v1",
+ "model_id": "restart-model",
+})
+assert use_response.status_code == 200, use_response.text
+assert use_response.json()["success"] is True
+assert seen["api_key"] == "sk_restart"
+"""
+ )
+
+ subprocess.run(
+ [sys.executable, "-c", write_credentials],
+ cwd = backend_dir,
+ env = env,
+ check = True,
+ timeout = 30,
+ )
+ subprocess.run(
+ [sys.executable, "-c", use_credentials_after_restart],
+ cwd = backend_dir,
+ env = env,
+ check = True,
+ timeout = 30,
+ )
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index e4a96121d16..c912f5125a2 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -26,6 +26,8 @@ def isolated_auth_db(tmp_path, monkeypatch):
monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
monkeypatch.setattr(storage, "_bootstrap_password", None)
monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+
+ monkeypatch.setattr(storage, "_credential_encryption_key_cache", None)
yield
@@ -574,6 +576,12 @@ def test_change_password_revokes_the_desktop_secret_only_for_browsers(desktop):
else web_bearer(client)
)
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+
+ credential_key = storage.get_or_create_credential_encryption_key()
+ nonce = os.urandom(12)
+ encrypted = AESGCM(credential_key).encrypt(nonce, b"hf-survives-password-change", b"test")
+
response = client.post(
"/api/auth/change-password",
headers = {"Authorization": f"Bearer {bearer}"},
@@ -584,6 +592,10 @@ def test_change_password_revokes_the_desktop_secret_only_for_browsers(desktop):
assert is_desktop_token(response.json()["access_token"]) is desktop
assert (storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME) is desktop
+ storage._credential_encryption_key_cache = None
+ reloaded_key = storage.get_or_create_credential_encryption_key()
+ assert AESGCM(reloaded_key).decrypt(nonce, encrypted, b"test") == b"hf-survives-password-change"
+
def test_local_recipe_token_authenticates_as_admin_for_desktop_user(loaded_local_model):
# _inject_local_providers mints an internal sk-unsloth-* API key (not a
@@ -682,10 +694,26 @@ def test_reset_password_removes_desktop_secret_files(tmp_path, monkeypatch):
from typer.testing import CliRunner
from unsloth_cli.commands import studio as studio_cli
+ from auth import storage as auth_storage
+ from storage import credential_secrets
+
auth_dir = tmp_path / "auth"
+ studio_db = tmp_path / "studio.db"
monkeypatch.setattr(studio_cli, "STUDIO_HOME", tmp_path)
+ monkeypatch.setattr(auth_storage, "DB_PATH", auth_dir / "auth.db")
+ monkeypatch.setattr(auth_storage, "_credential_encryption_key_cache", None)
+ monkeypatch.setattr(credential_secrets, "studio_db_path", lambda: studio_db)
+ monkeypatch.setattr(credential_secrets, "ensure_dir", lambda _path: None)
+ monkeypatch.setattr(
+ credential_secrets,
+ "get_or_create_credential_encryption_key",
+ auth_storage.get_or_create_credential_encryption_key,
+ )
+ credential_secrets._schema_ready = False
+
secret = studio_cli._create_desktop_secret_in_cli()
studio_cli._write_auth_secret(auth_dir / studio_cli.DESKTOP_SECRET_FILE, secret)
+ credential_secrets.save_hf_token("hf_survives_reset")
(auth_dir / studio_cli.BOOTSTRAP_PASSWORD_FILE).write_text("boot")
result = CliRunner().invoke(studio_cli.studio_app, ["reset-password"])
@@ -705,10 +733,21 @@ def test_reset_password_removes_desktop_secret_files(tmp_path, monkeypatch):
studio_cli.DESKTOP_SECRET_CREATED_AT_KEY,
),
).fetchone()[0]
+
+ credential_key = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ ("credential_encryption_key_v1",),
+ ).fetchone()
finally:
conn.close()
assert surviving == 0
+ assert credential_key is not None
+ auth_storage._credential_encryption_key_cache = None
+ assert credential_secrets.get_hf_token() == "hf_survives_reset"
+ credential_secrets._schema_ready = False
+ auth_storage._credential_encryption_key_cache = None
+
def test_reset_password_removes_desktop_secret_files_without_db(tmp_path, monkeypatch):
from typer.testing import CliRunner
diff --git a/studio/backend/tests/test_external_provider_usage_chunk.py b/studio/backend/tests/test_external_provider_usage_chunk.py
index e48ba02e8f7..e0830f90400 100644
--- a/studio/backend/tests/test_external_provider_usage_chunk.py
+++ b/studio/backend/tests/test_external_provider_usage_chunk.py
@@ -272,7 +272,8 @@ def test_custom_provider_test_endpoint_probes_chat_completion(monkeypatch):
base_url = "http://custom.example/v1",
model_id = "Qwen/Qwen3-0.6B",
),
- current_subject = "unsloth",
+ _current_subject = "unsloth",
+ via_api_key = False,
)
result = _drive(run())
@@ -312,7 +313,8 @@ def test_custom_provider_test_endpoint_requires_model_id(monkeypatch):
provider_type = "custom",
base_url = "http://custom.example/v1",
),
- current_subject = "unsloth",
+ _current_subject = "unsloth",
+ via_api_key = False,
)
result = _drive(run())
diff --git a/studio/backend/tests/test_gemini_provider.py b/studio/backend/tests/test_gemini_provider.py
index be409b02db5..81b269099e4 100644
--- a/studio/backend/tests/test_gemini_provider.py
+++ b/studio/backend/tests/test_gemini_provider.py
@@ -5181,7 +5181,9 @@ def test_gemini_custom_oai_compat_base_skips_native_allowlist():
provider_type = "gemini",
base_url = "https://litellm.example/v1",
)
- result = _asyncio.run(list_provider_models(req, current_subject = "unsloth"))
+ result = _asyncio.run(
+ list_provider_models(req, _current_subject = "unsloth", via_api_key = False)
+ )
finally:
_providers.ExternalProviderClient = orig
ids = {m.id for m in result}
diff --git a/studio/backend/tests/test_openai_container_crud.py b/studio/backend/tests/test_openai_container_crud.py
index e0604527fd2..a6997e18f79 100644
--- a/studio/backend/tests/test_openai_container_crud.py
+++ b/studio/backend/tests/test_openai_container_crud.py
@@ -15,10 +15,13 @@ from __future__ import annotations
import asyncio
import json
+from types import SimpleNamespace
import httpx
import pytest
+from fastapi import HTTPException
+
from core.inference import external_provider as ep_mod
from core.inference.external_provider import ExternalProviderClient
@@ -156,6 +159,241 @@ def test_delete_propagates_openai_4xx(monkeypatch):
_drive(_make_client().delete_openai_container("cntr_missing"))
+def test_external_chat_route_resolves_saved_provider_key(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import ChatCompletionRequest
+
+ class ResolverReached(Exception):
+ pass
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: {
+ "provider_type": "mistral",
+ "base_url": "https://api.mistral.ai/v1",
+ "display_name": "Mistral",
+ "is_enabled": True,
+ },
+ )
+
+ def resolve(provider_id, encrypted_api_key, **kwargs):
+ raise ResolverReached(provider_id, encrypted_api_key, kwargs)
+
+ monkeypatch.setattr(inf_mod, "resolve_provider_api_key_or_400", resolve)
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ provider_id = "provider-1",
+ external_model = "mistral-large-latest",
+ )
+
+ with pytest.raises(ResolverReached) as reached:
+ _drive(inf_mod._proxy_to_external_provider(payload, None, current_subject = "alice"))
+ assert reached.value.args == ("provider-1", None, {"allow_saved_key": True})
+
+
+def test_external_chat_api_keys_cannot_use_saved_provider_key(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import ChatCompletionRequest
+
+ class ResolverReached(Exception):
+ pass
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: {
+ "provider_type": "mistral",
+ "base_url": "https://api.mistral.ai/v1",
+ "display_name": "Mistral",
+ "is_enabled": True,
+ },
+ )
+
+ def resolve(provider_id, encrypted_api_key, **kwargs):
+ raise ResolverReached(provider_id, encrypted_api_key, kwargs)
+
+ monkeypatch.setattr(inf_mod, "resolve_provider_api_key_or_400", resolve)
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ provider_id = "provider-1",
+ external_model = "mistral-large-latest",
+ )
+ request = httpx.Request(
+ "POST",
+ "http://test/v1/chat/completions",
+ headers = {"Authorization": "Bearer sk-unsloth-internal-workflow"},
+ )
+
+ with pytest.raises(ResolverReached) as reached:
+ _drive(inf_mod._proxy_to_external_provider(payload, request))
+ assert reached.value.args == ("provider-1", None, {"allow_saved_key": False})
+
+
+def test_external_chat_explicit_key_honors_edited_target(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import ChatCompletionRequest
+
+ class ClientReached(Exception):
+ pass
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: (_ for _ in ()).throw(
+ AssertionError("explicit keys must not bind saved metadata")
+ ),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "resolve_provider_api_key_or_400",
+ lambda *_args, **_kwargs: "replacement-key",
+ )
+
+ def client(**kwargs):
+ raise ClientReached(kwargs)
+
+ monkeypatch.setattr(inf_mod, "ExternalProviderClient", client)
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ provider_id = "provider-1",
+ provider_type = "custom",
+ provider_base_url = "https://new.example/v1",
+ encrypted_api_key = "encrypted-replacement",
+ external_model = "new-model",
+ )
+
+ request = SimpleNamespace(headers = {}, state = SimpleNamespace(skip_api_monitor = True))
+ with pytest.raises(ClientReached) as reached:
+ _drive(inf_mod._proxy_to_external_provider(payload, request))
+ assert reached.value.args[0] == {
+ "provider_type": "custom",
+ "base_url": "https://new.example/v1",
+ "api_key": "replacement-key",
+ }
+
+
+def test_container_client_explicit_key_honors_request_target(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import OpenAIContainerRequest
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: (_ for _ in ()).throw(
+ AssertionError("explicit keys must not bind saved metadata")
+ ),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "resolve_provider_api_key_or_400",
+ lambda *_args, **_kwargs: "replacement-key",
+ )
+ client = inf_mod._resolve_openai_cloud_client(
+ OpenAIContainerRequest(
+ provider_id = "provider-1",
+ encrypted_api_key = "encrypted-replacement",
+ provider_base_url = "https://api.openai.com/v1",
+ ),
+ allow_saved_key = False,
+ )
+ assert client.api_key == "replacement-key"
+ assert client.base_url == "https://api.openai.com/v1"
+ _drive(client.close())
+
+
+def test_container_client_uses_saved_provider_key(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import OpenAIContainerRequest
+
+ calls: list[tuple[str | None, str | None, bool]] = []
+
+ def resolve(
+ provider_id,
+ encrypted_api_key,
+ *,
+ allow_saved_key = True,
+ ):
+ calls.append((provider_id, encrypted_api_key, allow_saved_key))
+ return "saved-key"
+
+ monkeypatch.setattr(inf_mod, "resolve_provider_api_key_or_400", resolve)
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: {
+ "provider_type": "openai",
+ "base_url": "https://api.openai.com/v1",
+ "display_name": "OpenAI",
+ "is_enabled": True,
+ },
+ )
+ client = inf_mod._resolve_openai_cloud_client(
+ OpenAIContainerRequest(
+ provider_id = "provider-1",
+ provider_base_url = "https://attacker.invalid/v1",
+ ),
+ allow_saved_key = True,
+ )
+
+ assert client.api_key == "saved-key"
+
+ assert client.base_url == "https://api.openai.com/v1"
+ assert calls == [("provider-1", None, True)]
+ _drive(client.close())
+
+
+def test_container_route_blocks_saved_keys_for_internal_api_key(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import OpenAIContainerRequest
+
+ class ResolverReached(Exception):
+ pass
+
+ def fake_resolve(_body, *, allow_saved_key):
+ raise ResolverReached(allow_saved_key)
+
+ monkeypatch.setattr(inf_mod, "_resolve_openai_cloud_client", fake_resolve)
+ request = httpx.Request(
+ "POST",
+ "http://test/api/external/openai/containers/list",
+ headers = {"Authorization": "Bearer sk-unsloth-internal-workflow"},
+ )
+ with pytest.raises(ResolverReached) as reached:
+ _drive(
+ inf_mod.list_openai_containers(
+ OpenAIContainerRequest(provider_id = "provider-1"),
+ request,
+ current_subject = "u",
+ )
+ )
+ assert reached.value.args == (False,)
+
+
+def test_container_client_rejects_openai_lookalike_host(monkeypatch):
+ from routes import inference as inf_mod
+ from models.inference import OpenAIContainerRequest
+
+ monkeypatch.setattr(
+ inf_mod.providers_db,
+ "get_provider",
+ lambda _provider_id: {
+ "provider_type": "openai",
+ "base_url": "https://api.openai.com.attacker.example/v1",
+ "display_name": "OpenAI",
+ "is_enabled": True,
+ },
+ )
+
+ with pytest.raises(HTTPException) as error:
+ inf_mod._resolve_openai_cloud_client(
+ OpenAIContainerRequest(provider_id = "provider-1"),
+ allow_saved_key = True,
+ )
+ assert error.value.status_code == 400
+
+
def test_list_route_filters_expired_containers(monkeypatch):
"""OpenAI keeps containers in /v1/containers with status="expired"
after their idle TTL passes — unusable but still listed. The list
@@ -177,7 +415,8 @@ def test_list_route_filters_expired_containers(monkeypatch):
_mock_http_client(monkeypatch, handler)
- def fake_resolve(_body):
+ def fake_resolve(_body, *, allow_saved_key):
+ assert allow_saved_key is True
return _make_client()
monkeypatch.setattr(inf_mod, "_resolve_openai_cloud_client", fake_resolve)
@@ -186,7 +425,8 @@ def test_list_route_filters_expired_containers(monkeypatch):
encrypted_api_key = "enc",
provider_base_url = "https://api.openai.com/v1",
)
- response = _drive(inf_mod.list_openai_containers(body, current_subject = "u"))
+ request = httpx.Request("POST", "http://test/api/external/openai/containers/list")
+ response = _drive(inf_mod.list_openai_containers(body, request, current_subject = "u"))
ids = [c.id for c in response.containers]
assert "cntr_active" in ids
assert "cntr_unknown" in ids # missing status is treated as usable
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 70f94632c32..eda5e2e8f33 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -6,7 +6,11 @@ import { Navbar } from "@/components/navbar";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";
-import { hasAuthToken } from "@/features/auth";
+import {
+ AUTH_SESSION_CLEARED_EVENT,
+ AUTH_SESSION_STORED_EVENT,
+ hasAuthToken,
+} from "@/features/auth";
import {
ChatPage,
type ChatSearch,
@@ -16,6 +20,7 @@ import {
} from "@/features/chat";
import { useExportRuntimeLifecycle } from "@/features/export";
import { HfTokenWarningDialog } from "@/features/hf-auth";
+import { bootstrapPersistedCredentials } from "@/features/credentials/bootstrap";
import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
import { usePersonalizationSync } from "@/features/profile";
import { RemoteCodeConsentDialog } from "@/features/security";
@@ -35,10 +40,14 @@ import {
import { AnimatePresence, motion } from "motion/react";
import {
lazy,
+
+ type ReactNode,
Suspense,
useEffect,
useLayoutEffect,
useMemo,
+ useRef,
+
useState,
} from "react";
import { AppProvider } from "../provider";
@@ -77,6 +86,44 @@ function PersonalizationSyncMount() {
return null;
}
+
+function CredentialBootstrapGate({ children }: { children: ReactNode }) {
+ const [ready, setReady] = useState(false);
+ const runRevision = useRef(0);
+
+ useEffect(() => {
+ let active = true;
+ const reconcile = () => {
+ const revision = ++runRevision.current;
+ if (!hasAuthToken()) {
+ setReady(false);
+ return;
+ }
+ setReady(false);
+ void bootstrapPersistedCredentials().finally(() => {
+ if (
+ active &&
+ revision === runRevision.current &&
+ hasAuthToken()
+ ) {
+ setReady(true);
+ }
+ });
+ };
+
+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, reconcile);
+ window.addEventListener(AUTH_SESSION_STORED_EVENT, reconcile);
+ reconcile();
+ return () => {
+ active = false;
+ runRevision.current += 1;
+ window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, reconcile);
+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, reconcile);
+ };
+ }, []);
+ return ready ? children : <RouteFallback />;
+}
+
const CHAT_ONLY_ALLOWED = new Set([
"/",
"/chat",
@@ -289,8 +336,8 @@ function RootLayout() {
chatRuntime.setIncognito(false);
}, [isChatRoute]);
- return (
- <AppProvider>
+ const content = (
+ <>
<PersonalizationSyncMount />
{!isAuthFlowRoute && <SettingsDialog />}
{/* Opens itself when API traffic arrives; hides on the full monitor page. */}
@@ -392,6 +439,16 @@ function RootLayout() {
</SidebarInset>
</SidebarProvider>
)}
+ </>
+ );
+
+ return (
+ <AppProvider>
+ {!isAuthFlowRoute || pathname === "/onboarding" ? (
+ <CredentialBootstrapGate>{content}</CredentialBootstrapGate>
+ ) : (
+ content
+ )}
</AppProvider>
);
}
diff --git a/studio/frontend/src/features/auth/index.ts b/studio/frontend/src/features/auth/index.ts
index b4fbc4ee8e3..08cf646dcdd 100644
--- a/studio/frontend/src/features/auth/index.ts
+++ b/studio/frontend/src/features/auth/index.ts
@@ -6,8 +6,11 @@ export { ChangePasswordPage } from "./change-password-page";
export { authFetch, logout, refreshSession } from "./api";
export {
AUTH_SESSION_CLEARED_EVENT,
+
+ AUTH_SESSION_STORED_EVENT,
clearAuthTokens,
getAuthToken,
+ getAuthSessionEpoch,
getPostAuthRoute,
hasAuthToken,
hasRefreshToken,
diff --git a/studio/frontend/src/features/auth/session-events.ts b/studio/frontend/src/features/auth/session-events.ts
new file mode 100644
index 00000000000..eee0e28ebad
--- /dev/null
+++ b/studio/frontend/src/features/auth/session-events.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const AUTH_SESSION_CLEARED_EVENT = "unsloth:auth-session-cleared";
+export const AUTH_SESSION_STORED_EVENT = "unsloth:auth-session-stored";
diff --git a/studio/frontend/src/features/auth/session.ts b/studio/frontend/src/features/auth/session.ts
index 691714ecb41..d9442e4ace7 100644
--- a/studio/frontend/src/features/auth/session.ts
+++ b/studio/frontend/src/features/auth/session.ts
@@ -4,11 +4,25 @@
import { usePlatformStore } from "@/config/env";
import { isTauri } from "@/lib/api-base";
+import {
+ AUTH_SESSION_CLEARED_EVENT,
+ AUTH_SESSION_STORED_EVENT,
+} from "./session-events";
+
+export { AUTH_SESSION_CLEARED_EVENT, AUTH_SESSION_STORED_EVENT } from "./session-events";
+
export const AUTH_TOKEN_KEY = "unsloth_auth_token";
export const AUTH_REFRESH_TOKEN_KEY = "unsloth_auth_refresh_token";
export const ONBOARDING_DONE_KEY = "unsloth_onboarding_done";
export const AUTH_MUST_CHANGE_PASSWORD_KEY = "unsloth_auth_must_change_password";
-export const AUTH_SESSION_CLEARED_EVENT = "unsloth:auth-session-cleared";
+
+
+let authSessionEpoch = 0;
+
+/** Stable across access-token refreshes; changes when an auth session starts or clears. */
+export function getAuthSessionEpoch(): number {
+ return authSessionEpoch;
+}
type PostAuthRoute = "/change-password" | "/chat";
@@ -44,12 +58,18 @@ export function storeAuthTokens(
// it through would let CodeQL trace the boolean into localStorage and flag the
// deliberate JWT writes as sensitive-info storage.
if (!canUseStorage()) return;
+ const sessionStarted = !localStorage.getItem(AUTH_TOKEN_KEY);
localStorage.setItem(AUTH_TOKEN_KEY, accessToken);
localStorage.setItem(AUTH_REFRESH_TOKEN_KEY, refreshToken);
+ if (sessionStarted) {
+ authSessionEpoch += 1;
+ window.dispatchEvent(new Event(AUTH_SESSION_STORED_EVENT));
+ }
}
export function clearAuthTokens(): void {
if (!canUseStorage()) return;
+ authSessionEpoch += 1;
localStorage.removeItem(AUTH_TOKEN_KEY);
localStorage.removeItem(AUTH_REFRESH_TOKEN_KEY);
localStorage.removeItem(AUTH_MUST_CHANGE_PASSWORD_KEY);
@@ -88,6 +108,8 @@ export function resetOnboardingDone(): void {
localStorage.removeItem(ONBOARDING_DONE_KEY);
}
+
+
export function getPostAuthRoute(): PostAuthRoute {
if (isTauri) return "/chat";
if (mustChangePassword()) return "/change-password";
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 271152d820f..8d5b811e7ba 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -3907,9 +3907,10 @@ export function createOpenAIStreamAdapter(
const selectedModelSummary = runtime.models.find(
(model) => model.id === params.checkpoint,
);
- const externalApiKey = externalProvider
- ? getExternalProviderApiKey(externalProvider.id).trim()
- : "";
+ const externalApiKey =
+ externalProvider && !externalProvider.hasApiKey
+ ? getExternalProviderApiKey(externalProvider.id).trim()
+ : "";
if (isExternalRequest && !externalProvider) {
toast.error("Connection not found.", {
@@ -3930,6 +3931,7 @@ export function createOpenAIStreamAdapter(
if (
isExternalRequest &&
!externalApiKey &&
+ !externalProvider?.hasApiKey &&
!externalProviderIsCustom &&
!externalProviderIsGeminiCustomBase
) {
@@ -4770,6 +4772,8 @@ export function createOpenAIStreamAdapter(
if (externalProvider.providerType === "openai") {
try {
const list = await listOpenAIContainers({
+ providerId: externalProvider.id,
+
apiKey: externalApiKey,
baseUrl: externalProvider.baseUrl || null,
});
@@ -4834,6 +4838,8 @@ export function createOpenAIStreamAdapter(
try {
const created = await createOpenAIContainer(
{
+ providerId: externalProvider.id,
+
apiKey: externalApiKey,
baseUrl: externalProvider.baseUrl || null,
},
diff --git a/studio/frontend/src/features/chat/api/openai-containers.ts b/studio/frontend/src/features/chat/api/openai-containers.ts
index f95b5a6349d..96eb7b95fa7 100644
--- a/studio/frontend/src/features/chat/api/openai-containers.ts
+++ b/studio/frontend/src/features/chat/api/openai-containers.ts
@@ -4,7 +4,7 @@
/**
* Wrappers for the backend's three OpenAI shell-tool container endpoints
* (studio/backend/routes/inference.py). Each proxies to OpenAI's
- * /v1/containers using the user's encrypted API key. Backend rejects any
+ * /v1/containers using a saved provider key or encrypted request override. Backend rejects any
* base URL but api.openai.com (the shell tool is managed-cloud only).
*/
@@ -46,13 +46,17 @@ async function parseError(response: Response): Promise<string> {
}
interface AuthInputs {
- apiKey: string;
+ providerId: string;
+ apiKey?: string | null;
baseUrl: string | null;
}
async function buildAuthBody(auth: AuthInputs) {
return {
- encrypted_api_key: await encryptProviderApiKey(auth.apiKey),
+ provider_id: auth.providerId,
+ ...(auth.apiKey
+ ? { encrypted_api_key: await encryptProviderApiKey(auth.apiKey) }
+ : {}),
provider_base_url: auth.baseUrl,
};
}
diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.ts
index c6c56132724..53f9254fcac 100644
--- a/studio/frontend/src/features/chat/api/providers-api.ts
+++ b/studio/frontend/src/features/chat/api/providers-api.ts
@@ -2,7 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import forge from "node-forge";
-import { authFetch } from "@/features/auth";
+import { authFetch } from "@/features/auth/api";
import { formatFastApiDetail } from "@/lib/format-fastapi-error";
export interface ProviderRegistryEntry {
@@ -23,6 +23,8 @@ export interface ProviderConfig {
display_name: string;
base_url: string;
is_enabled: boolean;
+
+ has_api_key: boolean;
models?: string[];
available_models?: string[];
created_at: string;
@@ -127,19 +129,23 @@ export async function createProviderConfig(payload: {
baseUrl?: string | null;
models?: string[];
availableModels?: string[];
+ apiKey?: string;
}): Promise<ProviderConfig> {
- const response = await authFetch("/api/providers/", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider_type: payload.providerType,
- display_name: payload.displayName,
- base_url: payload.baseUrl ?? null,
- models: payload.models ?? [],
- available_models: payload.availableModels ?? [],
- }),
+ return withApiKeyEncryptionRetry(payload.apiKey ?? "", async (encryptedApiKey) => {
+ const response = await authFetch("/api/providers/", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider_type: payload.providerType,
+ display_name: payload.displayName,
+ base_url: payload.baseUrl ?? null,
+ models: payload.models ?? [],
+ available_models: payload.availableModels ?? [],
+ encrypted_api_key: encryptedApiKey,
+ }),
+ });
+ return parseJsonOrThrow<ProviderConfig>(response);
});
- return parseJsonOrThrow<ProviderConfig>(response);
}
export async function deleteProviderConfig(providerId: string): Promise<void> {
@@ -166,24 +172,45 @@ export async function updateProviderConfig(
isEnabled?: boolean;
models?: string[];
availableModels?: string[];
+ apiKey?: string;
+ clearApiKey?: boolean;
},
): Promise<ProviderConfig> {
- const response = await authFetch(`/api/providers/${providerId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- ...(payload.displayName === undefined ? {} : { display_name: payload.displayName }),
- ...(payload.baseUrl === undefined ? {} : { base_url: payload.baseUrl }),
- ...(payload.isEnabled === undefined ? {} : { is_enabled: payload.isEnabled }),
- ...(payload.models === undefined ? {} : { models: payload.models }),
- ...(payload.availableModels === undefined
- ? {}
- : { available_models: payload.availableModels }),
- }),
+ return withApiKeyEncryptionRetry(payload.apiKey ?? "", async (encryptedApiKey) => {
+ const response = await authFetch(`/api/providers/${providerId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...(payload.displayName === undefined ? {} : { display_name: payload.displayName }),
+ ...(payload.baseUrl === undefined ? {} : { base_url: payload.baseUrl }),
+ ...(payload.isEnabled === undefined ? {} : { is_enabled: payload.isEnabled }),
+ ...(payload.models === undefined ? {} : { models: payload.models }),
+ ...(payload.availableModels === undefined
+ ? {}
+ : { available_models: payload.availableModels }),
+ ...(payload.apiKey === undefined ? {} : { encrypted_api_key: encryptedApiKey }),
+ ...(payload.clearApiKey === undefined ? {} : { clear_api_key: payload.clearApiKey }),
+ }),
+ });
+ return parseJsonOrThrow<ProviderConfig>(response);
});
- return parseJsonOrThrow<ProviderConfig>(response);
}
+export async function migrateProviderApiKey(
+ providerId: string,
+ apiKey: string,
+): Promise<ProviderConfig> {
+ return withApiKeyEncryptionRetry(apiKey, async (encryptedApiKey) => {
+ const response = await authFetch(`/api/providers/${providerId}/api-key/migrate`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ encrypted_api_key: encryptedApiKey }),
+ });
+ return parseJsonOrThrow<ProviderConfig>(response);
+ });
+}
+
+
async function withApiKeyEncryptionRetry<T>(
plaintextApiKey: string,
call: (encryptedApiKey: string | null) => Promise<T>,
@@ -207,6 +234,8 @@ async function withApiKeyEncryptionRetry<T>(
export async function testProviderConnection(payload: {
providerType: string;
+
+ providerId?: string | null;
apiKey: string;
baseUrl?: string | null;
modelId?: string | null;
@@ -217,6 +246,8 @@ export async function testProviderConnection(payload: {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider_type: payload.providerType,
+
+ provider_id: payload.providerId ?? null,
encrypted_api_key: encryptedApiKey,
base_url: payload.baseUrl ?? null,
model_id: payload.modelId ?? null,
@@ -228,6 +259,8 @@ export async function testProviderConnection(payload: {
export async function listProviderModels(payload: {
providerType: string;
+
+ providerId?: string | null;
apiKey: string;
baseUrl?: string | null;
}): Promise<ProviderModelInfo[]> {
@@ -237,6 +270,8 @@ export async function listProviderModels(payload: {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider_type: payload.providerType,
+
+ provider_id: payload.providerId ?? null,
encrypted_api_key: encryptedApiKey,
base_url: payload.baseUrl ?? null,
}),
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index d2ff6954481..6020bc653c1 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -189,7 +189,6 @@ import {
import { useChatPreferencesStore } from "./stores/chat-preferences-store";
import { useResearchRunStore } from "./stores/research-run-store";
import { useExternalProvidersStore } from "./stores/external-providers-store";
-import { syncExternalProvidersFromBackend } from "./sync-external-providers";
import { buildChatTourSteps } from "./tour";
import type { ChatView, MessageRecord } from "./types";
import { clearNewChatDraft } from "./utils/composer-draft";
@@ -1868,18 +1867,8 @@ export function ChatPage({
const externalProvidersForChat = connectionsEnabled ? externalProviders : [];
useEffect(() => {
- void (async () => {
- await hydratePersistedSettings();
- try {
- const synced = await syncExternalProvidersFromBackend(
- useExternalProvidersStore.getState().providers,
- );
- setExternalProviders(synced);
- } catch {
- // Silent on startup; Connections settings still surfaces load errors.
- }
- })();
- }, [hydratePersistedSettings, setExternalProviders]);
+ void hydratePersistedSettings();
+ }, [hydratePersistedSettings]);
useEffect(() => {
// Skip while off-route: ChatPage stays mounted, and toast+navigate here would
diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
index 7e0cebea4bc..524f41d7923 100644
--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
@@ -46,6 +46,8 @@ import {
testProviderConnection,
updateProviderConfig,
} from "./api/providers-api";
+
+import { resolveProviderCredentialEdit } from "./provider-credential-edit";
import type { ExternalProviderConfig } from "./external-providers";
import {
CUSTOM_PROVIDER_PRESETS,
@@ -59,7 +61,6 @@ import {
LEGACY_CUSTOM_PROVIDER_TYPE,
CUSTOM_PROVIDER_DISPLAY_NAME,
removeExternalProviderApiKey,
- setExternalProviderApiKey,
supportsProviderPromptCaching,
supportsProviderReasoningToggle,
supportsRemoteModelCatalog,
@@ -157,6 +158,8 @@ export function ChatProvidersSettings({
const [providerType, setProviderType] = useState<string>("");
const [apiKey, setApiKey] = useState("");
const [showApiKey, setShowApiKey] = useState(false);
+
+ const [clearApiKeyRequested, setClearApiKeyRequested] = useState(false);
const [baseUrlDraft, setBaseUrlDraft] = useState("");
const [editingProviderId, setEditingProviderId] = useState<string | null>(
null,
@@ -221,8 +224,15 @@ export function ChatProvidersSettings({
availableModels.length > 0;
const missingModelCatalogBaseUrl =
supportsRemoteModelCatalog(providerType) && baseUrlDraft.trim().length === 0;
+ const editingProviderHasSavedKey = Boolean(
+ editingProviderId &&
+ providers.find((provider) => provider.id === editingProviderId)?.hasApiKey,
+ );
const missingModelCatalogApiKey =
- !isCustomProvider && !isCuratedModelList && apiKey.trim().length === 0;
+ !isCustomProvider &&
+ !isCuratedModelList &&
+ apiKey.trim().length === 0 &&
+ !(editingProviderHasSavedKey && !clearApiKeyRequested);
const loadModelsDisabled =
modelsLoading ||
mutatingProvider ||
@@ -359,6 +369,8 @@ export function ChatProvidersSettings({
function resetForm() {
setEditingProviderId(null);
setApiKey("");
+
+ setClearApiKeyRequested(false);
setShowApiKey(false);
setBaseUrlDraft("");
setAvailableModels([]);
@@ -455,7 +467,7 @@ export function ChatProvidersSettings({
);
return;
}
- if (!isCustomProvider && !apiKey.trim()) {
+ if (!isCustomProvider && !apiKey.trim() && !editingProviderHasSavedKey) {
toast.error("Add an API key first.");
return;
}
@@ -470,6 +482,8 @@ export function ChatProvidersSettings({
toExternalBackendProviderType(providerType) ?? providerType;
const models = await listProviderModels({
providerType: backendProviderType,
+
+ providerId: editingProviderId,
apiKey: apiKey.trim(),
baseUrl,
});
@@ -586,6 +600,8 @@ export function ChatProvidersSettings({
availableModels: manualOnly
? []
: pruneProviderModelIds(providerType, availableModels),
+ apiKey: apiKey.trim(),
+
});
const createdAt = Number.isFinite(Date.parse(created.created_at))
? Date.parse(created.created_at)
@@ -605,15 +621,14 @@ export function ChatProvidersSettings({
availableModels: manualOnly
? []
: pruneProviderModelIds(providerType, availableModels),
+
+ hasApiKey: created.has_api_key,
isReasoningModel: supportsProviderReasoningToggle(uiProviderType)
? isReasoningModel
: undefined,
createdAt,
updatedAt,
};
- if (apiKey.trim()) {
- setExternalProviderApiKey(created.id, apiKey.trim());
- }
onProvidersChange([
...providers.filter((p) => p.id !== created.id),
provider,
@@ -640,7 +655,15 @@ export function ChatProvidersSettings({
}
const isEditingCustomProvider =
isCustomProviderType(existing.providerType);
- if (!isEditingCustomProvider && !apiKey.trim()) {
+ const credentialEdit = resolveProviderCredentialEdit(
+ Boolean(
+ existing.hasApiKey ||
+ (!existing.hasApiKey && getExternalProviderApiKey(existing.id).trim()),
+ ),
+ apiKey,
+ clearApiKeyRequested,
+ );
+ if (!isEditingCustomProvider && credentialEdit.action === "missing") {
toast.error("API key is required.");
return;
}
@@ -705,10 +728,17 @@ export function ChatProvidersSettings({
availableModels: manualOnly
? []
: pruneProviderModelIds(existing.providerType, availableModels),
+ ...(credentialEdit.action === "replace"
+ ? { apiKey: credentialEdit.apiKey }
+ : credentialEdit.action === "clear"
+ ? { clearApiKey: true }
+ : {}),
});
- if (apiKey.trim()) {
- setExternalProviderApiKey(editingProviderId, apiKey.trim());
- } else if (isEditingCustomProvider) {
+
+ if (
+ credentialEdit.action === "replace" ||
+ credentialEdit.action === "clear"
+ ) {
removeExternalProviderApiKey(editingProviderId);
}
const updatedAt = Number.isFinite(Date.parse(updated.updated_at))
@@ -725,6 +755,8 @@ export function ChatProvidersSettings({
availableModels: manualOnly
? []
: pruneProviderModelIds(existing.providerType, availableModels),
+
+ hasApiKey: updated.has_api_key,
isReasoningModel: supportsProviderReasoningToggle(
existing.providerType,
)
@@ -753,7 +785,11 @@ export function ChatProvidersSettings({
setCustomProviderName(
provider.name || customProviderDisplayName(provider.providerType),
);
- setApiKey(getExternalProviderApiKey(provider.id));
+ setApiKey(
+ provider.hasApiKey ? "" : getExternalProviderApiKey(provider.id),
+ );
+
+ setClearApiKeyRequested(false);
setShowApiKey(false);
setBaseUrlDraft(provider.baseUrl);
setModelSearchQuery("");
@@ -833,11 +869,14 @@ export function ChatProvidersSettings({
}
async function testProvider(provider: ExternalProviderConfig) {
- const savedKey = getExternalProviderApiKey(provider.id).trim();
+ const savedKey = provider.hasApiKey
+ ? ""
+ : getExternalProviderApiKey(provider.id).trim();
// Hosted registry providers require keys. Local OpenAI-compatible presets
// may be keyless.
if (
!savedKey &&
+ !provider.hasApiKey &&
!supportsRemoteModelCatalog(provider.providerType)
) {
if (isCustomProviderType(provider.providerType)) {
@@ -854,6 +893,8 @@ export function ChatProvidersSettings({
providerType:
toExternalBackendProviderType(provider.providerType) ??
provider.providerType,
+
+ providerId: provider.id,
apiKey: savedKey,
baseUrl: provider.baseUrl || null,
modelId:
@@ -1013,7 +1054,9 @@ export function ChatProvidersSettings({
API key {isCustomProvider ? "(optional)" : ""}
</Label>
<p className="text-xs leading-snug text-muted-foreground">
- Stored locally.
+ {editingProviderHasSavedKey
+ ? "Saved securely. Leave blank to keep it."
+ : "Saved securely after you connect."}
</p>
</div>
<div className="relative min-w-0">
@@ -1021,8 +1064,15 @@ export function ChatProvidersSettings({
id="provider-api-key"
type={showApiKey ? "text" : "password"}
value={apiKey}
- onChange={(event) => setApiKey(event.target.value)}
- placeholder="Enter API key"
+ onChange={(event) => {
+ setApiKey(event.target.value);
+ if (event.target.value.trim()) setClearApiKeyRequested(false);
+ }}
+ placeholder={
+ editingProviderHasSavedKey
+ ? "Leave blank to keep saved key"
+ : "Enter API key"
+ }
className="h-9 pr-9 text-sm"
/>
<button
@@ -1038,6 +1088,26 @@ export function ChatProvidersSettings({
<EyeOff className="size-3.5" />
)}
</button>
+ {editingProviderHasSavedKey ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="mt-1 h-7 px-2 text-xs"
+ onClick={() => {
+ setApiKey("");
+ setClearApiKeyRequested((requested) => !requested);
+ }}
+ >
+ {clearApiKeyRequested ? "Keep saved key" : "Remove saved key"}
+ </Button>
+ ) : null}
+ {clearApiKeyRequested ? (
+ <p className="mt-1 text-xs text-destructive">
+ The saved key will be removed when you save this connection.
+ </p>
+ ) : null}
+
</div>
</div>
) : null}
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index cb4fc01fb04..0b72ec3e2ff 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -730,9 +730,10 @@ export function ChatSettingsPanel({
externalSelection?.modelId,
);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
- const openAiApiKeyForSection = activeExternalProvider
- ? getExternalProviderApiKey(activeExternalProvider.id) || null
- : null;
+ const openAiApiKeyForSection =
+ activeExternalProvider && !activeExternalProvider.hasApiKey
+ ? getExternalProviderApiKey(activeExternalProvider.id) || null
+ : null;
function set<K extends keyof InferenceParams>(key: K) {
return (v: InferenceParams[K]) => {
diff --git a/studio/frontend/src/features/chat/components/openai-code-exec-section.tsx b/studio/frontend/src/features/chat/components/openai-code-exec-section.tsx
index 4da97741926..e7544a7d68a 100644
--- a/studio/frontend/src/features/chat/components/openai-code-exec-section.tsx
+++ b/studio/frontend/src/features/chat/components/openai-code-exec-section.tsx
@@ -87,6 +87,8 @@ export function OpenAICodeExecSection({
activeThreadId,
onProviderChange,
}: OpenAICodeExecSectionProps) {
+
+ const hasCredential = Boolean(apiKey || provider.hasApiKey);
const [containers, setContainers] = useState<OpenAIContainerSummary[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [creating, setCreating] = useState(false);
@@ -186,10 +188,12 @@ export function OpenAICodeExecSection({
: firstRunningContainer?.id) ?? null;
const refresh = useCallback(async () => {
- if (!apiKey) return;
+ if (!hasCredential) return;
setIsLoading(true);
try {
const list = await listOpenAIContainers({
+ providerId: provider.id,
+
apiKey,
baseUrl: provider.baseUrl || null,
});
@@ -218,7 +222,7 @@ export function OpenAICodeExecSection({
} finally {
setIsLoading(false);
}
- }, [apiKey, provider.baseUrl]);
+ }, [apiKey, hasCredential, provider.baseUrl, provider.id]);
// Fetch on mount (or provider change), then poll on a low cadence so an
// expired container's ACTIVE pill clears without a manual refresh. Also
@@ -318,7 +322,7 @@ export function OpenAICodeExecSection({
};
const onCreate = async () => {
- if (!apiKey) return;
+ if (!hasCredential) return;
const name = createName.trim();
if (!name) {
toast.error("Container name is required");
@@ -332,7 +336,7 @@ export function OpenAICodeExecSection({
setCreating(true);
try {
const created = await createOpenAIContainer(
- { apiKey, baseUrl: provider.baseUrl || null },
+ { providerId: provider.id, apiKey, baseUrl: provider.baseUrl || null },
{ name, ttlMinutes },
);
toast.success(`Created container ${name}`);
@@ -387,12 +391,12 @@ export function OpenAICodeExecSection({
};
const confirmDelete = async () => {
- if (!apiKey || !pendingDelete) return;
+ if (!hasCredential || !pendingDelete) return;
const { id, name } = pendingDelete;
setDeleting(true);
try {
await deleteOpenAIContainer(
- { apiKey, baseUrl: provider.baseUrl || null },
+ { providerId: provider.id, apiKey, baseUrl: provider.baseUrl || null },
id,
);
// Tombstone the id so the picker hides it at once even if OpenAI's list
@@ -467,7 +471,7 @@ export function OpenAICodeExecSection({
variant="ghost"
className="-mr-1 h-6 w-6 p-0 text-muted-foreground"
onClick={() => void refresh()}
- disabled={isLoading || !apiKey}
+ disabled={isLoading || !hasCredential}
aria-label="Refresh container list"
>
<RefreshCwIcon
@@ -588,7 +592,7 @@ export function OpenAICodeExecSection({
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
- if (createName.trim() && !creating && apiKey) {
+ if (createName.trim() && !creating && hasCredential) {
void onCreate();
}
} else if (e.key === "Escape") {
@@ -615,7 +619,7 @@ export function OpenAICodeExecSection({
size="sm"
className="h-7 shrink-0 px-3 text-xs"
onClick={() => void onCreate()}
- disabled={creating || !createName.trim() || !apiKey}
+ disabled={creating || !createName.trim() || !hasCredential}
>
{creating ? "Creating…" : "Create"}
</Button>
@@ -626,7 +630,7 @@ export function OpenAICodeExecSection({
variant="outline"
className="h-8"
onClick={() => setCreateOpen(true)}
- disabled={!apiKey}
+ disabled={!hasCredential}
>
<PlusIcon className="size-3.5 mr-1" />
New container
diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.ts
index eb9e4656b00..5b400f5164c 100644
--- a/studio/frontend/src/features/chat/external-providers.ts
+++ b/studio/frontend/src/features/chat/external-providers.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
export interface ExternalProviderConfig {
id: string;
/** Backend provider type (e.g. openai, mistral, gemini). */
@@ -14,6 +13,9 @@ export interface ExternalProviderConfig {
models: string[];
/** Cached available model ids from the provider's /models response. */
availableModels?: string[];
+
+ /** Whether the backend has an installation-saved key. */
+ hasApiKey?: boolean;
/** Whether to ask supported hosted providers to use prompt caching. */
enablePromptCaching?: boolean;
/**
@@ -421,8 +423,9 @@ export function loadExternalProviders(): ExternalProviderConfig[] {
}
}
-/** Load the raw key map from localStorage. Values are opaque strings: either
- * AES-GCM ciphertext or legacy plaintext. */
+
+
+/** Load legacy browser keys for retry-safe backend migration. */
function loadRawKeyMap(): Record<string, string> {
if (!canUseStorage()) return {};
try {
@@ -457,47 +460,53 @@ export function saveExternalProviders(
if (!canUseStorage()) return;
try {
localStorage.setItem(EXTERNAL_PROVIDERS_KEY, JSON.stringify(providers));
- // Prune keys for removed providers (works on raw ciphertext, no decryption)
- const allowedIds = new Set(providers.map((provider) => provider.id));
- const keys = loadRawKeyMap();
- const pruned: Record<string, string> = {};
- for (const [providerId, value] of Object.entries(keys)) {
- if (allowedIds.has(providerId)) {
- pruned[providerId] = value;
- }
- }
- saveRawKeyMap(pruned);
+ // Legacy keys are migration input. Preserve unmatched entries until the
+ // backend confirms the exact key was stored.
} catch {
// ignore
}
}
-/** Retrieve a provider API key from localStorage; "" if none stored. */
+/** Retrieve a legacy provider key used only as migration/request fallback. */
export function getExternalProviderApiKey(
providerId: string,
): string {
+
const keys = loadRawKeyMap();
return keys[providerId] ?? "";
}
-/** Store a provider API key in localStorage. */
-export function setExternalProviderApiKey(
- providerId: string,
- apiKey: string,
-): void {
+export function pruneExternalProviderApiKeys(providerIds: Iterable<string>): void {
if (!canUseStorage()) return;
- const keys = loadRawKeyMap();
- keys[providerId] = apiKey;
- saveRawKeyMap(keys);
+ const retainedIds = new Set(providerIds);
+ try {
+ const keys = loadRawKeyMap();
+ let changed = false;
+ for (const providerId of Object.keys(keys)) {
+ if (retainedIds.has(providerId)) continue;
+ delete keys[providerId];
+ changed = true;
+ }
+ if (changed) saveRawKeyMap(keys);
+ } catch {
+ // Keep legacy data untouched when storage is unavailable.
+ }
}
-export function removeExternalProviderApiKey(providerId: string): void {
+
+
+export function removeExternalProviderApiKey(
+ providerId: string,
+ expectedApiKey?: string,
+): void {
if (!canUseStorage()) return;
try {
const keys = loadRawKeyMap();
+
+ if (expectedApiKey !== undefined && keys[providerId] !== expectedApiKey) return;
delete keys[providerId];
saveRawKeyMap(keys);
} catch {
// ignore
}
-}
+}
\ No newline at end of file
diff --git a/studio/frontend/src/features/chat/provider-credential-edit.ts b/studio/frontend/src/features/chat/provider-credential-edit.ts
new file mode 100644
index 00000000000..1aa4593b80d
--- /dev/null
+++ b/studio/frontend/src/features/chat/provider-credential-edit.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type ProviderCredentialEdit =
+ | { action: "replace"; apiKey: string }
+ | { action: "clear" }
+ | { action: "keep" }
+ | { action: "missing" };
+
+export function resolveProviderCredentialEdit(
+ hasExistingCredential: boolean,
+ apiKey: string,
+ clearRequested: boolean,
+): ProviderCredentialEdit {
+ const replacement = apiKey.trim();
+ if (replacement) return { action: "replace", apiKey: replacement };
+ if (clearRequested) return { action: "clear" };
+ return hasExistingCredential ? { action: "keep" } : { action: "missing" };
+}
diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.ts
index cd966f7fd44..6af78cfc063 100644
--- a/studio/frontend/src/features/chat/sync-external-providers.ts
+++ b/studio/frontend/src/features/chat/sync-external-providers.ts
@@ -1,19 +1,28 @@
// 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 {
+ reconcileLegacyProviderKeys,
+ settleTasksIfCurrent,
+} from "@/features/credentials/reconciliation";
+
import {
type ProviderRegistryEntry,
listProviderConfigs,
listProviderRegistry,
+ migrateProviderApiKey,
updateProviderConfig,
} from "./api/providers-api";
import {
CUSTOM_BACKEND_PROVIDER_TYPE,
CUSTOM_PROVIDER_PRESETS,
type ExternalProviderConfig,
+ getExternalProviderApiKey,
isCustomProviderType,
isPromptCacheTtl,
LEGACY_CUSTOM_PROVIDER_TYPE,
+ pruneExternalProviderApiKeys,
+ removeExternalProviderApiKey,
supportsProviderPromptCaching,
supportsProviderPromptCacheTtl,
supportsProviderReasoningToggle,
@@ -118,21 +127,34 @@ export function mergeLocalProviderOptions(
};
}
+
+
/** Merge enabled backend provider configs with local store state. */
export async function syncExternalProvidersFromBackend(
existingProviders: ExternalProviderConfig[],
+ isCurrent?: () => boolean,
): Promise<ExternalProviderConfig[]> {
- const [registryRows, configRows] = await Promise.all([
+ const [registryRows, loadedConfigRows] = await Promise.all([
listProviderRegistry(),
listProviderConfigs(),
]);
+ const configRows = await reconcileLegacyProviderKeys(loadedConfigRows, {
+ getLegacyKey: getExternalProviderApiKey,
+ saveLegacyKey: migrateProviderApiKey,
+ removeLegacyKey: removeExternalProviderApiKey,
+
+ isCurrent,
+ });
+
+ if (isCurrent && !isCurrent()) return existingProviders;
+ pruneExternalProviderApiKeys(loadedConfigRows.map((config) => config.id));
const existingById = new Map<string, ExternalProviderConfig>();
for (const provider of existingProviders) {
existingById.set(provider.id, provider);
}
- const backfillTasks: Promise<unknown>[] = [];
+ const backfillTasks: Array<() => Promise<unknown>> = [];
const syncedProviders = configRows
.filter((config) => config.is_enabled)
.map((config) => {
@@ -188,7 +210,7 @@ export async function syncExternalProvidersFromBackend(
const needsAvailableBackfill =
serverAvailableModels.length === 0 && savedAvailableModels.length > 0;
if (needsModelBackfill || needsAvailableBackfill) {
- backfillTasks.push(
+ backfillTasks.push(() =>
updateProviderConfig(config.id, {
models: resolvedModels,
availableModels: resolvedAvailableModels,
@@ -202,6 +224,8 @@ export async function syncExternalProvidersFromBackend(
baseUrl: config.base_url ?? "",
models: resolvedModels,
availableModels: resolvedAvailableModels,
+
+ hasApiKey: config.has_api_key,
enablePromptCaching: supportsProviderPromptCaching(uiProviderType)
? (existing?.enablePromptCaching ?? true)
: undefined,
@@ -214,8 +238,8 @@ export async function syncExternalProvidersFromBackend(
return mergeLocalProviderOptions(existing, synced);
});
- if (backfillTasks.length > 0) {
- await Promise.allSettled(backfillTasks);
- }
+ if (isCurrent && !isCurrent()) return existingProviders;
+
+ await settleTasksIfCurrent(backfillTasks, isCurrent);
return syncedProviders;
}
diff --git a/studio/frontend/src/features/credentials/bootstrap.ts b/studio/frontend/src/features/credentials/bootstrap.ts
new file mode 100644
index 00000000000..13d428fb92a
--- /dev/null
+++ b/studio/frontend/src/features/credentials/bootstrap.ts
@@ -0,0 +1,23 @@
+// 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 { getAuthSessionEpoch, hasAuthToken } from "@/features/auth";
+import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
+import { syncExternalProvidersFromBackend } from "@/features/chat/sync-external-providers";
+import { hydrateHfTokenFromBackend } from "@/features/hub/stores/hf-token-store";
+import { runCredentialBootstrap } from "./reconciliation";
+
+export function bootstrapPersistedCredentials(): Promise<void> {
+ const sessionEpoch = getAuthSessionEpoch();
+ const isCurrent = () =>
+ hasAuthToken() && getAuthSessionEpoch() === sessionEpoch;
+ return runCredentialBootstrap({
+ hydrateHfToken: hydrateHfTokenFromBackend,
+ getProviders: () => useExternalProvidersStore.getState().providers,
+ syncProviders: (providers) =>
+ syncExternalProvidersFromBackend(providers, isCurrent),
+ setProviders: (providers) =>
+ useExternalProvidersStore.getState().setProviders(providers),
+ isCurrent,
+ });
+}
diff --git a/studio/frontend/src/features/credentials/reconciliation.ts b/studio/frontend/src/features/credentials/reconciliation.ts
new file mode 100644
index 00000000000..f984e49784b
--- /dev/null
+++ b/studio/frontend/src/features/credentials/reconciliation.ts
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export interface HfCredentialStatus {
+ has_token: boolean;
+ token: string | null;
+}
+
+export interface LegacyHfTokenReconciliationDependencies<
+ T extends HfCredentialStatus,
+> {
+ loadSavedToken: () => Promise<T>;
+ getLegacyToken: () => string;
+ saveLegacyToken: (token: string) => Promise<T>;
+ removeLegacyToken: (expectedToken: string) => void;
+ applyToken: (token: string) => void;
+}
+
+export async function reconcileLegacyHfToken<T extends HfCredentialStatus>(
+ dependencies: LegacyHfTokenReconciliationDependencies<T>,
+): Promise<T> {
+
+ const legacyTokenBeforeLoad = dependencies.getLegacyToken().trim();
+ let saved: T;
+ try {
+ saved = await dependencies.loadSavedToken();
+ } catch (error) {
+ const retainedToken = dependencies.getLegacyToken().trim();
+ if (retainedToken) dependencies.applyToken(retainedToken);
+ throw error;
+ }
+ if (saved.has_token && saved.token) {
+ dependencies.applyToken(saved.token);
+ if (legacyTokenBeforeLoad) {
+ dependencies.removeLegacyToken(legacyTokenBeforeLoad);
+ }
+ return saved;
+ }
+
+ const legacyToken = dependencies.getLegacyToken().trim();
+ if (!legacyToken) {
+ dependencies.applyToken("");
+ return saved;
+ }
+
+ let migrated: T;
+ try {
+ migrated = await dependencies.saveLegacyToken(legacyToken);
+ } catch (error) {
+ // Keep upgraded users working from their retained legacy token while the
+ // backend is unavailable. The caller still sees the failure and can retry.
+ dependencies.applyToken(legacyToken);
+ throw error;
+ }
+ if (migrated.has_token) {
+ dependencies.applyToken(migrated.token ?? legacyToken);
+ dependencies.removeLegacyToken(legacyToken);
+ }
+ return migrated;
+}
+
+
+export interface ProviderCredentialStatus {
+ id: string;
+ has_api_key: boolean;
+}
+
+export interface LegacyProviderKeyReconciliationDependencies<
+ T extends ProviderCredentialStatus,
+> {
+ getLegacyKey: (providerId: string) => string;
+ saveLegacyKey: (providerId: string, apiKey: string) => Promise<T>;
+ removeLegacyKey: (providerId: string, expectedApiKey: string) => void;
+
+ isCurrent?: () => boolean;
+}
+
+export async function reconcileLegacyProviderKeys<
+ T extends ProviderCredentialStatus,
+>(
+ configs: T[],
+ dependencies: LegacyProviderKeyReconciliationDependencies<T>,
+): Promise<T[]> {
+ const reconciled = [...configs];
+ for (let index = 0; index < reconciled.length; index += 1) {
+
+ if (dependencies.isCurrent && !dependencies.isCurrent()) return reconciled;
+ const config = reconciled[index];
+ if (config.has_api_key) {
+ const legacyKey = dependencies.getLegacyKey(config.id);
+ if (legacyKey) dependencies.removeLegacyKey(config.id, legacyKey);
+ continue;
+ }
+ const legacyKey = dependencies.getLegacyKey(config.id);
+ const normalizedLegacyKey = legacyKey.trim();
+ if (!normalizedLegacyKey) continue;
+ try {
+ const saved = await dependencies.saveLegacyKey(config.id, normalizedLegacyKey);
+ if (dependencies.isCurrent && !dependencies.isCurrent()) return reconciled;
+ reconciled[index] = saved;
+ if (saved.has_api_key) {
+ dependencies.removeLegacyKey(config.id, legacyKey);
+ }
+ } catch {
+ // Preserve local input for retry and per-request fallback.
+ }
+ }
+ return reconciled;
+}
+
+
+export async function settleTasksIfCurrent(
+ tasks: Array<() => Promise<unknown>>,
+ isCurrent?: () => boolean,
+): Promise<void> {
+ if (isCurrent && !isCurrent()) return;
+ await Promise.allSettled(tasks.map((task) => task()));
+}
+
+export interface CredentialBootstrapDependencies<T> {
+ hydrateHfToken: () => Promise<void>;
+ getProviders: () => T[];
+ syncProviders: (providers: T[]) => Promise<T[]>;
+ setProviders: (providers: T[]) => void;
+
+ isCurrent?: () => boolean;
+}
+
+/** Wait for both server-first reconciliations before releasing app content. */
+export async function runCredentialBootstrap<T>(
+ dependencies: CredentialBootstrapDependencies<T>,
+): Promise<void> {
+
+ if (dependencies.isCurrent && !dependencies.isCurrent()) return;
+ const providerSync = dependencies.syncProviders(dependencies.getProviders());
+ const [, providerResult] = await Promise.allSettled([
+ dependencies.hydrateHfToken(),
+ providerSync,
+ ]);
+ if (
+ providerResult.status === "fulfilled" &&
+ (!dependencies.isCurrent || dependencies.isCurrent())
+ ) {
+ dependencies.setProviders(providerResult.value);
+ }
+}
diff --git a/studio/frontend/src/features/hub/api/hf-token-api.ts b/studio/frontend/src/features/hub/api/hf-token-api.ts
new file mode 100644
index 00000000000..ec971c3df9e
--- /dev/null
+++ b/studio/frontend/src/features/hub/api/hf-token-api.ts
@@ -0,0 +1,73 @@
+// 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 { authFetch } from "@/features/auth/api";
+import { formatFastApiDetail } from "@/lib/format-fastapi-error";
+
+export interface SavedHfTokenResponse {
+ token: string | null;
+ has_token: boolean;
+}
+
+function isSavedHfTokenResponse(value: unknown): value is SavedHfTokenResponse {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<SavedHfTokenResponse>;
+ return (
+ typeof candidate.has_token === "boolean" &&
+ (typeof candidate.token === "string" || candidate.token === null)
+ );
+}
+
+
+async function parse(response: Response): Promise<SavedHfTokenResponse> {
+ const body = (await response.json().catch(() => null)) as
+ | SavedHfTokenResponse
+ | { detail?: unknown }
+ | null;
+ if (!response.ok) {
+ const detail =
+ body && "detail" in body ? formatFastApiDetail(body.detail) : null;
+ throw new Error(
+ detail || `Hugging Face credential request failed (${response.status})`,
+ );
+ }
+ if (!isSavedHfTokenResponse(body)) {
+ throw new Error("Hugging Face credential request returned an invalid response");
+ }
+ return body;
+}
+
+export async function loadSavedHfToken(): Promise<SavedHfTokenResponse> {
+ return parse(await authFetch("/api/settings/hugging-face-token"));
+}
+
+export async function saveHfToken(
+ token: string,
+): Promise<SavedHfTokenResponse> {
+ return parse(
+ await authFetch("/api/settings/hugging-face-token", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ }),
+ );
+}
+
+export async function migrateHfToken(
+ token: string,
+): Promise<SavedHfTokenResponse> {
+ return parse(
+ await authFetch("/api/settings/hugging-face-token/migrate", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token }),
+ }),
+ );
+}
+
+
+export async function clearSavedHfToken(): Promise<SavedHfTokenResponse> {
+ return parse(
+ await authFetch("/api/settings/hugging-face-token", { method: "DELETE" }),
+ );
+}
diff --git a/studio/frontend/src/features/hub/stores/hf-token-store.ts b/studio/frontend/src/features/hub/stores/hf-token-store.ts
index e6014546561..60365de22f7 100644
--- a/studio/frontend/src/features/hub/stores/hf-token-store.ts
+++ b/studio/frontend/src/features/hub/stores/hf-token-store.ts
@@ -1,109 +1,336 @@
// 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 { AUTH_SESSION_CLEARED_EVENT } from "../../auth/session-events.ts";
+import { reconcileLegacyHfToken } from "../../credentials/reconciliation.ts";
+
import { create } from "zustand";
+type HfTokenApi = typeof import("../api/hf-token-api");
+
+async function loadHfTokenApi(): Promise<HfTokenApi> {
+ return import("../api/hf-token-api");
+}
const HF_TOKEN_KEY = "unsloth_hf_token";
const LEGACY_TRAINING_KEY = "unsloth_training_config_v1";
-let storageSyncStarted = false;
-let storageSyncListener: ((event: StorageEvent) => void) | null = null;
+const HF_TOKEN_MIGRATION_KEY = "unsloth_hf_token_migration_v1";
+
+const HF_TOKEN_SYNC_KEY = "unsloth_hf_token_backend_revision";
+
+let backendNotificationRevision = 0;
+
+let stagedLegacyToken = "";
function canUseStorage(): boolean {
return typeof window !== "undefined";
}
-function loadInitial(): string {
- if (!canUseStorage()) return "";
+export function normalizeHfToken(raw: string): string {
+ return raw.replace(/^[\s"']+|[\s"']+$/g, "");
+}
+
+function loadLegacyToken(): string {
+
+ if (!canUseStorage()) return stagedLegacyToken;
try {
const direct = window.localStorage.getItem(HF_TOKEN_KEY);
- if (direct !== null) {
- const normalized = normalizeHfToken(direct);
- if (normalized !== direct) persist(normalized);
- return normalized;
- }
+ const migrationCopy = window.localStorage.getItem(HF_TOKEN_MIGRATION_KEY);
+ if (migrationCopy !== null) return normalizeHfToken(migrationCopy);
+ if (direct !== null) return normalizeHfToken(direct);
const legacy = window.localStorage.getItem(LEGACY_TRAINING_KEY);
- if (legacy) {
- const parsed = JSON.parse(legacy) as {
- state?: Record<string, unknown>;
- [key: string]: unknown;
- };
- const fromTraining = parsed?.state?.hfToken;
- if (typeof fromTraining === "string" && fromTraining.length > 0) {
- const normalized = normalizeHfToken(fromTraining);
- persist(normalized);
- return normalized;
- }
- }
+ if (!legacy) return stagedLegacyToken;
+ const parsed = JSON.parse(legacy) as { state?: Record<string, unknown> };
+ const token = parsed?.state?.hfToken;
+ return typeof token === "string"
+ ? normalizeHfToken(token)
+ : stagedLegacyToken;
} catch {
- return "";
+ return stagedLegacyToken;
}
- return "";
}
-function persist(value: string): void {
+function removeLegacyToken(expectedToken: string): void {
+ const expected = normalizeHfToken(expectedToken);
+ if (!expected) return;
+ if (normalizeHfToken(stagedLegacyToken) === expected) stagedLegacyToken = "";
if (!canUseStorage()) return;
try {
- window.localStorage.setItem(HF_TOKEN_KEY, value);
+ const direct = window.localStorage.getItem(HF_TOKEN_KEY);
+ if (direct !== null && normalizeHfToken(direct) === expected) {
+ window.localStorage.removeItem(HF_TOKEN_KEY);
+ }
+ const migrationCopy = window.localStorage.getItem(HF_TOKEN_MIGRATION_KEY);
+ if (migrationCopy !== null && normalizeHfToken(migrationCopy) === expected) {
+ window.localStorage.removeItem(HF_TOKEN_MIGRATION_KEY);
+ }
+ const raw = window.localStorage.getItem(LEGACY_TRAINING_KEY);
+ if (!raw) return;
+ const parsed = JSON.parse(raw) as { state?: Record<string, unknown> };
+ const trainingToken = parsed.state?.hfToken;
+ if (
+ !parsed.state ||
+ typeof trainingToken !== "string" ||
+ normalizeHfToken(trainingToken) !== expected
+ ) {
+ return;
+ }
+ delete parsed.state.hfToken;
+ window.localStorage.setItem(LEGACY_TRAINING_KEY, JSON.stringify(parsed));
} catch {
- void 0;
+ // Keep legacy data untouched on malformed/unavailable storage.
}
}
-export function normalizeHfToken(raw: string): string {
- return raw.replace(/^[\s"']+|[\s"']+$/g, "");
-}
+let persistenceRevision = 0;
+let persistenceChain: Promise<void> = Promise.resolve();
+let lastPersistedToken = "";
-function stopStorageSync(): void {
+function announcePersistedTokenChange(): void {
if (!canUseStorage()) return;
- if (storageSyncListener !== null) {
- window.removeEventListener("storage", storageSyncListener);
- storageSyncListener = null;
+ try {
+ window.localStorage.setItem(
+ HF_TOKEN_SYNC_KEY,
+ `${Date.now()}:${Math.random().toString(36).slice(2)}`,
+ );
+ } catch {
+ // The current tab is already synchronized; cross-tab sync is best effort.
}
- storageSyncStarted = false;
}
-if (import.meta.hot) {
- import.meta.hot.dispose(stopStorageSync);
+function persistenceErrorMessage(error: unknown): string {
+ return error instanceof Error
+ ? error.message
+ : "Could not save the Hugging Face token.";
}
+function persistTokenToBackend(token: string): void {
+ const revision = ++persistenceRevision;
+ const sessionRevision = authSessionRevision;
+ useHfTokenStore.setState({ isPersisting: true, persistenceError: null });
+ persistenceChain = persistenceChain
+ .catch(() => undefined)
+ .then(async () => {
+ // Collapse rapid field edits before they reach the network. In-flight
+ // writes remain ordered, so an older response can never win last.
+ if (revision !== persistenceRevision) return;
+
+ const legacyTokenBeforeSave = loadLegacyToken();
+ try {
+ const { clearSavedHfToken, loadSavedHfToken, saveHfToken } =
+ await loadHfTokenApi();
+ const notificationRevisionBeforeWrite = backendNotificationRevision;
+ let response = token
+ ? await saveHfToken(token)
+ : await clearSavedHfToken();
+
+ if (notificationRevisionBeforeWrite !== backendNotificationRevision) {
+ // A cross-tab commit landed while this write's response was delayed.
+ // Read until no newer notification arrives during the GET, so the
+ // value applied below is the backend's latest committed credential.
+ let notificationRevision: number;
+ do {
+ notificationRevision = backendNotificationRevision;
+ response = await loadSavedHfToken();
+ } while (notificationRevision !== backendNotificationRevision);
+ }
+ const persistedToken = response.token
+ ? normalizeHfToken(response.token)
+ : "";
+ if (sessionRevision !== authSessionRevision) return;
+ lastPersistedToken = persistedToken;
+ if (revision === persistenceRevision) {
+ removeLegacyToken(legacyTokenBeforeSave);
+ announcePersistedTokenChange();
+ useHfTokenStore.setState({
+ token: persistedToken,
+ isPersisting: false,
+ persistenceError: null,
+ });
+ }
+ } catch (error) {
+ if (revision === persistenceRevision) {
+ useHfTokenStore.setState({
+ token: lastPersistedToken,
+ isPersisting: false,
+ persistenceError: persistenceErrorMessage(error),
+ });
+ }
+ }
+ });
+}
+
+
+/** Wait until the latest queued token edit is durable, or surface its save error. */
+export async function waitForHfTokenPersistence(): Promise<void> {
+ while (true) {
+ const revision = persistenceRevision;
+ await persistenceChain;
+ if (revision !== persistenceRevision) continue;
+ const state = useHfTokenStore.getState();
+ if (state.isPersisting) continue;
+ if (state.persistenceError) throw new Error(state.persistenceError);
+ return;
+ }
+}
+
+
interface HfTokenStore {
token: string;
+ isPersisting: boolean;
+ persistenceError: string | null;
setToken: (value: string) => void;
clearToken: () => void;
}
export const useHfTokenStore = create<HfTokenStore>((set) => {
- const applyToken = (value: string, shouldPersist: boolean) => {
- const next = normalizeHfToken(value);
- if (shouldPersist || next !== value) persist(next);
- set((state) => {
- if (state.token === next) return state;
- return { token: next };
- });
+ const applyNormalizedToken = (value: string) => {
+ const token = normalizeHfToken(value);
+ set((state) => (state.token === token ? state : { token }));
+ return token;
};
+ return {
+ // Legacy value remains available until authenticated bootstrap reconciles it.
+ token: loadLegacyToken(),
+
+ isPersisting: false,
+ persistenceError: null,
+ setToken: (value) => {
+ persistTokenToBackend(applyNormalizedToken(value));
+ },
+ clearToken: () => {
+ applyNormalizedToken("");
+ persistTokenToBackend("");
+ },
+ };
+});
+
+let serverCredentialHydrated = false;
- if (!storageSyncStarted && canUseStorage()) {
- storageSyncStarted = true;
- storageSyncListener = (event) => {
- if (event.key !== HF_TOKEN_KEY) return;
- applyToken(event.newValue ?? "", false);
- };
- window.addEventListener("storage", storageSyncListener);
+let authSessionRevision = 0;
+
+/** Retain a pre-v12 training-store token as migration input until server save succeeds. */
+export function stageLegacyHfTokenForMigration(value: string): void {
+ if (serverCredentialHydrated) return;
+ const token = normalizeHfToken(value);
+ if (!token) return;
+ stagedLegacyToken ||= token;
+ if (canUseStorage()) {
+ try {
+ window.localStorage.setItem(HF_TOKEN_MIGRATION_KEY, token);
+ } catch {
+ // The in-memory copy still keeps this session working.
+ }
}
+ if (!useHfTokenStore.getState().token) {
+ useHfTokenStore.setState({ token });
+ }
+}
- return {
- token: loadInitial(),
- setToken: (value) => applyToken(value, true),
- clearToken: () => applyToken("", true),
+
+
+let hydrationPromise: Promise<void> | null = null;
+let hydrationReplayRequested = false;
+
+/** Server-first, retry-safe migration and hydration after authentication. */
+export function hydrateHfTokenFromBackend(): Promise<void> {
+ if (hydrationPromise) return hydrationPromise;
+ const sessionRevision = authSessionRevision;
+ const persistenceRevisionAtStart = persistenceRevision;
+ const persistenceWasPending = useHfTokenStore.getState().isPersisting;
+ const canApplyHydratedToken = () =>
+ !persistenceWasPending && persistenceRevisionAtStart === persistenceRevision;
+ const assertCurrentSession = () => {
+ if (sessionRevision !== authSessionRevision) {
+ throw new Error("Authentication session changed during credential hydration.");
+ }
};
-});
+
+ hydrationPromise = (async () => {
+ const { loadSavedHfToken, migrateHfToken } = await loadHfTokenApi();
+ await reconcileLegacyHfToken({
+ loadSavedToken: async () => {
+ const response = await loadSavedHfToken();
+ assertCurrentSession();
+ serverCredentialHydrated = true;
+ return response;
+ },
+ getLegacyToken: () => {
+ assertCurrentSession();
+ return loadLegacyToken();
+ },
+ saveLegacyToken: async (token) => {
+ const response = await migrateHfToken(token);
+ assertCurrentSession();
+ return response;
+ },
+ applyToken: (token) => {
+ assertCurrentSession();
+ if (!canApplyHydratedToken()) return;
+ lastPersistedToken = normalizeHfToken(token);
+ useHfTokenStore.setState({
+ token: lastPersistedToken,
+ isPersisting: false,
+ persistenceError: null,
+ });
+ },
+ removeLegacyToken: (expectedToken) => {
+ assertCurrentSession();
+ removeLegacyToken(expectedToken);
+ },
+ });
+ })().finally(() => {
+ if (sessionRevision === authSessionRevision) hydrationPromise = null;
+ });
+ return hydrationPromise;
+}
+
+
+/** Re-read after an active hydration when another tab reports a newer backend value. */
+export async function refreshHfTokenFromBackend(): Promise<void> {
+
+ backendNotificationRevision += 1;
+ if (!hydrationPromise) return hydrateHfTokenFromBackend();
+ hydrationReplayRequested = true;
+ try {
+ await hydrationPromise;
+ } catch {
+ // The replay is the authoritative retry for the cross-tab notification.
+ }
+ if (!hydrationReplayRequested) return;
+ hydrationReplayRequested = false;
+ return hydrateHfTokenFromBackend();
+}
+
+function resetHfCredentialSession(): void {
+ authSessionRevision += 1;
+ persistenceRevision += 1;
+ hydrationPromise = null;
+ hydrationReplayRequested = false;
+ serverCredentialHydrated = false;
+
+ stagedLegacyToken = "";
+ lastPersistedToken = "";
+ useHfTokenStore.setState({
+ token: "",
+ isPersisting: false,
+ persistenceError: null,
+ });
+}
+
+if (typeof window !== "undefined") {
+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, resetHfCredentialSession);
+
+ window.addEventListener("storage", (event) => {
+ if (event.key !== HF_TOKEN_SYNC_KEY || !event.newValue) return;
+ void refreshHfTokenFromBackend().catch(() => undefined);
+ });
+}
export function getHfToken(): string {
return useHfTokenStore.getState().token;
}
-// Keep a plain zustand store's `hfToken` in sync with the shared token: seed the current
-// value, then mirror later edits. Returns the unsubscribe so callers can wire it to HMR.
+// Keep a plain zustand store's `hfToken` in sync with the shared token.
export function mirrorHfTokenInto<T extends { hfToken: string }>(store: {
getState: () => T;
setState: (partial: Partial<T>) => void;
@@ -116,8 +343,7 @@ export function mirrorHfTokenInto<T extends { hfToken: string }>(store: {
});
}
-// HF's JS client throws on a non-empty token without the `hf_` prefix instead
-// of browsing anonymously. Action-time validation handles legacy `hf_` shapes.
+// HF's JS client throws on a non-empty token without the `hf_` prefix.
export function hfApiToken(
token: string | undefined | null,
): string | undefined {
diff --git a/studio/frontend/src/features/onboarding/components/hf-token-field.tsx b/studio/frontend/src/features/onboarding/components/hf-token-field.tsx
index 2ef6d8b7b97..114844e30ea 100644
--- a/studio/frontend/src/features/onboarding/components/hf-token-field.tsx
+++ b/studio/frontend/src/features/onboarding/components/hf-token-field.tsx
@@ -17,6 +17,10 @@ export function HfTokenField() {
const t = useT();
const token = useHfTokenStore((state) => state.token);
const setToken = useHfTokenStore((state) => state.setToken);
+
+ const persistenceError = useHfTokenStore(
+ (state) => state.persistenceError,
+ );
const validation = useHfTokenValidation(token);
return (
@@ -52,7 +56,9 @@ export function HfTokenField() {
onChange={(event) => setToken(event.target.value)}
/>
</InputGroup>
- {validation.isChecking ? (
+ {persistenceError ? (
+ <p className="text-xs text-destructive">{persistenceError}</p>
+ ) : validation.isChecking ? (
<p className="text-xs text-muted-foreground">
{t("studio.wizard.hfTokenChecking")}
</p>
diff --git a/studio/frontend/src/features/onboarding/components/wizard-footer.tsx b/studio/frontend/src/features/onboarding/components/wizard-footer.tsx
index 8b8e6e1afe5..74bdd1d0d6c 100644
--- a/studio/frontend/src/features/onboarding/components/wizard-footer.tsx
+++ b/studio/frontend/src/features/onboarding/components/wizard-footer.tsx
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { usePlatformStore } from "@/config/env";
import { STEPS } from "@/config/training";
import { markOnboardingDone } from "@/features/auth";
+import { waitForHfTokenPersistence } from "@/features/hub/stores/hf-token-store";
import {
isTrainingLoraVariantSupportedOnDevice,
isTrainingMethodSupportedOnDevice,
@@ -71,7 +72,12 @@ export function WizardFooter({
<Button
variant="outline"
className="px-4"
- onClick={() => {
+ onClick={async () => {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
markOnboardingDone();
window.location.assign(returnTo);
}}
@@ -81,7 +87,12 @@ export function WizardFooter({
)}
{isLast ? (
<Button
- onClick={() => {
+ onClick={async () => {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
markOnboardingDone();
window.location.assign(returnTo);
}}
@@ -93,11 +104,16 @@ export function WizardFooter({
</Button>
) : (
<Button
- onClick={() => {
+ onClick={async () => {
if (
currentStep === 1 &&
sessionStorage.getItem("unsloth_chat_only") === "1"
) {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
sessionStorage.removeItem("unsloth_chat_only");
markOnboardingDone();
window.location.assign("/chat");
diff --git a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx b/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
index b8219d1eb54..8f043265101 100644
--- a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
+++ b/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
@@ -9,6 +9,7 @@ import { Suspense, lazy, useEffect, useRef, useState } from "react";
import type { ConfettiRef } from "@/components/ui/confetti";
import { STEPS } from "@/config/training";
import { isOnboardingDone, markOnboardingDone } from "@/features/auth";
+import { waitForHfTokenPersistence } from "@/features/hub/stores/hf-token-store";
import { prefersReducedMotion } from "@/features/settings";
import { useTrainingConfigStore } from "@/features/training";
import { SplashScreen } from "./splash-screen";
@@ -82,7 +83,12 @@ export function WizardLayout() {
{showSplash && (
<SplashScreen
onStartOnboarding={() => setShowSplash(false)}
- onSkipOnboarding={() => {
+ onSkipOnboarding={async () => {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
markOnboardingDone();
exitToReturnTo();
}}
diff --git a/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx b/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx
index d5e11110ab1..5adc15fe509 100644
--- a/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx
+++ b/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { STEPS } from "@/config/training";
import { markOnboardingDone } from "@/features/auth";
+import { waitForHfTokenPersistence } from "@/features/hub/stores/hf-token-store";
import { useTrainingConfigStore } from "@/features/training";
import { ArrowRight02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -38,7 +39,12 @@ export function WizardSidebar({ returnTo }: { returnTo: string }) {
<Button
size="sm"
className="mt-2 w-full md:hidden"
- onClick={() => {
+ onClick={async () => {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
markOnboardingDone();
window.location.assign(returnTo);
}}
@@ -54,7 +60,12 @@ export function WizardSidebar({ returnTo }: { returnTo: string }) {
<Button
size="sm"
className="mt-3 hidden w-full md:flex"
- onClick={() => {
+ onClick={async () => {
+ try {
+ await waitForHfTokenPersistence();
+ } catch {
+ return;
+ }
markOnboardingDone();
window.location.assign(returnTo);
}}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 1c9ac43141e..17f7af8b8c3 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -20,6 +20,8 @@ import {
setShowLoadedModels,
useShowLoadedModels,
} from "@/features/loaded-models";
+
+import { useHfTokenStore } from "@/features/hub";
import {
emitTrainingRunsChanged,
TRAINING_UI_PREFERENCE_KEYS,
@@ -170,6 +172,10 @@ export function GeneralTab() {
});
const hfToken = useChatRuntimeStore((s) => s.hfToken);
const setHfToken = useChatRuntimeStore((s) => s.setHfToken);
+
+ const hfTokenPersistenceError = useHfTokenStore(
+ (s) => s.persistenceError,
+ );
const chatOnly = usePlatformStore((s) => s.chatOnly);
const showLlamaUpdates = useShowLlamaUpdateBanner();
const showLoadedModels = useShowLoadedModels();
@@ -592,7 +598,11 @@ export function GeneralTab() {
{t("settings.general.clearToken")}
</Button>
</div>
- {tokenValidation.isChecking ? (
+ {hfTokenPersistenceError ? (
+ <p className="max-w-[330px] text-right text-xs text-destructive">
+ {hfTokenPersistenceError}
+ </p>
+ ) : tokenValidation.isChecking ? (
<p className="text-xs text-muted-foreground">
{t("settings.general.checkingToken")}
</p>
diff --git a/studio/frontend/src/features/training/stores/training-config-persistence.ts b/studio/frontend/src/features/training/stores/training-config-persistence.ts
index f11ed5f139d..283729e2600 100644
--- a/studio/frontend/src/features/training/stores/training-config-persistence.ts
+++ b/studio/frontend/src/features/training/stores/training-config-persistence.ts
@@ -9,10 +9,7 @@ import {
LR_DEFAULT_LORA,
} from "@/config/training";
// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's unrelated React exports.
-import {
- getHfToken,
- useHfTokenStore,
-} from "@/features/hub/stores/hf-token-store";
+import { stageLegacyHfTokenForMigration } from "@/features/hub/stores/hf-token-store";
import { isTrainingMethod } from "@/types/training";
import type { DatasetFormat } from "@/types/training";
import type {
@@ -51,6 +48,8 @@ export function partializeTrainingConfig(
): Partial<TrainingConfigStore> {
const partial = Object.fromEntries(
Object.entries(state).filter(([key, value]) => {
+
+ if (key === "hfToken") return false;
if (typeof value === "function") {
return false;
}
@@ -130,10 +129,10 @@ function migrateThroughVersion12(
if (version < 12) {
const legacyToken =
typeof state.hfToken === "string" ? state.hfToken.trim() : "";
- if (legacyToken && !getHfToken()) {
- useHfTokenStore.getState().setToken(legacyToken);
+ if (legacyToken) {
+ stageLegacyHfTokenForMigration(legacyToken);
}
- state.hfToken = undefined;
+ // Keep the legacy value persisted until authenticated migration confirms the backend write.
}
}
@@ -285,8 +284,9 @@ export function mergeTrainingConfig(
persisted: unknown,
current: TrainingConfigStore,
): TrainingConfigStore {
- const persistedState = persisted as Partial<TrainingConfigState>;
- const persistedRecord = persisted as PersistedTrainingConfig;
+ const persistedRecord = { ...(persisted as PersistedTrainingConfig) };
+ delete persistedRecord.hfToken;
+ const persistedState = persistedRecord as Partial<TrainingConfigState>;
const modelDefaultsAppliedFor =
typeof persistedState.modelDefaultsAppliedFor === "string" &&
persistedState.modelDefaultsAppliedFor.length > 0 &&
diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.ts
new file mode 100644
index 00000000000..15d0db93ba8
--- /dev/null
+++ b/studio/frontend/tests/credential-persistence.test.ts
@@ -0,0 +1,721 @@
+// 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 assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+
+import type { ProviderConfig } from "../src/features/chat/api/providers-api.ts";
+
+import {
+ installLocalStorageFake,
+ registerStoreStubResolver,
+} from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+
+const {
+ reconcileLegacyHfToken,
+ reconcileLegacyProviderKeys,
+ runCredentialBootstrap,
+
+ settleTasksIfCurrent,
+} = await import("../src/features/credentials/reconciliation.ts");
+
+const { resolveProviderCredentialEdit } = await import(
+ "../src/features/chat/provider-credential-edit.ts"
+);
+
+
+type UiProviderConfig = ReturnType<
+ Parameters<typeof runCredentialBootstrap>[0]["getProviders"]
+>[number];
+
+function provider(id: string, hasApiKey: boolean): ProviderConfig {
+ return {
+ id,
+ provider_type: "openai",
+ display_name: id,
+ base_url: "https://api.openai.com/v1",
+ is_enabled: true,
+ has_api_key: hasApiKey,
+ models: [],
+ available_models: [],
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+}
+
+
+function uiProvider(id: string, hasApiKey: boolean): UiProviderConfig {
+ return {
+ id,
+ providerType: "openai",
+ name: id,
+ baseUrl: "https://api.openai.com/v1",
+ hasApiKey,
+ models: [],
+ createdAt: 1,
+ updatedAt: 1,
+ };
+}
+
+test("provider migration is server-first and removes only confirmed keys", async () => {
+ const removed: string[] = [];
+ const saved: string[] = [];
+ const result = await reconcileLegacyProviderKeys(
+ [provider("server", true), provider("legacy", false)],
+ {
+ getLegacyKey: (id) => (id === "legacy" ? " old-key " : "stale-key"),
+ saveLegacyKey: async (id, key) => {
+ saved.push(`${id}:${key}`);
+ return provider(id, true);
+ },
+ removeLegacyKey: (id, key) => removed.push(`${id}:${key}`),
+ },
+ );
+
+ assert.deepEqual(saved, ["legacy:old-key"]);
+ assert.deepEqual(removed, ["server:stale-key", "legacy: old-key "]);
+ assert.equal(result.every((row) => row.has_api_key), true);
+});
+
+test("provider migration retains failed and orphaned legacy input", async () => {
+ const removed: string[] = [];
+ const requested: string[] = [];
+ const result = await reconcileLegacyProviderKeys([provider("existing", false)], {
+ getLegacyKey: (id) => {
+ requested.push(id);
+ return "retry-me";
+ },
+ saveLegacyKey: async () => {
+ throw new Error("offline");
+ },
+ removeLegacyKey: (id) => removed.push(id),
+ });
+
+ assert.equal(result[0].has_api_key, false);
+ assert.deepEqual(requested, ["existing"]);
+ assert.deepEqual(removed, []);
+ assert.equal(requested.includes("orphan"), false);
+});
+
+
+test("provider migration retains plaintext when a successful response has no saved key", async () => {
+ const removed: string[] = [];
+ const result = await reconcileLegacyProviderKeys([provider("legacy", false)], {
+ getLegacyKey: () => "retry-me",
+ saveLegacyKey: async () => provider("legacy", false),
+ removeLegacyKey: (id) => removed.push(id),
+ });
+
+ assert.equal(result[0].has_api_key, false);
+ assert.deepEqual(removed, []);
+});
+
+test("provider migration is retry-safe after partial success", async () => {
+ const removed = new Set<string>();
+ let attempts = 0;
+ const dependencies = {
+ getLegacyKey: (id: string) => (removed.has(id) ? "" : `key-${id}`),
+ saveLegacyKey: async (id: string) => {
+ attempts += 1;
+ if (id === "second" && attempts === 2) throw new Error("offline");
+ return provider(id, true);
+ },
+ removeLegacyKey: (id: string) => removed.add(id),
+ };
+
+ const first = await reconcileLegacyProviderKeys(
+ [provider("first", false), provider("second", false)],
+ dependencies,
+ );
+ assert.deepEqual([...removed], ["first"]);
+ const second = await reconcileLegacyProviderKeys(first, dependencies);
+ assert.equal(second.every((row) => row.has_api_key), true);
+ assert.deepEqual([...removed], ["first", "second"]);
+});
+
+test("superseded provider backfills are not launched", async () => {
+ let launched = 0;
+ await settleTasksIfCurrent(
+ [async () => { launched += 1; }],
+ () => false,
+ );
+ assert.equal(launched, 0);
+
+ await settleTasksIfCurrent([async () => { launched += 1; }], () => true);
+ assert.equal(launched, 1);
+});
+
+
+test("authoritative provider cleanup removes only orphaned legacy keys", async () => {
+ const { store } = installLocalStorageFake();
+ store.set(
+ "unsloth_chat_external_provider_keys",
+ JSON.stringify({ retained: "sk-retained", orphan: "sk-orphan" }),
+ );
+ try {
+ const { pruneExternalProviderApiKeys } = await import(
+ "../src/features/chat/external-providers.ts"
+ );
+ pruneExternalProviderApiKeys(["retained"]);
+ assert.deepEqual(
+ JSON.parse(store.get("unsloth_chat_external_provider_keys") ?? "{}"),
+ { retained: "sk-retained" },
+ );
+ } finally {
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("browser credential migration uses insert-if-absent endpoints", () => {
+ const hfSource = readFileSync(
+ new URL("../src/features/hub/stores/hf-token-store.ts", import.meta.url),
+ "utf8",
+ );
+ const providerSource = readFileSync(
+ new URL("../src/features/chat/sync-external-providers.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(hfSource, /migrateHfToken\(token\)/);
+ assert.match(providerSource, /saveLegacyKey: migrateProviderApiKey/);
+});
+
+
+
+test("HF migration is server-first, retry-safe, and idempotent", async () => {
+ const applied: string[] = [];
+ const removed: string[] = [];
+ let saves = 0;
+ const server = await reconcileLegacyHfToken({
+ loadSavedToken: async () => ({ has_token: true, token: "hf_server" }),
+ getLegacyToken: () => "hf_legacy",
+ saveLegacyToken: async () => {
+ saves += 1;
+ return { has_token: true, token: "hf_legacy" };
+ },
+ removeLegacyToken: (token) => {
+ removed.push(token);
+ },
+ applyToken: (token) => applied.push(token),
+ });
+ assert.equal(server.token, "hf_server");
+ assert.deepEqual(applied, ["hf_server"]);
+ assert.equal(saves, 0);
+ assert.deepEqual(removed, ["hf_legacy"]);
+
+
+ await assert.rejects(
+ reconcileLegacyHfToken({
+ loadSavedToken: async () => {
+ throw new Error("backend unavailable");
+ },
+ getLegacyToken: () => "hf_read_retry",
+ saveLegacyToken: async () => {
+ throw new Error("must not upload without server status");
+ },
+ removeLegacyToken: (token) => {
+ removed.push(token);
+ },
+ applyToken: (token) => applied.push(token),
+ }),
+ /backend unavailable/,
+ );
+
+ await assert.rejects(
+ reconcileLegacyHfToken({
+ loadSavedToken: async () => ({ has_token: false, token: null }),
+ getLegacyToken: () => "hf_retry",
+ saveLegacyToken: async () => {
+ throw new Error("offline");
+ },
+ removeLegacyToken: (token) => {
+ removed.push(token);
+ },
+ applyToken: (token) => applied.push(token),
+ }),
+ /offline/,
+ );
+ assert.deepEqual(removed, ["hf_legacy"]);
+ assert.deepEqual(applied, ["hf_server", "hf_read_retry", "hf_retry"]);
+});
+
+
+test("HF cleanup removes only the value observed before the request", async () => {
+ let legacyToken = "hf_old";
+ const removed: string[] = [];
+ await reconcileLegacyHfToken({
+ loadSavedToken: async () => {
+ legacyToken = "hf_new";
+ return { has_token: true, token: "hf_server" };
+ },
+ getLegacyToken: () => legacyToken,
+ saveLegacyToken: async () => {
+ throw new Error("server token must win");
+ },
+ removeLegacyToken: (expectedToken) => {
+ removed.push(expectedToken);
+ if (legacyToken === expectedToken) legacyToken = "";
+ },
+ applyToken: () => undefined,
+ });
+
+ assert.deepEqual(removed, ["hf_old"]);
+ assert.equal(legacyToken, "hf_new");
+});
+
+test("credential bootstrap releases providers only after both attempts settle", async () => {
+ let releaseHf!: () => void;
+ let releaseProviders!: (value: UiProviderConfig[]) => void;
+ const hf = new Promise<void>((resolve) => {
+ releaseHf = resolve;
+ });
+ const providers = new Promise<UiProviderConfig[]>((resolve) => {
+ releaseProviders = resolve;
+ });
+ const applied: UiProviderConfig[][] = [];
+ const boot = runCredentialBootstrap({
+ hydrateHfToken: () => hf,
+ getProviders: () => [uiProvider("local", false)],
+ syncProviders: () => providers,
+ setProviders: (rows) => applied.push(rows),
+ });
+
+ releaseProviders([uiProvider("server", true)]);
+ await Promise.resolve();
+ assert.deepEqual(applied, []);
+ releaseHf();
+ await boot;
+ assert.deepEqual(applied, [[uiProvider("server", true)]]);
+});
+
+
+test("provider bootstrap cannot publish a previous authentication session", async () => {
+ let current = true;
+ let releaseProviders!: (value: UiProviderConfig[]) => void;
+ const providers = new Promise<UiProviderConfig[]>((resolve) => {
+ releaseProviders = resolve;
+ });
+ const applied: UiProviderConfig[][] = [];
+ const boot = runCredentialBootstrap({
+ hydrateHfToken: async () => undefined,
+ getProviders: () => [uiProvider("first-session", false)],
+ syncProviders: () => providers,
+ setProviders: (rows) => applied.push(rows),
+ isCurrent: () => current,
+ });
+
+ current = false;
+ releaseProviders([uiProvider("stale-response", true)]);
+ await boot;
+ assert.deepEqual(applied, []);
+});
+
+test("provider migration does not consume local input after a session change", async () => {
+ let current = true;
+ const removed: string[] = [];
+ const result = await reconcileLegacyProviderKeys(
+ [provider("provider-1", false)],
+ {
+ getLegacyKey: () => "legacy-key",
+ saveLegacyKey: async () => {
+ current = false;
+ return provider("provider-1", true);
+ },
+ removeLegacyKey: (id) => removed.push(id),
+ isCurrent: () => current,
+ },
+ );
+
+ assert.equal(result[0].has_api_key, false);
+ assert.deepEqual(removed, []);
+});
+
+test("legacy migration remains installation-wide and retry-safe", () => {
+ const bootstrapSource = readFileSync(
+ new URL("../src/features/credentials/bootstrap.ts", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(bootstrapSource, /migration-owner|legacy_credential_owner/);
+ assert.doesNotMatch(bootstrapSource, /authSubjectFromJwt|currentOwner/);
+});
+
+
+test("HF credential API rejects a successful non-JSON response", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async () =>
+ new Response("not json", {
+ status: 200,
+ headers: { "Content-Type": "text/plain" },
+ })) as typeof fetch;
+
+ try {
+ const { loadSavedHfToken } = await import(
+ "../src/features/hub/api/hf-token-api.ts"
+ );
+ await assert.rejects(loadSavedHfToken(), /returned an invalid response/);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("legacy training HF token gets a durable migration copy", async () => {
+ const { store } = installLocalStorageFake();
+ try {
+ const hfStore = await import(
+ "../src/features/hub/stores/hf-token-store.ts"
+ );
+ hfStore.stageLegacyHfTokenForMigration(" hf_durable ");
+ assert.equal(store.get("unsloth_hf_token_migration_v1"), "hf_durable");
+ } finally {
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("HF store hydrates from the API without recreating plaintext storage", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ store.set("unsloth_hf_token", "hf_legacy");
+ const originalFetch = globalThis.fetch;
+ const requests: string[] = [];
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ requests.push(String(input));
+ return new Response(
+ JSON.stringify({ token: "hf_server", has_token: true }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+ }) as typeof fetch;
+
+ try {
+ const hfStore = await import(
+ "../src/features/hub/stores/hf-token-store.ts"
+ );
+ await hfStore.hydrateHfTokenFromBackend();
+ assert.equal(hfStore.getHfToken(), "hf_server");
+ assert.deepEqual(requests, ["/api/settings/hugging-face-token"]);
+ assert.equal(store.has("unsloth_hf_token"), false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("HF hydration does not overwrite an in-flight user edit", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ let resolveLoad!: (response: Response) => void;
+ let resolveSave!: (response: Response) => void;
+ const loadResponse = new Promise<Response>((resolve) => {
+ resolveLoad = resolve;
+ });
+ const saveResponse = new Promise<Response>((resolve) => {
+ resolveSave = resolve;
+ });
+
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) =>
+ init?.method === "PUT" ? saveResponse : loadResponse) as typeof fetch;
+
+ try {
+ const hfStore = await import(
+ "../src/features/hub/stores/hf-token-store.ts"
+ );
+ const hydration = hfStore.hydrateHfTokenFromBackend();
+ hfStore.useHfTokenStore.getState().setToken("hf_user_edit");
+
+ resolveLoad(
+ new Response(JSON.stringify({ token: "hf_server", has_token: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ await hydration;
+ assert.equal(hfStore.getHfToken(), "hf_user_edit");
+ assert.equal(hfStore.useHfTokenStore.getState().isPersisting, true);
+
+ resolveSave(
+ new Response(JSON.stringify({ token: "hf_user_edit", has_token: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ if (!hfStore.useHfTokenStore.getState().isPersisting) break;
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ assert.equal(hfStore.getHfToken(), "hf_user_edit");
+ assert.equal(hfStore.useHfTokenStore.getState().isPersisting, false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("cross-tab refresh replays after an active HF hydration", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ let resolveFirst!: (response: Response) => void;
+ let firstStarted!: () => void;
+ const firstResponse = new Promise<Response>((resolve) => { resolveFirst = resolve; });
+ const started = new Promise<void>((resolve) => { firstStarted = resolve; });
+ let reads = 0;
+ globalThis.fetch = (async () => {
+ reads += 1;
+ if (reads === 1) {
+ firstStarted();
+ return firstResponse;
+ }
+ return new Response(JSON.stringify({ token: "hf_new_tab", has_token: true }), {
+ status: 200, headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+
+ try {
+ const hfStore = await import("../src/features/hub/stores/hf-token-store.ts");
+ const hydration = hfStore.hydrateHfTokenFromBackend();
+ await started;
+ const refresh = hfStore.refreshHfTokenFromBackend();
+ resolveFirst(new Response(JSON.stringify({ token: "hf_old", has_token: true }), {
+ status: 200, headers: { "Content-Type": "application/json" },
+ }));
+ await Promise.all([hydration, refresh]);
+ assert.equal(reads, 2);
+ assert.equal(hfStore.getHfToken(), "hf_new_tab");
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("a delayed HF write response reconciles a newer cross-tab commit", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ let resolveWrite!: (response: Response) => void;
+ let writeStarted!: () => void;
+ const writeResponse = new Promise<Response>((resolve) => { resolveWrite = resolve; });
+ const startedWrite = new Promise<void>((resolve) => { writeStarted = resolve; });
+ let reads = 0;
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method === "PUT") {
+ writeStarted();
+ return writeResponse;
+ }
+ reads += 1;
+ return new Response(JSON.stringify({ token: "hf_new_tab", has_token: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+
+ try {
+ const hfStore = await import("../src/features/hub/stores/hf-token-store.ts");
+ hfStore.useHfTokenStore.getState().setToken("hf_delayed_tab");
+ await startedWrite;
+
+ // Another tab commits while this write's response is still delayed.
+ await hfStore.refreshHfTokenFromBackend();
+ resolveWrite(new Response(JSON.stringify({ token: "hf_delayed_tab", has_token: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }));
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ if (!hfStore.useHfTokenStore.getState().isPersisting) break;
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ assert.equal(reads, 2);
+ assert.equal(hfStore.getHfToken(), "hf_new_tab");
+ assert.equal(hfStore.useHfTokenStore.getState().isPersisting, false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+
+test("pending HF edits can be drained before onboarding navigation", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ let resolveSave!: (response: Response) => void;
+ let saveStarted!: () => void;
+ const response = new Promise<Response>((resolve) => { resolveSave = resolve; });
+ const started = new Promise<void>((resolve) => { saveStarted = resolve; });
+ globalThis.fetch = (async () => { saveStarted(); return response; }) as typeof fetch;
+
+ try {
+ const hfStore = await import("../src/features/hub/stores/hf-token-store.ts");
+ hfStore.useHfTokenStore.getState().setToken("hf_before_exit");
+ await started;
+ let drained = false;
+ const drain = hfStore.waitForHfTokenPersistence().then(() => { drained = true; });
+ await Promise.resolve();
+ assert.equal(drained, false);
+ resolveSave(new Response(JSON.stringify({ token: "hf_before_exit", has_token: true }), {
+ status: 200, headers: { "Content-Type": "application/json" },
+ }));
+ await drain;
+ assert.equal(drained, true);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("a superseded successful HF write advances the rollback baseline", async () => {
+ const { store } = installLocalStorageFake();
+ store.set("unsloth_auth_token", "session-token");
+ const originalFetch = globalThis.fetch;
+ let resolveFirst!: (response: Response) => void;
+ let resolveSecond!: (response: Response) => void;
+ let firstStarted!: () => void;
+ let secondStarted!: () => void;
+ const firstRequest = new Promise<void>((resolve) => { firstStarted = resolve; });
+ const secondRequest = new Promise<void>((resolve) => { secondStarted = resolve; });
+ const firstResponse = new Promise<Response>((resolve) => { resolveFirst = resolve; });
+ const secondResponse = new Promise<Response>((resolve) => { resolveSecond = resolve; });
+ let requestCount = 0;
+ globalThis.fetch = (async () => {
+ requestCount += 1;
+ if (requestCount === 1) { firstStarted(); return firstResponse; }
+ secondStarted();
+ return secondResponse;
+ }) as typeof fetch;
+
+ try {
+ const hfStore = await import("../src/features/hub/stores/hf-token-store.ts");
+ hfStore.useHfTokenStore.getState().setToken("hf_first");
+ await firstRequest;
+ hfStore.useHfTokenStore.getState().setToken("hf_second");
+ resolveFirst(new Response(JSON.stringify({ token: "hf_first", has_token: true }), {
+ status: 200, headers: { "Content-Type": "application/json" },
+ }));
+ await secondRequest;
+ resolveSecond(new Response(JSON.stringify({ detail: "failed" }), {
+ status: 500, headers: { "Content-Type": "application/json" },
+ }));
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ if (!hfStore.useHfTokenStore.getState().isPersisting) break;
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ assert.equal(hfStore.getHfToken(), "hf_first");
+ assert.match(hfStore.useHfTokenStore.getState().persistenceError ?? "", /failed/);
+ } finally {
+ globalThis.fetch = originalFetch;
+ Reflect.deleteProperty(globalThis, "window");
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+
+test("onboarding exits wait for the latest HF save", () => {
+ for (const relativePath of [
+ "../src/features/onboarding/components/wizard-footer.tsx",
+ "../src/features/onboarding/components/wizard-sidebar.tsx",
+ "../src/features/onboarding/components/wizard-layout.tsx",
+ ]) {
+ const source = readFileSync(new URL(relativePath, import.meta.url), "utf8");
+ assert.match(source, /await waitForHfTokenPersistence\(\)/);
+ }
+});
+
+
+test("new HF edits never write the token back to localStorage", () => {
+ const source = readFileSync(
+ new URL("../src/features/hub/stores/hf-token-store.ts", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(source, /localStorage\.setItem\(HF_TOKEN_KEY/);
+
+ assert.match(source, /persistenceError:/);
+ assert.match(source, /HF_TOKEN_SYNC_KEY/);
+});
+
+
+test("legacy training HF tokens never merge back into persisted state", () => {
+ const source = readFileSync(
+ new URL(
+ "../src/features/training/stores/training-config-persistence.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(source, /if \(key === "hfToken"\) return false/);
+ assert.match(source, /delete persistedRecord\.hfToken/);
+});
+
+test("provider edit state keeps, replaces, and explicitly clears saved keys", () => {
+ assert.deepEqual(resolveProviderCredentialEdit(true, "", false), {
+ action: "keep",
+ });
+ assert.deepEqual(resolveProviderCredentialEdit(true, "", true), {
+ action: "clear",
+ });
+ assert.deepEqual(resolveProviderCredentialEdit(true, " replacement ", true), {
+ action: "replace",
+ apiKey: "replacement",
+ });
+ assert.deepEqual(resolveProviderCredentialEdit(false, "", false), {
+ action: "missing",
+ });
+
+ const source = readFileSync(
+ new URL("../src/features/chat/chat-providers-dialog.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(source, /Saved securely\. Leave blank to keep it\./);
+ assert.match(source, /Remove saved key/);
+
+ assert.match(source, /removeExternalProviderApiKey\(editingProviderId\)/);
+});
+
+test("credential gate follows authentication session transitions", () => {
+ const rootSource = readFileSync(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ const sessionSource = readFileSync(
+ new URL("../src/features/auth/session.ts", import.meta.url),
+ "utf8",
+ );
+
+ assert.match(rootSource, /AUTH_SESSION_CLEARED_EVENT, reconcile/);
+ assert.match(rootSource, /AUTH_SESSION_STORED_EVENT, reconcile/);
+ assert.match(rootSource, /!isAuthFlowRoute \|\| pathname === "\/onboarding"/);
+ assert.match(sessionSource, /const sessionStarted = !localStorage\.getItem\(AUTH_TOKEN_KEY\)/);
+ assert.match(sessionSource, /dispatchEvent\(new Event\(AUTH_SESSION_STORED_EVENT\)\)/);
+ const bootstrapSource = readFileSync(
+ new URL("../src/features/credentials/bootstrap.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(sessionSource, /authSessionEpoch \+= 1/);
+ assert.match(bootstrapSource, /const sessionEpoch = getAuthSessionEpoch\(\)/);
+ assert.match(
+ bootstrapSource,
+ /hasAuthToken\(\) && getAuthSessionEpoch\(\) === sessionEpoch/,
+ );
+
+});