The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(providers): route LAN OpenAI-compat endpoints through Rust proxy (#49)
purple8378c7e8b72e
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsindex d58dad6f..423b55a8 100644--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@ -114,6 +114,26 @@ fn configured_host(url_or_host: &str) -> String {url_or_host.trim().to_lowercase()}+/// Cloud-metadata / link-local addresses that must NEVER be proxied, even if a+/// host somehow lands in an allow-list. These are the classic SSRF targets+/// (AWS/GCP/Azure 169.254.169.254, Alibaba 100.100.100.200, GCP IPv6 IMDS+/// fd00:ec2::254) plus the whole IPv4 link-local block — a real LAN LLM backend+/// never lives there. Defense-in-depth on top of host registration (Bug A).+fn is_blocked_proxy_host(host: &str) -> bool {+ let h = host.trim_matches(|c| c == '[' || c == ']').to_lowercase();+ if matches!(h.as_str(), "169.254.169.254" | "100.100.100.200" | "fd00:ec2::254") {+ return true;+ }+ // Entire IPv4 link-local 169.254.0.0/16 — never a legitimate backend.+ if let Ok(ip) = h.parse::<std::net::Ipv4Addr>() {+ let o = ip.octets();+ if o[0] == 169 && o[1] == 254 {+ return true;+ }+ }+ false+}+/// Validate that a URL targets either localhost or one of the user-configured/// backend hosts (Ollama via `ollama_base`, ComfyUI via `comfy_host`).///@@ -131,6 +151,14 @@ fn validate_proxy_url(raw: &str, state: &crate::state::AppState) -> Result<(), Slet host = parsed.host_str().unwrap_or("").to_lowercase();+ // Hard block: cloud-metadata / link-local — never proxied, even if a host+ // somehow got allow-listed (SSRF defense-in-depth, Bug A).+ if is_blocked_proxy_host(&host) {+ return Err(format!(+ "Blocked: '{}' is a metadata/link-local address and is never proxied", host+ ));+ }+// Always-allowed: localhost variants. Covers the common case + any// backend bound to 0.0.0.0 on the same machine.let is_local = matches!(host.as_str(),@@ -158,12 +186,48 @@ fn validate_proxy_url(raw: &str, state: &crate::state::AppState) -> Result<(), Sreturn Ok(());}+ // Configured OpenAI-compatible LAN backends (Bug A / GH #49). Registered+ // via `register_openai_host` when the provider points at a non-localhost+ // host. Only these specific user-configured hosts are forwarded.+ if let Ok(hosts) = state.openai_hosts.lock() {+ if hosts.contains(&host) {+ return Ok(());+ }+ }+Err(format!(- "proxy_localhost: host '{}' not allowed. Configure remote backends via Settings → Providers (Ollama) or Settings → ComfyUI (Host).",+ "proxy_localhost: host '{}' not allowed. Configure remote backends via Settings → Providers or Settings → ComfyUI (Host).",host))}+/// Register a user-configured OpenAI-compatible backend host (LAN LM Studio,+/// vLLM, …) into the proxy allow-list so `proxy_localhost` will forward to it.+/// Mirrors the Ollama/ComfyUI host-registration model (Bug A / GH #49): the+/// webview CSP + the backend's CORS block a direct LAN fetch, so these requests+/// are proxied through Rust instead.+///+/// SSRF policy: only the host the user explicitly pointed LU at is added, and+/// metadata/link-local addresses are refused outright (defense-in-depth on top+/// of validate_proxy_url's hard block). Accepts a bare host or a full URL.+#[tauri::command]+pub fn register_openai_host(+ host: String,+ state: tauri::State<'_, crate::state::AppState>,+) -> Result<(), String> {+ let h = configured_host(&host);+ if h.is_empty() || h.contains('/') || h.contains(' ') {+ return Err("invalid host".to_string());+ }+ if is_blocked_proxy_host(&h) {+ return Err(format!("refused: '{}' is a metadata/link-local address", h));+ }+ if let Ok(mut hosts) = state.openai_hosts.lock() {+ hosts.insert(h);+ }+ Ok(())+}+/// Generic localhost proxy — fetch any localhost or configured-backend URL/// bypassing CORS. Used for Ollama and ComfyUI API calls in production mode.///@@ -516,3 +580,36 @@ pub async fn ollama_search(query: String) -> Result<serde_json::Value, String> {Err(_) => Ok(serde_json::json!({"models": []})),}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn blocks_cloud_metadata_and_link_local() {+ // Classic SSRF metadata targets — must be blocked even if registered.+ assert!(is_blocked_proxy_host("169.254.169.254")); // AWS/GCP/Azure IMDS+ assert!(is_blocked_proxy_host("100.100.100.200")); // Alibaba+ assert!(is_blocked_proxy_host("fd00:ec2::254")); // GCP IPv6 IMDS+ assert!(is_blocked_proxy_host("[fd00:ec2::254]")); // bracketed form+ // Whole IPv4 link-local 169.254.0.0/16.+ assert!(is_blocked_proxy_host("169.254.0.1"));+ assert!(is_blocked_proxy_host("169.254.255.255"));+ }++ #[test]+ fn allows_real_lan_and_localhost() {+ for h in ["192.168.1.50", "10.0.0.5", "172.16.4.4", "localhost",+ "127.0.0.1", "100.64.0.1" /* Tailscale CGNAT, not metadata */] {+ assert!(!is_blocked_proxy_host(h), "{} should not be blocked", h);+ }+ }++ #[test]+ fn configured_host_extracts_from_url_or_bare() {+ assert_eq!(configured_host("http://192.168.1.50:1234/v1"), "192.168.1.50");+ assert_eq!(configured_host("192.168.1.50"), "192.168.1.50");+ assert_eq!(configured_host("HTTP://Host.LAN:8080"), "host.lan");+ assert_eq!(configured_host(" nas "), "nas");+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 8c0c5559..4a959b92 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -203,6 +203,7 @@ fn main() {commands::proxy::proxy_localhost,commands::proxy::proxy_localhost_stream,commands::proxy::proxy_localhost_stream_chunked,+ commands::proxy::register_openai_host,commands::proxy::pull_model_stream,commands::proxy::cancel_model_pull,// Cloud "Hosted LU Workflows" waitlist — opt-in email capturediff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex cc5aa033..048c91d2 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::process::Child;use std::sync::atomic::AtomicBool;use std::sync::{Arc, Mutex};@@ -141,6 +141,13 @@ pub struct AppState {/// `set_ollama_host` command. Every call that proxies Ollama reads this/// value so GUI changes reflect everywhere without a restart.pub ollama_base: Mutex<String>,+ /// Hosts of user-configured OpenAI-compatible backends reachable over the+ /// LAN (LM Studio / vLLM / etc. bound to 0.0.0.0 on another machine).+ /// Registered at runtime via `register_openai_host` so `validate_proxy_url`+ /// forwards to them — same allow-list model as `ollama_base`/`comfy_host`.+ /// In-memory only; rebuilt lazily from the persisted provider config the+ /// first time a LAN endpoint is used after launch (Bug A / GH #49).+ pub openai_hosts: Mutex<HashSet<String>>,pub whisper: Arc<Mutex<WhisperServer>>,pub downloads: Arc<Mutex<HashMap<String, DownloadProgress>>>,pub download_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,@@ -226,6 +233,7 @@ impl AppState {comfy_port: Mutex::new(initial_port),comfy_host: Mutex::new(initial_host),ollama_base: Mutex::new(initial_ollama_base),+ openai_hosts: Mutex::new(HashSet::new()),whisper: Arc::new(Mutex::new(WhisperServer::new())),downloads: Arc::new(Mutex::new(HashMap::new())),download_tokens: Arc::new(Mutex::new(HashMap::new())),diff --git a/src/api/__tests__/lan-host.test.ts b/src/api/__tests__/lan-host.test.tsnew file mode 100644index 00000000..2c1f5397--- /dev/null+++ b/src/api/__tests__/lan-host.test.ts@@ -0,0 +1,61 @@+/**+ * LAN / private-host detection tests (Bug A / GH #49).+ *+ * The LAN OpenAI-compat "Test" button failed because a 192.168.x.x endpoint was+ * classified as cloud → direct webview fetch → CSP/CORS-blocked. These helpers+ * decide proxy-vs-direct routing, so their classification is the heart of the fix.+ * Run: npx vitest run src/api/__tests__/lan-host.test.ts+ */+import { describe, it, expect } from 'vitest'+import { isLoopbackHost, isPrivateOrLanHost, hostnameOf } from '../backend'++describe('isLoopbackHost', () => {+ it('detects loopback variants', () => {+ for (const h of ['localhost', '127.0.0.1', '::1', '0.0.0.0', 'foo.localhost'])+ expect(isLoopbackHost(h)).toBe(true)+ })+ it('rejects non-loopback hosts', () => {+ for (const h of ['192.168.1.50', 'api.openai.com', '10.0.0.1'])+ expect(isLoopbackHost(h)).toBe(false)+ })+})++describe('isPrivateOrLanHost (Bug A / #49)', () => {+ it('treats RFC1918 + CGNAT + loopback as LAN', () => {+ for (const h of ['127.0.0.1', 'localhost', '192.168.1.50', '10.0.0.5',+ '172.16.0.1', '172.31.255.254', '100.64.0.1'])+ expect(isPrivateOrLanHost(h)).toBe(true)+ })+ it('treats LAN DNS suffixes + bare machine names as LAN', () => {+ for (const h of ['nas', 'mypc', 'server.local', 'box.lan', 'host.internal'])+ expect(isPrivateOrLanHost(h)).toBe(true)+ })+ it('treats IPv6 ULA + link-local as LAN', () => {+ for (const h of ['fd00::1', 'fc00::1', 'fe80::1', '[fd00::1]'])+ expect(isPrivateOrLanHost(h)).toBe(true)+ })+ it('treats public hosts + cloud APIs as NOT LAN', () => {+ for (const h of ['api.openai.com', 'openrouter.ai', '8.8.8.8', '1.1.1.1',+ '2606:4700::1111'])+ expect(isPrivateOrLanHost(h)).toBe(false)+ })+ it('does NOT treat 169.254 link-local/metadata as LAN (proxy hard-blocks it)', () => {+ expect(isPrivateOrLanHost('169.254.169.254')).toBe(false)+ expect(isPrivateOrLanHost('169.254.0.1')).toBe(false)+ })+ it('rejects malformed octets', () => {+ expect(isPrivateOrLanHost('999.1.1.1')).toBe(false)+ expect(isPrivateOrLanHost('')).toBe(false)+ })+})++describe('hostnameOf', () => {+ it('extracts a lowercase host from a URL', () => {+ expect(hostnameOf('http://192.168.1.50:1234/v1')).toBe('192.168.1.50')+ expect(hostnameOf('https://API.OpenAI.com/v1')).toBe('api.openai.com')+ expect(hostnameOf('http://[fd00::1]:1234')).toBe('fd00::1')+ })+ it('returns empty for junk', () => {+ expect(hostnameOf('not a url')).toBe('')+ })+})diff --git a/src/api/backend.ts b/src/api/backend.tsindex 2605e87a..6e5adb69 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -534,3 +534,89 @@ export async function checkGitInstalled(): Promise<GitStatus> {const invoke = await getInvoke()return (await invoke('check_git_installed')) as GitStatus}++// ── LAN / private-host detection + proxy registration (Bug A / GH #49) ──────+//+// A LAN OpenAI-compat endpoint (LM Studio / vLLM bound to 0.0.0.0 and reached+// over the network as e.g. http://192.168.1.50:1234) cannot be fetched directly+// from the Tauri webview: the CSP `connect-src` only whitelists localhost ++// 127.0.0.1, and the backend doesn't send CORS headers for the tauri.localhost+// origin. So those requests must go through the Rust proxy, exactly like+// Ollama/ComfyUI. These helpers classify a host (proxy vs direct fetch) and+// register the host with the proxy's allow-list (validate_proxy_url).++/** Strip IPv6 brackets and lowercase. */+function _canonHost(hostname: string): string {+ return hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '')+}++/** localhost / loopback — always proxy-allowed, no registration needed. */+export function isLoopbackHost(hostname: string): boolean {+ const h = _canonHost(hostname)+ return h === 'localhost' || h === '127.0.0.1' || h === '::1'+ || h === '0.0.0.0' || h.endsWith('.localhost')+}++/**+ * True for localhost AND private/LAN addresses: RFC1918 (10/8, 172.16/12,+ * 192.168/16), CGNAT/Tailscale (100.64/10), IPv6 ULA (fc00::/7) + link-local+ * (fe80::/10), the common LAN DNS suffixes, and bare machine names (no dots).+ *+ * Deliberately NOT treated as LAN: IPv4 link-local 169.254/16. It is never a+ * real LLM backend and 169.254.169.254 is the classic cloud-metadata SSRF+ * target — the Rust proxy hard-blocks it regardless.+ */+export function isPrivateOrLanHost(hostname: string): boolean {+ const h = _canonHost(hostname)+ if (!h) return false+ if (isLoopbackHost(h)) return true+ if (/\.(local|lan|internal|intra|home|home\.arpa)$/.test(h)) return true+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)+ if (v4) {+ const a = +v4[1], b = +v4[2]+ if (a > 255 || b > 255 || +v4[3] > 255 || +v4[4] > 255) return false+ if (a === 169 && b === 254) return false // link-local / metadata: not LAN+ if (a === 10) return true // 10.0.0.0/8+ if (a === 172 && b >= 16 && b <= 31) return true // 172.16.0.0/12+ if (a === 192 && b === 168) return true // 192.168.0.0/16+ if (a === 127) return true // loopback+ if (a === 100 && b >= 64 && b <= 127) return true // 100.64.0.0/10 CGNAT (Tailscale)+ return false // public IPv4+ }+ if (h.includes(':')) { // IPv6 literal+ if (/^f[cd]/.test(h)) return true // fc00::/7 unique-local+ if (/^fe[89ab]/.test(h)) return true // fe80::/10 link-local+ return false // public IPv6+ }+ if (!h.includes('.')) return true // bare LAN machine name (nas, mypc)+ return false // FQDN → public/cloud+}++/** Lowercase hostname from a URL, or '' if unparseable. */+export function hostnameOf(url: string): string {+ try { return _canonHost(new URL(url).hostname) } catch { return '' }+}++// Hosts already registered with the proxy this session (avoid duplicate IPC).+const _registeredProxyHosts = new Set<string>()++/**+ * Ensure the Rust proxy's allow-list contains this endpoint's host so+ * `proxy_localhost` will forward to a user-configured LAN backend. No-op for+ * loopback (already allowed), in browser dev mode (no Rust proxy), and for+ * hosts already registered this session. Best-effort: a failure (e.g. an older+ * build without the command) is swallowed — the direct-fetch fallback applies.+ */+export async function ensureProxyAllowsHost(baseUrl: string): Promise<void> {+ if (!isTauri()) return+ const host = hostnameOf(baseUrl)+ if (!host || isLoopbackHost(host)) return+ if (_registeredProxyHosts.has(host)) return+ try {+ const invoke = await getInvoke()+ await invoke('register_openai_host', { host })+ _registeredProxyHosts.add(host)+ } catch (err) {+ log.warn('[ensureProxyAllowsHost] proxy host registration failed', { host, err: String(err) })+ }+}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex da6d8c9f..2b2322a9 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -16,24 +16,15 @@ import type {import { ProviderError } from './types'import { parseSSEStream } from '../sse'import { repairJson } from '../../lib/tool-call-repair'-import { localFetch, localFetchStream } from '../backend'+import { localFetch, localFetchStream, isPrivateOrLanHost, hostnameOf, ensureProxyAllowsHost } from '../backend'-/**- * Local OpenAI-compat backends (LM Studio, vLLM, llama.cpp, KoboldCpp, etc.)- * are hit over plain HTTP on localhost. From the Tauri webview that triggers- * CORS, so use `localFetch`/`localFetchStream` which bypass via the Rust- * proxy (with direct-fetch fallback).- * Cloud endpoints (OpenAI, OpenRouter, Groq, Together, etc.) don't need the- * proxy and skip it via a simple host check.- */-function isLocalUrl(baseUrl: string): boolean {- try {- const h = new URL(baseUrl).hostname.toLowerCase()- return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '0.0.0.0'- } catch {- return false- }-}+// Local/LAN vs cloud routing now lives in the `useLocalProxy` getter (below)+// plus the shared host helpers in backend.ts (isPrivateOrLanHost/hostnameOf).+// A local OR LAN OpenAI-compat backend (LM Studio/vLLM bound to 0.0.0.0,+// reached over the network) is hit through the Rust proxy to bypass CORS + the+// webview CSP; cloud endpoints use a direct fetch. Fixes GH #49 (LAN endpoint+// "Test" failed because a 192.168.x.x host fell back to a CSP/CORS-blocked+// direct fetch).// ── OpenAI API Types ───────────────────────────────────────────@@ -144,6 +135,18 @@ export class OpenAIProvider implements ProviderClient {return this.config.baseUrl.replace(/\/+$/, '')}+ /**+ * Whether requests must go through the Rust proxy instead of a direct webview+ * fetch. True for any local/LAN endpoint — declared by the preset+ * (`config.isLocal`) OR detected from the host (localhost, RFC1918, CGNAT,+ * IPv6 ULA/link-local, .local, bare machine name). Cloud endpoints (public+ * hostnames, isLocal=false) use a direct fetch. Fixes GH #49 where a LAN LM+ * Studio (e.g. 192.168.1.50) used a direct fetch and was CSP/CORS-blocked.+ */+ private get useLocalProxy(): boolean {+ return this.config.isLocal === true || isPrivateOrLanHost(hostnameOf(this.baseUrl))+ }+private get headers(): Record<string, string> {const h: Record<string, string> = {'Content-Type': 'application/json',@@ -181,9 +184,10 @@ export class OpenAIProvider implements ProviderClient {else if (options?.thinking === false) body.reasoning_effort = 'minimal'// Ask LM Studio / local openai-compat servers for REAL token usage in a// final stream chunk (choices:[] + usage:{...}). Dropped on 400 below.- if (isLocalUrl(this.baseUrl)) body.stream_options = { include_usage: true }+ if (this.useLocalProxy) body.stream_options = { include_usage: true }- const fetcher = isLocalUrl(this.baseUrl) ? localFetchStream : fetch+ if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)+ const fetcher = this.useLocalProxy ? localFetchStream : fetchlet res = await fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,@@ -303,7 +307,8 @@ export class OpenAIProvider implements ProviderClient {if (options?.thinking === true) body.reasoning_effort = 'high'else if (options?.thinking === false) body.reasoning_effort = 'minimal'- const fetcher = isLocalUrl(this.baseUrl) ? localFetch : fetch+ if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)+ const fetcher = this.useLocalProxy ? localFetch : fetchlet res = await fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,@@ -348,7 +353,8 @@ export class OpenAIProvider implements ProviderClient {}async listModels(): Promise<ProviderModel[]> {- const fetcher = isLocalUrl(this.baseUrl) ? localFetch : fetch+ if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)+ const fetcher = this.useLocalProxy ? localFetch : fetchconst res = await fetcher(`${this.baseUrl}/models`, {headers: this.headers,} as any)@@ -364,7 +370,7 @@ export class OpenAIProvider implements ProviderClient {// Context-Limit vom Server. Sonst zeigen wir 8K obwohl das Modell 32K+// kann. Probes laufen parallel; bei Cloud-Providers (OpenAI/OpenRouter)// wuerde N+1 zu Rate-Limits fuehren, deshalb nur KNOWN_CONTEXT/Heuristik.- if (isLocalUrl(this.baseUrl)) {+ if (this.useLocalProxy) {return Promise.all(models.map(async m => ({id: m.id,name: m.id,@@ -390,7 +396,8 @@ export class OpenAIProvider implements ProviderClient {async checkConnection(): Promise<boolean> {try {- const fetcher = isLocalUrl(this.baseUrl) ? localFetch : fetch+ if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)+ const fetcher = this.useLocalProxy ? localFetch : fetchconst res = await fetcher(`${this.baseUrl}/models`, {headers: this.headers,} as any)@@ -416,7 +423,7 @@ export class OpenAIProvider implements ProviderClient {* Returnt `null` wenn nichts gefunden, damit Callers cascaden koennen.*/private async probeContextFromServer(model: string): Promise<number | null> {- if (!isLocalUrl(this.baseUrl)) return null+ if (!this.useLocalProxy) return null// 1. LM Studio Enhanced API: /api/v0/models/<id>// Base-URL ist typischerweise http://localhost:1234/v1 — wir tauschen