Skip to content

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

Launch: the Linux lease identity check stays; probe cache keys on what execCli runs (Windows shims too)

milind-soni551dd074bd07
diff --git a/electron/data-dir-lease-host.node-test.mjs b/electron/data-dir-lease-host.node-test.mjs
index 469e6c58f5..ce6abfbb1b 100644
--- a/electron/data-dir-lease-host.node-test.mjs
+++ b/electron/data-dir-lease-host.node-test.mjs
@@ -71,7 +71,7 @@ test("a handed host identity is taken only when well formed, and is removed from
assert.equal(consumeHostIdentity({}), null);
});
-test("Windows matches a live pid to a record by its creation time, except for the parent that handed this process the record", () => {
+test("only Windows asks a live pid's creation time, and never for the parent that handed this process the record", () => {
assert.equal(creationTimeNeeded("win32", 4242, null), true);
assert.equal(creationTimeNeeded("win32", 4242, 77), true);
assert.equal(creationTimeNeeded("win32", 4242, 4242), false);
diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjs
index c00818b652..4ad1c7921f 100644
--- a/electron/data-dir-lease.mjs
+++ b/electron/data-dir-lease.mjs
@@ -140,7 +140,7 @@ function ownerPredatesThisBoot(owner) {
/** The only liveness question this module should ever ask about a record. `parentPid`: the pid of the process that started
* this one, when the record is that parent's own (a delegated child checking the lease it was handed). */
function ownerIsAlive(owner, parentPid = null) {
- return !ownerPredatesThisBoot(owner) && processIsAlive(owner.pid) && (!creationTimeNeeded(process.platform, owner.pid, parentPid) || ownerIdentityMatches(owner));
+ return !ownerPredatesThisBoot(owner) && processIsAlive(owner.pid) && ownerIdentityMatches(owner, parentPid);
}
/**
@@ -467,13 +467,13 @@ function cimHasPid(pid) {
}
/** Pids are reused within a boot: a process that started at another moment, or after the lease, is not its owner. */
-function ownerIdentityMatches(owner) {
+function ownerIdentityMatches(owner, parentPid = null) {
if (process.platform === "linux") {
if (!Number.isSafeInteger(owner.start) || typeof owner.ns !== "string" || owner.ns !== pidNamespace()) return true;
const started = processStartTicks(owner.pid);
return started === null || started === owner.start;
}
- if (process.platform !== "win32") return true;
+ if (process.platform !== "win32" || !creationTimeNeeded(process.platform, owner.pid, parentPid)) return true;
return windowsCreationFitsLease(processCreationTimeMs(owner.pid), owner.createdAt);
}
diff --git a/server/cli-probe-cache.test.ts b/server/cli-probe-cache.test.ts
index 208285e307..02f5ff9481 100644
--- a/server/cli-probe-cache.test.ts
+++ b/server/cli-probe-cache.test.ts
@@ -1,8 +1,10 @@
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+const windows = process.platform === "win32";
+
import { createCliProbeCache, probeCacheFile, probedProgram } from "./cli-probe-cache.ts";
const roots: string[] = [];
@@ -17,7 +19,7 @@ function place() {
}
function program(bin: string, name: string, body = "#!/usr/bin/env node\nconsole.log('1.0.0');\n"): string {
- const path = join(bin, name);
+ const path = join(bin, windows ? `${name}.exe` : name);
writeFileSync(path, body);
chmodSync(path, 0o755);
return path;
@@ -34,6 +36,9 @@ function runner(answer: (args: string[]) => { err?: Error; stdout: string; stder
return { run, calls };
}
+/** On Windows a program on a PATH needs its extension, and execCli resolves a bare name on the app's own PATH: these
+ * tests name the program by its full path there. */
+const cliFor = (bin: string, name: string) => (windows ? join(bin, `${name}.exe`) : name);
const ask = (exec: ReturnType<typeof createCliProbeCache>["exec"], cli: string, args: string[], path: string) =>
new Promise<{ err: Error | null; stdout: string; stderr?: string }>((resolve) => exec(cli, args, { env: { PATH: path } }, (err, stdout, stderr) => resolve({ err, stdout, stderr })));
@@ -51,15 +56,15 @@ describe("engine probe answers kept between desktop starts", () => {
program(bin, "engine");
const first = runner((args) => ({ stdout: args[0] === "--help" ? "usage: engine --autocompact\n" : "1.0.0\n" }));
const cache = createCliProbeCache({ file, appVersion: "0.1.180", run: first.run });
- expect(await ask(cache.exec, "engine", ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });
- expect(await ask(cache.exec, "engine", ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });
- expect(await ask(cache.exec, "engine", ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });
- expect(await ask(cache.exec, "engine", ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });
+ expect(await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });
+ expect(await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin)).toEqual({ err: null, stdout: "1.0.0\n", stderr: "" });
+ expect(await ask(cache.exec, cliFor(bin, "engine"), ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });
+ expect(await ask(cache.exec, cliFor(bin, "engine"), ["--help"], bin)).toMatchObject({ stdout: "usage: engine --autocompact\n" });
expect(first.calls).toEqual([["--version"], ["--help"]]);
const next = runner();
const restarted = createCliProbeCache({ file, appVersion: "0.1.180", run: next.run });
- expect(await ask(restarted.exec, "engine", ["--version"], bin)).toMatchObject({ stdout: "1.0.0\n" });
+ expect(await ask(restarted.exec, cliFor(bin, "engine"), ["--version"], bin)).toMatchObject({ stdout: "1.0.0\n" });
expect(next.calls).toEqual([]);
});
@@ -70,17 +75,17 @@ describe("engine probe answers kept between desktop starts", () => {
utimesSync(path, npmTime, npmTime);
const counted = runner();
const cache = createCliProbeCache({ file, appVersion: "0.1.180", run: counted.run });
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
// Same size and modification time npm gives every file, but a new file: still asked again.
rmSync(path);
utimesSync(program(bin, "engine"), npmTime, npmTime);
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
expect(counted.calls).toHaveLength(2);
program(bin, "engine", "#!/usr/bin/env node\nconsole.log('2.0.0');\n");
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
expect(counted.calls).toHaveLength(3);
const upgraded = createCliProbeCache({ file, appVersion: "0.1.181", run: counted.run });
- await ask(upgraded.exec, "engine", ["--version"], bin);
+ await ask(upgraded.exec, cliFor(bin, "engine"), ["--version"], bin);
expect(counted.calls).toHaveLength(4);
});
@@ -90,20 +95,20 @@ describe("engine probe answers kept between desktop starts", () => {
let answer: { err?: Error; stdout: string } = { err: new Error("exit 1"), stdout: "" };
const counted = runner(() => answer);
const cache = createCliProbeCache({ file, appVersion: "1", run: counted.run });
- expect((await ask(cache.exec, "engine", ["--version"], bin)).err?.message).toBe("exit 1");
+ expect((await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin)).err?.message).toBe("exit 1");
answer = { stdout: " \n" };
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
answer = { stdout: "Logged in\n" };
- await ask(cache.exec, "engine", ["auth", "status"], bin);
- await ask(cache.exec, "engine", ["auth", "status"], bin);
- await ask(cache.exec, "missing", ["--version"], bin);
- await ask(cache.exec, "missing", ["--version"], bin);
- await ask(cache.exec, "engine", ["--version"], bin);
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["auth", "status"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["auth", "status"], bin);
+ await ask(cache.exec, cliFor(bin, "missing"), ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "missing"), ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
expect(counted.calls).toHaveLength(7);
});
- it("does not keep a shell script or a version manager's shim, whose file stays while the version it runs changes", () => {
+ it.skipIf(windows)("does not keep a shell script or a version manager's shim, whose file stays while the version it runs changes", () => {
const { root, bin } = place();
program(bin, "viaShell", "#!/bin/bash\nexec real-engine \"$@\"\n");
program(bin, "viaEnvShell", "#!/usr/bin/env -S bash -e\nexec real-engine \"$@\"\n");
@@ -114,13 +119,13 @@ describe("engine probe answers kept between desktop starts", () => {
program(shims, "other");
program(bin, "native", "\u007fELF binary");
program(bin, "node-cli");
- expect(probedProgram("viaShell", bin)).toBeNull();
- expect(probedProgram("viaEnvShell", bin)).toBeNull();
- expect(probedProgram("engine", bin)).toBeNull();
- expect(probedProgram("other", shims)).toBeNull();
- expect(probedProgram("engine --flag", bin)).toBeNull();
- expect(probedProgram("native", bin)).toMatch(/native$/);
- expect(probedProgram("node-cli", bin)).toMatch(/node-cli$/);
+ expect(probedProgram("viaShell", { env: { PATH: bin } })).toBeNull();
+ expect(probedProgram("viaEnvShell", { env: { PATH: bin } })).toBeNull();
+ expect(probedProgram("engine", { env: { PATH: bin } })).toBeNull();
+ expect(probedProgram("other", { env: { PATH: shims } })).toBeNull();
+ expect(probedProgram("engine --flag", { env: { PATH: bin } })).toBeNull();
+ expect(probedProgram("native", { env: { PATH: bin } })).toMatch(/native$/);
+ expect(probedProgram("node-cli", { env: { PATH: bin } })).toMatch(/node-cli$/);
});
it("runs every probe where nothing may be kept", async () => {
@@ -128,8 +133,17 @@ describe("engine probe answers kept between desktop starts", () => {
program(bin, "engine");
const counted = runner();
const cache = createCliProbeCache({ file: null, appVersion: "1", run: counted.run });
- await ask(cache.exec, "engine", ["--version"], bin);
- await ask(cache.exec, "engine", ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
expect(counted.calls).toHaveLength(2);
});
+
+ it.runIf(windows)("keeps an npm .cmd shim's answer under the script it runs, not the shim", () => {
+ const { bin } = place();
+ const script = join(bin, "node_modules", "engine", "bin", "engine.js");
+ mkdirSync(join(bin, "node_modules", "engine", "bin"), { recursive: true });
+ writeFileSync(script, "console.log('1.0.0');\n");
+ writeFileSync(join(bin, "engine.cmd"), '@ECHO off\r\n"%~dp0\\node_modules\\engine\\bin\\engine.js" %*\r\n');
+ expect(probedProgram(join(bin, "engine.cmd"), {})?.toLowerCase()).toBe(realpathSync(script).toLowerCase());
+ });
});
diff --git a/server/cli-probe-cache.ts b/server/cli-probe-cache.ts
index 0cb9392866..2cb8f2d524 100644
--- a/server/cli-probe-cache.ts
+++ b/server/cli-probe-cache.ts
@@ -14,8 +14,8 @@ import { basename, dirname, isAbsolute, join } from "node:path";
import type { ExecFileOptions } from "node:child_process";
import { writeFileAtomic } from "./atomic.ts";
-import { findCliCandidates, resolveCliSpawn, splitCliString } from "./env-path.ts";
-import { execCli } from "./procs.ts";
+import { findCliCandidates, splitCliString } from "./env-path.ts";
+import { execCli, outsideBoxOptions, resolveCli } from "./procs.ts";
export const PROBE_CACHE_FILE = "engine-probes.json";
const KEPT = 64;
@@ -32,27 +32,34 @@ export function probeCacheFile(env: NodeJS.ProcessEnv = process.env): string | n
return env.OMB_DESKTOP_PARENT === "1" && env.OMB_USER_DATA && isAbsolute(env.OMB_USER_DATA) ? join(env.OMB_USER_DATA, PROBE_CACHE_FILE) : null;
}
-/** The file a probe of `cli` actually runs (a Windows .cmd shim's script, not the shim), or null when it is not one whose
- * answer may be kept. */
-export function probedProgram(cli: string, path: string, platform: NodeJS.Platform = process.platform): string | null {
+/** The file a probe of `cli` actually runs, found the way execCli finds it (procs.ts): on Windows a shim or #! script
+ * becomes Node plus the script, so the script; elsewhere a bare name is looked up on the PATH the probe runs with. Null
+ * when it is not a file whose answer may be kept. */
+export function probedProgram(cli: string, opts: ExecFileOptions): string | null {
if (splitCliString(cli).length !== 1) return null;
- const found = findCliCandidates(cli, path)[0];
- if (!found) return null;
- let file = found;
- if (platform === "win32" && /\.(?:cmd|bat)$/i.test(found)) {
- const resolved = resolveCliSpawn(found, []);
- const script = resolved.args[0];
- if (resolved.command === found || !script || !isAbsolute(script)) return null;
- file = script;
+ let command: string, rest: string[], env: NodeJS.ProcessEnv;
+ try {
+ ({ command, args: rest } = resolveCli(cli, []));
+ env = outsideBoxOptions(command, opts).env ?? process.env;
+ } catch {
+ return null;
}
+ const file = rest.length
+ ? rest.find((arg) => isAbsolute(arg) && isFile(arg))
+ : /[\\/]/.test(command) ? command : findCliCandidates(command, String(env.PATH ?? env.Path ?? ""))[0];
+ if (!file) return null;
let real: string;
try { real = realpathSync(file); } catch { return null; }
const name = basename(real).toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
if (SHIM_PROGRAMS.has(name) || real.toLowerCase().split(/[\\/]/).includes("shims")) return null;
- if (/\.(?:ps1|sh)$/i.test(real) || shellScript(real)) return null;
+ if (/\.(?:ps1|sh|cmd|bat)$/i.test(real) || shellScript(real)) return null;
return real;
}
+function isFile(path: string): boolean {
+ try { return statSync(path).isFile(); } catch { return false; }
+}
+
function shellScript(file: string): boolean {
let fd: number | undefined;
try {
@@ -107,7 +114,7 @@ export function createCliProbeCache(options: { file: string | null; appVersion:
} catch {}
};
const exec: ExecCli = (cli, args, opts, cb) => {
- const program = options.file && args.length === 1 && CACHED_ARGS.has(args[0]!) ? probedProgram(cli, String((opts.env ?? process.env).PATH ?? ""), platform) : null;
+ const program = options.file && args.length === 1 && CACHED_ARGS.has(args[0]!) ? probedProgram(cli, opts) : null;
const key = program ? probeKey(program, args, options.appVersion, platform) : null;
const kept = key ? loaded().get(key) : undefined;
if (kept) {