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

Bun 1.2 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox

Enforces strict subprocess execution boundaries in Bun 1.2+ by leveraging the native shell AST tagged-template parser and prohibiting unsafe raw interpolations, string concatenations, and intermediate shell passes. Guarantees deterministic parameter escaping, explicit execution environments, and bounded input sanitization when invoking external system CLI binaries.

Prohibited Anti-Pattern: Dynamic String Concatenation and Unsafe Raw String Injections in Bun Shell Subprocesses

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox - Enforces strict subprocess execution boundaries in Bun 1.2+ by leveraging the native shell AST tagged-template parser and prohibiting unsafe raw interpolations, string concatenations, and intermediate shell passes. Guarantees deterministic parameter escaping, explicit execution environments, and bounded input sanitization when invoking external system CLI binaries.
globs: src/**/*.{ts,tsx}, scripts/**/*.{ts,tsx}, infra/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-shell-subprocess-injection-sandbox-guardrail"
---

# Bun 1.2 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic String Concatenation and Unsafe Raw String Injections in Bun Shell Subprocesses

## System Constraints
You are a Principal Platform Security Architect and Runtime Engineer enforcing the Bun 1.2 Shell API Subprocess Deserialization Sandbox Guardrail. You must prohibit string-interpolated shell commands, manual shell escaping hacks, and unauthorized $.raw() invocations. Mandate direct argument parameterization through Bun's tagged-template shell compiler ($), explicit cwd/env isolation, strict non-zero exit handling, and schema validation on deserialized inputs before subprocess dispatch.

## Strict Guidelines
- Engineers MUST ALWAYS invoke Bun Shell via native tagged template literals (`await $`binary ${arg}``) to guarantee that inputs are parsed into discrete argv tokens by Bun's AST compiler rather than an ambient shell.
- Engineers MUST NOT utilize `$.raw()` with untrusted, externally sourced, or deserialized user inputs; `$.raw()` is strictly reserved for static, build-time validated flags.
- Code MUST define deterministic subprocess sandboxes by explicitly configuring `.cwd()`, clearing or declaring explicit environment variables via `.env()`, and scoping execution limits.
- Services MUST validate and exhaustively match dynamic subcommands or CLI binary names against an immutable allowlist prior to dispatching process execution.
- Components NEVER pipe unvalidated deserialized user payloads directly into privileged CLI utilities without prior schema validation, size limits, and stream backpressure handling.

## Bad vs Good Implementations
### Subprocess Argument Interpolation & Sandbox Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Concatenating user input into a string before passing to $.raw() or combining dynamic directory navigation via 'cd &&' bypasses Bun's AST-level argument isolation, enabling remote code execution if userSearchPattern contains characters like `" || rm -rf / #`.
```typescript
import { $ } from "bun";

// CRITICAL VULNERABILITY: Pre-concatenating user input or using $.raw() bypasses the Bun Shell AST parser,
// exposing the host process to command injection via shell metacharacters (; | && `).
export async function queryGitLog(userRepoPath: string, userSearchPattern: string): Promise<string> {
  const unescapedCommand = `git log --grep="${userSearchPattern}"`;
  // Insecure raw execution and dynamic directory traversal
  const result = await $`cd ${userRepoPath} && ${$.raw(unescapedCommand)}`;
  return result.text();
}
```

#### Production Standard (Correct)
> **Standard**: Validates inputs using a strict schema, prevents directory traversal using path resolution against a safe root, confines process context with `.cwd()` and scoped `.env()`, and allows Bun's tagged template AST to treat `searchPattern` as a literal argument value without shell expansion.
```typescript
import { $ } from "bun";
import { resolve } from "node:path";
import { z } from "zod";

const SearchInputSchema = z.object({
  repoPath: z.string().regex(/^[a-zA-Z0-9_\-\./]+$/),
  searchPattern: z.string().max(256)
});

export async function queryGitLog(rawRepoPath: string, rawSearchPattern: string): Promise<string> {
  const { repoPath, searchPattern } = SearchInputSchema.parse({
    repoPath: rawRepoPath,
    searchPattern: rawSearchPattern
  });

  const safeCwd = resolve("/var/repos/sandbox", repoPath);

  // SAFE: Bound parameters are automatically escaped as discrete AST tokens.
  // Sandboxed via .cwd() and isolated environment variables without ambient shell leakage.
  const result = await $`git log --grep=${searchPattern}`
    .cwd(safeCwd)
    .env({ PATH: "/usr/bin:/bin", GIT_CONFIG_NOSYSTEM: "1" })
    .quiet();

  return result.text();
}
```

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 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox

Bun 1.2 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox defines an industrial-grade behavioral standard for backend engineering. Enforces strict subprocess execution boundaries in Bun 1.2+ by leveraging the native shell AST tagged-template parser and prohibiting unsafe raw interpolations, string concatenations, and intermediate shell passes. Guarantees deterministic parameter escaping, explicit execution environments, and bounded input sanitization when invoking external system CLI binaries. 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: Dynamic String Concatenation and Unsafe Raw String Injections in Bun Shell Subprocesses 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 DriftDynamic String Concatenation and Unsafe Raw String Injections in Bun Shell SubprocessesCritical
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 invoke Bun Shell via native tagged template literals (`await $`binary ${arg}``) to guarantee that inputs are parsed into discrete argv tokens by Bun's AST compiler rather than an ambient shell.

Engineers MUST ALWAYS invoke Bun Shell via native tagged template literals (`await $`binary ${arg}``) to guarantee that inputs are parsed into discrete argv tokens by Bun's AST compiler rather than an ambient shell.

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 utilize `$.raw()` with untrusted, externally sourced, or deserialized user inputs

Engineers MUST NOT utilize `$.raw()` with untrusted, externally sourced, or deserialized user inputs; `$.raw()` is strictly reserved for static, build-time validated flags.

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 define deterministic subprocess sandboxes by explicitly configuring `.cwd()`, clearing or declaring explicit environment variables via `.env()`, and scoping execution limits.

Code MUST define deterministic subprocess sandboxes by explicitly configuring `.cwd()`, clearing or declaring explicit environment variables via `.env()`, and scoping execution limits.

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 validate and exhaustively match dynamic subcommands or CLI binary names against an immutable allowlist prior to dispatching process execution.

Services MUST validate and exhaustively match dynamic subcommands or CLI binary names against an immutable allowlist prior to dispatching process execution.

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 pipe unvalidated deserialized user payloads directly into privileged CLI utilities without prior schema validation, size limits, and stream backpressure handling.

Components NEVER pipe unvalidated deserialized user payloads directly into privileged CLI utilities without prior schema validation, size limits, and stream backpressure handling.

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 Shell API Tagged-Template Sanitization and Subprocess Deserialization Sandbox critical for AI coding assistants?

Enforces strict subprocess execution boundaries in Bun 1.2+ by leveraging the native shell AST tagged-template parser and prohibiting unsafe raw interpolations, string concatenations, and intermediate shell passes. Guarantees deterministic parameter escaping, explicit execution environments, and bounded input sanitization when invoking external system CLI binaries. 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 (Dynamic String Concatenation and Unsafe Raw String Injections in Bun Shell Subprocesses) 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