Files
opencode-manager/backend/src/services/filesystem.ts
T
Alexander DrewekeandChris Scott f8e361c0b8 feat(repo): add graphical folder picker for adding local repositories (#324)
* feat(repo): add graphical folder picker for adding local repositories

Previously, adding a local repository or scanning a folder in the
"Add Repository" dialog required typing an absolute filesystem path by
hand. This adds a navigable directory browser so users can select a
folder graphically instead.

Backend
- New shared Zod schemas (DirectoryEntry, BrowseDirectoryResponse,
  BrowseDirectoryRequest) exported via shared/types and shared/schemas.
- New env var REPO_BROWSE_ROOT plus getBrowseRootPath() helper. It is
  intentionally NOT defaulted to WORKSPACE_PATH: folder browsing is
  opt-in and only works when an administrator explicitly configures a
  root directory.
- New filesystem service (browseDirectory) that lists only directories
  (hidden entries filtered), flags Git repositories, and confines all
  access to the configured root:
    - 501 when REPO_BROWSE_ROOT is not configured
    - 403 on path traversal outside the root
    - 404 for missing directories, 400 when the target is a file
- New authenticated route GET /api/filesystem/browse, registered under
  the protected API group.

Frontend
- New api client browseDirectory() (uses fetchWrapper, so auth cookies
  are sent).
- New DirectoryPickerDialog: navigate into subfolders, go up a level,
  Git repos marked with an icon, and a "Select This Folder" action.
  Retries are disabled so a configuration error is not polled
  repeatedly.
- When browsing is disabled (501), the dialog shows a clear, actionable
  message telling the user to set REPO_BROWSE_ROOT and to enter the
  path manually in the meantime, instead of a generic error.
- AddRepoDialog gains a "Browse" button next to both the Local and
  Folder path inputs; the chosen path is written back into the active
  field.

Tests
- Service and route tests covering listing, Git-repo detection, hidden
  filtering, parent navigation, and the 400/403/404/501 error paths.

Security note: because there is no default root, the picker is inert
until REPO_BROWSE_ROOT is set, and it can never escape that root.

* fix(fs): reject symlink escapes in directory browse

Canonicalize root and requested path with fs.realpath() and gate on
path.relative() so symlinks inside REPO_BROWSE_ROOT pointing outside
are rejected with 403 before fs.stat/fs.readdir follow them. Handles
root '/' correctly. Adds regression test for symlink escape.

* fix(ui): make directory picker fill dialog height

Replace grid content-start packing with explicit grid-rows tracks so
the directory list grows to fill the dialog and scrolls while the
header, path, and footer stay fixed. Drops the ineffective flex-1
from the grid child on the scroll container.

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
2026-07-26 21:12:13 -04:00

90 lines
2.6 KiB
TypeScript

import { promises as fs } from 'node:fs'
import path from 'node:path'
import { getBrowseRootPath } from '@opencode-manager/shared/config/env'
import type { BrowseDirectoryResponse, DirectoryEntry } from '@opencode-manager/shared/types'
function getRoot(): string {
const configured = getBrowseRootPath()
if (!configured) {
throw {
message: 'Folder browsing is disabled. Set REPO_BROWSE_ROOT in the server environment to enable it.',
statusCode: 501,
}
}
return path.resolve(configured)
}
async function resolveWithinRoot(root: string, requestedPath?: string): Promise<string> {
const resolved = (!requestedPath || requestedPath.trim() === '') ? root : path.resolve(requestedPath)
const realRoot = await fs.realpath(root)
let realResolved: string
try {
realResolved = await fs.realpath(resolved)
} catch (err: unknown) {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT' || code === 'ENOTDIR') {
throw { message: 'Directory not found', statusCode: 404 }
}
throw err
}
const rel = path.relative(realRoot, realResolved)
if (rel === '..' || rel.startsWith(`..${path.sep}`)) {
throw { message: 'Path is outside the allowed browse root', statusCode: 403 }
}
return resolved
}
async function isGitRepo(entryPath: string): Promise<boolean> {
try {
const stats = await fs.lstat(path.join(entryPath, '.git'))
return stats.isDirectory() || stats.isFile()
} catch {
return false
}
}
export async function browseDirectory(requestedPath?: string): Promise<BrowseDirectoryResponse> {
const root = getRoot()
const targetPath = await resolveWithinRoot(root, requestedPath)
let stats
try {
stats = await fs.stat(targetPath)
} catch {
throw { message: 'Directory not found', statusCode: 404 }
}
if (!stats.isDirectory()) {
throw { message: 'Path is not a directory', statusCode: 400 }
}
const dirEntries = await fs.readdir(targetPath, { withFileTypes: true })
const directories = dirEntries.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
const entries: DirectoryEntry[] = await Promise.all(
directories.map(async (entry) => {
const entryPath = path.join(targetPath, entry.name)
return {
name: entry.name,
path: entryPath,
isGitRepo: await isGitRepo(entryPath),
}
})
)
entries.sort((a, b) => a.name.localeCompare(b.name))
const isRoot = targetPath === root
const parentPath = isRoot ? null : path.dirname(targetPath)
return {
path: targetPath,
parentPath,
isRoot,
entries,
}
}