Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(desktop): restrict local file previews (#14789)

Innei1914ae6d4357
diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.ts
index 4978684cc5f..292e265e431 100644
--- a/apps/desktop/src/main/const/store.ts
+++ b/apps/desktop/src/main/const/store.ts
@@ -35,6 +35,7 @@ export const STORE_DEFAULTS: ElectronMainStore = {
gatewayEnabled: true,
gatewayUrl: 'https://device-gateway.lobehub.com',
locale: 'auto',
+ localFileWorkspaceRoots: [],
networkProxy: defaultProxySettings,
shortcuts: DEFAULT_ELECTRON_DESKTOP_SHORTCUTS,
storagePath: appStorageDir,
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 167927c16d3..7d59c4db092 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -12,6 +12,8 @@ import {
type GrepContentParams,
type GrepContentResult,
type ListLocalFileParams,
+ type LocalFilePreviewUrlParams,
+ type LocalFilePreviewUrlResult,
type LocalMoveFilesResultItem,
type LocalReadFileParams,
type LocalReadFileResult,
@@ -370,6 +372,28 @@ export default class LocalFileCtr extends ControllerModule {
};
}
+ @IpcMethod()
+ async getLocalFilePreviewUrl({
+ path: filePath,
+ workingDirectory,
+ }: LocalFilePreviewUrlParams): Promise<LocalFilePreviewUrlResult> {
+ try {
+ const url = await this.app.localFileProtocolManager.createPreviewUrl({
+ filePath,
+ workspaceRoot: workingDirectory,
+ });
+
+ if (!url) {
+ return { error: 'File is outside the approved workspace', success: false };
+ }
+
+ return { success: true, url };
+ } catch (error) {
+ logger.error('Failed to create local file preview URL:', error);
+ return { error: (error as Error).message, success: false };
+ }
+ }
+
@IpcMethod()
async handlePrepareSkillDirectory({
forceRefresh,
@@ -532,6 +556,7 @@ export default class LocalFileCtr extends ControllerModule {
requestedScope,
root,
});
+ await this.approveProjectRootForPreview(root);
return {
entries,
@@ -560,6 +585,7 @@ export default class LocalFileCtr extends ControllerModule {
engine: fallback.engine,
requestedScope,
});
+ await this.approveProjectRootForPreview(requestedScope);
return {
entries,
@@ -641,4 +667,12 @@ export default class LocalFileCtr extends ControllerModule {
logger.debug(`Editing file ${params.file_path}`, { replace_all: params.replace_all });
return editLocalFile(params);
}
+
+ private async approveProjectRootForPreview(root: string) {
+ try {
+ await this.app.localFileProtocolManager.approveIndexedProjectRoot(root);
+ } catch (error) {
+ logger.error(`Failed to approve project preview root ${root}:`, error);
+ }
+ }
}
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index a969b57bb20..59fd9a8b7d0 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -186,6 +186,19 @@ export default class SystemController extends ControllerModule {
const folderPath = result.filePaths[0];
const repoType = await detectRepoType(folderPath);
+ try {
+ const approvedRoot = await this.app.localFileProtocolManager.approveWorkspaceRoot(folderPath);
+
+ if (approvedRoot) {
+ const storedRoots = this.app.storeManager.get('localFileWorkspaceRoots', []);
+ if (!storedRoots.includes(approvedRoot)) {
+ this.app.storeManager.set('localFileWorkspaceRoots', [approvedRoot, ...storedRoots]);
+ }
+ }
+ } catch (error) {
+ logger.error(`Failed to approve local file workspace root ${folderPath}:`, error);
+ }
+
return { path: folderPath, repoType };
}
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 5076da17f0c..c18a7fd814b 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -84,6 +84,12 @@ const mockContentSearchService = {
checkToolAvailable: vi.fn(),
};
+const mockLocalFileProtocolManager = {
+ approveIndexedProjectRoot: vi.fn(),
+ approveProjectRootFromScope: vi.fn(),
+ createPreviewUrl: vi.fn(),
+};
+
// Mock makeSureDirExist
vi.mock('@/utils/file-system', () => ({
makeSureDirExist: vi.fn(),
@@ -98,6 +104,7 @@ const mockApp = {
}
return mockSearchService;
}),
+ localFileProtocolManager: mockLocalFileProtocolManager,
toolDetectorManager: {
getBestTool: vi.fn(() => null), // No external tools available, use Node.js fallback
},
@@ -180,6 +187,42 @@ describe('LocalFileCtr', () => {
// they exercise real fs + file-loaders without fighting the heavy mocks
// this suite needs for execa-driven tools, electron, and the like.
+ describe('getLocalFilePreviewUrl', () => {
+ it('should return a main-issued preview URL for an approved workspace file', async () => {
+ mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(
+ 'localfile://file/workspace/app.ts?token=abc',
+ );
+
+ const result = await localFileCtr.getLocalFilePreviewUrl({
+ path: '/workspace/app.ts',
+ workingDirectory: '/workspace',
+ });
+
+ expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({
+ filePath: '/workspace/app.ts',
+ workspaceRoot: '/workspace',
+ });
+ expect(result).toEqual({
+ success: true,
+ url: 'localfile://file/workspace/app.ts?token=abc',
+ });
+ });
+
+ it('should reject preview URL creation outside an approved workspace', async () => {
+ mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(null);
+
+ const result = await localFileCtr.getLocalFilePreviewUrl({
+ path: '/Users/alice/.ssh/id_rsa',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result).toEqual({
+ error: 'File is outside the approved workspace',
+ success: false,
+ });
+ });
+ });
+
describe('handleWriteFile', () => {
it('should write file successfully', async () => {
vi.mocked(mockFsPromises.mkdir).mockResolvedValue(undefined);
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index c12efdac8fa..dcb72c31549 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -105,6 +105,9 @@ export class App {
this.rendererUrlManager = new RendererUrlManager();
this.localFileProtocolManager = new LocalFileProtocolManager();
+ void this.localFileProtocolManager.approveWorkspaceRoots(
+ this.storeManager.get('localFileWorkspaceRoots', []),
+ );
protocol.registerSchemesAsPrivileged([
{
privileges: {
diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.ts
index 3972e01b10d..8e45ac0d167 100644
--- a/apps/desktop/src/main/core/__tests__/App.test.ts
+++ b/apps/desktop/src/main/core/__tests__/App.test.ts
@@ -115,9 +115,9 @@ vi.mock('../infrastructure/I18nManager', () => ({
vi.mock('../infrastructure/StoreManager', () => ({
StoreManager: vi.fn().mockImplementation(() => ({
- get: vi.fn((key) => {
- if (key === 'storagePath') return '/mock/storage/path';
- return undefined;
+ get: vi.fn((_key, defaultValue) => {
+ if (_key === 'storagePath') return '/mock/storage/path';
+ return defaultValue;
}),
set: vi.fn(),
})),
diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
index 8a8c90a0434..93733d59480 100644
--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
@@ -1,4 +1,5 @@
-import { readFile, stat } from 'node:fs/promises';
+import { randomUUID } from 'node:crypto';
+import { readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
import { app, protocol } from 'electron';
@@ -19,6 +20,7 @@ const LOCAL_FILE_PROTOCOL_PRIVILEGES = {
} as const;
const logger = createLogger('core:LocalFileProtocolManager');
+const PREVIEW_TOKEN_TTL_MS = 5 * 60 * 1000;
const EXTRA_MIME_TYPES: Record<string, string> = {
'.avif': 'image/avif',
@@ -34,21 +36,53 @@ const getMimeType = (filePath: string): string => {
return getExportMimeType(filePath) ?? EXTRA_MIME_TYPES[ext] ?? 'application/octet-stream';
};
+const normalizeAbsolutePath = (filePath: string): string | null => {
+ const normalized = path.normalize(filePath);
+ return path.isAbsolute(normalized) ? normalized : null;
+};
+
+const isPathWithinRoot = (targetPath: string, rootPath: string): boolean => {
+ const relative = path.relative(rootPath, targetPath);
+ return (
+ relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative))
+ );
+};
+
+const buildLocalFileUrl = (absolutePath: string, token: string): string => {
+ const forwardSlashed = absolutePath.replaceAll('\\', '/');
+ const stripped = forwardSlashed.startsWith('/') ? forwardSlashed.slice(1) : forwardSlashed;
+ const encoded = stripped.split('/').map(encodeURIComponent).join('/');
+ const url = new URL(`${LOCAL_FILE_PROTOCOL_SCHEME}://${LOCAL_FILE_PROTOCOL_HOST}/${encoded}`);
+ url.searchParams.set('token', token);
+ return url.toString();
+};
+
+interface PreviewTokenRecord {
+ expiresAt: number;
+ realPath: string;
+}
+
/**
- * Custom `localfile://` protocol that serves arbitrary local files to the
- * Electron renderer (e.g. previews for the project Files tree).
+ * Custom `localfile://` protocol for project file previews.
*
- * URL shape: `localfile://file/<percent-encoded-absolute-path>`
+ * URL shape: `localfile://file/<percent-encoded-absolute-path>?token=<main-issued-token>`
* - host is fixed to `file` so the scheme behaves as `standard`
* - the absolute path is encoded in the URL pathname
+ * - every request must carry a short-lived token minted by the main process
*
* Examples:
- * localfile://file//Users/alice/Pictures/cat.png
- * localfile://file/C:/Users/alice/Pictures/cat.png
+ * localfile://file//Users/alice/project/cat.png?token=...
+ * localfile://file/C:/Users/alice/project/cat.png?token=...
*/
export class LocalFileProtocolManager {
+ private readonly approvedWorkspaceRoots = new Set<string>();
+
+ private readonly indexedProjectRoots = new Set<string>();
+
private handlerRegistered = false;
+ private readonly previewTokens = new Map<string, PreviewTokenRecord>();
+
get protocolScheme() {
return {
privileges: LOCAL_FILE_PROTOCOL_PRIVILEGES,
@@ -75,14 +109,28 @@ export class LocalFileProtocolManager {
return new Response('Invalid path', { status: 400 });
}
- const fileStat = await stat(resolvedPath);
+ const token = url.searchParams.get('token');
+ if (!token) {
+ return new Response('Forbidden', { status: 403 });
+ }
+
+ if (!this.hasPreviewToken(token)) {
+ return new Response('Forbidden', { status: 403 });
+ }
+
+ const realResolvedPath = normalizeAbsolutePath(await realpath(resolvedPath));
+ if (!realResolvedPath || !this.verifyPreviewToken(token, realResolvedPath)) {
+ return new Response('Forbidden', { status: 403 });
+ }
+
+ const fileStat = await stat(realResolvedPath);
if (!fileStat.isFile()) {
return new Response('Not a file', { status: 404 });
}
- const buffer = await readFile(resolvedPath);
+ const buffer = await readFile(realResolvedPath);
const headers = new Headers();
- headers.set('Content-Type', getMimeType(resolvedPath));
+ headers.set('Content-Type', getMimeType(realResolvedPath));
headers.set('Content-Length', String(buffer.byteLength));
// Local files are immutable from the renderer's perspective for a
// single preview session; allow short-lived caching to avoid
@@ -114,6 +162,102 @@ export class LocalFileProtocolManager {
}
}
+ async approveWorkspaceRoot(rootPath: string): Promise<string | null> {
+ const normalizedRoot = normalizeAbsolutePath(rootPath);
+ if (!normalizedRoot) return null;
+
+ const realRoot = normalizeAbsolutePath(await realpath(normalizedRoot));
+ if (!realRoot) return null;
+
+ this.approvedWorkspaceRoots.add(realRoot);
+ return realRoot;
+ }
+
+ async approveWorkspaceRoots(rootPaths: string[] = []): Promise<string[]> {
+ const approvedRoots = await Promise.allSettled(
+ rootPaths.map((rootPath) => this.approveWorkspaceRoot(rootPath)),
+ );
+
+ return approvedRoots
+ .map((result) => (result.status === 'fulfilled' ? result.value : null))
+ .filter((rootPath): rootPath is string => !!rootPath);
+ }
+
+ async approveProjectRootFromScope({
+ projectRoot,
+ requestedScope,
+ }: {
+ projectRoot: string;
+ requestedScope: string;
+ }): Promise<string | null> {
+ const [realProjectRoot, realRequestedScope] = await Promise.all([
+ realpath(projectRoot),
+ realpath(requestedScope),
+ ]);
+ const normalizedProjectRoot = normalizeAbsolutePath(realProjectRoot);
+ const normalizedRequestedScope = normalizeAbsolutePath(realRequestedScope);
+ if (!normalizedProjectRoot || !normalizedRequestedScope) return null;
+
+ const scopeIsApproved = [...this.approvedWorkspaceRoots].some(
+ (approvedRoot) =>
+ normalizedRequestedScope === approvedRoot ||
+ isPathWithinRoot(normalizedRequestedScope, approvedRoot),
+ );
+ if (!scopeIsApproved) return null;
+
+ this.approvedWorkspaceRoots.add(normalizedProjectRoot);
+ return normalizedProjectRoot;
+ }
+
+ async approveIndexedProjectRoot(projectRoot: string): Promise<string | null> {
+ const normalizedProjectRoot = normalizeAbsolutePath(projectRoot);
+ if (!normalizedProjectRoot) return null;
+
+ const realProjectRoot = normalizeAbsolutePath(await realpath(normalizedProjectRoot));
+ if (!realProjectRoot) return null;
+
+ this.indexedProjectRoots.add(realProjectRoot);
+ return realProjectRoot;
+ }
+
+ async createPreviewUrl({
+ filePath,
+ workspaceRoot,
+ }: {
+ filePath: string;
+ workspaceRoot: string;
+ }): Promise<string | null> {
+ const normalizedFilePath = normalizeAbsolutePath(filePath);
+ const normalizedWorkspaceRoot = normalizeAbsolutePath(workspaceRoot);
+ if (!normalizedFilePath || !normalizedWorkspaceRoot) return null;
+
+ const [realFilePath, realWorkspaceRoot] = await Promise.all([
+ realpath(normalizedFilePath),
+ realpath(normalizedWorkspaceRoot),
+ ]);
+ const normalizedRealFilePath = normalizeAbsolutePath(realFilePath);
+ const normalizedRealWorkspaceRoot = normalizeAbsolutePath(realWorkspaceRoot);
+
+ if (!normalizedRealFilePath || !normalizedRealWorkspaceRoot) return null;
+ if (
+ !this.approvedWorkspaceRoots.has(normalizedRealWorkspaceRoot) &&
+ !this.indexedProjectRoots.has(normalizedRealWorkspaceRoot)
+ ) {
+ return null;
+ }
+ if (!isPathWithinRoot(normalizedRealFilePath, normalizedRealWorkspaceRoot)) return null;
+
+ this.cleanupExpiredTokens();
+
+ const token = randomUUID();
+ this.previewTokens.set(token, {
+ expiresAt: Date.now() + PREVIEW_TOKEN_TTL_MS,
+ realPath: normalizedRealFilePath,
+ });
+
+ return buildLocalFileUrl(normalizedFilePath, token);
+ }
+
/**
* Decode the URL pathname back into an absolute filesystem path.
*
@@ -152,4 +296,32 @@ export class LocalFileProtocolManager {
return normalized;
}
+
+ private cleanupExpiredTokens() {
+ const now = Date.now();
+ for (const [token, record] of this.previewTokens) {
+ if (record.expiresAt <= now) {
+ this.previewTokens.delete(token);
+ }
+ }
+ }
+
+ private hasPreviewToken(token: string): boolean {
+ const record = this.previewTokens.get(token);
+ if (!record) return false;
+
+ if (record.expiresAt <= Date.now()) {
+ this.previewTokens.delete(token);
+ return false;
+ }
+
+ return true;
+ }
+
+ private verifyPreviewToken(token: string, realResolvedPath: string): boolean {
+ const record = this.previewTokens.get(token);
+ if (!record) return false;
+
+ return record.realPath === realResolvedPath;
+ }
}
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
index f881eccc9b1..3af4794c64b 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
@@ -2,24 +2,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LocalFileProtocolManager } from '../LocalFileProtocolManager';
-const { mockApp, mockProtocol, mockReadFile, mockStat, protocolHandlerRef } = vi.hoisted(() => {
- const protocolHandlerRef = { current: null as any };
-
- return {
- mockApp: {
- isReady: vi.fn().mockReturnValue(true),
- whenReady: vi.fn().mockResolvedValue(undefined),
- },
- mockProtocol: {
- handle: vi.fn((_scheme: string, handler: any) => {
- protocolHandlerRef.current = handler;
- }),
- },
- mockReadFile: vi.fn(),
- mockStat: vi.fn(),
- protocolHandlerRef,
- };
-});
+const { mockApp, mockProtocol, mockReadFile, mockRealpath, mockStat, protocolHandlerRef } =
+ vi.hoisted(() => {
+ const protocolHandlerRef = { current: null as any };
+
+ return {
+ mockApp: {
+ isReady: vi.fn().mockReturnValue(true),
+ whenReady: vi.fn().mockResolvedValue(undefined),
+ },
+ mockProtocol: {
+ handle: vi.fn((_scheme: string, handler: any) => {
+ protocolHandlerRef.current = handler;
+ }),
+ },
+ mockReadFile: vi.fn(),
+ mockRealpath: vi.fn(),
+ mockStat: vi.fn(),
+ protocolHandlerRef,
+ };
+ });
vi.mock('electron', () => ({
app: mockApp,
@@ -27,6 +29,7 @@ vi.mock('electron', () => ({
}));
vi.mock('node:fs/promises', () => ({
+ realpath: mockRealpath,
readFile: mockReadFile,
stat: mockStat,
}));
@@ -45,6 +48,7 @@ describe('LocalFileProtocolManager', () => {
vi.clearAllMocks();
protocolHandlerRef.current = null;
mockApp.isReady.mockReturnValue(true);
+ mockRealpath.mockImplementation(async (filePath: string) => filePath);
mockStat.mockImplementation(async () => ({ isFile: () => true, size: 1024 }));
mockReadFile.mockImplementation(async () => Buffer.from('image-bytes'));
});
@@ -69,6 +73,12 @@ describe('LocalFileProtocolManager', () => {
it('serves a POSIX absolute path with the correct mime type', async () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/Pictures/cat.png',
+ workspaceRoot: '/Users/alice',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
expect(mockProtocol.handle).toHaveBeenCalledWith('localfile', expect.any(Function));
const handler = protocolHandlerRef.current;
@@ -76,7 +86,7 @@ describe('LocalFileProtocolManager', () => {
const response = await handler({
headers: new Headers(),
method: 'GET',
- url: 'localfile://file/Users/alice/Pictures/cat.png',
+ url,
});
expect(mockStat).toHaveBeenCalledWith('/Users/alice/Pictures/cat.png');
@@ -89,12 +99,18 @@ describe('LocalFileProtocolManager', () => {
it('serves source files as text through the localfile protocol', async () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice/project');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/project/App.tsx',
+ workspaceRoot: '/Users/alice/project',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
const handler = protocolHandlerRef.current;
const response = await handler({
headers: new Headers(),
method: 'GET',
- url: 'localfile://file/Users/alice/project/App.tsx',
+ url,
});
expect(mockStat).toHaveBeenCalledWith('/Users/alice/project/App.tsx');
@@ -106,12 +122,18 @@ describe('LocalFileProtocolManager', () => {
it('decodes percent-encoded characters in the path', async () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/My Pictures/ε›Ύ #.png',
+ workspaceRoot: '/Users/alice',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
const handler = protocolHandlerRef.current;
await handler({
headers: new Headers(),
method: 'GET',
- url: 'localfile://file/Users/alice/My%20Pictures/%E5%9B%BE%20%23.png',
+ url,
});
expect(mockStat).toHaveBeenCalledWith('/Users/alice/My Pictures/ε›Ύ #.png');
@@ -137,12 +159,18 @@ describe('LocalFileProtocolManager', () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/folder',
+ workspaceRoot: '/Users/alice',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
const handler = protocolHandlerRef.current;
const response = await handler({
headers: new Headers(),
method: 'GET',
- url: 'localfile://file/Users/alice/folder',
+ url,
});
expect(response.status).toBe(404);
@@ -158,17 +186,98 @@ describe('LocalFileProtocolManager', () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
+ await manager.approveWorkspaceRoot('/');
const handler = protocolHandlerRef.current;
+ const url = await manager.createPreviewUrl({
+ filePath: '/nonexistent.png',
+ workspaceRoot: '/',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
const response = await handler({
headers: new Headers(),
method: 'GET',
- url: 'localfile://file/nonexistent.png',
+ url,
});
expect(response.status).toBe(404);
});
+ it('rejects direct localfile requests without a main-issued preview token', async () => {
+ const manager = new LocalFileProtocolManager();
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ const response = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'localfile://file/Users/alice/.ssh/id_rsa',
+ });
+
+ expect(response.status).toBe(403);
+ expect(mockStat).not.toHaveBeenCalled();
+ expect(mockReadFile).not.toHaveBeenCalled();
+ });
+
+ it('rejects forged preview tokens before resolving the requested path', async () => {
+ const manager = new LocalFileProtocolManager();
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ const response = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'localfile://file/Users/alice/.ssh/id_rsa?token=forged',
+ });
+
+ expect(response.status).toBe(403);
+ expect(mockRealpath).not.toHaveBeenCalled();
+ expect(mockStat).not.toHaveBeenCalled();
+ expect(mockReadFile).not.toHaveBeenCalled();
+ });
+
+ it('does not mint preview URLs outside an approved workspace root', async () => {
+ const manager = new LocalFileProtocolManager();
+ await manager.approveWorkspaceRoot('/Users/alice/project');
+
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/.ssh/id_rsa',
+ workspaceRoot: '/Users/alice/project',
+ });
+
+ expect(url).toBeNull();
+ });
+
+ it('can approve a project root derived from an already approved nested scope', async () => {
+ const manager = new LocalFileProtocolManager();
+ await manager.approveWorkspaceRoot('/Users/alice/project/packages/app');
+ await manager.approveProjectRootFromScope({
+ projectRoot: '/Users/alice/project',
+ requestedScope: '/Users/alice/project/packages/app',
+ });
+
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/project/root.ts',
+ workspaceRoot: '/Users/alice/project',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
+
+ expect(url).toContain('token=');
+ });
+
+ it('can mint preview URLs for roots produced by the main-process project index', async () => {
+ const manager = new LocalFileProtocolManager();
+ await manager.approveIndexedProjectRoot('/Users/alice/project');
+
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/project/App.tsx',
+ workspaceRoot: '/Users/alice/project',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
+
+ expect(url).toContain('token=');
+ });
+
it('defers registration until app ready when not yet ready', async () => {
mockApp.isReady.mockReturnValue(false);
let resolveReady: () => void = () => undefined;
diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.ts
index 09fdd33afda..266573db994 100644
--- a/apps/desktop/src/main/types/store.ts
+++ b/apps/desktop/src/main/types/store.ts
@@ -19,6 +19,7 @@ export interface ElectronMainStore {
gatewayEnabled: boolean;
gatewayUrl: string;
locale: string;
+ localFileWorkspaceRoots: string[];
networkProxy: NetworkProxySettings;
shortcuts: Record<string, string>;
storagePath: string;
diff --git a/package.json b/package.json
index ba901a2eea2..d381449e743 100644
--- a/package.json
+++ b/package.json
@@ -312,7 +312,7 @@
"@xterm/xterm": "^5.5.0",
"@zumer/snapdom": "^1.9.14",
"ahooks": "^3.9.6",
- "antd": "^6.2.1",
+ "antd": "6.3.5",
"antd-style": "4.1.0",
"async-retry": "^1.3.3",
"bcryptjs": "^3.0.3",
@@ -394,9 +394,9 @@
"query-string": "^9.3.1",
"random-words": "^2.0.1",
"rc-util": "^5.44.4",
- "react": "^19.2.3",
+ "react": "19.2.5",
"react-confetti": "^6.4.0",
- "react-dom": "^19.2.3",
+ "react-dom": "19.2.5",
"react-fast-marquee": "^1.6.5",
"react-hotkeys-hook": "^5.2.3",
"react-i18next": "^16.5.3",
@@ -553,12 +553,15 @@
"overrides": {
"@react-pdf/image": "3.0.4",
"@types/react": "19.2.13",
+ "antd": "6.3.5",
"better-auth": "1.4.6",
"better-call": "1.1.8",
"drizzle-orm": "^0.45.1",
"fast-xml-parser": "5.4.2",
"lexical": "0.42.0",
"pdfjs-dist": "5.4.530",
+ "react": "19.2.5",
+ "react-dom": "19.2.5",
"stylelint-config-clean-order": "7.0.0"
},
"patchedDependencies": {
diff --git a/packages/const/src/protocol.ts b/packages/const/src/protocol.ts
index 146792d47dc..e3b1712b644 100644
--- a/packages/const/src/protocol.ts
+++ b/packages/const/src/protocol.ts
@@ -7,8 +7,8 @@ export const withElectronProtocolIfElectron = (url: string) => {
};
/**
- * Custom protocol the desktop main process exposes for serving arbitrary
- * absolute local-disk files to the renderer (e.g. project file previews).
+ * Custom protocol the desktop main process exposes for serving approved
+ * local workspace file previews to the renderer.
* Backed by `LocalFileProtocolManager` in
* `apps/desktop`.
*/
@@ -18,6 +18,10 @@ export const LOCAL_FILE_PROTOCOL_HOST = 'file';
/**
* Build a `localfile://file/<abs-path>` URL from an absolute filesystem path.
*
+ * The desktop protocol handler requires a main-process authorization token
+ * before serving bytes. Renderer preview code should request that URL through
+ * desktop IPC instead of using this helper directly.
+ *
* - POSIX `/Users/a/img.png` -> `localfile://file/Users/a/img.png`
* - Win32 `C:\\Users\\a\\img.png` -> `localfile://file/C:/Users/a/img.png`
*
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 18142e1f82c..f42673b60ae 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -111,6 +111,17 @@ export interface AuditSafePathsResult {
allSafe: boolean;
}
+export interface LocalFilePreviewUrlParams {
+ path: string;
+ workingDirectory: string;
+}
+
+export interface LocalFilePreviewUrlResult {
+ error?: string;
+ success: boolean;
+ url?: string;
+}
+
export interface LocalReadFileResult {
/**
* Character count of the content within the specified `loc` range.
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index 5e4ee58be58..2c687ecc7e6 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -1,10 +1,11 @@
-import { buildLocalFileUrl, isDesktop } from '@lobechat/const';
+import { isDesktop } from '@lobechat/const';
import { Center, Empty, Flexbox, Highlighter } from '@lobehub/ui';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Loading from '@/components/Loading/CircleLoading';
import { useClientDataSWR } from '@/libs/swr';
+import { localFileService } from '@/services/electron/localFileService';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -104,28 +105,34 @@ interface ActiveFileViewProps {
workingDirectory: string;
}
-const ActiveFileView = memo<ActiveFileViewProps>(({ filePath }) => {
+const ActiveFileView = memo<ActiveFileViewProps>(({ filePath, workingDirectory }) => {
const { t } = useTranslation('chat');
const filename = filePath.split('/').at(-1) ?? '';
- const localFileUrl = isDesktop ? buildLocalFileUrl(filePath) : null;
const {
data: preview,
error,
isLoading,
} = useClientDataSWR(
- localFileUrl ? ['local-file-preview', localFileUrl] : null,
+ isDesktop && workingDirectory ? ['local-file-preview', filePath, workingDirectory] : null,
async () => {
- if (!localFileUrl) throw new Error('Missing local file URL');
- return fetchLocalFilePreview(localFileUrl);
+ const result = await localFileService.getLocalFilePreviewUrl({
+ path: filePath,
+ workingDirectory,
+ });
+
+ if (!result.success || !result.url) {
+ throw new Error(result.error || 'Missing local file preview URL');
+ }
+
+ return fetchLocalFilePreview(result.url);
},
{ revalidateOnFocus: false },
);
// Chromium blocks `file://` from a non-file origin. The desktop main process
- // exposes local disk files through `localfile://`; the renderer fetches that
- // URL for every file type and keeps rendering inside our own components.
- if (!localFileUrl) {
+ // mints short-lived `localfile://` preview URLs for approved workspace files.
+ if (!isDesktop) {
return (
<Center height={'100%'} width={'100%'}>
<Empty description={t('workingPanel.localFile.binary')} />
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index 858c782d2dd..3f4ddb7b2d7 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -26,6 +26,7 @@ const gitFilesMock = vi.hoisted(() => ({
modified: ['src/foo/bar.ts'],
},
}));
+const openLocalFileMock = vi.hoisted(() => vi.fn());
// ─── mocks ────────────────────────────────────────────────────────────────────
@@ -93,7 +94,7 @@ vi.mock('../useProjectFiles', () => ({
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({ openLocalFile: vi.fn() }),
+ selector({ openLocalFile: openLocalFileMock }),
}));
const messageSpy = vi.hoisted(() => ({ warning: vi.fn() }));
@@ -143,6 +144,7 @@ beforeEach(() => {
handleSpies.select.mockClear();
handleSpies.setExpanded.mockClear();
messageSpy.warning.mockClear();
+ openLocalFileMock.mockClear();
useGlobalStore.setState({
...initialState,
status: { ...initialState.status, workingSidebarRevealRequest: undefined },
@@ -190,6 +192,29 @@ describe('Files β€” reveal request integration', () => {
]);
});
+ it('opens file previews with the indexed project root as the approved workspace root', () => {
+ render(<Files workingDirectory="/repo/packages/app" />);
+
+ const nodes = explorerTreeProps.current?.nodes as {
+ data: { path: string };
+ id: string;
+ isFolder: boolean;
+ }[];
+ const rootFileNode = nodes.find((node) => node.id === 'root.ts');
+ const getContextMenuItems = explorerTreeProps.current?.getContextMenuItems as (
+ node: unknown,
+ ) => Array<{ key: string; onClick?: () => void }>;
+
+ getContextMenuItems(rootFileNode)
+ .find((item) => item.key === 'open')
+ ?.onClick?.();
+
+ expect(openLocalFileMock).toHaveBeenCalledWith({
+ filePath: '/repo/root.ts',
+ workingDirectory: '/repo',
+ });
+ });
+
it('(a) reveals existing path: calls setExpanded with ancestors, then select and focus', async () => {
render(<Files workingDirectory="/repo" />);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
index 8b99285ba7a..0064002a74a 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -100,6 +100,7 @@ const Files = memo<FilesProps>(({ workingDirectory }) => {
const { t } = useTranslation('chat');
const { data, isLoading, isValidating, mutate } = useProjectFiles(workingDirectory);
const { data: gitFiles } = useGitWorkingTreeFiles(workingDirectory, data?.source === 'git');
+ const projectRoot = data?.root ?? workingDirectory;
const entries = useMemo(() => data?.entries ?? [], [data]);
const nodes = useMemo(() => buildTreeNodes(entries), [entries]);
@@ -161,9 +162,9 @@ const Files = memo<FilesProps>(({ workingDirectory }) => {
void localFileService.openLocalFileOrFolder(node.data.path, true);
return;
}
- openLocalFile({ filePath: node.data.path, workingDirectory });
+ openLocalFile({ filePath: node.data.path, workingDirectory: projectRoot });
},
- [openLocalFile, workingDirectory],
+ [openLocalFile, projectRoot],
);
const handleNodeClick = useCallback(
diff --git a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
index 277541f57e9..3db56bc39c9 100644
--- a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
+++ b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
@@ -23,6 +23,7 @@ const createRuntimeState = (models: EnabledAiModel[], keyVaults: Record<string,
const createExecutor = (privateOverrides?: Partial<MemoryExtractionPrivateConfig>) => {
const basePrivateConfig: MemoryExtractionPrivateConfig = {
+ agentBenchmarkLoCoMo: { model: 'benchmark-1', provider: 'provider-b' },
agentGateKeeper: { model: 'gate-2', provider: 'provider-b' },
agentLayerExtractor: {
contextLimit: 2048,
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 92a49aac647..09e9d9be168 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -14,6 +14,8 @@ import {
type ListLocalFileParams,
type ListLocalFilesResult,
type LocalFileItem,
+ type LocalFilePreviewUrlParams,
+ type LocalFilePreviewUrlResult,
type LocalMoveFilesResultItem,
type LocalReadFileParams,
type LocalReadFileResult,
@@ -84,6 +86,12 @@ class LocalFileService {
return ensureElectronIpc().localSystem.auditSafePaths(params);
}
+ async getLocalFilePreviewUrl(
+ params: LocalFilePreviewUrlParams,
+ ): Promise<LocalFilePreviewUrlResult> {
+ return ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
+ }
+
async prepareSkillDirectory(
params: PrepareSkillDirectoryParams,
): Promise<PrepareSkillDirectoryResult> {