Skip to content
Shell
1010 B
Raw Blame
/**
 * Safe command execution utility
 * Uses execFile instead of exec to prevent shell injection
 */

import { execFile } from 'child_process';
import { promisify } from 'util';

const execFileAsync = promisify(execFile);

export interface ExecResult {
  stdout: string;
  stderr: string;
  status: 'success' | 'error';
  code?: number;
}

/**
 * Execute a command safely without shell interpolation
 */
export async function execFileNoThrow(
  command: string,
  args: string[],
  options: { maxBuffer?: number; timeout?: number } = {}
): Promise<ExecResult> {
  try {
    const { stdout, stderr } = await execFileAsync(command, args, {
      maxBuffer: options.maxBuffer || 10 * 1024 * 1024, // 10MB
      timeout: options.timeout || 30000, // 30s
    });

    return {
      stdout,
      stderr,
      status: 'success',
    };
  } catch (error: any) {
    return {
      stdout: error.stdout || '',
      stderr: error.stderr || error.message,
      status: 'error',
      code: error.code,
    };
  }
}