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): a custom cloud endpoint had no way out of the webview
purple9800541d6ce0
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsindex f86f4043..6d63a6c4 100644--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@ -240,6 +240,29 @@ fn is_registerable_lan_host(host: &str) -> bool {!h.contains('.') && !h.contains(':')}+/// True for a public hostname a user can legitimately host an OpenAI-compatible+/// backend on (their own domain, or a cloud vendor LU has no preset for). These+/// need the proxy too: the pinned webview CSP only permits a DIRECT fetch to the+/// handful of hosts listed in tauri.conf.json, so anything else is blocked+/// before it leaves the webview (GH #87 family).+///+/// Deliberately narrow: FQDNs only. IP literals are refused — a bare public IP+/// backend is not a case LU needs to serve, and IP/numeric host forms are the+/// classic SSRF-bypass surface (decimal `2852039166`, hex `0xA9FEA9FE`).+fn is_registerable_public_host(host: &str) -> bool {+ let h = host.trim_matches(|c| c == '[' || c == ']').to_lowercase();+ if h.is_empty() || !h.contains('.') || h.ends_with('.') || h.starts_with('.') {+ return false;+ }+ if h.parse::<std::net::IpAddr>().is_ok() {+ return false;+ }+ if h.chars().all(|c| c.is_ascii_digit() || c == '.') {+ return false;+ }+ h.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')+}+/// Validate that a URL targets either localhost or one of the user-configured/// backend hosts (Ollama via `ollama_base`, ComfyUI via `comfy_host`).///@@ -328,11 +351,13 @@ pub fn register_openai_host(if is_blocked_proxy_host(&h) {return Err(format!("refused: '{}' is a metadata/link-local address", h));}- // SSRF hardening (M2): only allow-list private/LAN hosts. The Rust boundary- // enforces the LAN-only intent rather than trusting the JS caller — public- // endpoints don't need the proxy (they use a direct fetch).- if !is_registerable_lan_host(&h) {- return Err(format!("refused: '{}' is not a private/LAN host", h));+ // SSRF hardening (M2): the Rust boundary decides which hosts are usable as a+ // backend, not the JS caller. Private/LAN hosts (CORS) and public FQDNs (the+ // pinned CSP blocks a direct fetch to anything outside tauri.conf.json's+ // connect-src) both need the proxy; IP literals, metadata addresses and+ // numeric IP encodings stay refused.+ if !is_registerable_lan_host(&h) && !is_registerable_public_host(&h) {+ return Err(format!("refused: '{}' is not a usable backend host", h));}if let Ok(mut hosts) = state.openai_hosts.lock() {// Bound the set (m1) — defend against a runaway registration loop.@@ -900,6 +925,21 @@ mod tests {}}+ #[test]+ fn register_accepts_the_users_own_public_backend() {+ // A custom OpenAI-compatible provider on a public domain has no other+ // route out: the pinned CSP only allows a direct fetch to the presets.+ for ok in ["api.fireworks.ai", "llm.example.com", "api.x.ai", "my-vllm.example.org"] {+ assert!(is_registerable_public_host(ok), "{} should be registerable", ok);+ }+ // IP literals and IP-encoding tricks stay out.+ for bad in ["8.8.8.8", "2606:4700::1111", "2852039166", "0xa9fea9fe",+ "169.254.169.254", "nas", "", "javascript:alert(1)",+ "evil.com/path", ".example.com", "example.com."] {+ assert!(!is_registerable_public_host(bad), "{} should NOT be registerable", bad);+ }+ }+#[test]fn configured_host_extracts_from_url_or_bare() {assert_eq!(configured_host("http://192.168.1.50:1234/v1"), "192.168.1.50");diff --git a/src/api/__tests__/csp-direct-hosts.test.ts b/src/api/__tests__/csp-direct-hosts.test.tsnew file mode 100644index 00000000..92ac3636--- /dev/null+++ b/src/api/__tests__/csp-direct-hosts.test.ts@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { isDirectFetchAllowed } from '../backend'++// The webview may only fetch hosts the pinned CSP lists — anything else dies+// inside the webview before it reaches the network, so it has to take the Rust+// proxy instead. isDirectFetchAllowed() mirrors that list by hand; if the two+// drift apart a provider breaks with an unexplainable network error.+describe('CSP direct-fetch allow-list', () => {+ const conf = JSON.parse(+ readFileSync(resolve(process.cwd(), 'src-tauri/tauri.conf.json'), 'utf8'),+ )+ const csp: string = conf.app.security.csp+ const connectSrc = csp.split(';').map(p => p.trim()).find(p => p.startsWith('connect-src')) ?? ''+ const httpsHosts = connectSrc+ .split(/\s+/)+ .filter(t => t.startsWith('https://'))+ .map(t => t.slice('https://'.length))++ it('mirrors every https host the CSP allows', () => {+ expect(httpsHosts.length).toBeGreaterThan(5)+ for (const host of httpsHosts) {+ const probe = host.startsWith('*.') ? `sub.${host.slice(2)}` : host+ expect(isDirectFetchAllowed(probe), `${probe} is in the CSP but not in CSP_DIRECT_HOSTS`).toBe(true)+ }+ })++ it('routes a user-configured cloud endpoint through the proxy', () => {+ for (const host of ['api.fireworks.ai', 'api.x.ai', 'api.cerebras.ai', 'llm.example.com']) {+ expect(isDirectFetchAllowed(host), `${host} must not use a direct fetch`).toBe(false)+ }+ })++ it('ignores case and empty hosts', () => {+ expect(isDirectFetchAllowed('API.GROQ.COM')).toBe(true)+ expect(isDirectFetchAllowed('')).toBe(false)+ })+})diff --git a/src/api/backend.ts b/src/api/backend.tsindex f89fe8df..87c25bcc 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -17,6 +17,7 @@ export function isTauri(): boolean {// Tauri v2 renamed the global from `__TAURI__` to `__TAURI_INTERNALS__`.// Check both so the app keeps working across both versions (and also// during the migration window when people might be on either).+ if (typeof window === "undefined") return false;const w = window as any;return !!(w.__TAURI_INTERNALS__ || w.__TAURI__);}@@ -847,6 +848,37 @@ export function hostnameOf(url: string): string {try { return _canonHost(new URL(url).hostname) } catch { return '' }}+/**+ * Hosts the webview is allowed to fetch DIRECTLY. Mirrors `connect-src` in+ * src-tauri/tauri.conf.json — keep the two in sync. Everything else has to take+ * the Rust proxy, because the pinned CSP kills the request inside the webview+ * before it reaches the network. That is why a user's own cloud endpoint (a+ * custom OpenAI-compatible provider on their domain, or a vendor LU ships no+ * preset for) used to fail with an unexplainable network error.+ */+const CSP_DIRECT_HOSTS = new Set([+ 'lu-labs.ai',+ 'lrrhheztdytyfpizvuup.supabase.co',+ 'openrouter.ai',+ 'api.openai.com',+ 'api.groq.com',+ 'api.together.xyz',+ 'api.deepseek.com',+ 'api.mistral.ai',+ 'api.anthropic.com',+ 'ollama.com',+ 'huggingface.co',+ 'civitai.com',+])++export function isDirectFetchAllowed(hostname: string): boolean {+ const h = _canonHost(hostname)+ if (!h) return false+ return CSP_DIRECT_HOSTS.has(h)+ || h.endsWith('.huggingface.co')+ || h.endsWith('.civitai.com')+}+// Hosts already registered with the proxy this session (avoid duplicate IPC).const _registeredProxyHosts = new Set<string>()diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex ceda7a28..10477c04 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -17,15 +17,14 @@ import { ProviderError } from './types'import { parseSSEStream } from '../sse'import { repairJson } from '../../lib/tool-call-repair'import { signalCreditsExhausted } from '../../lib/credits-exhausted'-import { localFetch, localFetchStream, isPrivateOrLanHost, hostnameOf, ensureProxyAllowsHost } from '../backend'+import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost } from '../backend'-// 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).+// Transport routing lives in the `useLocalProxy` getter (below) plus the shared+// host helpers in backend.ts. A direct webview fetch only works for hosts the+// pinned CSP lists; everything else — LAN backends (also CORS-blocked, GH #49)+// and any cloud endpoint LU ships no preset for — goes through the Rust proxy.+// `isLanBackend` stays separate: it decides local-only BEHAVIOUR (context+// probing), which must not follow the transport decision.// ── OpenAI API Types ───────────────────────────────────────────@@ -172,17 +171,28 @@ export class OpenAIProvider implements ProviderClient {}/**- * Whether requests must go through the Rust proxy instead of a direct webview- * fetch. True for any local/LAN endpoint — declared by the preset+ * A backend on this machine or the LAN — 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.+ * IPv6 ULA/link-local, .local, bare machine name). Drives behaviour that only+ * makes sense locally: per-model context probing and the LM Studio enhanced+ * API. Cloud endpoints must not do those (N+1 requests → rate limits).*/- private get useLocalProxy(): boolean {+ private get isLanBackend(): boolean {return this.config.isLocal === true || isPrivateOrLanHost(hostnameOf(this.baseUrl))}+ /**+ * Whether requests must go through the Rust proxy instead of a direct webview+ * fetch. Two reasons: a LAN endpoint has no CORS headers for the+ * tauri.localhost origin (GH #49), and a public host outside the pinned CSP+ * allow-list gets killed inside the webview before it hits the network — that+ * is every custom OpenAI-compatible provider a user configures themselves+ * (their own domain, or a vendor LU ships no preset for).+ */+ private get useLocalProxy(): boolean {+ return this.isLanBackend || !isDirectFetchAllowed(hostnameOf(this.baseUrl))+ }+private get headers(): Record<string, string> {const h: Record<string, string> = {'Content-Type': 'application/json',@@ -478,7 +488,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 (this.useLocalProxy) {+ if (this.isLanBackend) {return Promise.all(models.map(async m => ({id: m.id,name: m.id,@@ -545,7 +555,7 @@ export class OpenAIProvider implements ProviderClient {* Returnt `null` wenn nichts gefunden, damit Callers cascaden koennen.*/private async probeContextFromServer(model: string): Promise<number | null> {- if (!this.useLocalProxy) return null+ if (!this.isLanBackend) return null// 1. LM Studio Enhanced API: /api/v0/models/<id>// Base-URL ist typischerweise http://localhost:1234/v1 — wir tauschen