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): the byte read has a way through the browser, with the same jail

David435893c89dc6
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 98a74979..2fbbc92c 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -478,6 +478,10 @@ export async function backendCall<T = any>(
// Agent tools (Phase 1 — new commands)
shell_execute: { path: "/local-api/shell-execute", method: "POST" },
fs_read: { path: "/local-api/fs-read", method: "POST" },
+ // Capped, jailed byte read for the Explorer image preview (2.6.6 C3).
+ // Without this entry the browser dev surface answered "Unknown backend
+ // command" and every preview fell over.
+ fs_read_bytes: { path: "/local-api/fs-read-bytes", method: "POST" },
fs_write: { path: "/local-api/fs-write", method: "POST" },
fs_list: { path: "/local-api/fs-list", method: "POST" },
fs_search: { path: "/local-api/fs-search", method: "POST" },
diff --git a/src/lib/__tests__/dev-fs-jail.test.ts b/src/lib/__tests__/dev-fs-jail.test.ts
new file mode 100644
index 00000000..c07637c8
--- /dev/null
+++ b/src/lib/__tests__/dev-fs-jail.test.ts
@@ -0,0 +1,152 @@
+/**
+ * The dev server's byte-read door has the SAME jail and the SAME cap as the
+ * Rust command it stands in for.
+ *
+ * `fs_read_bytes` (src-tauri/src/commands/filesystem.rs) resolves through
+ * resolve_path -> contain_within and refuses anything over 16 MiB. In the
+ * browser dev surface there is no Rust, so vite.config.ts's
+ * /local-api/fs-read-bytes middleware carries the boundary — these tests pin
+ * the pure half of that middleware, case by case against the Rust unit tests
+ * next to `fs_read_bytes`.
+ *
+ * NEGATIVE CONTROL (verified by hand): make containWithin return the candidate
+ * unconditionally and every escape case below goes red; drop the `Math.min` in
+ * effectiveByteCap and "a caller cannot raise the ceiling" goes red.
+ *
+ * Run: npx vitest run src/lib/__tests__/dev-fs-jail.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ devResolveWithinJail,
+ devWorkspaceRoot,
+ containWithin,
+ lexicalNormalize,
+ isAbsolutePath,
+ normalizeDuplicateDrivePrefix,
+ effectiveByteCap,
+ DEV_READ_BYTES_CAP,
+ JailEscapeError,
+} from '../dev-fs-jail'
+
+const HOME = '/Users/dev'
+const ROOT = '/Users/dev/projects/lu'
+
+describe('devWorkspaceRoot', () => {
+ it('prefers the picked folder workspace', () => {
+ expect(devWorkspaceRoot(HOME, 'chat-1', ROOT)).toBe(ROOT)
+ })
+
+ it('falls back to the per-chat sandbox', () => {
+ expect(devWorkspaceRoot(HOME, 'chat-1', '')).toBe('/Users/dev/agent-workspace/chat-1')
+ expect(devWorkspaceRoot(HOME, null, null)).toBe('/Users/dev/agent-workspace/default')
+ })
+
+ it('sanitises the chat id the way the Rust side does', () => {
+ expect(devWorkspaceRoot(HOME, '../../etc', null)).toBe('/Users/dev/agent-workspace/.._.._etc')
+ expect(devWorkspaceRoot(HOME, 'a/b c', null)).toBe('/Users/dev/agent-workspace/a_b_c')
+ })
+
+ it('caps the chat id at 64 chars', () => {
+ const long = 'a'.repeat(200)
+ expect(devWorkspaceRoot(HOME, long, null)).toBe(`/Users/dev/agent-workspace/${'a'.repeat(64)}`)
+ })
+})
+
+describe('the jail', () => {
+ it('resolves a relative path inside the root', () => {
+ expect(devResolveWithinJail({ path: 'src/app.ts', homeDir: HOME, workingDirectory: ROOT })).toBe(
+ `${ROOT}/src/app.ts`,
+ )
+ })
+
+ it('accepts an absolute path that already sits inside the root', () => {
+ expect(
+ devResolveWithinJail({ path: `${ROOT}/assets/logo.png`, homeDir: HOME, workingDirectory: ROOT }),
+ ).toBe(`${ROOT}/assets/logo.png`)
+ })
+
+ it('refuses a climb out of the root', () => {
+ expect(() =>
+ devResolveWithinJail({ path: '../../.ssh/id_rsa', homeDir: HOME, workingDirectory: ROOT }),
+ ).toThrow(JailEscapeError)
+ })
+
+ it('refuses an absolute path outside the root', () => {
+ expect(() =>
+ devResolveWithinJail({ path: '/etc/passwd', homeDir: HOME, workingDirectory: ROOT }),
+ ).toThrow(JailEscapeError)
+ expect(() =>
+ devResolveWithinJail({ path: '/Users/dev/.ssh/id_rsa', homeDir: HOME, workingDirectory: ROOT }),
+ ).toThrow(JailEscapeError)
+ })
+
+ it('refuses a sibling folder that merely shares the root prefix', () => {
+ expect(() => containWithin('/w/root', '/w/rootless/secret')).toThrow(JailEscapeError)
+ })
+
+ it('jails the per-chat sandbox too, not just a picked folder', () => {
+ expect(devResolveWithinJail({ path: 'note.txt', homeDir: HOME, chatId: 'c1' })).toBe(
+ '/Users/dev/agent-workspace/c1/note.txt',
+ )
+ expect(() =>
+ devResolveWithinJail({ path: '../c2/note.txt', homeDir: HOME, chatId: 'c1' }),
+ ).toThrow(JailEscapeError)
+ })
+
+ it('lets the root itself through', () => {
+ expect(containWithin(ROOT, '.')).toBe(ROOT)
+ })
+
+ it('handles a backslash climb (the dev server also runs on Windows)', () => {
+ expect(() => containWithin('C:/work/lu', '..\\..\\Windows\\System32\\config')).toThrow(
+ JailEscapeError,
+ )
+ expect(containWithin('C:/work/lu', 'src\\main.ts')).toBe('C:/work/lu/src/main.ts')
+ })
+
+ it('compares Windows roots case-insensitively', () => {
+ expect(containWithin('C:/Work/LU', 'c:/work/lu/src/a.ts')).toBe('c:/work/lu/src/a.ts')
+ })
+
+ it('strips a duplicated drive prefix before judging', () => {
+ expect(normalizeDuplicateDrivePrefix('D:/a/D:/a/file.txt')).toBe('D:/a/file.txt')
+ expect(containWithin('D:/a', 'D:/a/D:/a/file.txt')).toBe('D:/a/file.txt')
+ })
+})
+
+describe('path primitives', () => {
+ it('normalizes . and .. lexically', () => {
+ expect(lexicalNormalize('/a/b/../c/./d')).toBe('/a/c/d')
+ expect(lexicalNormalize('a/../../b')).toBe('b')
+ expect(lexicalNormalize('C:\\a\\b\\..\\c')).toBe('C:/a/c')
+ })
+
+ it('knows an absolute path on both platforms', () => {
+ expect(isAbsolutePath('/etc')).toBe(true)
+ expect(isAbsolutePath('C:\\Windows')).toBe(true)
+ expect(isAbsolutePath('c:/windows')).toBe(true)
+ expect(isAbsolutePath('\\\\server\\share')).toBe(true)
+ expect(isAbsolutePath('src/app.ts')).toBe(false)
+ expect(isAbsolutePath('')).toBe(false)
+ })
+})
+
+describe('the byte cap', () => {
+ it('matches READ_BYTES_CAP in filesystem.rs', () => {
+ expect(DEV_READ_BYTES_CAP).toBe(16 * 1024 * 1024)
+ })
+
+ it('defaults to the ceiling', () => {
+ expect(effectiveByteCap(undefined)).toBe(DEV_READ_BYTES_CAP)
+ expect(effectiveByteCap(null)).toBe(DEV_READ_BYTES_CAP)
+ expect(effectiveByteCap(0)).toBe(DEV_READ_BYTES_CAP)
+ })
+
+ it('honours a SMALLER request', () => {
+ expect(effectiveByteCap(1024)).toBe(1024)
+ })
+
+ it('a caller cannot raise the ceiling', () => {
+ expect(effectiveByteCap(1024 * 1024 * 1024)).toBe(DEV_READ_BYTES_CAP)
+ })
+})
diff --git a/src/lib/dev-fs-jail.ts b/src/lib/dev-fs-jail.ts
new file mode 100644
index 00000000..55b9211f
--- /dev/null
+++ b/src/lib/dev-fs-jail.ts
@@ -0,0 +1,151 @@
+/**
+ * Path jail for the DEV SERVER's file endpoints (vite.config.ts middlewares).
+ *
+ * The packaged app routes every file op through Rust, where
+ * `commands/filesystem.rs` resolves a path against the workspace root and then
+ * `contain_within` refuses anything that escapes it. `npm run dev` in a browser
+ * has no Rust, so each `/local-api/fs-*` middleware is on its own. This module
+ * is the port of that boundary: same root rule (a configured workingDirectory
+ * wins, otherwise `~/agent-workspace/<chatId>`), same containment rule
+ * (relative paths resolve inside the root, absolute paths are accepted only
+ * when they already fall inside it), same lexical `..` normalization so a path
+ * that does not exist yet can still be judged.
+ *
+ * PURE STRINGS ON PURPOSE: no `node:path`, no `node:fs`. The app tsconfig
+ * carries no node types, and a helper that needs them could not live in `src`
+ * next to its test. Both separators are handled because the dev server also
+ * runs on Windows.
+ */
+
+/** Read cap for one dev byte-read, mirroring READ_BYTES_CAP in filesystem.rs. */
+export const DEV_READ_BYTES_CAP = 16 * 1024 * 1024
+
+/**
+ * Strip duplicate drive-letter prefixes (`D:/a/D:/a/f.txt` → `D:/a/f.txt`),
+ * the port of `normalize_duplicate_drive_prefix`. Windows-only in practice;
+ * a posix path has no `X:` sequence to find.
+ */
+export function normalizeDuplicateDrivePrefix(path: string): string {
+ if (path.length < 3) return path
+ let lastDrive = -1
+ for (let i = 1; i + 1 < path.length; i++) {
+ const prev = path[i - 1]
+ const next = path[i + 1]
+ if (path[i] === ':' && /[a-z]/i.test(prev) && (next === '/' || next === '\\')) {
+ lastDrive = i - 1
+ }
+ }
+ return lastDrive > 0 ? path.slice(lastDrive) : path
+}
+
+/** True for `/x`, `C:/x`, `C:\x` and UNC `\\server\share`. */
+export function isAbsolutePath(path: string): boolean {
+ if (!path) return false
+ if (path[0] === '/' || path[0] === '\\') return true
+ return /^[a-z]:[/\\]/i.test(path)
+}
+
+/**
+ * Lexically resolve `.` and `..` without touching the filesystem, returning a
+ * forward-slash path. Port of `lexical_normalize`: `..` pops, `.` drops, and a
+ * `..` that would climb past the root is simply absorbed (matching
+ * `PathBuf::pop` on an empty tail), which is what makes the containment check
+ * below the real boundary rather than the normalizer.
+ */
+export function lexicalNormalize(path: string): string {
+ const unified = path.replace(/\\/g, '/')
+ const uncPrefix = unified.startsWith('//') ? '//' : ''
+ const driveMatch = /^([a-z]:)\//i.exec(unified)
+ const drive = driveMatch ? driveMatch[1] : ''
+ const rooted = !uncPrefix && !drive && unified.startsWith('/')
+
+ const body = unified.slice(uncPrefix.length + drive.length)
+ const out: string[] = []
+ for (const seg of body.split('/')) {
+ if (seg === '' || seg === '.') continue
+ if (seg === '..') {
+ out.pop()
+ continue
+ }
+ out.push(seg)
+ }
+ const joined = out.join('/')
+ if (uncPrefix) return `//${joined}`
+ if (drive) return `${drive}/${joined}`
+ return rooted ? `/${joined}` : joined
+}
+
+/** Case-insensitive comparison on Windows-shaped paths, exact elsewhere. */
+function compareKey(normalized: string): string {
+ const trimmed = normalized.replace(/\/+$/, '')
+ return /^[a-z]:/i.test(trimmed) || trimmed.startsWith('//')
+ ? trimmed.toLowerCase()
+ : trimmed
+}
+
+/**
+ * The jail root for a dev file op — port of `workspace_root`. A non-empty
+ * `workingDirectory` (the folder the user picked) wins; otherwise the per-chat
+ * sandbox `<homeDir>/agent-workspace/<chatId>`, with the id sanitised to
+ * `[A-Za-z0-9_.-]` and capped at 64 chars exactly like the Rust side.
+ */
+export function devWorkspaceRoot(
+ homeDir: string,
+ chatId?: string | null,
+ workingDirectory?: string | null,
+): string {
+ const wd = (workingDirectory ?? '').trim()
+ if (wd) return lexicalNormalize(wd)
+ const id = chatId || 'default'
+ const safe = id
+ .slice(0, 64)
+ .replace(/[^A-Za-z0-9_.-]/g, '_')
+ return lexicalNormalize(`${homeDir}/agent-workspace/${safe || 'default'}`)
+}
+
+/** Thrown for any path that leaves the workspace root. */
+export class JailEscapeError extends Error {}
+
+/**
+ * Resolve `path` inside `root` or throw. Relative paths resolve against the
+ * root; absolute paths are allowed ONLY when they already sit inside it, so
+ * the desktop habit of passing absolute paths within the picked project folder
+ * keeps working while `../../.ssh/id_rsa` does not.
+ */
+export function containWithin(root: string, path: string): string {
+ const cleaned = normalizeDuplicateDrivePrefix(path)
+ const nroot = lexicalNormalize(root)
+ const candidate = isAbsolutePath(cleaned)
+ ? lexicalNormalize(cleaned)
+ : lexicalNormalize(`${nroot}/${cleaned}`)
+
+ const r = compareKey(nroot)
+ const c = compareKey(candidate)
+ if (c === r || c.startsWith(`${r}/`)) return candidate
+
+ throw new JailEscapeError(
+ `Path escapes the allowed workspace.\n workspace root: ${root}\n requested path: ${path}`,
+ )
+}
+
+/** One call: root from the request, then containment. Throws on escape. */
+export function devResolveWithinJail(args: {
+ path: string
+ homeDir: string
+ chatId?: string | null
+ workingDirectory?: string | null
+}): string {
+ const root = devWorkspaceRoot(args.homeDir, args.chatId, args.workingDirectory)
+ return containWithin(root, args.path)
+}
+
+/**
+ * The effective byte cap for one read: the caller may ask for LESS than the
+ * ceiling, never more. Same `min` the Rust command applies.
+ */
+export function effectiveByteCap(requested?: number | null): number {
+ if (typeof requested !== 'number' || !Number.isFinite(requested) || requested <= 0) {
+ return DEV_READ_BYTES_CAP
+ }
+ return Math.min(requested, DEV_READ_BYTES_CAP)
+}
diff --git a/vite.config.ts b/vite.config.ts
index d46c476c..bbada347 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -12,6 +12,7 @@ import { dirname } from 'path'
import os from 'os'
import dns from 'node:dns'
import net from 'node:net'
+import { devResolveWithinJail, effectiveByteCap, JailEscapeError } from './src/lib/dev-fs-jail'
// ── Dev-server SSRF guard ───────────────────────────────────────
// The dev proxies that fetch a *user-supplied* ?url= (proxy-image,
@@ -1514,6 +1515,53 @@ function comfyLauncher(): Plugin {
})
})
+ // API: FS read bytes — base64 payload of ONE file for the Explorer image
+ // preview (2.6.6 C3). Parity port of the `fs_read_bytes` Tauri command:
+ // SAME jail (workspace root, then containment — see lib/dev-fs-jail) and
+ // the SAME 16 MiB ceiling, because a preview is a picture on a 280px
+ // panel, not a payload. Deliberately stricter than the fs-read
+ // middleware above, which predates the jail and stays as it is.
+ server.middlewares.use('/local-api/fs-read-bytes', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ const fail = (status: number, error: string) => {
+ res.writeHead(status, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error }))
+ }
+ try {
+ const { path: filePath, chatId, workingDirectory, maxBytes } = JSON.parse(body)
+ if (typeof filePath !== 'string' || !filePath) {
+ fail(400, 'Missing path')
+ return
+ }
+ const resolved = devResolveWithinJail({
+ path: filePath,
+ homeDir: os.homedir(),
+ chatId,
+ workingDirectory,
+ })
+ const fs = require('fs')
+ if (!existsSync(resolved) || !statSync(resolved).isFile()) {
+ fail(400, `File not found: ${resolved}`)
+ return
+ }
+ const cap = effectiveByteCap(maxBytes)
+ const size = statSync(resolved).size
+ if (size > cap) {
+ fail(400, `File is too large to preview: ${size} bytes (limit ${cap})`)
+ return
+ }
+ const buf = fs.readFileSync(resolved)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ base64: buf.toString('base64'), bytes: buf.length }))
+ } catch (err) {
+ fail(err instanceof JailEscapeError ? 403 : 400, String(err instanceof Error ? err.message : err))
+ }
+ })
+ })
+
// API: FS write (unsandboxed)
server.middlewares.use('/local-api/fs-write', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }