Repository navigation
Studio: add --secure Cloudflare-only mode and revamp API usage examples - #6300
Conversation
--secure / --not-secure on `unsloth studio` and `unsloth studio run`: - --secure binds 127.0.0.1, requires the Cloudflare tunnel, and advertises only the Cloudflare link. cloudflared reaches the server over localhost, so the raw port is never exposed on a public interface. - If the tunnel cannot start, fail closed with a clear message instead of silently leaving a raw 0.0.0.0 link. - Default stays not-secure (no behavior change); coexists with the existing --cloudflare/--no-cloudflare flag. Host defaults are unchanged. - /api/health (authed) now reports the live tunnel URL. API usage examples (Profile > API): - Example tabs for curl, Python, curl + tools, Python + tools, plus an OS row (Linux/macOS/WSL vs Windows) auto-detected from the platform. - Windows curl passes the JSON body via a file so PowerShell does not strip the quotes when calling curl.exe. - Python + tools forwards enable_tools/enabled_tools through extra_body and guards chunk.choices, since tool-lifecycle events carry no choices. - Shows the loaded model name and the real API key while it is still revealed. - A Cloudflare Tunnel toggle (default on) shows the public tunnel URL and uses it as the base_url in the examples when a tunnel is running. Tests cover the tunnel start gate and the --secure flag on both commands.
There was a problem hiding this comment.
Code Review
This pull request introduces a --secure flag to Unsloth Studio, which forces a loopback bind and exposes the application exclusively via a Cloudflare HTTPS tunnel, failing closed if the tunnel cannot be established. It also updates the frontend to display the tunnel URL and refactors the API usage examples to support OS-specific commands (Unix vs. Windows PowerShell) and tools. The review feedback highlights several robustness issues in the frontend snippet generation, specifically warning that manual JSON construction and lack of quote escaping for model names containing single or double quotes could break the generated curl and PowerShell commands.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| function winBody(model: string, tools: boolean): string { | ||
| const toolsPart = tools | ||
| ? `,"enable_tools":true,"enabled_tools":[${TOOLS.map((t) => `"${t}"`).join(",")}]` | ||
| : ""; | ||
| return `{"model":"${model}","messages":[{"role":"user","content":"${PROMPT}"}]${toolsPart},"stream":true}`; | ||
| } |
There was a problem hiding this comment.
Manually constructing JSON strings via template literals can lead to invalid JSON if the model name or path contains double quotes or backslashes (which is common for local paths on Windows). Using JSON.stringify is much safer and automatically handles escaping.
function winBody(model: string, tools: boolean): string {
const body = {
model,
messages: [{ role: "user", content: PROMPT }],
stream: true,
...(tools ? {
enable_tools: true,
enabled_tools: TOOLS,
} : {}),
};
return JSON.stringify(body);
}
| function curlUnix( | ||
| base: string, | ||
| key: string, | ||
| model: string, | ||
| tools: boolean, | ||
| ): string { | ||
| const toolsLines = tools | ||
| ? ` | ||
| "enable_tools": true, | ||
| "enabled_tools": [${TOOLS.map((t) => `"${t}"`).join(", ")}],` | ||
| : ""; | ||
| return `curl ${base}/v1/chat/completions \\ | ||
| -H "Authorization: Bearer ${key}" \\ | ||
| -H "Content-Type: application/json" \\ | ||
| -d '{ | ||
| "messages": [{"role": "user", "content": "Hello"}], | ||
| "model": "${model}", | ||
| "messages": [{"role": "user", "content": "${PROMPT}"}],${toolsLines} | ||
| "stream": true | ||
| }'`, | ||
| python: `from openai import OpenAI | ||
| }'`; | ||
| } |
There was a problem hiding this comment.
If the model name or path contains single quotes (e.g., /path/to/John's-model.gguf), it will break the single-quoted shell argument -d '...' and cause syntax errors in the terminal. We should use JSON.stringify to safely format the JSON fields and then escape single quotes for the shell by replacing ' with '\''.
function curlUnix(
base: string,
key: string,
model: string,
tools: boolean,
): string {
const toolsLines = tools
? "\n \"enable_tools\": true,\n \"enabled_tools\": " + JSON.stringify(TOOLS) + ","
: "";
const payload = "{\n \"model\": " + JSON.stringify(model) + ",\n \"messages\": [{\"role\": \"user\", \"content\": " + JSON.stringify(PROMPT) + "}]," + toolsLines + "\n \"stream\": true\n}";
const escapedPayload = payload.replace(/'/g, "'\\''");
return "curl " + base + "/v1/chat/completions \\\n" + " -H \"Authorization: Bearer " + key + "\" \\\n" + " -H \"Content-Type: application/json\" \\\n" + " -d '" + escapedPayload + "'";
}
| function curlWindows( | ||
| base: string, | ||
| key: string, | ||
| model: string, | ||
| tools: boolean, | ||
| ): string { | ||
| return `$body = '${winBody(model, tools)}' | ||
| Set-Content -Path body.json -Value $body -Encoding ascii | ||
| curl.exe ${base}/v1/chat/completions \` | ||
| -H "Authorization: Bearer ${key}" \` | ||
| -H "Content-Type: application/json" \` | ||
| -d "@body.json"`; | ||
| } |
There was a problem hiding this comment.
In PowerShell, single quotes are used for literal strings. If the model name or path contains a single quote, it will prematurely terminate the single-quoted string $body = '...' and cause a PowerShell syntax error. We should escape single quotes by replacing ' with ''.
function curlWindows(
base: string,
key: string,
model: string,
tools: boolean,
): string {
const escapedBody = winBody(model, tools).replace(/'/g, "''");
return "$body = '" + escapedBody + "'\nSet-Content -Path body.json -Value $body -Encoding ascii\ncurl.exe " + base + "/v1/chat/completions -H \"Authorization: Bearer " + key + "\" -H \"Content-Type: application/json\" -d \"@body.json\"";
}
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0ca712e9fe
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| err = True, | ||
| ) | ||
| raise typer.Exit(2) | ||
| host = "127.0.0.1" |
There was a problem hiding this comment.
Keep secure tunnels from enabling tools by default
When unsloth studio run --secure is used, this changes host to 127.0.0.1 before the resolve_tool_policy(...) call just below. That resolver treats loopback as non-external and defaults server-side tools on, but secure mode still exposes the API through a public Cloudflare URL, so anyone with the API key can reach Python/terminal tools without the external-bind default-off behavior or warning that 0.0.0.0 receives. Preserve the requested/exposure host for the tool policy, or explicitly default tools off for --secure unless the user passes --enable-tools.
Useful? React with 👍 / 👎.
| args.append("--api-only") | ||
| # Forward the explicit polarity (matches run.py's BooleanOptionalAction). | ||
| args.append("--cloudflare" if cloudflare else "--no-cloudflare") | ||
| args.append("--secure" if secure else "--not-secure") |
There was a problem hiding this comment.
Use the argparse spelling for non-secure launches
In the plain unsloth studio re-exec path, the default non-secure launch now always appends --not-secure, but studio/backend/run.py registers --secure with argparse.BooleanOptionalAction, whose negative form is --no-secure (not --not-secure). In the common installed path where the outer CLI execs run.py, a default unsloth studio launch therefore exits with an unrecognized-argument error before starting Studio; either forward --no-secure here or teach run.py to accept --not-secure.
Useful? React with 👍 / 👎.
| const [os, setOs] = useState<Os>( | ||
| deviceType === "windows" ? "windows" : "unix", | ||
| ); |
There was a problem hiding this comment.
Default curl OS from the browser, not the server
When a Windows user opens Studio on a Linux/WSL/SSH GPU host, deviceType has already been replaced with the server-reported /api/health platform, so this initializer selects the Unix curl variant even though the copied command is meant to run in the user's local PowerShell. That is the exact scenario the Windows file-body curl example is supposed to fix, so keep a separate client-side platform value for this default or derive it directly from navigator here.
Useful? React with 👍 / 👎.
In secure mode the server binds loopback but is reachable via the public Cloudflare tunnel, so resolve the tool policy against the public exposure (0.0.0.0) rather than the loopback bind. This keeps server-side tools off by default and prompts before enabling them, instead of inheriting the loopback default of on. The startup tool notice now names the public surface. Also reject --secure with --no-cloudflare directly in run_server and the run.py argparse (not only the CLI), JSON-encode interpolated model names so Windows paths and quotes cannot produce invalid JSON or broken snippets, and force-refresh /api/health on the API panel so a tunnel that starts after the first health read still surfaces its URL.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 717ceb2e6f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| ? `for chunk in response: | ||
| if chunk.choices: | ||
| print(chunk.choices[0].delta.content or "", end="")` |
There was a problem hiding this comment.
Use raw SSE for Python tool examples
When the copied Python + tools example actually triggers a Studio tool, the backend interleaves custom SSE payloads such as {"type":"tool_status", ...} without the ChatCompletionChunk fields emitted in the normal text chunks (see routes/inference.py around the tool-status yield). The OpenAI Python client parses this stream as chat completion chunks before user code sees it, so the sample can fail or produce objects without .choices before this guard helps; use a raw SSE/requests example for tool streams or make those backend tool events OpenAI-chunk-shaped.
Useful? React with 👍 / 👎.
| if secure: | ||
| host = "127.0.0.1" |
There was a problem hiding this comment.
Point secure tunnels at the IPv4 bind
On hosts where localhost resolves only to ::1 (a case this file already detects in _localhost_ipv6_mismatch_url), forcing secure mode to bind only 127.0.0.1 leaves the existing cloudflared origin (http://localhost:<port> in cloudflare_tunnel.py) pointed at the wrong loopback address. The tunnel can register and be advertised, but requests through the only public URL won't reach Studio; secure mode should either bind an address cloudflared uses or start the tunnel against 127.0.0.1.
Useful? React with 👍 / 👎.
… Copy onto code The Cloudflare Tunnel toggle had no visible effect when Studio was opened through the tunnel: the off state fell back to window.location.origin, which equals the tunnel URL in that case. /api/health now reports the direct host:port (server_url), and the API panel uses it for the off state so it shows the real non-tunnel base. Also move the Copy button out of the tab row and onto the code block.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0e4ebdfbd2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # resolve 0.0.0.0 to the LAN IP, keep an explicit host (incl. secure's loopback). | ||
| if port and port > 0: | ||
| _direct_host = _resolve_external_ip() if host == "0.0.0.0" else host | ||
| app.state.server_url = f"http://{_direct_host}:{port}" |
There was a problem hiding this comment.
Bracket IPv6 hosts in generated API base URL
When Studio is started with an IPv6 bind such as --host ::1 or --host :: (the startup code already treats :: as a supported wildcard bind), this builds server_url as http://::1:8888 / http://:::8888, which is not a valid URL. The API Keys panel now prefers this server_url for copied examples, so those snippets fail for IPv6 launches; wrap IPv6 literals in brackets before formatting the host and port.
Useful? React with 👍 / 👎.
| """Whether to start the Cloudflare quick-tunnel. --secure tunnels a loopback bind | ||
| too (cloudflared targets localhost); non-secure keeps the 0.0.0.0-only rule. | ||
| Colab has its own proxy; api-only has no UI to share.""" | ||
| return cloudflare and (host == "0.0.0.0" or secure) and not api_only and not is_colab |
There was a problem hiding this comment.
Reject secure API-only before starting
When --secure is combined with --api-only (or run_server(secure=True, api_only=True)), this gate suppresses the Cloudflare tunnel because api_only is true, but the secure fail-closed check later exits whenever _cloudflare_url is empty. That accepted combination therefore starts a loopback server and waits through tunnel setup before inevitably exiting; either allow secure API-only tunneling or reject the invalid combination up front.
Useful? React with 👍 / 👎.
Syntax-highlight the curl/PowerShell/Python snippets with the app's shared shiki plugin (bash/powershell/python). Add 'curl + advanced' and 'Python + advanced' tabs that set temperature/top_p/top_k/min_p/ repetition_penalty/max_tokens, enable thinking, and turn on all tools. The Cloudflare Tunnel row no longer shifts the code block: the tunnel URL is always rendered (dimmed when off) so toggling keeps the row height constant. Key the highlighted block on its content so it remounts when only the base URL changes (the renderer's block memo otherwise kept a stale URL).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d942769c6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // accessed through the tunnel, so origin is only a last-resort fallback). | ||
| const origin = typeof window !== "undefined" ? window.location.origin : ""; | ||
| const base = | ||
| useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin); |
There was a problem hiding this comment.
Prefer the browser origin for direct snippets
When Studio is reached through an SSH local-forward, reverse proxy, or any direct URL that differs from the server's guessed external IP, /api/health now provides serverUrl and this line prefers it over the actually working window.location.origin. That makes copied examples switch from the reachable page origin to http://<server-guessed-ip>:<port>, which often fails from the user's machine; prefer the current origin whenever it is not the Cloudflare tunnel, and only fall back to serverUrl when needed.
Useful? React with 👍 / 👎.
…exposed Rename the API examples toggle from Cloudflare Tunnel to Secure HTTPS. When the server was not launched with --secure, show an info tooltip noting the raw 0.0.0.0 port is still globally reachable and pointing at --secure. /api/health now reports whether --secure was used so the hint is hidden in secure mode.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: af3eb039b8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| api_only = api_only, | ||
| llama_parallel_slots = parallel, | ||
| cloudflare = cloudflare, | ||
| secure = secure, |
There was a problem hiding this comment.
Disable tools by default for plain secure launches
When the plain unsloth studio --secure path reaches run_server here, it starts a public Cloudflare endpoint but never resolves or installs a state.tool_policy override (unlike the run subcommand below). After a model is loaded through the UI, any bearer of an API key can send enable_tools: true to /v1 and run the Python/terminal tools through the public tunnel, bypassing the external-bind default-off behavior and warning.
Useful? React with 👍 / 👎.
The plain 'unsloth studio --secure' (and '-H 0.0.0.0') launcher re-execs run.py and never installed a tool policy, so the process default (honor per-request enable_tools) let any API-key holder run Python/terminal tools over the public endpoint. Force the policy off at the run.py entrypoint when network-reachable (0.0.0.0 or --secure); 'unsloth studio run' still installs its own resolved policy and does not go through this path.
…point The plain launcher runs from the studio venv and calls run_server directly, so it never hit the run.py __main__ guard. Move the network/secure default-off tool policy into run_server so every launch path (plain, --secure, direct run.py) gets it; the run subcommand still overrides it with its resolved policy.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3477c13e36
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // accessed through the tunnel, so origin is only a last-resort fallback). | ||
| const origin = typeof window !== "undefined" ? window.location.origin : ""; | ||
| const base = | ||
| useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin); |
There was a problem hiding this comment.
Force tunnel URLs for secure-mode snippets
When /api/health reports secure: true and unsloth_api_use_tunnel is already false in localStorage (or the user toggles this switch off), this falls back to serverUrl, which secure launches set to http://127.0.0.1:<port>. Users opening Studio through the only public Cloudflare URL then copy examples that target their own loopback instead of the reachable tunnel, so secure-mode snippets fail; ignore the direct preference or hide/disable the toggle when secure is true.
Useful? React with 👍 / 👎.
| cloudflareUrl: data.cloudflare_url ?? null, | ||
| serverUrl: data.server_url ?? null, | ||
| secure: data.secure ?? false, |
There was a problem hiding this comment.
Retry tunnel health after auth refresh
When the stored access token has expired but the refresh token is still valid, this raw /api/health call gets a 200 launcher-only payload because the endpoint swallows invalid bearers, so these new fields are stored as null/false. The API Keys tab can then refresh auth through authFetch, but UsageExamples has already done its one forced health read, leaving the Cloudflare toggle and tunnel URL missing until another route-level platform fetch happens; avoid committing the tunnel fields from an unauthenticated health response or trigger a retry after auth refresh.
Useful? React with 👍 / 👎.
Spell out in --help (both unsloth studio and unsloth studio run, plus the run.py argparse) that --not-secure also serves the raw 0.0.0.0 port reachable from anywhere on the network, matching the API panel's Secure HTTPS hint.
…verhead validate_api_key re-ran the 100k-round PBKDF2 on every authenticated request, adding ~15ms to each /v1 call made with an sk-unsloth- key. Benchmarked against the bare llama-server it proxies to, API-key requests carried ~22ms of fixed overhead vs ~7ms for the JWT path; the gap was entirely this redundant key derivation (Pydantic validation measured 0.005ms, so it is not a factor). The raw-key to hash mapping is a pure deterministic function of the fixed server salt, so memoize it per process, keyed by a salted HMAC of the key (never the key or a recoverable digest). The cached value equals what is already stored at rest. Revocation and expiry remain enforced by the SQLite read on every call, so a cache hit only skips the KDF, never the active or expiry checks. Only keys that exist in the DB are cached, so unknown-key spam cannot grow it. After the change the API-key /v1 overhead drops to ~8ms, at parity with JWT, while the at-rest PBKDF2 hashing is unchanged. Adds test_api_key_expiry.py covering API-key and JWT expiry enforcement and the new cache: it skips the KDF on repeat and still rejects revoked or expired keys.
Condense multi-line comments and docstrings to one or two lines, drop the ones that restate obvious code, and remove an orphaned test section header. Comment-only: verified with comment_tools.py check (9/9 code unchanged), the auth/secure-tunnel/CLI test suites, and a clean frontend typecheck and build.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ecb10dca20
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return | ||
| from state.tool_policy import set_tool_policy | ||
|
|
||
| set_tool_policy(False) |
There was a problem hiding this comment.
Allow tool examples to work on network launches
When plain unsloth studio -H 0.0.0.0 is used, this sets the process tool policy to False; _effective_enable_tools() then returns that policy instead of the request's enable_tools, so the new API-panel curl + tools / Python + tools snippets are silently prevented from entering the tool loop. Unlike unsloth studio run, the plain studio command has no --enable-tools override, so this turns a default-off policy into an unconfigurable hard-disable for that launch mode.
Useful? React with 👍 / 👎.
Summary
Two related improvements to the Unsloth Studio API experience.
--secure/--not-secure(bothunsloth studioandunsloth studio run)A network launch today advertises two entry points: the raw
http://<ip>:portlink (often unreachable behind HTTPS-only proxies or closed security groups) and a best-effort Cloudflare link.--securemakes the Cloudflare link the single, safe entry point:127.0.0.1(even if-H 0.0.0.0is passed), so the raw port is never exposed. cloudflared reaches the server overhttp://localhost:port, which is why a loopback bind still tunnels fine.A secure Cloudflare link is not allowed, use --not-secure which provides a 0.0.0.0 linkrather than silently leaving a raw link open.Defaults are unchanged: without the flag, behavior is exactly as before (
--not-secure).--securecoexists with the existing--cloudflare/--no-cloudflareflag, and the host defaults stay127.0.0.1. The authed/api/healthnow reports the live tunnel URL.API usage examples (Profile > API)
curl,Python,curl + tools,Python + tools, plus an OS row (Linux / macOS / WSLvsWindows) auto-detected from the platform.curlpasses the JSON body via a file, since PowerShell strips inline double quotes when invokingcurl.exe.Python + toolsforwardsenable_tools/enabled_toolsthroughextra_bodyand guardschunk.choices(tool-lifecycle events carry no choices, which would otherwise raise).base_urlin the examples when a tunnel is running.Tests
studio/backend/tests/test_secure_tunnel_gate.py: the tunnel start gate across secure/non-secure, host, api-only, and Colab.unsloth_cli/tests/test_studio_secure_flag.py: the--secure/--not-secureoption on both commands, re-exec forwarding, the forced loopback bind, and rejection of--secure --no-cloudflare.--cloudflareflag tests stay green.Verification
unsloth studio -H 0.0.0.0 --securebinds127.0.0.1only, prints just the Cloudflare link, and serves over the tunnel (HTTP 200)./api/healthreturnscloudflare_url; unauthenticated callers do not.tsc -b,vite build, eslint, and the i18n parity check all pass.