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

Bun 1.2 Standalone Binary Embedded VFS Sandbox Enforcement

Enforces strict boundary isolation between Bun 1.2's read-only embedded Virtual File System ($bunfs) and the host operating system during standalone compiled binary execution. Prevents host filesystem breakout vulnerabilities and runtime panics caused by directory traversal out of embedded virtual roots or illegal write operations on bundled assets.

Prohibited Anti-Pattern: Unchecked Path Resolution and Mutative Operations Against Bun Embedded VFS Roots

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Standalone Binary Embedded VFS Sandbox Enforcement - Enforces strict boundary isolation between Bun 1.2's read-only embedded Virtual File System ($bunfs) and the host operating system during standalone compiled binary execution. Prevents host filesystem breakout vulnerabilities and runtime panics caused by directory traversal out of embedded virtual roots or illegal write operations on bundled assets.
globs: src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-standalone-vfs-sandbox-enforcement"
---

# Bun 1.2 Standalone Binary Embedded VFS Sandbox Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Path Resolution and Mutative Operations Against Bun Embedded VFS Roots

## System Constraints
You are a Principal Software Architect enforcing runtime sandboxing invariants for Bun 1.2 standalone compiled executables (`bun build --compile`). You must ensure that all code treats embedded virtual filesystem resources as strictly immutable, guarantees that user-controlled path parameters cannot break out of designated storage roots via relative traversal (`../`), and completely decouples host filesystem write targets from virtual `$bunfs` directories.

## Strict Guidelines
- Engineers MUST ALWAYS treat `import.meta.dir` and paths prefixed with `/$bunfs/` as strictly read-only virtual mounts.
- Engineers MUST NOT invoke mutative filesystem APIs (`Bun.write`, `node:fs/promises.writeFile`, `chmod`, `unlink`) against paths resolved within `import.meta.dir` in compiled standalone targets.
- Code MUST strictly validate and canonicalize any input-derived path using `path.resolve()` combined with `path.relative()` prefix boundaries before passing to `Bun.file()` or host filesystem APIs.
- Services MUST explicitly redirect dynamic runtime writes to isolated, verified host operating system directories (such as validated subdirectories of `os.tmpdir()` or specific application data paths), never falling back to execution binary roots.
- Components NEVER trust relative path traversals (`../`) originating from embedded asset roots to access the host operating system.

## Bad vs Good Implementations
### VFS Traversal and Illegal VFS Write in Standalone Binary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In a Bun 1.2 compiled binary, `import.meta.dir` resolves inside the embedded VFS (`/$bunfs/root/...`). Writing to this path causes unhandled runtime IO panics because the embedded filesystem is read-only. Furthermore, evaluating relative paths without boundary validation allows path traversal to escape the VFS and access arbitrary host files.
```typescript
import { resolve } from "node:path";

// ANTI-PATTERN: In Bun standalone binaries, import.meta.dir points to the virtual embedded filesystem ($bunfs/root).
// Attempting to resolve untrusted paths from it allows breakout to host root, or writing to VFS crashes at runtime.
export async function handleFileRequest(userRelativePath: string, payload?: string) {
  const targetPath = resolve(import.meta.dir, "public", userRelativePath);
  
  if (payload) {
    // Throws EROFS / EPERM: Bun's standalone VFS is immutable
    await Bun.write(targetPath, payload);
    return { success: true };
  }

  // Potential path breakout: userRelativePath of "../../../../etc/passwd" leaves VFS to host
  const file = Bun.file(targetPath);
  return await file.text();
}
```

#### Production Standard (Correct)
> **Standard**: Separates the read-only embedded VFS assets from mutable host filesystem state. Employs a strict containment assertion (`assertPathContained`) using `relative()` checks to prevent directory traversal breakout vectors, guaranteeing that writes only touch designated host directories and embedded reads cannot escape the virtual mount.
```typescript
import { resolve, relative, normalize } from "node:path";
import { tmpdir } from "node:os";
import { realpathSync } from "node:fs";

const VFS_ASSET_ROOT = resolve(import.meta.dir, "public");
const HOST_WRITABLE_ROOT = resolve(process.env.APP_DATA_DIR ?? tmpdir(), "app-sandbox");

function assertPathContained(basePath: string, targetPath: string): string {
  const canonicalBase = normalize(basePath);
  const resolvedTarget = resolve(canonicalBase, targetPath);
  const rel = relative(canonicalBase, resolvedTarget);

  if (rel.startsWith("..") || resolve(canonicalBase, rel) !== resolvedTarget) {
    throw new Error("Security Exception: Path traversal out of sandbox boundary.");
  }
  return resolvedTarget;
}

export async function handleFileRequest(userRelativePath: string, payload?: string) {
  if (payload) {
    // Host writes are strictly isolated to validated host storage directories
    const safeWritePath = assertPathContained(HOST_WRITABLE_ROOT, userRelativePath);
    await Bun.write(safeWritePath, payload);
    return { success: true };
  }

  // Embedded VFS reads are strictly contained within read-only asset boundaries
  const safeReadPath = assertPathContained(VFS_ASSET_ROOT, userRelativePath);
  const asset = Bun.file(safeReadPath);
  
  if (!(await asset.exists())) {
    throw new Error("File not found");
  }
  return await asset.text();
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Standalone Binary Embedded VFS Sandbox Enforcement

Bun 1.2 Standalone Binary Embedded VFS Sandbox Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict boundary isolation between Bun 1.2's read-only embedded Virtual File System ($bunfs) and the host operating system during standalone compiled binary execution. Prevents host filesystem breakout vulnerabilities and runtime panics caused by directory traversal out of embedded virtual roots or illegal write operations on bundled assets. 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: Unchecked Path Resolution and Mutative Operations Against Bun Embedded VFS Roots 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 DriftUnchecked Path Resolution and Mutative Operations Against Bun Embedded VFS RootsCritical
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 treat `import.meta.dir` and paths prefixed with `/$bunfs/` as strictly read-only virtual mounts.

Engineers MUST ALWAYS treat `import.meta.dir` and paths prefixed with `/$bunfs/` as strictly read-only virtual mounts.

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 invoke mutative filesystem APIs (`Bun.write`, `node

Engineers MUST NOT invoke mutative filesystem APIs (`Bun.write`, `node:fs/promises.writeFile`, `chmod`, `unlink`) against paths resolved within `import.meta.dir` in compiled standalone targets.

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 strictly validate and canonicalize any input-derived path using `path.resolve()` combined with `path.relative()` prefix boundaries before passing to `Bun.file()` or host filesystem APIs.

Code MUST strictly validate and canonicalize any input-derived path using `path.resolve()` combined with `path.relative()` prefix boundaries before passing to `Bun.file()` or host filesystem APIs.

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 explicitly redirect dynamic runtime writes to isolated, verified host operating system directories (such as validated subdirectories of `os.tmpdir()` or specific application data paths), never falling back to execution binary roots.

Services MUST explicitly redirect dynamic runtime writes to isolated, verified host operating system directories (such as validated subdirectories of `os.tmpdir()` or specific application data paths), never falling back to execution binary roots.

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 trust relative path traversals (`../`) originating from embedded asset roots to access the host operating system.

Components NEVER trust relative path traversals (`../`) originating from embedded asset roots to access the host operating system.

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 Binary Embedded VFS Sandbox Enforcement critical for AI coding assistants?

Enforces strict boundary isolation between Bun 1.2's read-only embedded Virtual File System ($bunfs) and the host operating system during standalone compiled binary execution. Prevents host filesystem breakout vulnerabilities and runtime panics caused by directory traversal out of embedded virtual roots or illegal write operations on bundled assets. 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 (Unchecked Path Resolution and Mutative Operations Against Bun Embedded VFS Roots) 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