This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-vfs-path-traversal-isolation

Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation

Enforces strict virtual file system (VFS) boundaries within Bun 1.2 standalone compiled executables (`bun build --compile`). Prevents canonicalized path traversal (`../`) and symlink dereference attacks from breaking out of `$bunfs/root` into host OS filesystems (`/etc`, `C:\Windows`). Requires safe resolution primitives and explicit verification against embed roots before calling `Bun.file()` or `node:fs` APIs.

Prohibited Anti-Pattern: Unsanitized Path Concatenation and Blind Symlink Resolution Escaping Bun Embedded VFS Root

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation - Enforces strict virtual file system (VFS) boundaries within Bun 1.2 standalone compiled executables (`bun build --compile`). Prevents canonicalized path traversal (`../`) and symlink dereference attacks from breaking out of `$bunfs/root` into host OS filesystems (`/etc`, `C:\Windows`). Requires safe resolution primitives and explicit verification against embed roots before calling `Bun.file()` or `node:fs` APIs.
globs: src/**/*.{ts,tsx,js,jsx}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-vfs-path-traversal-isolation"
---

# Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsanitized Path Concatenation and Blind Symlink Resolution Escaping Bun Embedded VFS Root

## System Constraints
You are a Principal Security Architect enforcing boundary isolation for Bun 1.2 standalone compiled binaries. When code compiles via `bun build --compile`, embedded assets are mounted within a virtual filesystem (`$bunfs/root` or embedded base directories). You must prevent directory traversal, canonicalization leaks via `path.resolve`, and symlink-based jailbreaks from the virtual filesystem into the host operating system. Mandate absolute jail containment, root prefix matching, and strict rejection of unverified paths.

## Strict Guidelines
- Engineers MUST ALWAYS determine the canonical VFS base prefix using `import.meta.dir` or an explicit embedded asset mount path prior to resolving user inputs.
- Engineers MUST NOT resolve user-controlled relative paths directly using `path.resolve()` or `path.join()` without asserting that the canonicalized path starts with the designated VFS base directory.
- Code MUST sanitize incoming path tokens, stripping null bytes (`\0`), and verifying that `path.normalize(target)` remains prefixed by the strict base directory before calling `Bun.file()` or `node:fs` methods.
- Services MUST reject symlink traversal that targets paths outside the VFS jail by inspecting `node:fs.lstatSync` or `node:fs.realpathSync` where symbolic references are permitted.
- Components NEVER expose direct raw URL parameter mapping to filesystem lookups inside standalone binaries without bounding validation against the embedded sandbox root.

## Bad vs Good Implementations
### Securing Embedded VFS File Resolution against Host Root Jailbreaks

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Bun 1.2 compiled binaries, `join` with user-supplied input allows `../` sequences to traverse beyond the embedded asset folder and access sensitive host operating system paths if the runtime resolves outward past the virtual mount point.
```typescript
import { join } from 'node:path';

export async function serveEmbeddedAsset(userPath: string): Promise<Response> {
  // Anti-pattern: Direct join resolves traversal tokens ('../../etc/passwd')
  // which can break out of Bun's embedded $bunfs root into the host filesystem
  const resolvedPath = join(import.meta.dir, 'assets', userPath);
  const asset = Bun.file(resolvedPath);

  if (!(await asset.exists())) {
    return new Response('Not Found', { status: 404 });
  }

  return new Response(asset);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict lexicographical and symlink containment within the VFS assets boundary. Strips poisoned characters, canonicalizes via `realpath`, and verifies that resolution remains within `VFS_ASSET_ROOT` before invoking `Bun.file()`.
```typescript
import { resolve, normalize } from 'node:path';
import { realpath } from 'node:fs/promises';

const VFS_ASSET_ROOT = resolve(import.meta.dir, 'assets');

export async function serveEmbeddedAsset(userPath: string): Promise<Response> {
  // Invariant: Strip null bytes, normalize, and enforce strict prefix containment
  const sanitized = normalize(userPath).replace(/\0/g, '');
  const targetPath = resolve(VFS_ASSET_ROOT, sanitized);

  // Guardrail 1: Lexical prefix containment check
  if (!targetPath.startsWith(VFS_ASSET_ROOT)) {
    return new Response('Access Denied: Path Traversal Detected', { status: 403 });
  }

  try {
    // Guardrail 2: Symlink boundary verification against VFS escape
    const realTarget = await realpath(targetPath);
    if (!realTarget.startsWith(VFS_ASSET_ROOT)) {
      return new Response('Access Denied: Symlink Jailbreak Detected', { status: 403 });
    }

    const asset = Bun.file(realTarget);
    if (!(await asset.exists())) {
      return new Response('Not Found', { status: 404 });
    }

    return new Response(asset);
  } catch {
    return new Response('Not Found', { status: 404 });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation

Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation defines an industrial-grade behavioral standard for backend engineering. Enforces strict virtual file system (VFS) boundaries within Bun 1.2 standalone compiled executables (`bun build --compile`). Prevents canonicalized path traversal (`../`) and symlink dereference attacks from breaking out of `$bunfs/root` into host OS filesystems (`/etc`, `C:\Windows`). Requires safe resolution primitives and explicit verification against embed roots before calling `Bun.file()` or `node:fs` APIs. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unsanitized Path Concatenation and Blind Symlink Resolution Escaping Bun Embedded VFS Root Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnsanitized Path Concatenation and Blind Symlink Resolution Escaping Bun Embedded VFS RootCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS determine the canonical VFS base prefix using `import.meta.dir` or an explicit embedded asset mount path prior to resolving user inputs.

Engineers MUST ALWAYS determine the canonical VFS base prefix using `import.meta.dir` or an explicit embedded asset mount path prior to resolving user inputs.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT resolve user-controlled relative paths directly using `path.resolve()` or `path.join()` without asserting that the canonicalized path starts with the designated VFS base directory.

Engineers MUST NOT resolve user-controlled relative paths directly using `path.resolve()` or `path.join()` without asserting that the canonicalized path starts with the designated VFS base directory.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST sanitize incoming path tokens, stripping null bytes (`\0`), and verifying that `path.normalize(target)` remains prefixed by the strict base directory before calling `Bun.file()` or `node

Code MUST sanitize incoming path tokens, stripping null bytes (`\0`), and verifying that `path.normalize(target)` remains prefixed by the strict base directory before calling `Bun.file()` or `node:fs` methods.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST reject symlink traversal that targets paths outside the VFS jail by inspecting `node

Services MUST reject symlink traversal that targets paths outside the VFS jail by inspecting `node:fs.lstatSync` or `node:fs.realpathSync` where symbolic references are permitted.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER expose direct raw URL parameter mapping to filesystem lookups inside standalone binaries without bounding validation against the embedded sandbox root.

Components NEVER expose direct raw URL parameter mapping to filesystem lookups inside standalone binaries without bounding validation against the embedded sandbox root.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Bun 1.2 Standalone Executable VFS Path Traversal and Symlink Isolation critical for AI coding assistants?

Enforces strict virtual file system (VFS) boundaries within Bun 1.2 standalone compiled executables (`bun build --compile`). Prevents canonicalized path traversal (`../`) and symlink dereference attacks from breaking out of `$bunfs/root` into host OS filesystems (`/etc`, `C:\Windows`). Requires safe resolution primitives and explicit verification against embed roots before calling `Bun.file()` or `node:fs` APIs. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unsanitized Path Concatenation and Blind Symlink Resolution Escaping Bun Embedded VFS Root) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Bun