How ShellSupport Executes Commands and Handles Privileges in vorssaint-utils

ShellSupport in vorssaint-utils provides three distinct APIs—Shell.run, AdminShell.runSync, and Sudoers.pmsetDisableSleep—that execute external binaries with bounded timeouts, elevate privileges via macOS SecurityAgent dialogs, and perform password-less sudo operations through dedicated NOPASSWD rules.

The vorssaint-utils repository centralizes all command-line interactions inside the Shell Support module. Located at Sources/Vorssaint/Services/ShellSupport.swift, this Swift implementation abstracts subprocess management, privilege elevation, and safety boundaries for a menu-bar agent that cannot afford to hang or leak resources.

Standard Command Execution with Shell.run

The Shell enum provides the foundation for running external binaries through the run(_ path: String, _ args: [String] …) method. This API delegates to BoundedProcessRunner.run to enforce strict resource limits on every subprocess.

Key implementation details in ShellSupport.swift (lines 14-23):

  • Default timeout of 5 seconds prevents indefinite hangs
  • Maximum output size of 4 MiB caps memory consumption
  • Returns a tuple (status: Int32, output: String) for stdout capture and exit-code inspection
// Execute pmset and capture system power settings
let (status, output) = Shell.run("/usr/bin/pmset", ["-g"])
if status == 0 {
    print("Power settings:\n\(output)")
}

Privileged Execution with AdminShell

When a command requires administrator privileges, AdminShell.runSync(_ command: String, prompt: String) triggers the macOS SecurityAgent dialog rather than prompting for a terminal password.

AppleScript-Based Elevation

The method constructs an AppleScript command (do shell script … with administrator privileges) via the internal appleScriptSource helper (lines 11-13). It then executes this script using osascript (line 72) or, for signed-updater contexts, runs it directly via AppleScriptRunner.run (lines 74-80) to preserve code-signing identity.

Prompt Serialization and UI Safety

To prevent stacked password dialogs, the implementation uses a global NSLock named promptLock and a Boolean flag prompting (lines 36-39). If a second privileged request arrives while a dialog is active, the API returns false immediately, signaling "permission not granted" without blocking.

Because vorssaint-utils runs as a menu-bar agent (LSUIElement), bringAppToFront() (lines 66-69) explicitly activates the application with NSApp.activate before showing the password prompt, ensuring the dialog appears above the current front-most window.

// Request admin rights to modify system sleep behavior
AdminShell.runSync("pmset disablesleep 1",
                  prompt: "Vorssaint needs permission to prevent sleep while the lid is closed.") { granted in
    if granted {
        print("Administrative privilege granted")
    }
}

Password-Less Sudo Operations

For frequent toggling of sleep settings without user interruption, the Sudoers enum implements pmsetDisableSleep(_ on: Bool). This method executes sudo -n (non-interactive) against a dedicated NOPASSWD rule installed at /etc/sudoers.d/vorssaint-clamshell (lines 27-34).

The workflow relies on Shell.run to invoke sudo -n pmset disablesleep (line 202), allowing the "clamshell" closed-lid mode to switch instantly after the one-time sudo rule setup.

// Toggle sleep prevention without password prompt
let success = Sudoers.pmsetDisableSleep(true)  // true disables sleep
print("Password-less toggle succeeded: \(success)")

Safety Mechanisms and Process Bounding

All subprocesses route through BoundedProcessRunner, guaranteeing that misbehaving commands cannot freeze the menu-bar agent or exhaust system memory. The 5-second timeout and 4 MiB output cap (lines 14-23) apply universally to standard shell calls, creating a fail-safe boundary for operations like parsing ps output or querying pmset.

UI Handling and Front-Most Guarantees

Lines 98-108 implement bringAppToFront() to solve a critical UX issue: menu-bar agents typically lack front-most status. By invoking NSApp.activate before privilege requests, ShellSupport ensures the SecurityAgent password dialog surfaces above the user's current application window, preventing the dialog from being buried or missed.

Summary

  • Three-tier API design: Shell.run for standard binaries, AdminShell.runSync for elevation dialogs, and Sudoers.pmsetDisableSleep for automated sudo operations
  • Resource safety: BoundedProcessRunner enforces 5-second timeouts and 4 MiB output limits on every subprocess
  • Privilege serialization: promptLock and prompting Boolean prevent concurrent password dialogs from stacking
  • UI activation: bringAppToFront() ensures SecurityAgent prompts appear above the current window for menu-bar agents
  • Password-less workflow: Dedicated /etc/sudoers.d/vorssaint-clamshell rule enables non-interactive sudo -n calls for sleep management

Frequently Asked Questions

How does vorssaint-utils prevent shell commands from hanging indefinitely?

According to the source code in Sources/Vorssaint/Services/ShellSupport.swift, every command routes through BoundedProcessRunner.run which enforces a default timeout of 5 seconds and a maximum output buffer of 4 MiB. These hard limits ensure that a frozen subprocess cannot block the main menu-bar agent or consume excessive memory.

Why does AdminShell use AppleScript instead of directly calling sudo?

AdminShell.runSync builds an AppleScript command using do shell script … with administrator privileges (lines 11-13) and executes it via osascript. This approach leverages the native macOS SecurityAgent dialog, attributing the elevation request to the system script process rather than the main application. For signed updater flows, it can also run via AppleScriptRunner.run to maintain the application's code-signing identity during privilege escalation.

What prevents multiple password dialogs from appearing simultaneously?

The implementation uses a global NSLock instance named promptLock paired with a Boolean prompting flag (lines 36-39) to serialize privilege requests. If a second command requires admin rights while a dialog is already displayed, the API returns false immediately without showing a new dialog, treating the scenario as "permission not granted."

How does the password-less sudo feature work for sleep management?

The Sudoers enum manages a dedicated NOPASSWD rule at /etc/sudoers.d/vorssaint-clamshell. Once installed, Sudoers.pmsetDisableSleep executes sudo -n pmset disablesleep via Shell.run (line 202), allowing the command to complete without interactive password entry while limiting the privilege scope strictly to power management settings.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →