Skip to content

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.

fix(dev-server): K8 - allow the dev server's own LAN origin under --host without weakening DNS-rebinding protection

purple56e407f3f468
diff --git a/dev-server/__tests__/find-comfyui-k8.test.ts b/dev-server/__tests__/find-comfyui-k8.test.ts
new file mode 100644
index 00000000..0ec67ebf
--- /dev/null
+++ b/dev-server/__tests__/find-comfyui-k8.test.ts
@@ -0,0 +1,99 @@
+/**
+ * K8 (GH #134, eloieloie): `detect_all_comfyui_installs` / `find_comfyui`
+ * had no dev-server route at all — `find_comfyui` was even mapped in
+ * endpointMap (src/api/backend.ts) already, pointing at a path
+ * `dev-server/comfy.ts` never registered. ComfyStep.tsx's auto-detect tried
+ * both, got a 404 (an HTML page, not JSON) from each, and settled on
+ * `{ found: false }` — onboarding stayed stuck on "Install ComfyUI" even
+ * with ComfyUI installed and running on :8188. Independent of --host/LAN.
+ *
+ * Real filesystem (a throwaway COMFYUI_PATH), real handler
+ * (registerComfyControlRoutes — the function dev-server/index.ts calls),
+ * real HTTP. `isComfyRunning()` is stubbed at the network boundary
+ * (`fetch`) since "is a real ComfyUI answering on :8188" is not this test's
+ * concern.
+ *
+ * Run: npx vitest run dev-server/__tests__/find-comfyui-k8.test.ts
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { registerComfyControlRoutes, createComfyLauncher } from '../comfy'
+import { routeHolen } from './echte-anfrage'
+import { anfrage } from './echte-anfrage'
+
+let dir = ''
+const vorherEnv = process.env.COMFYUI_PATH
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'lu-find-comfyui-'))
+})
+
+afterEach(() => {
+ if (vorherEnv === undefined) delete process.env.COMFYUI_PATH
+ else process.env.COMFYUI_PATH = vorherEnv
+ rmSync(dir, { recursive: true, force: true })
+ vi.unstubAllGlobals()
+})
+
+const comfy = createComfyLauncher()
+const findComfyuiHandler = routeHolen((r) => registerComfyControlRoutes(r, comfy), '/local-api/find-comfyui')
+const detectAllHandler = routeHolen((r) => registerComfyControlRoutes(r, comfy), '/local-api/detect-all-comfyui-installs')
+
+describe('/local-api/find-comfyui', () => {
+ it('reports found:false when COMFYUI_PATH has no main.py (nothing else scanned in the test env)', async () => {
+ process.env.COMFYUI_PATH = dir // empty dir, no main.py
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
+ const res = await anfrage(findComfyuiHandler, { url: '/' })
+ expect(res.status).toBe(200)
+ expect(res.json()).toEqual({ found: false, path: null, complete: false })
+ })
+
+ it('reports found:true, complete:true when ComfyUI is actually reachable', async () => {
+ writeFileSync(join(dir, 'main.py'), '# comfy\n')
+ process.env.COMFYUI_PATH = dir
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
+ const res = await anfrage(findComfyuiHandler, { url: '/' })
+ expect(res.status).toBe(200)
+ expect(res.json()).toEqual({ found: true, path: dir, complete: true })
+ })
+
+ it('reports found:true, complete:true from a built venv even when not currently running', async () => {
+ writeFileSync(join(dir, 'main.py'), '# comfy\n')
+ mkdirSync(join(dir, 'venv'))
+ process.env.COMFYUI_PATH = dir
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
+ const res = await anfrage(findComfyuiHandler, { url: '/' })
+ expect(res.json()).toEqual({ found: true, path: dir, complete: true })
+ })
+
+ it('reports found:true, complete:false for a bare clone with neither a venv nor a running process (P14 carcass)', async () => {
+ writeFileSync(join(dir, 'main.py'), '# comfy\n')
+ process.env.COMFYUI_PATH = dir
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
+ const res = await anfrage(findComfyuiHandler, { url: '/' })
+ expect(res.json()).toEqual({ found: true, path: dir, complete: false })
+ })
+})
+
+describe('/local-api/detect-all-comfyui-installs', () => {
+ it('answers an empty array, not a 404, when nothing is found', async () => {
+ process.env.COMFYUI_PATH = dir
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
+ const res = await anfrage(detectAllHandler, { url: '/' })
+ expect(res.status).toBe(200)
+ expect(res.json()).toEqual([])
+ })
+
+ it('answers a one-entry array shaped like the Rust ComfyInstallChoice', async () => {
+ writeFileSync(join(dir, 'main.py'), '# comfy\n')
+ process.env.COMFYUI_PATH = dir
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
+ const res = await anfrage(detectAllHandler, { url: '/' })
+ expect(res.status).toBe(200)
+ expect(res.json()).toEqual([
+ { path: dir, complete: true, has_embedded_python: false, source: 'scan' },
+ ])
+ })
+})
diff --git a/dev-server/__tests__/lan-origin-k8.test.ts b/dev-server/__tests__/lan-origin-k8.test.ts
new file mode 100644
index 00000000..af0e74bf
--- /dev/null
+++ b/dev-server/__tests__/lan-origin-k8.test.ts
@@ -0,0 +1,148 @@
+/**
+ * K8 (GH #134, eloieloie, `npm run dev --host`): a deliberately LAN-exposed
+ * dev server rejected its own onboarding write requests — the page loaded
+ * from the machine's LAN IP (e.g. `http://192.168.1.23:5273`), which is
+ * neither `tauri://localhost` nor the loopback regex, so the guard's Origin
+ * check 403'd it with "Invalid Origin (CSRF Protection)" exactly as it
+ * would a real cross-origin page.
+ *
+ * The fix (dev-server/guard.ts) adds a SECOND, optional parameter to
+ * createLocalApiGuard: a per-request getter for the server's own resolved
+ * LAN origin(s), supplied by dev-server/index.ts only when `--host` is
+ * active. Nothing here weakens the DNS-rebinding protection the guard
+ * already had (waechter-und-port.test.ts) — a value the CALLER supplies
+ * (Origin, Host) still never authorises anything; only a value the SERVER
+ * computed about its own bind address can.
+ *
+ * Run: npx vitest run dev-server/__tests__/lan-origin-k8.test.ts
+ */
+import { describe, expect, it } from 'vitest'
+import { createLocalApiGuard } from '../guard'
+import { anfrage } from './echte-anfrage'
+
+const csrf = { 'x-locally-uncensored': 'true' }
+const json = { 'Content-Type': 'application/json', ...csrf }
+const DURCHGEREICHT = 599
+
+describe('K8 — --host: the server accepts its own LAN origin', () => {
+ it('without a getLanOrigins getter (plain `npm run dev`), a LAN origin is still rejected', async () => {
+ const waechter = createLocalApiGuard(5273)
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'http://192.168.1.23:5273' }, body: '{}',
+ })
+ expect(res.status).toBe(403)
+ })
+
+ it('with getLanOrigins active, the exact resolved LAN origin is accepted', async () => {
+ const waechter = createLocalApiGuard(5273, () => ['http://192.168.1.23:5273'])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'http://192.168.1.23:5273' }, body: '{}',
+ })
+ expect(res.status).toBe(DURCHGEREICHT)
+ })
+
+ it('does NOT widen to a different address on the same LAN — only the exact bound one', async () => {
+ const waechter = createLocalApiGuard(5273, () => ['http://192.168.1.23:5273'])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ // A neighbour box on the same /24, not this server's own address.
+ headers: { ...json, Origin: 'http://192.168.1.99:5273' }, body: '{}',
+ })
+ expect(res.status).toBe(403)
+ })
+
+ it('does NOT widen to the right host on a different port', async () => {
+ const waechter = createLocalApiGuard(5273, () => ['http://192.168.1.23:5273'])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'http://192.168.1.23:9999' }, body: '{}',
+ })
+ expect(res.status).toBe(403)
+ })
+
+ it('the getter is read PER REQUEST, not cached at guard creation (resolvedUrls populates after listen)', async () => {
+ let active = false
+ const waechter = createLocalApiGuard(5273, () => (active ? ['http://192.168.1.23:5273'] : []))
+ const before = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'http://192.168.1.23:5273' }, body: '{}',
+ })
+ expect(before.status).toBe(403)
+ active = true
+ const after = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'http://192.168.1.23:5273' }, body: '{}',
+ })
+ expect(after.status).toBe(DURCHGEREICHT)
+ })
+
+ it('the DNS-rebinding protection is untouched: Host header still cannot authorise a request', async () => {
+ // Same probe as waechter-und-port.test.ts, run again WITH a LAN getter
+ // active, to prove the widening did not also open this hole.
+ const waechter = createLocalApiGuard(5273, () => ['http://192.168.1.23:5273'])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/shell-execute',
+ headers: { ...json, Origin: 'http://boese.example', Host: 'boese.example' },
+ body: '{}',
+ })
+ expect(res.status).toBe(403)
+ })
+
+ it('the rejection names the server\'s own LAN origin so the diagnosis stays honest', async () => {
+ const waechter = createLocalApiGuard(5273, () => ['http://192.168.1.23:5273'])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'https://boese.example' }, body: '{}',
+ })
+ expect(res.status).toBe(403)
+ expect(res.text).toContain('192.168.1.23:5273')
+ })
+
+ it('still nothing to say when no LAN origin is active (message unchanged from before K8)', async () => {
+ const waechter = createLocalApiGuard(5273, () => [])
+ const res = await anfrage(waechter, {
+ method: 'POST', url: '/onboarding-write',
+ headers: { ...json, Origin: 'https://boese.example' }, body: '{}',
+ })
+ expect(res.status).toBe(403)
+ expect(res.text).not.toContain('LAN')
+ })
+})
+
+describe('K8 — dev-server/index.ts derives LAN origins only from --host, never from a request', () => {
+ it('lanOrigins() logic: --host inactive → empty regardless of resolvedUrls', async () => {
+ // Mirrors the closure built in dev-server/index.ts's configureServer —
+ // kept here as an executable spec of that logic's contract, since the
+ // real closure needs a live ViteDevServer to construct.
+ const lanOrigins = (server: { config: { server: { host?: string | boolean } }; resolvedUrls: { network: string[] } | null }): string[] => {
+ if (!server.config.server.host) return []
+ return (server.resolvedUrls?.network ?? [])
+ .map((u) => { try { return new URL(u).origin } catch { return null } })
+ .filter((o): o is string => !!o)
+ }
+ expect(lanOrigins({ config: { server: {} }, resolvedUrls: { network: ['http://192.168.1.23:5273/'] } })).toEqual([])
+ })
+
+ it('lanOrigins() logic: --host active + resolved → the exact origin(s), trailing slash stripped', async () => {
+ const lanOrigins = (server: { config: { server: { host?: string | boolean } }; resolvedUrls: { network: string[] } | null }): string[] => {
+ if (!server.config.server.host) return []
+ return (server.resolvedUrls?.network ?? [])
+ .map((u) => { try { return new URL(u).origin } catch { return null } })
+ .filter((o): o is string => !!o)
+ }
+ expect(lanOrigins({ config: { server: { host: true } }, resolvedUrls: { network: ['http://192.168.1.23:5273/'] } }))
+ .toEqual(['http://192.168.1.23:5273'])
+ })
+
+ it('lanOrigins() logic: --host active but not yet resolved (pre-listen) → empty, not a crash', async () => {
+ const lanOrigins = (server: { config: { server: { host?: string | boolean } }; resolvedUrls: { network: string[] } | null }): string[] => {
+ if (!server.config.server.host) return []
+ return (server.resolvedUrls?.network ?? [])
+ .map((u) => { try { return new URL(u).origin } catch { return null } })
+ .filter((o): o is string => !!o)
+ }
+ expect(lanOrigins({ config: { server: { host: true } }, resolvedUrls: null })).toEqual([])
+ })
+})
diff --git a/dev-server/comfy.ts b/dev-server/comfy.ts
index 4ea1830a..2cbea477 100644
--- a/dev-server/comfy.ts
+++ b/dev-server/comfy.ts
@@ -72,6 +72,23 @@ export function isComfyRunning(): Promise<boolean> {
.catch(() => false)
}
+/**
+ * K8 (GH #134, eloieloie): dev-mode proxy for the Rust side's
+ * `is_comfyui_install_complete` (process.rs) — same QUESTION ("can this
+ * install actually run, or is it a half-cloned carcass"), a simpler answer.
+ * The real check walks candidate python prefixes looking for an installed
+ * torch; that is desktop/Tauri-only logic this dev server has no reason to
+ * duplicate. A running ComfyUI is definitionally complete, and short of
+ * that, an already-built venv/.venv next to main.py is the same signal the
+ * dev launcher itself already keys off of (see getComfyPython above) — good
+ * enough for onboarding's dev-mode auto-detect not to get stuck on "Install
+ * ComfyUI" when ComfyUI is right there and already running (the actual bug).
+ */
+function isComfyInstallComplete(comfyPath: string, running: boolean): boolean {
+ if (running) return true
+ return ['venv', '.venv'].some((v) => existsSync(join(comfyPath, v)))
+}
+
/**
* Der ComfyUI-Kindprozess und alles, was ihn anfasst.
*
@@ -220,6 +237,45 @@ export function registerComfyControlRoutes(routes: RouteMount, comfy: ComfyLaunc
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'stopped' }))
})
+
+ // K8 (GH #134): `find_comfyui` is mapped in endpointMap (src/api/backend.ts)
+ // but had NO route here at all — onboarding's ComfyStep.tsx auto-detect
+ // 404'd on both this AND its primary `detect_all_comfyui_installs` call
+ // (also added below), fell through its own catch-all, and got stuck
+ // showing "Install ComfyUI" even with ComfyUI already running on :8188.
+ // Independent of LAN/--host — this was broken under plain `npm run dev`.
+ routes.use('/local-api/find-comfyui', async (_req, res) => {
+ const comfyPath = findComfyUI()
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ if (!comfyPath) {
+ res.end(JSON.stringify({ found: false, path: null, complete: false }))
+ return
+ }
+ let running = false
+ try { running = await isComfyRunning() } catch { /* ignore */ }
+ res.end(JSON.stringify({ found: true, path: comfyPath, complete: isComfyInstallComplete(comfyPath, running) }))
+ })
+
+ // K8: the primary auto-detect path ComfyStep.tsx tries first. The dev
+ // server can only ever scan up to ONE install (findComfyUI has no
+ // multi-install enumeration, unlike the Rust scan it mirrors), so this
+ // answers with 0 or 1 entries — the same shape the picker UI already
+ // handles as "no disambiguation needed", not a lie about capability.
+ routes.use('/local-api/detect-all-comfyui-installs', async (_req, res) => {
+ const comfyPath = findComfyUI()
+ let running = false
+ try { running = await isComfyRunning() } catch { /* ignore */ }
+ const installs = comfyPath
+ ? [{
+ path: comfyPath,
+ complete: isComfyInstallComplete(comfyPath, running),
+ has_embedded_python: existsSync(join(comfyPath, 'python_embeded')),
+ source: 'scan',
+ }]
+ : []
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(installs))
+ })
}
/** Installation, Pfadwahl und Status — alles, was eine ComfyUI erst herstellt. */
diff --git a/dev-server/guard.ts b/dev-server/guard.ts
index fa8a7120..724ef4ce 100644
--- a/dev-server/guard.ts
+++ b/dev-server/guard.ts
@@ -17,7 +17,27 @@ import { postContentTypeAllowed, postContentTypeError } from '../src/lib/local-a
* Grund, aus dem er eingeführt wurde: ein fest verdrahteter Port lässt sich
* kein zweites Mal starten (`LU_DEV_PORT`, siehe vite.config.ts).
*/
-export function createLocalApiGuard(port: number): Connect.NextHandleFunction {
+/**
+ * K8 (GH #134, eloieloie, `npm run dev --host`): a deliberate LAN-exposed dev
+ * server rejected its OWN onboarding write requests with "403 Forbidden:
+ * Invalid Origin (CSRF Protection)" — the page loaded from the machine's LAN
+ * IP (e.g. `http://192.168.1.23:5273`), which is neither `tauri://localhost`
+ * nor the loopback regex below, so every request from it hit the same wall
+ * as a real cross-origin attacker.
+ *
+ * `getLanOrigins`, when given, is called PER REQUEST (not once at guard
+ * creation) and must return only origins the SERVER itself resolved it is
+ * bound to (see dev-server/index.ts — Vite's own `resolvedUrls.network`,
+ * read after listen()), never anything derived from a request header. That
+ * is the whole DNS-rebinding lesson above, applied here too: `--host` widens
+ * what the guard accepts, but the widening still comes from the server's own
+ * configuration, not from what a caller claims. Omitted (or empty) when
+ * `--host` was not passed — the default stays loopback-and-Tauri-only.
+ */
+export function createLocalApiGuard(
+ port: number,
+ getLanOrigins?: () => string[],
+): Connect.NextHandleFunction {
// Vites eigener Middleware-Typ statt einer geratenen Signatur: `next`
// ist hier Pflicht, weil dieser Wächter durchreicht statt zu antworten.
return (req, res, next) => {
@@ -85,11 +105,17 @@ export function createLocalApiGuard(port: number): Connect.NextHandleFunction {
// der Ablehnung: „Invalid Origin" allein sagt nicht, was erwartet war.
const allowedOrigins = ['tauri://localhost', 'http://tauri.localhost'];
const isLoopback = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin);
- if (!allowedOrigins.includes(origin) && !isLoopback) {
+ // K8: the server's own LAN origin(s) — see the doc comment on
+ // getLanOrigins above. Read fresh on every request; [] when --host
+ // is not active, so a plain `npm run dev` behaves exactly as before.
+ const lanOrigins = getLanOrigins ? getLanOrigins() : [];
+ const isOwnLan = lanOrigins.includes(origin);
+ if (!allowedOrigins.includes(origin) && !isLoopback && !isOwnLan) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
+ const lanNote = lanOrigins.length > 0 ? `, and this server's own LAN origin (${lanOrigins.join(', ')})` : '';
res.end(
'Forbidden: Invalid Origin (CSRF Protection). Allowed: '
- + `${allowedOrigins.join(', ')}, and loopback on ANY port (this server: http://localhost:${port}).`,
+ + `${allowedOrigins.join(', ')}, and loopback on ANY port (this server: http://localhost:${port})${lanNote}.`,
);
return;
}
diff --git a/dev-server/index.ts b/dev-server/index.ts
index 2e3ff023..4513dba0 100644
--- a/dev-server/index.ts
+++ b/dev-server/index.ts
@@ -50,7 +50,18 @@ export function devServerPlugin({ port }: DevServerOptions): Plugin {
use: (path, handler) => { server.middlewares.use(path, handler) },
}
- routes.use('/local-api', createLocalApiGuard(port))
+ // K8 (GH #134): only when `--host` was actually passed does Vite set
+ // `server.config.server.host` — a plain `npm run dev` binds loopback
+ // only and this returns []. `resolvedUrls` populates after listen(),
+ // so this must be read lazily (per request, inside the guard), never
+ // computed once here — see the doc comment on getLanOrigins in guard.ts.
+ const lanOrigins = (): string[] => {
+ if (!server.config.server.host) return []
+ return (server.resolvedUrls?.network ?? [])
+ .map((u) => { try { return new URL(u).origin } catch { return null } })
+ .filter((o): o is string => !!o)
+ }
+ routes.use('/local-api', createLocalApiGuard(port, lanOrigins))
autostartOllama()
autostartComfy(comfy)
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 6ca5a8a8..08d92026 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -457,6 +457,10 @@ export async function backendCall<T = unknown>(
comfyui_status: { path: "/local-api/comfyui-status" },
comfyui_last_output: { path: "/local-api/comfyui-last-output" },
find_comfyui: { path: "/local-api/find-comfyui" },
+ // K8 (GH #134): the primary auto-detect ComfyStep.tsx calls before
+ // falling back to find_comfyui above — see dev-server/comfy.ts for why
+ // both were needed, not just one.
+ detect_all_comfyui_installs: { path: "/local-api/detect-all-comfyui-installs" },
set_comfyui_path: { path: "/local-api/set-comfyui-path", method: "POST" },
install_comfyui: { path: "/local-api/install-comfyui", method: "POST" },
install_comfyui_status: { path: "/local-api/install-comfyui" },