Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(lending): a lent terminal's commands get the person's shell PATH (#3652)

Aditya Umale9d68a0aa4874
diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjs
index 1b59189651..8de21e4273 100644
--- a/electron/shared-computer-access.mjs
+++ b/electron/shared-computer-access.mjs
@@ -8,6 +8,7 @@ import readline from "node:readline";
import { lentScreenArguments, lentScreenToolListing } from "./lent-screen-tools.mjs";
import { typeOneCharacterAtATime, typesInOneBurst } from "./paced-typing.mjs";
import { helperMissing } from "./lent-screen-failures.mjs";
+import { commandPath } from "./shell-path.mjs";
/** Reads stay under the 4 MB body that carries a result to the server (base64 of 2 MiB is 2.8 MB); writes stay small. */
const READ_LIMIT = 2 * 1024 * 1024;
@@ -165,10 +166,12 @@ const hostEnvironment = () => Object.fromEntries(["PATH", "PATHEXT", "HOME", "US
export const validCommandSeconds = value => value === undefined || (Number.isInteger(value) && value >= 1 && value <= MAX_COMMAND_SECONDS);
-export function sharedCommand(command, cwd, signal, seconds = COMMAND_SECONDS) {
+export async function sharedCommand(command, cwd, signal, seconds = COMMAND_SECONDS) {
if (typeof command !== "string" || !command.trim() || command.length > 8000) throw new Error("Give a command of at most 8000 characters");
if (!validCommandSeconds(seconds)) throw new Error(`Give timeout_seconds as a whole number from 1 to ${MAX_COMMAND_SECONDS}`);
signal.throwIfAborted();
+ const PATH = await commandPath();
+ signal.throwIfAborted();
return new Promise((resolve, reject) => {
const windows = process.platform === "win32";
// PowerShell searches third-party modules before its own cmdlets, so a cold `echo` can exhaust the deadline: prefer built-ins.
@@ -179,7 +182,7 @@ export function sharedCommand(command, cwd, signal, seconds = COMMAND_SECONDS) {
const child = spawn(windows ? "powershell.exe" : "/bin/sh", windows ? ["-NoProfile", "-NonInteractive", "-Command", script] : ["-c", script], {
cwd, detached: !windows, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
// Without PATHEXT, PowerShell treats even .exe files as documents.
- env: hostEnvironment(),
+ env: { ...hostEnvironment(), ...(PATH ? { PATH } : {}) },
});
const chunks = []; let bytes = 0; let reason; let settled = false;
const graces = [];
diff --git a/electron/shell-path.mjs b/electron/shell-path.mjs
new file mode 100644
index 0000000000..bfba27ef95
--- /dev/null
+++ b/electron/shell-path.mjs
@@ -0,0 +1,29 @@
+// A Mac app opened from the Dock or Finder gets launchd's bare PATH (/usr/bin:/bin:/usr/sbin:/sbin), not the person's
+// shell PATH, so Homebrew's tools and ~/.local/bin are missing from a lent terminal's commands.
+import { execFile } from "node:child_process";
+import { existsSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const MARK = "__OMB_PATH__";
+
+/** -l -i: Homebrew, nvm and friends live in rc files that only an interactive login shell reads; the mark isolates
+ * $PATH from what those files print. */
+export function probeShellPath({ shell = process.env.SHELL || "/bin/zsh" } = {}) {
+ return new Promise(resolve => {
+ execFile(shell, ["-l", "-i", "-c", `printf "${MARK}%s" "$PATH"`], { timeout: 5000 }, (error, stdout) => {
+ const found = error ? null : new RegExp(`${MARK}([^\\n]*)`).exec(String(stdout));
+ resolve(found?.[1] || null);
+ });
+ });
+}
+
+let shellPath;
+
+/** The person's shell PATH first, then the app's own, then the usual install folders; read from the shell once. */
+export async function commandPath({ platform = process.platform, env = process.env, home = os.homedir(), probe, exists = existsSync } = {}) {
+ if (platform === "win32") return env.PATH;
+ const fromShell = probe ? await probe() : await (shellPath ??= probeShellPath());
+ const known = ["/opt/homebrew/bin", "/usr/local/bin", path.join(home, ".local", "bin")].filter(dir => exists(dir));
+ return [...new Set([fromShell, env.PATH].flatMap(list => list?.split(":") ?? []).concat(known).filter(Boolean))].join(":");
+}
diff --git a/electron/shell-path.node-test.mjs b/electron/shell-path.node-test.mjs
new file mode 100644
index 0000000000..cbc5ef17ab
--- /dev/null
+++ b/electron/shell-path.node-test.mjs
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { chmod, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { sharedCommand } from "./shared-computer-access.mjs";
+import { commandPath, probeShellPath } from "./shell-path.mjs";
+
+const payload = result => JSON.parse(result.content[0].text);
+
+test("a lent command finds the tools on the person's shell PATH though the app was opened from the Dock", { skip: process.platform === "win32" }, async t => {
+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-shell-path-")));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const bin = path.join(dir, "brew", "bin");
+ await mkdir(bin, { recursive: true });
+ await writeFile(path.join(bin, "fixture-gh"), "#!/bin/sh\necho fixture-gh-ran\n");
+ await chmod(path.join(bin, "fixture-gh"), 0o755);
+ const shell = path.join(dir, "login-shell");
+ await writeFile(shell, `#!/bin/sh\necho "Last login: rc noise"\nprintf '__OMB_PATH__%s' '${bin}:/usr/bin:/bin'\n`);
+ await chmod(shell, 0o755);
+ const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL };
+ t.after(() => Object.assign(process.env, saved));
+ Object.assign(process.env, { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", SHELL: shell });
+ const result = payload(await sharedCommand("fixture-gh", dir, new AbortController().signal));
+ assert.equal(result.exitCode, 0, result.output);
+ assert.match(result.output, /fixture-gh-ran/);
+});
+
+test("the shell PATH comes first, then the app's own and the usual install folders, each once", async () => {
+ const merged = await commandPath({ platform: "darwin", env: { PATH: "/usr/bin:/bin" }, home: "/nowhere", probe: async () => "/opt/fixture/bin:/usr/bin", exists: dir => dir === "/opt/homebrew/bin" });
+ assert.equal(merged, "/opt/fixture/bin:/usr/bin:/bin:/opt/homebrew/bin");
+ const unread = await commandPath({ platform: "darwin", env: { PATH: "/usr/bin:/bin" }, home: "/nowhere", probe: async () => null, exists: () => true });
+ assert.equal(unread, "/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/nowhere/.local/bin");
+ assert.equal(await commandPath({ platform: "win32", env: { PATH: "C:\\Windows" }, probe: async () => assert.fail("never probed on Windows") }), "C:\\Windows");
+});
+
+test("a login shell that fails, prints nothing or hangs gives no PATH", { skip: process.platform === "win32" }, async () => {
+ assert.equal(await probeShellPath({ shell: "/nonexistent/shell" }), null);
+ assert.equal(await probeShellPath({ shell: "/usr/bin/true" }), null);
+});