or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-sudo-prompt

Run a command using sudo, prompting the user with an OS dialog if necessary

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sudo-prompt@9.2.x

To install, run

npx @tessl/cli install tessl/npm-sudo-prompt@9.2.0

index.mddocs/

sudo-prompt

sudo-prompt is a cross-platform Node.js library that enables applications to execute terminal commands with elevated privileges (sudo) through native OS dialogs. It supports macOS, Linux, and Windows, automatically presenting the appropriate authentication dialog without requiring external dependencies or native bindings.

Package Information

  • Package Name: sudo-prompt
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install sudo-prompt

Core Imports

const sudo = require('sudo-prompt');

ES6/TypeScript:

import * as sudo from 'sudo-prompt';

Basic Usage

const sudo = require('sudo-prompt');

const options = {
  name: 'MyApp',
  icns: '/path/to/icon.icns', // macOS only
  env: { 'MY_VAR': 'value' }
};

sudo.exec('echo hello', options, (error, stdout, stderr) => {
  if (error) throw error;
  console.log('stdout: ' + stdout);
});

Capabilities

Command Execution

Executes a terminal command with elevated privileges using OS native authentication dialogs.

/**
 * Execute a command using sudo with OS native authentication dialog
 * @param {string} command - The command to execute (must not start with "sudo")
 * @param {object|function} [options] - Configuration options object, or callback function
 * @param {string} [options.name] - Application name for dialog (max 70 chars, alphanumeric + spaces)
 * @param {string} [options.icns] - Path to icon file (macOS only, .icns format)
 * @param {object} [options.env] - Environment variables to set
 * @param {function} [callback] - Callback function (error, stdout, stderr) => void
 * @returns {void}
 */
function exec(command, options, callback);

// Alternative signatures:
function exec(command, callback);
function exec(command, options);

Usage Examples:

const sudo = require('sudo-prompt');

// Basic usage with callback
sudo.exec('ls /root', (error, stdout, stderr) => {
  if (error) throw error;
  console.log(stdout);
});

// With options
const options = {
  name: 'File Manager',
  icns: '/Applications/MyApp.app/Contents/Resources/app.icns'
};

sudo.exec('mkdir /usr/local/myapp', options, (error, stdout, stderr) => {
  if (error) {
    console.error('Failed to create directory:', error.message);
    return;
  }
  console.log('Directory created successfully');
});

// With environment variables
sudo.exec('echo $MY_CUSTOM_VAR', {
  name: 'Environment Test',
  env: { 'MY_CUSTOM_VAR': 'hello world' }
}, (error, stdout, stderr) => {
  console.log('Environment variable output:', stdout.trim());
});

// Fire-and-forget (no callback)
sudo.exec('touch /tmp/sudo-test', { name: 'Test App' });

Options Configuration

Configuration object for customizing the sudo execution behavior.

/**
 * @typedef {Object} Options
 * @property {string} [name] - Application name displayed in the authentication dialog
 * @property {string} [icns] - Path to icon file for the dialog (macOS only, .icns format)
 * @property {Object.<string, string>} [env] - Environment variables to set for command execution
 */

Validation Rules:

  • name: Must be alphanumeric with spaces allowed, maximum 70 characters. Defaults to process.title if valid
  • icns: Must be a non-empty string pointing to a valid .icns file (macOS only)
  • env: Object with string keys and values, keys must be valid POSIX environment variable names (start with letter/underscore, contain only letters/digits/underscores), values cannot contain newlines

Error Handling

The callback function receives specific error types for different failure conditions.

/**
 * Callback function signature for sudo.exec
 * @callback CallbackFunction
 * @param {Error|undefined} error - Error object or undefined if successful
 * @param {string|Buffer|undefined} stdout - Command output or undefined
 * @param {string|Buffer|undefined} stderr - Command error output or undefined  
 */

Common Errors:

  • "User did not grant permission." - User denied authentication
  • "No polkit authentication agent found." - Linux polkit agent missing
  • "Platform not yet supported." - Unsupported operating system
  • "Command should not be prefixed with \"sudo\"." - Invalid command format
  • "Wrong number of arguments." - Invalid function arguments (must be 1-3 arguments)
  • "Command should be a string." - Command parameter is not a string
  • "Expected options or callback." - Second argument is neither options object nor callback function
  • "Expected options to be an object." - Options parameter is not an object
  • "Expected callback to be a function." - Callback parameter is not a function
  • "process.title cannot be used as a valid name." - Default process.title is invalid
  • "options.name must be alphanumeric only (spaces are allowed) and <= 70 characters." - Invalid name format
  • "options.icns must be a string if provided." - icns is not a string
  • "options.icns must not be empty if provided." - icns is empty string
  • "options.env must be an object if provided." - env is not an object
  • "options.env must not be empty if provided." - env is empty object
  • "options.env environment variables must be strings." - env contains non-string values
  • "options.env has an invalid environment variable name" - env key doesn't match POSIX pattern
  • "options.env has an invalid environment variable value" - env value contains newlines

Error Handling Example:

sudo.exec('rm -rf /important/directory', { name: 'Cleanup Tool' }, (error, stdout, stderr) => {
  if (error) {
    switch (error.message) {
      case 'User did not grant permission.':
        console.log('User cancelled the operation');
        break;
      case 'No polkit authentication agent found.':
        console.log('Please install a polkit authentication agent');
        break;
      default:
        console.error('Command failed:', error.message);
        if (error.code) {
          console.error('Exit code:', error.code);
        }
    }
    return;
  }
  
  console.log('Command completed successfully');
  if (stdout) console.log('Output:', stdout);
  if (stderr) console.log('Errors:', stderr);
});

Platform-Specific Behavior

macOS

  • Uses temporary .app bundle with AppleScript for authentication
  • Supports custom icons via options.icns (must be .icns format)
  • Preserves current working directory and environment variables

Linux

  • Uses pkexec (preferred) or kdesudo for authentication
  • Searches for binaries in: /usr/bin/kdesudo, /usr/bin/pkexec
  • Icons not currently supported
  • Preserves current working directory and environment variables

Windows

  • Uses PowerShell with User Account Control (UAC) for elevation
  • Custom names and icons not currently supported
  • Preserves current working directory and environment variables

Key Features

  • Cross-platform: Works on macOS, Linux, and Windows
  • Native dialogs: Uses OS-specific authentication prompts
  • No dependencies: Pure JavaScript with no external dependencies
  • No native bindings: Doesn't require compilation or native modules
  • Working directory preservation: Commands run in the same directory as the parent process
  • Environment variable support: Pass custom environment variables to elevated commands
  • Concurrent execution: Handles multiple simultaneous sudo requests appropriately
  • Error handling: Provides detailed error messages and codes

Important Notes

  • Commands must not start with "sudo" - this is handled automatically
  • Designed for non-graphical terminal commands only - never use for GUI applications
  • Each execution may prompt for password depending on system sudo timestamp settings
  • Unlike child_process.exec(), this function does not return a child process object
  • Command output is limited to 128MB buffer size (134,217,728 bytes)
  • For security, avoid logging or exposing the command parameters in production environments
  • Working directory is preserved across all platforms
  • Environment variables can be passed explicitly via options.env
  • Multiple concurrent calls are supported but may result in multiple password prompts