# How the Understand Anything Dashboard Fetches Source Code with Path Allowlist Gating

> Discover how EgonexAI Understand Anything fetches source code securely. Learn about protected endpoints, path validation, and allowlist gating to safeguard your files.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: how-to-guide
- Published: 2026-06-13

---

**The code viewer in Egonex-AI Understand Anything retrieves source files through a protected [`/file-content.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main//file-content.json) endpoint that validates a one-time access token, normalizes paths against traversal attacks, and enforces an allowlist derived from the knowledge graph to prevent exposure of arbitrary files.**

The Egonex-AI Understand Anything dashboard provides a secure code viewing experience by gating file access through a sophisticated allowlist mechanism. Located in [`understand-anything-plugin/packages/dashboard/vite.config.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/dashboard/vite.config.ts), the implementation uses a custom Vite development server middleware to handle requests for source code. This server-side approach ensures that only files explicitly referenced in the project's knowledge graph are accessible to the viewer.

## The Secure Endpoint Architecture

### Vite Middleware Configuration

The protected endpoint is defined within the dashboard's Vite configuration. When a request hits [`/file-content.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main//file-content.json), the middleware first validates the `?token=` query parameter before routing to the `readSourceFile` function.

```typescript
// Inside Vite middleware
if (pathname === "/file-content.json") {
  const result = readSourceFile(url);
  sendJson(res, result.statusCode, result.payload);
  return;
}

```

### Token-Based Authentication

Each request must include a valid one-time access token. The middleware rejects unauthenticated requests before any file system operations occur, ensuring that the path validation logic only processes authorized traffic.

## Path Allowlist Enforcement Mechanism

### Input Validation and Normalization

The `readSourceFile` function implements defense-in-depth through multiple validation layers. It first checks that the `path` parameter exists, contains no null bytes, and is not an absolute path. The function then normalizes the path using `path.normalize()` and blocks any traversal attempts that would escape the project root, including paths starting with `..` or resolving to absolute locations.

```typescript
function readSourceFile(url: URL) {
  const requestedPath = url.searchParams.get("path") ?? "";
  // 1️⃣ Validate query param
  if (!requestedPath) return rejectFileRequest("Missing path");
  if (requestedPath.includes("\0")) return rejectFileRequest("Invalid path");
  if (path.isAbsolute(requestedPath)) return rejectFileRequest("Absolute paths are not allowed");

  // 2️⃣ Normalize and block path traversal
  const normalizedPath = path.normalize(requestedPath);
  if (
    normalizedPath === "." ||
    normalizedPath.startsWith(`..${path.sep}`) ||
    normalizedPath === ".." ||
    path.isAbsolute(normalizedPath)
  ) {
    return rejectFileRequest("Path must stay inside the project");
  }
  // ... additional checks
}

```

### Knowledge Graph Integration

The allowlist is constructed dynamically from the [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file. The system locates the graph file to determine the project root, then parses every node's `filePath` property into a normalized `Set` of allowed relative paths. The requested file must exist in this `graphFilePathSet`, or the server returns a 404 response.

```typescript
  // 3️⃣ Locate the knowledge‑graph to find the project root
  const graphFile = findGraphFile("knowledge-graph.json");
  const projectRoot = projectRootFromGraphFile(graphFile);
  const absoluteFile = path.resolve(projectRoot, normalizedPath);
  const relativeToRoot = path.relative(projectRoot, absoluteFile);

  // 4️⃣ Ensure the file is listed in the graph’s allowlist
  if (!graphFilePathSet(graphFile, projectRoot).has(safeRelativePath)) {
    return rejectFileRequest("File is not in the knowledge graph", 404);
  }

```

## File Safety and Content Delivery

### Binary and Size Restrictions

Before reading content, the system verifies the target is a regular file under 1 MiB (`MAX_SOURCE_FILE_BYTES`). Files containing null bytes are rejected as binary content (HTTP 415), preventing the viewer from attempting to display non-text resources.

### Language Detection and Response

For valid files, the `detectLanguage` function maps file extensions to Prism language identifiers. The server returns a JSON payload containing the relative path, detected language, raw content, size in bytes, and line count.

```typescript
  // 5️⃣ Size / binary checks, then read & return JSON payload
  const stat = fs.statSync(absoluteFile);
  if (!stat.isFile()) return rejectFileRequest("Path is not a file");
  if (stat.size > MAX_SOURCE_FILE_BYTES) return rejectFileRequest("File is too large to preview", 413);
  const buffer = fs.readFileSync(absoluteFile);
  if (buffer.includes(0)) return rejectFileRequest("Binary files cannot be previewed", 415);
  const content = buffer.toString("utf8");

  return {
    statusCode: 200,
    payload: {
      path: safeRelativePath,
      language: detectLanguage(relativeToRoot),
      content,
      sizeBytes: buffer.byteLength,
      lineCount: content.split(/\r\n|\n|\r/).length,
    },
  };

```

## Client-Side Integration

The browser-side code fetches the endpoint using the one-time token, receives the JSON payload, and initializes the Prism-based syntax highlighter. The sliding panel viewer displays the highlighted source while the allowlist guarantee ensures users cannot manipulate the path parameter to access files outside the analyzed project scope.

```typescript
async function fetchSource(path: string, token: string) {
  const resp = await fetch(`/file-content.json?token=${token}&path=${encodeURIComponent(path)}`);
  if (!resp.ok) throw new Error(`Failed: ${resp.status}`);
  return await resp.json(); // {path, language, content, …}
}

```

## Summary

- The [`/file-content.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main//file-content.json) endpoint in [`vite.config.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/vite.config.ts) gates all file access through the `readSourceFile` function.
- Path allowlist enforcement uses the [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file to build a canonical `Set` of permitted relative paths via `graphFilePathSet`.
- Multiple security layers include token authentication, path normalization, traversal prevention (`..` blocking), and binary file rejection.
- Valid responses include language detection metadata for Prism syntax highlighting, with file size capped at 1 MiB.

## Frequently Asked Questions

### How does the path allowlist prevent directory traversal attacks?

The `readSourceFile` function normalizes input paths using `path.normalize()` and explicitly rejects any path that starts with `..` or resolves to an absolute location. More critically, the requested file must exist in the `Set` built by `graphFilePathSet` from the knowledge graph's nodes, ensuring only explicitly cataloged project files are accessible regardless of path manipulation.

### What is the maximum file size the code viewer can display?

The server enforces a hard limit of 1 MiB defined as `MAX_SOURCE_FILE_BYTES`. Files exceeding this size return an HTTP 413 status code, while binary files containing null bytes return HTTP 415, ensuring the Prism-based viewer only processes manageable text content suitable for browser-based display.

### Where is the allowlist of permitted files stored?

The allowlist is dynamically generated from the [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file located at the project root. The `graphFilePathSet` function parses every node's `filePath` property, normalizes these paths, and stores them in a `Set` that serves as the authoritative whitelist of accessible source files.

### Why use a Vite middleware instead of a separate API server?

The Vite middleware approach eliminates the need for a separate backend service during development, allowing the dashboard to automatically resolve the project root from the knowledge graph location. This integration keeps the security logic—token validation, path normalization, and allowlist enforcement—co-located with the build tooling while providing a seamless development experience.