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

Bun 1.2 Standalone Executable VFS Boundary Isolation and Asset Immutability Guardrail

Protects Bun 1.2 standalone compiled executables against arbitrary virtual filesystem (VFS) traversal, host filesystem escapes, and runtime panics caused by attempted mutations on embedded assets. Mandates strict boundary verification between the read-only embedded VFS (bunfs) and writable host storage.

Prohibited Anti-Pattern: Unchecked Path Resolution Across Bun Virtual File System (bunfs) Leading to Host Escapes or Unhandled VFS Mutation Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Standalone Executable VFS Boundary Isolation and Asset Immutability Guardrail - Protects Bun 1.2 standalone compiled executables against arbitrary virtual filesystem (VFS) traversal, host filesystem escapes, and runtime panics caused by attempted mutations on embedded assets. Mandates strict boundary verification between the read-only embedded VFS (bunfs) and writable host storage.
globs: src/**/*.{ts,tsx,js,jsx}, scripts/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-standalone-vfs-boundary-guardrail"
---

# Bun 1.2 Standalone Executable VFS Boundary Isolation and Asset Immutability Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unchecked Path Resolution Across Bun Virtual File System (bunfs) Leading to Host Escapes or Unhandled VFS Mutation Panics

## System Constraints
You are a Principal Systems and Security Architect enforcing runtime file-system isolation in Bun 1.2 compiled single-binary executables. When Bun compiles into a standalone binary (`bun build --compile`), bundled modules and embedded assets reside in a virtual, immutable filesystem namespace (`/$bunfs/root/` or virtual drive mounts). You must prevent arbitrary path traversal out of the VFS boundary into host filesystems, prevent untrusted user inputs from traversing VFS boundaries, and block all mutation or write operations directed at virtual asset namespaces.

## Strict Guidelines
- Engineers MUST ALWAYS isolate writable host directories from read-only embedded virtual filesystem assets by establishing explicit canonical root boundaries.
- Engineers MUST NOT use unvalidated relative paths with `import.meta.dir` or `import.meta.url` for dynamic runtime file writes, as standalone binaries execute from an immutable embedded VFS mount.
- Code MUST strictly validate and normalize paths using `path.resolve` and verify that normalized paths start with the intended root boundary before invoking `Bun.file()` or `node:fs` methods.
- Services MUST reject write operations (`Bun.write`, `fs.promises.writeFile`) targeting paths containing virtual system prefixes (e.g., `/$bunfs/` or embedded bundle scopes).
- Components NEVER expose raw static file serving endpoints without strict sandboxing checks that verify the resolved path remains wholly within the embedded asset directory.

## Bad vs Good Implementations
### VFS Asset Resolution and Path Traversal Boundary Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In a Bun 1.2 compiled executable, `import.meta.dir` points to an immutable virtual file path (`/$bunfs/...`). Joining untrusted user input without canonical boundary verification allows traversal outside the asset subtree or into the host OS. Furthermore, calling `Bun.write` against `import.meta.dir` triggers runtime panics because the embedded VFS is strictly read-only.
```typescript
import { join } from 'path';

// Flaw: Unchecked path joining permits '../' escapes out of VFS into host filesystem,
// and attempting to write user data relative to import.meta.dir panics inside a compiled binary.
export async function serveEmbeddedAsset(userInputPath: string) {
  const assetPath = join(import.meta.dir, 'public', userInputPath);
  return Bun.file(assetPath);
}

export async function saveUserUpload(filename: string, data: Buffer) {
  // In a Bun compiled binary, import.meta.dir is read-only VFS (/$bunfs/root/...)
  // Writing here results in an unhandled EROFS / VFS mutation panic
  const targetPath = join(import.meta.dir, 'uploads', filename);
  await Bun.write(targetPath, data);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly separates embedded read-only VFS assets from writable host storage. Resolves and checks canonical path prefixes to eliminate directory traversal escapes, ensures files exist before access, and blocks writes targeting virtual `bunfs` namespaces.
```typescript
import { resolve, normalize } from 'node:path';
import { tmpdir } from 'node:os';

const EMBEDDED_ASSET_ROOT = resolve(import.meta.dir, 'public');
const HOST_WRITABLE_ROOT = resolve(process.env.APP_DATA_DIR ?? tmpdir(), 'app-storage');

export async function serveEmbeddedAsset(userInputPath: string): Promise<Response> {
  const sanitized = normalize(userInputPath).replace(/^(\/|\\)+/, '');
  const resolvedPath = resolve(EMBEDDED_ASSET_ROOT, sanitized);

  // Boundary check: Enforce that path strictly remains within VFS asset root
  if (!resolvedPath.startsWith(EMBEDDED_ASSET_ROOT)) {
    return new Response('Access Denied: VFS Boundary Violation', { status: 403 });
  }

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

  return new Response(file);
}

export async function saveUserUpload(filename: string, data: Uint8Array): Promise<string> {
  const sanitized = normalize(filename).replace(/^(\/|\\)+/, '');
  const targetPath = resolve(HOST_WRITABLE_ROOT, sanitized);

  // Boundary check: Ensure write targets host storage and never attempts VFS mutation
  if (!targetPath.startsWith(HOST_WRITABLE_ROOT) || targetPath.includes('$bunfs')) {
    throw new Error('Security Error: Invalid host storage path');
  }

  await Bun.write(targetPath, data);
  return targetPath;
}
```

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 Boundary Isolation and Asset Immutability Guardrail

Bun 1.2 Standalone Executable VFS Boundary Isolation and Asset Immutability Guardrail defines an industrial-grade behavioral standard for devops engineering. Protects Bun 1.2 standalone compiled executables against arbitrary virtual filesystem (VFS) traversal, host filesystem escapes, and runtime panics caused by attempted mutations on embedded assets. Mandates strict boundary verification between the read-only embedded VFS (bunfs) and writable host storage. 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 Across Bun Virtual File System (bunfs) Leading to Host Escapes or Unhandled VFS Mutation Panics 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 Across Bun Virtual File System (bunfs) Leading to Host Escapes or Unhandled VFS Mutation PanicsCritical
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 isolate writable host directories from read-only embedded virtual filesystem assets by establishing explicit canonical root boundaries.

Engineers MUST ALWAYS isolate writable host directories from read-only embedded virtual filesystem assets by establishing explicit canonical root boundaries.

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 use unvalidated relative paths with `import.meta.dir` or `import.meta.url` for dynamic runtime file writes, as standalone binaries execute from an immutable embedded VFS mount.

Engineers MUST NOT use unvalidated relative paths with `import.meta.dir` or `import.meta.url` for dynamic runtime file writes, as standalone binaries execute from an immutable embedded VFS mount.

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 normalize paths using `path.resolve` and verify that normalized paths start with the intended root boundary before invoking `Bun.file()` or `node

Code MUST strictly validate and normalize paths using `path.resolve` and verify that normalized paths start with the intended root boundary before invoking `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 write operations (`Bun.write`, `fs.promises.writeFile`) targeting paths containing virtual system prefixes (e.g., `/$bunfs/` or embedded bundle scopes).

Services MUST reject write operations (`Bun.write`, `fs.promises.writeFile`) targeting paths containing virtual system prefixes (e.g., `/$bunfs/` or embedded bundle scopes).

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 raw static file serving endpoints without strict sandboxing checks that verify the resolved path remains wholly within the embedded asset directory.

Components NEVER expose raw static file serving endpoints without strict sandboxing checks that verify the resolved path remains wholly within the embedded asset 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.
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 Boundary Isolation and Asset Immutability Guardrail critical for AI coding assistants?

Protects Bun 1.2 standalone compiled executables against arbitrary virtual filesystem (VFS) traversal, host filesystem escapes, and runtime panics caused by attempted mutations on embedded assets. Mandates strict boundary verification between the read-only embedded VFS (bunfs) and writable host storage. 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 Across Bun Virtual File System (bunfs) Leading to Host Escapes or Unhandled VFS Mutation Panics) 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