GuardAPI Logo
GuardAPI

Fix Command Injection in Blitz.js

Command injection in Blitz.js RPC mutations is a critical failure. When you pass unsanitized user input directly into a shell-executing function, you grant remote attackers full OS-level access. In the Blitz/Next.js ecosystem, this usually happens in server-side resolvers where developers incorrectly handle file system operations or external CLI tools.

The Vulnerable Pattern

import { exec } from 'child_process'
import { resolver } from '@blitzjs/rpc'

export default resolver.pipe(async ({ filename }) => { // CRITICAL: User-controlled ‘filename’ is concatenated into a shell command // An attacker can send: ‘file.txt; rm -rf /’ exec(ls -l ./uploads/${filename}, (err, stdout) => { if (err) console.error(err) console.log(stdout) }) return { success: true } })

The Secure Implementation

The vulnerability lies in 'exec', which spawns a shell (/bin/sh or cmd.exe) to execute the string. This allows shell metacharacters (e.g., ;, &, |) to trigger secondary commands. The fix implements two layers of defense: First, 'path.basename' strips directory traversal attempts. Second, 'spawn' is used without the 'shell: true' option. This treats the arguments as a discrete array passed directly to the executable's argv, ensuring the OS treats the input as data, not as executable code.

import { spawn } from 'child_process'
import { resolver } from '@blitzjs/rpc'
import path from 'path'

export default resolver.pipe(async ({ filename }) => { // 1. Sanitize: Extract only the base name to prevent path traversal const safeName = path.basename(filename) const uploadDir = path.join(process.cwd(), ‘uploads’)

// 2. Use spawn: Arguments are passed as an array, bypassing shell interpretation return new Promise((resolve, reject) => { const child = spawn(‘ls’, [‘-l’, path.join(uploadDir, safeName)])

let output = ''
child.stdout.on('data', (data) => (output += data))
child.on('close', (code) => {
  code === 0 ? resolve({ output }) : reject(new Error('Process failed'))
})

}) })

System Alert • ID: 2421
Target: Blitz.js API
Potential Vulnerability

Your Blitz.js API might be exposed to Command Injection

74% of Blitz.js apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.