refactor: improve file browser path resolution and navigation (#193)

- Add query parameter support for file paths to handle special characters
- Enable navigation above base path with proper validation
- Centralize URL encoding logic for file API calls
- Update path validation to use workspace base instead of repos base
- Add normalizePath utility for consistent path handling
This commit is contained in:
Chris Scott authored and GitHub committed 2026-04-23 17:06:49 -04:00
1 parent 40a2af7521
commit 31755c23f8
10 files changed
+153 -50

No files matched your search

+16 -8
View File
@@ -1,10 +1,18 @@
import { Hono } from 'hono'
import { Hono, type Context } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import * as fileService from '../services/files'
import * as archiveService from '../services/archive'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
function decodeFilePath(path: string): string {
return decodeURIComponent(path)
}
function getFilePathFromRequest(c: Context, fallbackPath: string): string {
return c.req.query('path') ?? decodeFilePath(fallbackPath)
}
export function createFileRoutes() {
const app = new Hono()
@@ -13,7 +21,7 @@ export function createFileRoutes() {
if (path.endsWith('/download-zip')) {
const match = path.match(/\/api\/files\/(.+?)\/download-zip$/)
const userPath = match?.[1]
const userPath = match?.[1] ? decodeFilePath(match[1]) : undefined
if (!userPath) {
return c.json({ error: 'No path provided' }, 400)
@@ -61,7 +69,7 @@ export function createFileRoutes() {
}
if (path.endsWith('/ignored-paths')) {
const userPath = path.replace(/\/api\/files\/(.+?)\/ignored-paths$/, '$1')
const userPath = decodeFilePath(path.replace(/\/api\/files\/(.+?)\/ignored-paths$/, '$1'))
if (!userPath || userPath === '/ignored-paths') {
return c.json({ error: 'No path provided' }, 400)
@@ -77,7 +85,7 @@ export function createFileRoutes() {
}
try {
const userPath = path.replace(/^\/api\/files\//, '') || ''
const userPath = getFilePathFromRequest(c, path.replace(/^\/api\/files\//, '') || '')
const download = c.req.query('download') === 'true'
const raw = c.req.query('raw') === 'true'
const startLineParam = c.req.query('startLine')
@@ -127,7 +135,7 @@ export function createFileRoutes() {
app.post('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
const body = await c.req.parseBody()
const file = body.file as File
@@ -146,7 +154,7 @@ export function createFileRoutes() {
app.put('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
const body = await c.req.json()
const result = await fileService.createFileOrFolder(path, body)
@@ -159,7 +167,7 @@ export function createFileRoutes() {
app.delete('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
await fileService.deleteFileOrFolder(path)
return c.json({ success: true })
@@ -171,7 +179,7 @@ export function createFileRoutes() {
app.patch('/*', async (c) => {
try {
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const path = getFilePathFromRequest(c, c.req.path.replace(/^\/api\/files\//, '') || '')
const body = await c.req.json()
if (body.patches && Array.isArray(body.patches)) {
+6 -5
View File
@@ -13,11 +13,12 @@ import {
getFileStats,
listDirectory
} from './file-operations'
import { getReposPath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
import { getReposPath, getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
import { ALLOWED_MIME_TYPES, type AllowedMimeType } from '@opencode-manager/shared'
import type { ChunkedFileInfo, PatchOperation } from '@opencode-manager/shared'
const SHARED_WORKSPACE_BASE = getReposPath()
const WORKSPACE_BASE = getWorkspacePath()
interface FileInfo {
name: string
@@ -234,12 +235,12 @@ export async function renameOrMoveFile(userPath: string, body: { newPath: string
function validatePath(userPath: string): string {
const trimmed = userPath.trim()
const normalized = path.normalize(trimmed).replace(/^(\.\.(\/|\\|$))+/, '')
const normalized = path.normalize(trimmed || '.')
const fullPath = path.join(SHARED_WORKSPACE_BASE, normalized)
const resolved = path.resolve(fullPath)
const basePath = path.resolve(SHARED_WORKSPACE_BASE)
if (!resolved.startsWith(basePath)) {
const basePath = path.resolve(WORKSPACE_BASE)
if (resolved !== basePath && !resolved.startsWith(`${basePath}${path.sep}`)) {
throw { message: 'Path traversal detected', statusCode: 403 }
}
@@ -369,4 +370,4 @@ export async function applyFilePatches(userPath: string, patches: PatchOperation
await fs.writeFile(validatedPath, lines.join('\n'), 'utf8')
return { success: true, totalLines: lines.length }
}
}
+11 -3
View File
@@ -3,8 +3,16 @@ import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files'
function getFileApiUrl(path: string): string {
if (path.includes('..')) {
return `${API_BASE_URL}/api/files/?path=${encodeURIComponent(path)}`
}
return `${API_BASE_URL}/api/files/${path.split('/').map(encodeURIComponent).join('/')}`
}
async function fetchFile(path: string): Promise<FileInfo> {
return fetchWrapper(`${API_BASE_URL}/api/files/${path}`)
return fetchWrapper(getFileApiUrl(path))
}
export function useFile(path: string | undefined) {
@@ -16,13 +24,13 @@ export function useFile(path: string | undefined) {
}
export async function fetchFileRange(path: string, startLine: number, endLine: number): Promise<ChunkedFileInfo> {
return fetchWrapper(`${API_BASE_URL}/api/files/${path}`, {
return fetchWrapper(getFileApiUrl(path), {
params: { startLine, endLine },
})
}
export async function applyFilePatches(path: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> {
return fetchWrapper(`${API_BASE_URL}/api/files/${path}`, {
return fetchWrapper(getFileApiUrl(path), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patches }),
@@ -27,6 +27,7 @@ interface FileBrowserProps {
initialSelectedFile?: string
onDirectoryLoad?: (info: { workspaceRoot?: string; currentPath: string }) => void
onPreviewStateChange?: (isOpen: boolean) => void
allowNavigateAboveBase?: boolean
}
interface UploadItem {
@@ -122,7 +123,7 @@ function getUploadItemsFromFileList(fileList: FileList): UploadItem[] {
return items
}
export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad, onPreviewStateChange }, ref) {
export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad, onPreviewStateChange, allowNavigateAboveBase = false }, ref) {
const [currentPath, setCurrentPath] = useState(basePath)
const [files, setFiles] = useState<FileInfo | null>(null)
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null)
@@ -137,7 +138,7 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
const uploadCancelledRef = useRef(false)
const isMobile = useMobile()
const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)
const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)
useEffect(() => {
if (initialFileData) {
@@ -155,12 +156,25 @@ useEffect(() => {
}
}, [initialFileError])
const getFileApiUrl = useCallback((path: string) => {
if (path.includes('..')) {
return `${API_BASE_URL}/api/files/?path=${encodeURIComponent(path)}`
}
const encodedPath = path
.split('/')
.map(segment => encodeURIComponent(segment))
.join('/')
return `${API_BASE_URL}/api/files/${encodedPath}`
}, [])
const loadFiles = useCallback(async (path: string) => {
setLoading(true)
setError(null)
try {
const response = await fetch(`${API_BASE_URL}/api/files/${path}`)
const response = await fetch(getFileApiUrl(path))
if (!response.ok) {
throw new Error(`Failed to load files: ${response.statusText}`)
}
@@ -174,28 +188,64 @@ useEffect(() => {
} finally {
setLoading(false)
}
}, [onDirectoryLoad])
}, [getFileApiUrl, onDirectoryLoad])
const getPathParts = useCallback((path: string) => path.split('/').filter(Boolean), [])
const normalizePath = useCallback((path: string) => {
const normalized = path
.trim()
.replace(/\\/g, '/')
.replace(/\/+/g, '/')
.replace(/\/+$/, '')
if (normalized === '.' || normalized === './') {
return ''
}
if (normalized.startsWith('./')) {
return normalized.slice(2)
}
return normalized
}, [])
const getPathParts = useCallback((path: string) => normalizePath(path).split('/').filter(Boolean), [normalizePath])
const canNavigateUp = useCallback(() => {
if (allowNavigateAboveBase && normalizePath(currentPath) === '') {
return true
}
if (normalizePath(currentPath) === '..') {
return false
}
const pathParts = getPathParts(currentPath)
if (allowNavigateAboveBase) {
return pathParts.length > 0
}
return pathParts.length > 0 && normalizePath(currentPath) !== normalizePath(basePath)
}, [allowNavigateAboveBase, basePath, currentPath, getPathParts, normalizePath])
const goToParentDirectory = useCallback(() => {
if (allowNavigateAboveBase && normalizePath(currentPath) === '') {
loadFiles('..')
return
}
const pathParts = getPathParts(currentPath)
if (pathParts.length > 0) {
pathParts.pop()
const parentPath = pathParts.join('/')
loadFiles(parentPath || basePath)
loadFiles(allowNavigateAboveBase ? parentPath : parentPath || basePath)
}
}, [currentPath, basePath, loadFiles, getPathParts])
}, [allowNavigateAboveBase, currentPath, basePath, loadFiles, getPathParts, normalizePath])
useImperativeHandle(ref, () => ({
goBack: goToParentDirectory,
canGoBack: () => {
const pathParts = getPathParts(currentPath)
const joinedPath = pathParts.join('/')
return pathParts.length > 0 && joinedPath !== basePath
},
canGoBack: canNavigateUp,
getCurrentPath: () => currentPath,
}), [currentPath, basePath, goToParentDirectory, getPathParts])
}), [currentPath, goToParentDirectory, canNavigateUp])
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
@@ -206,7 +256,7 @@ useEffect(() => {
// Fetch the full file content when selecting a file
setLoading(true)
try {
const response = await fetch(`${API_BASE_URL}/api/files/${file.path}`)
const response = await fetch(getFileApiUrl(file.path))
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
@@ -226,7 +276,7 @@ useEffect(() => {
} finally {
setLoading(false)
}
}, [onFileSelect, isMobile, onPreviewStateChange])
}, [getFileApiUrl, onFileSelect, isMobile, onPreviewStateChange])
const handleCloseModal = useCallback(() => {
setIsPreviewModalOpen(false)
@@ -248,7 +298,7 @@ useEffect(() => {
formData.append('relativePath', item.relativePath)
try {
const response = await fetch(`${API_BASE_URL}/api/files/${currentPath}`, {
const response = await fetch(getFileApiUrl(currentPath), {
method: 'POST',
body: formData,
})
@@ -262,7 +312,7 @@ useEffect(() => {
} catch (err) {
return err instanceof Error ? err.message : 'Upload failed'
}
}, [currentPath])
}, [currentPath, getFileApiUrl])
const handleUploadItems = useCallback(async (items: UploadItem[]) => {
if (items.length === 0) return
@@ -318,7 +368,7 @@ useEffect(() => {
const handleCreateFile = useCallback(async (name: string, type: 'file' | 'folder') => {
try {
const response = await fetch(`${API_BASE_URL}/api/files/${currentPath}/${name}`, {
const response = await fetch(getFileApiUrl([currentPath, name].filter(Boolean).join('/')), {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, content: type === 'file' ? '' : undefined }),
@@ -332,11 +382,11 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Create failed')
}
}, [currentPath, loadFiles])
}, [currentPath, getFileApiUrl, loadFiles])
const handleDelete = useCallback(async (path: string) => {
try {
const response = await fetch(`${API_BASE_URL}/api/files/${path}`, {
const response = await fetch(getFileApiUrl(path), {
method: 'DELETE',
})
@@ -349,11 +399,11 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed')
}
}, [currentPath, loadFiles])
}, [currentPath, getFileApiUrl, loadFiles])
const handleRename = useCallback(async (oldPath: string, newPath: string) => {
try {
const response = await fetch(`${API_BASE_URL}/api/files/${oldPath}`, {
const response = await fetch(getFileApiUrl(oldPath), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPath }),
@@ -367,7 +417,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Rename failed')
}
}, [currentPath, loadFiles])
}, [currentPath, getFileApiUrl, loadFiles])
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
@@ -427,6 +477,10 @@ useEffect(() => {
return () => document.removeEventListener('keydown', handleEscape)
}, [isPreviewModalOpen, handleCloseModal])
const showNavigateUp = allowNavigateAboveBase && normalizePath(currentPath) !== '..'
? true
: canNavigateUp()
const filteredFiles = files?.children?.filter(file =>
file.name.toLowerCase().includes(searchQuery.toLowerCase())
)
@@ -557,6 +611,7 @@ useEffect(() => {
currentPath={currentPath}
basePath={basePath}
onNavigateUp={goToParentDirectory}
canNavigateUp={showNavigateUp}
/>
)}
</div>
@@ -657,6 +712,7 @@ useEffect(() => {
currentPath={currentPath}
basePath={basePath}
onNavigateUp={goToParentDirectory}
canNavigateUp={showNavigateUp}
/>
</div>
)}
@@ -23,9 +23,10 @@ interface FileBrowserSheetProps {
repoName?: string
repoId?: number
initialSelectedFile?: string
allowNavigateAboveBase?: boolean
}
export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, repoId, initialSelectedFile }: FileBrowserSheetProps) {
export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, repoId, initialSelectedFile, allowNavigateAboveBase = false }: FileBrowserSheetProps) {
const normalizedBasePath = basePath || '.'
const [isEditing, setIsEditing] = useState(false)
const [displayPath, setDisplayPath] = useState<string>('/')
@@ -57,9 +58,20 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
}, [isOpen])
const handleDirectoryLoad = useCallback((info: { workspaceRoot?: string; currentPath: string }) => {
if (allowNavigateAboveBase) {
const pathParts = info.currentPath.split('/').filter(Boolean)
const displayParts = pathParts[0] === '..'
? ['workspace', ...pathParts.slice(1)]
: ['workspace', 'repos', ...pathParts]
setDisplayPath('/' + displayParts.join('/'))
setCurrentPath(info.currentPath || '.')
return
}
if (!info.currentPath || info.currentPath === '.' || info.currentPath === '') {
setDisplayPath('/')
setCurrentPath(basePath || '.')
setCurrentPath(info.currentPath || '.')
return
}
@@ -78,7 +90,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
} else {
setDisplayPath('/' + pathParts.join('/'))
}
}, [repoName, basePath])
}, [allowNavigateAboveBase, repoName])
const handleDownloadDirectory = useCallback(async (options: { includeGit?: boolean, includePaths?: string[] }) => {
if (!currentPath) return
@@ -139,7 +151,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
{repoName}
</h1>
)}
<PathDisplay path={displayPath} maxSegments={2} className="truncate" />
<PathDisplay path={displayPath} maxSegments={4} className="truncate" />
</div>
<div className="flex items-center gap-2">
{repoId && !isEditing && (
@@ -187,6 +199,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
initialSelectedFile={initialSelectedFile}
onDirectoryLoad={handleDirectoryLoad}
onPreviewStateChange={setIsPreviewOpen}
allowNavigateAboveBase={allowNavigateAboveBase}
/>
</FullscreenSheetContent>
</FullscreenSheet>
@@ -12,6 +12,17 @@ const API_BASE = API_BASE_URL
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
const MARKDOWN_PREVIEW_SIZE_LIMIT = 1_000_000
function getFileApiUrl(path: string, query?: string): string {
const separator = query ? (path.includes('..') ? '&' : '?') : ''
const suffix = query ? `${separator}${query}` : ''
if (path.includes('..')) {
return `${API_BASE}/api/files/?path=${encodeURIComponent(path)}${suffix}`
}
return `${API_BASE}/api/files/${path.split('/').map(encodeURIComponent).join('/')}${suffix}`
}
interface FilePreviewProps {
file: FileInfo
hideHeader?: boolean
@@ -95,7 +106,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const handleDownload = () => {
const link = document.createElement('a')
link.href = `${API_BASE}/api/files/${file.path}?download=true`
link.href = getFileApiUrl(file.path, 'download=true')
link.download = file.name
document.body.appendChild(link)
link.click()
@@ -137,7 +148,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const handleSave = async () => {
setIsSaving(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`, {
const response = await fetch(getFileApiUrl(file.path), {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'file', content: editContent }),
@@ -189,7 +200,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
return (
<div className="flex justify-center p-4">
<img
src={`${API_BASE}/api/files/${file.path}?raw=true`}
src={getFileApiUrl(file.path, 'raw=true')}
alt={file.name}
className="max-w-full h-auto object-contain rounded"
/>
@@ -33,6 +33,7 @@ interface FileTreeProps {
currentPath?: string
basePath?: string
onNavigateUp?: () => void
canNavigateUp?: boolean
}
interface TreeNodeProps {
@@ -93,8 +94,10 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o
const handleDownload = () => {
if (file.isDirectory) return
const downloadUrl = `${API_BASE_URL}/api/files/${file.path}?download=true`
const downloadUrl = file.path.includes('..')
? `${API_BASE_URL}/api/files/?path=${encodeURIComponent(file.path)}&download=true`
: `${API_BASE_URL}/api/files/${file.path.split('/').map(encodeURIComponent).join('/')}?download=true`
const link = document.createElement('a')
link.href = downloadUrl
link.download = file.name
@@ -239,12 +242,12 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o
)
}
export const FileTree = memo(function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '', onNavigateUp }: FileTreeProps) {
export const FileTree = memo(function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '', onNavigateUp, canNavigateUp }: FileTreeProps) {
const handleGoUp = () => {
onNavigateUp?.()
}
const showGoUp = currentPath && currentPath !== basePath
const showGoUp = canNavigateUp ?? Boolean(currentPath && currentPath !== basePath)
return (
<div className="overflow-y-auto">
@@ -20,6 +20,7 @@ export function MobileSheetHost() {
onClose={close}
basePath=""
repoName="Workspace Root"
allowNavigateAboveBase={true}
/>
)}
{openSheet === 'notifications' && <NotificationsSheet isOpen onClose={close} />}
+1
View File
@@ -224,6 +224,7 @@ export function RepoDetail() {
basePath={repo.localPath}
repoName={displayName}
repoId={repoId}
allowNavigateAboveBase={true}
/>
<RepoMcpDialog
+1
View File
@@ -67,6 +67,7 @@ export function Repos() {
onClose={handleCloseFileBrowser}
basePath=""
repoName="Workspace Root"
allowNavigateAboveBase={true}
/>
</div>
);