or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# sudo-prompt

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: sudo-prompt

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install sudo-prompt`

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

ES6/TypeScript:

18

19

```javascript

20

import * as sudo from 'sudo-prompt';

21

```

22

23

## Basic Usage

24

25

```javascript

26

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

27

28

const options = {

29

name: 'MyApp',

30

icns: '/path/to/icon.icns', // macOS only

31

env: { 'MY_VAR': 'value' }

32

};

33

34

sudo.exec('echo hello', options, (error, stdout, stderr) => {

35

if (error) throw error;

36

console.log('stdout: ' + stdout);

37

});

38

```

39

40

## Capabilities

41

42

### Command Execution

43

44

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

45

46

```javascript { .api }

47

/**

48

* Execute a command using sudo with OS native authentication dialog

49

* @param {string} command - The command to execute (must not start with "sudo")

50

* @param {object|function} [options] - Configuration options object, or callback function

51

* @param {string} [options.name] - Application name for dialog (max 70 chars, alphanumeric + spaces)

52

* @param {string} [options.icns] - Path to icon file (macOS only, .icns format)

53

* @param {object} [options.env] - Environment variables to set

54

* @param {function} [callback] - Callback function (error, stdout, stderr) => void

55

* @returns {void}

56

*/

57

function exec(command, options, callback);

58

59

// Alternative signatures:

60

function exec(command, callback);

61

function exec(command, options);

62

```

63

64

**Usage Examples:**

65

66

```javascript

67

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

68

69

// Basic usage with callback

70

sudo.exec('ls /root', (error, stdout, stderr) => {

71

if (error) throw error;

72

console.log(stdout);

73

});

74

75

// With options

76

const options = {

77

name: 'File Manager',

78

icns: '/Applications/MyApp.app/Contents/Resources/app.icns'

79

};

80

81

sudo.exec('mkdir /usr/local/myapp', options, (error, stdout, stderr) => {

82

if (error) {

83

console.error('Failed to create directory:', error.message);

84

return;

85

}

86

console.log('Directory created successfully');

87

});

88

89

// With environment variables

90

sudo.exec('echo $MY_CUSTOM_VAR', {

91

name: 'Environment Test',

92

env: { 'MY_CUSTOM_VAR': 'hello world' }

93

}, (error, stdout, stderr) => {

94

console.log('Environment variable output:', stdout.trim());

95

});

96

97

// Fire-and-forget (no callback)

98

sudo.exec('touch /tmp/sudo-test', { name: 'Test App' });

99

```

100

101

### Options Configuration

102

103

Configuration object for customizing the sudo execution behavior.

104

105

```javascript { .api }

106

/**

107

* @typedef {Object} Options

108

* @property {string} [name] - Application name displayed in the authentication dialog

109

* @property {string} [icns] - Path to icon file for the dialog (macOS only, .icns format)

110

* @property {Object.<string, string>} [env] - Environment variables to set for command execution

111

*/

112

```

113

114

**Validation Rules:**

115

116

- `name`: Must be alphanumeric with spaces allowed, maximum 70 characters. Defaults to `process.title` if valid

117

- `icns`: Must be a non-empty string pointing to a valid .icns file (macOS only)

118

- `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

119

120

### Error Handling

121

122

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

123

124

```javascript { .api }

125

/**

126

* Callback function signature for sudo.exec

127

* @callback CallbackFunction

128

* @param {Error|undefined} error - Error object or undefined if successful

129

* @param {string|Buffer|undefined} stdout - Command output or undefined

130

* @param {string|Buffer|undefined} stderr - Command error output or undefined

131

*/

132

```

133

134

**Common Errors:**

135

136

- `"User did not grant permission."` - User denied authentication

137

- `"No polkit authentication agent found."` - Linux polkit agent missing

138

- `"Platform not yet supported."` - Unsupported operating system

139

- `"Command should not be prefixed with \"sudo\"."` - Invalid command format

140

- `"Wrong number of arguments."` - Invalid function arguments (must be 1-3 arguments)

141

- `"Command should be a string."` - Command parameter is not a string

142

- `"Expected options or callback."` - Second argument is neither options object nor callback function

143

- `"Expected options to be an object."` - Options parameter is not an object

144

- `"Expected callback to be a function."` - Callback parameter is not a function

145

- `"process.title cannot be used as a valid name."` - Default process.title is invalid

146

- `"options.name must be alphanumeric only (spaces are allowed) and <= 70 characters."` - Invalid name format

147

- `"options.icns must be a string if provided."` - icns is not a string

148

- `"options.icns must not be empty if provided."` - icns is empty string

149

- `"options.env must be an object if provided."` - env is not an object

150

- `"options.env must not be empty if provided."` - env is empty object

151

- `"options.env environment variables must be strings."` - env contains non-string values

152

- `"options.env has an invalid environment variable name"` - env key doesn't match POSIX pattern

153

- `"options.env has an invalid environment variable value"` - env value contains newlines

154

155

**Error Handling Example:**

156

157

```javascript

158

sudo.exec('rm -rf /important/directory', { name: 'Cleanup Tool' }, (error, stdout, stderr) => {

159

if (error) {

160

switch (error.message) {

161

case 'User did not grant permission.':

162

console.log('User cancelled the operation');

163

break;

164

case 'No polkit authentication agent found.':

165

console.log('Please install a polkit authentication agent');

166

break;

167

default:

168

console.error('Command failed:', error.message);

169

if (error.code) {

170

console.error('Exit code:', error.code);

171

}

172

}

173

return;

174

}

175

176

console.log('Command completed successfully');

177

if (stdout) console.log('Output:', stdout);

178

if (stderr) console.log('Errors:', stderr);

179

});

180

```

181

182

## Platform-Specific Behavior

183

184

### macOS

185

- Uses temporary `.app` bundle with AppleScript for authentication

186

- Supports custom icons via `options.icns` (must be .icns format)

187

- Preserves current working directory and environment variables

188

189

### Linux

190

- Uses `pkexec` (preferred) or `kdesudo` for authentication

191

- Searches for binaries in: `/usr/bin/kdesudo`, `/usr/bin/pkexec`

192

- Icons not currently supported

193

- Preserves current working directory and environment variables

194

195

### Windows

196

- Uses PowerShell with User Account Control (UAC) for elevation

197

- Custom names and icons not currently supported

198

- Preserves current working directory and environment variables

199

200

## Key Features

201

202

- **Cross-platform**: Works on macOS, Linux, and Windows

203

- **Native dialogs**: Uses OS-specific authentication prompts

204

- **No dependencies**: Pure JavaScript with no external dependencies

205

- **No native bindings**: Doesn't require compilation or native modules

206

- **Working directory preservation**: Commands run in the same directory as the parent process

207

- **Environment variable support**: Pass custom environment variables to elevated commands

208

- **Concurrent execution**: Handles multiple simultaneous sudo requests appropriately

209

- **Error handling**: Provides detailed error messages and codes

210

211

## Important Notes

212

213

- Commands must **not** start with "sudo" - this is handled automatically

214

- Designed for **non-graphical terminal commands only** - never use for GUI applications

215

- Each execution may prompt for password depending on system `sudo` timestamp settings

216

- Unlike `child_process.exec()`, this function does **not** return a child process object

217

- Command output is limited to 128MB buffer size (134,217,728 bytes)

218

- For security, avoid logging or exposing the command parameters in production environments

219

- Working directory is preserved across all platforms

220

- Environment variables can be passed explicitly via `options.env`

221

- Multiple concurrent calls are supported but may result in multiple password prompts