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

Bun 1.2 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail

Enforces strict parameter escaping, execution timeouts, and bounded concurrency for Bun 1.2 subprocess scripting. Prohibits unescaped raw shell interpolations and unmetered parallel process spawns to eliminate command injection vulnerabilities, file descriptor exhaustion, and fork-bomb denial-of-service failures.

Prohibited Anti-Pattern: Unescaped Raw Template Interpolation Coupled with Unbounded Concurrency in Bun Shell Scripts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail - Enforces strict parameter escaping, execution timeouts, and bounded concurrency for Bun 1.2 subprocess scripting. Prohibits unescaped raw shell interpolations and unmetered parallel process spawns to eliminate command injection vulnerabilities, file descriptor exhaustion, and fork-bomb denial-of-service failures.
globs: scripts/**/*.{ts,js}, src/**/*.{ts,js}, ci/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-subprocess-shell-sandbox-guardrail"
---

# Bun 1.2 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unescaped Raw Template Interpolation Coupled with Unbounded Concurrency in Bun Shell Scripts

## System Constraints
You are a Principal Security and DevOps Architect enforcing Bun 1.2 subprocess execution invariants. Your goal is to eliminate shell injection vulnerabilities and systemic process-exhaustion failures in automation workloads.

Strictly mandate the following invariant rules:
1. Zero Raw String Interpolation: Bun's shell ($) automatically escapes tagged template literals. You MUST NOT use `$.raw` or string concatenation to insert dynamic inputs or user-supplied data into command invocations.
2. Bounded Concurrency: High-throughput batch processing MUST ALWAYS be constrained by strict concurrency limiters (e.g., p-limit or chunked iteration). Unbounded `Promise.all` calls over external processes are strictly forbidden to prevent fork bombs and FD exhaustion.
3. Mandatory Timeouts & Abort Signals: Every process invocation MUST declare an explicit execution ceiling via `AbortSignal.timeout()` or the `.timeout()` fluent modifier on Bun shell instances.
4. Error Resilience & Memory Discipline: Subprocess standard I/O streams MUST be drained or piped to `/dev/null` using `.quiet()` or explicit redirections to avoid buffer deadlocks and memory bloat on large outputs.

## Strict Guidelines
- Engineers MUST ALWAYS rely on native `bun.$` template literal parameterization, which automatically handles argument escaping and quoting.
- Engineers MUST NOT invoke `$.raw` or pass concatenated string arguments containing dynamic, untrusted, or multi-tenant parameters.
- Engineers MUST NOT spawn external child processes within unbounded arrays using `Promise.all` or `Promise.allSettled` without strict concurrency ceilings.
- Services MUST enforce strict execution deadlines on all subprocesses via `AbortSignal.timeout(ms)` or Bun's `.timeout()` execution modifier.
- Services MUST configure stdout/stderr buffering explicitly via `.quiet()`, `.text()`, or file descriptors to prevent unbounded memory growth on long-running worker tasks.
- Components NEVER execute raw intermediate shells (e.g., `sh -c`, `bash -c`, or `cmd.exe /c`) when invoking system binaries or automations in Bun scripts.

## Bad vs Good Implementations
### Dynamic Command Execution and Unbounded Batch Processing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using $.raw bypasses Bun's built-in parameter sanitizer, allowing command injection via shell metacharacters in targetHost or artifactTag. Additionally, firing unbounded processes across large task lists risks hitting system PID/FD limits, leading to process crashes or server-wide fork bombs.
```typescript
import { $ } from "bun";

interface DeploymentTask {
  targetHost: string;
  artifactTag: string;
}

export async function deployArtifactsUnsafe(tasks: DeploymentTask[]): Promise<void> {
  // VULNERABILITY 1: Unbounded concurrency leads to fork bomb / socket starvation
  await Promise.all(
    tasks.map(async (task) => {
      // VULNERABILITY 2: $.raw bypasses Bun's built-in escaping, exposing RCE via targetHost or artifactTag
      const commandStr = `ssh deploy@${task.targetHost} "docker pull registry.internal/${task.artifactTag}"`;
      
      // VULNERABILITY 3: No timeout or abort signal allows zombie processes to hang indefinitely
      await $.raw`${commandStr}`;
    })
  );
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation leverages Bun's native $ tag parser which safely escapes dynamic arguments, enforces a strict 30-second AbortSignal timeout, buffers output reliably with .quiet(), and throttles concurrent subprocesses with p-limit to protect system resources.
```typescript
import { $ } from "bun";
import pLimit from "p-limit";

interface DeploymentTask {
  targetHost: string;
  artifactTag: string;
}

const MAX_CONCURRENT_SPAWNS = 8;
const PROCESS_TIMEOUT_MS = 30_000;

export async function deployArtifactsSafe(tasks: readonly DeploymentTask[]): Promise<void> {
  const limit = pLimit(MAX_CONCURRENT_SPAWNS);

  // INVARIANT 1: Bound concurrency to prevent PID and FD exhaustion
  await Promise.all(
    tasks.map((task) =>
      limit(async () => {
        // INVARIANT 2: Enforce deterministic timeout via AbortSignal
        const signal = AbortSignal.timeout(PROCESS_TIMEOUT_MS);
        const remoteCommand = `docker pull registry.internal/${task.artifactTag}`;

        // INVARIANT 3: Native template literals are safely escaped by Bun's internal shell parser
        // INVARIANT 4: Standardize exit code handling and suppress uncontrolled buffer bloat with .quiet()
        const result = await $
          `ssh -o BatchMode=yes deploy@${task.targetHost} ${remoteCommand}`
          .quiet()
          .env({ ...process.env, LANG: "C.UTF-8" })
          .signal(signal)
          .nothrow();

        if (result.exitCode !== 0) {
          throw new Error(
            `Failed deploying ${task.artifactTag} to ${task.targetHost}: exit code ${result.exitCode}`
          );
        }
      })
    )
  );
}
```

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 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail

Bun 1.2 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict parameter escaping, execution timeouts, and bounded concurrency for Bun 1.2 subprocess scripting. Prohibits unescaped raw shell interpolations and unmetered parallel process spawns to eliminate command injection vulnerabilities, file descriptor exhaustion, and fork-bomb denial-of-service failures. 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: Unescaped Raw Template Interpolation Coupled with Unbounded Concurrency in Bun Shell Scripts 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 DriftUnescaped Raw Template Interpolation Coupled with Unbounded Concurrency in Bun Shell ScriptsCritical
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 rely on native `bun.$` template literal parameterization, which automatically handles argument escaping and quoting.

Engineers MUST ALWAYS rely on native `bun.$` template literal parameterization, which automatically handles argument escaping and quoting.

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 `$.raw` or pass concatenated string arguments containing dynamic, untrusted, or multi-tenant parameters.

Engineers MUST NOT invoke `$.raw` or pass concatenated string arguments containing dynamic, untrusted, or multi-tenant parameters.

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

Engineers MUST NOT spawn external child processes within unbounded arrays using `Promise.all` or `Promise.allSettled` without strict concurrency ceilings.

Engineers MUST NOT spawn external child processes within unbounded arrays using `Promise.all` or `Promise.allSettled` without strict concurrency ceilings.

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 enforce strict execution deadlines on all subprocesses via `AbortSignal.timeout(ms)` or Bun's `.timeout()` execution modifier.

Services MUST enforce strict execution deadlines on all subprocesses via `AbortSignal.timeout(ms)` or Bun's `.timeout()` execution modifier.

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

Services MUST configure stdout/stderr buffering explicitly via `.quiet()`, `.text()`, or file descriptors to prevent unbounded memory growth on long-running worker tasks.

Services MUST configure stdout/stderr buffering explicitly via `.quiet()`, `.text()`, or file descriptors to prevent unbounded memory growth on long-running worker tasks.

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.
6

Components NEVER execute raw intermediate shells (e.g., `sh -c`, `bash -c`, or `cmd.exe /c`) when invoking system binaries or automations in Bun scripts.

Components NEVER execute raw intermediate shells (e.g., `sh -c`, `bash -c`, or `cmd.exe /c`) when invoking system binaries or automations in Bun scripts.

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 Sandboxed Subprocess Shell and Fork-Bomb Protection Guardrail critical for AI coding assistants?

Enforces strict parameter escaping, execution timeouts, and bounded concurrency for Bun 1.2 subprocess scripting. Prohibits unescaped raw shell interpolations and unmetered parallel process spawns to eliminate command injection vulnerabilities, file descriptor exhaustion, and fork-bomb denial-of-service failures. 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 (Unescaped Raw Template Interpolation Coupled with Unbounded Concurrency in Bun Shell Scripts) 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