Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(runtime): install a real system Node+npm when the machine has none

Chaitanya Giri0b95976470dc
diff --git a/package.json b/package.json
index a5b3703f..5a07c656 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --git a/src/main/cliInstall.ts b/src/main/cliInstall.ts
index e280e66e..c3642fdc 100644
--- a/src/main/cliInstall.ts
+++ b/src/main/cliInstall.ts
@@ -7,6 +7,10 @@
*/
import type { AgentProvider, ProviderInstallInfo } from '../shared/agentProvider';
import { installInfoForProvider } from '../shared/agentProvider';
+import type { NodeInstaller } from './nodeInstall';
+import { buildNodeInstallScript } from './nodeInstall';
+
+export type InstallRungKind = 'npm' | 'node-then-npm' | 'native' | 'manual';
/** Pick which rung of the install ladder to run, given what this machine has.
*
@@ -15,17 +19,27 @@ import { installInfoForProvider } from '../shared/agentProvider';
* command anyway and run it — so the user watched `npm: command not found`
* scroll past and concluded the app was broken. Classify first:
*
- * npm present → npm install (unchanged; the common case)
- * npm absent, native installer → the vendor's self-contained installer
- * npm absent, no native → manual only. Do NOT run a doomed command.
+ * npm usable → npm install (unchanged; the common case)
+ * npm absent, Node installer found → install real Node + npm, THEN npm install
+ * npm absent, native installer → the vendor's self-contained installer
+ * neither → manual only. Do NOT run a doomed command.
+ *
+ * Founder decision (2026-08-07) put `node-then-npm` ABOVE `native`, reversing the
+ * earlier "never auto-install a system Node" rule: a user who only ever gets the
+ * node-free Claude installer still has no runtime for MCP servers, hooks, or any
+ * other provider — so the default is to fix the machine, not to route around it.
+ * `native` survives as the fallback for when no installer could be resolved
+ * (offline, or a platform nodejs.org ships no package for).
*
- * We never auto-install a system Node, touch nvm, or edit the user's shell rc —
- * a missing runtime is the user's to resolve, and the manual rung says so. */
+ * `npmAvailable` means npm is present AND its Node is new enough (see
+ * nodeInstall.NODE_FLOOR_MAJOR) — an ancient Node routes into the upgrade rung. */
export function chooseInstallRung(
info: ProviderInstallInfo,
- npmAvailable: boolean
-): { command?: string; kind: 'npm' | 'native' | 'manual'; nodeMissing: boolean } {
+ npmAvailable: boolean,
+ nodeInstaller?: NodeInstaller | null
+): { command?: string; kind: InstallRungKind; nodeMissing: boolean } {
if (info.command && npmAvailable) return { command: info.command, kind: 'npm', nodeMissing: false };
+ if (info.command && nodeInstaller) return { command: info.command, kind: 'node-then-npm', nodeMissing: true };
if (info.nativeCommand) return { command: info.nativeCommand, kind: 'native', nodeMissing: !npmAvailable };
return { kind: 'manual', nodeMissing: !npmAvailable };
}
@@ -42,11 +56,16 @@ export function buildMissingCliScript(
bin: string,
provider: AgentProvider,
npmAvailable: boolean,
- platform: string = process.platform
+ platform: string = process.platform,
+ nodeInstaller?: NodeInstaller | null
): string {
const info: ProviderInstallInfo = installInfoForProvider(provider, platform);
const safeBin = (bin || provider).replace(/[^A-Za-z0-9._-]/g, '') || provider;
- const rung = chooseInstallRung(info, npmAvailable);
+ const rung = chooseInstallRung(info, npmAvailable, nodeInstaller);
+ // Only the rung that actually needs it gets the Node install spliced in.
+ const nodeSteps = rung.kind === 'node-then-npm' && nodeInstaller
+ ? buildNodeInstallScript(nodeInstaller, platform)
+ : null;
const cmd = rung.command; // trusted constant, or undefined → manual hint only
const label = info.label;
const docs = info.docsUrl;
@@ -58,7 +77,16 @@ export function buildMissingCliScript(
// We avoid `if errorlevel` branching (untestable here) — a combined success/
// failure hint after the install is robust and satisfies the manual-fallback DoD.
const parts: string[] = ['echo.', `echo ${rule}`, `echo Engine CLI not found: ${safeBin}`, 'echo.'];
- if (rung.nodeMissing) {
+ if (nodeSteps && nodeInstaller) {
+ parts.push(
+ 'echo Node.js is not installed on this machine, so the usual npm',
+ `echo installer cannot run yet. Installing Node ${nodeInstaller.version} ^(+ npm^) first,`,
+ 'echo straight from nodejs.org, checksum-verified.',
+ 'echo.',
+ ...nodeSteps,
+ 'echo.'
+ );
+ } else if (rung.nodeMissing) {
parts.push('echo Node.js is not installed on this machine, so the usual', 'echo npm installer cannot run here.', 'echo.');
}
if (cmd) {
@@ -102,7 +130,19 @@ export function buildMissingCliScript(
`echo ' Engine CLI not found: ${safeBin}'`,
`echo ''`
];
- if (rung.nodeMissing) {
+ if (nodeSteps && nodeInstaller) {
+ // The default path on a bare machine: fix the runtime, then use it. Every
+ // step aborts the whole script on failure, so the npm install below only
+ // ever runs against a Node that actually landed.
+ lines.push(
+ `echo ' Node.js is not installed on this machine, so the usual npm'`,
+ `echo ' installer cannot run yet. Installing Node ${nodeInstaller.version} (+ npm) first,'`,
+ `echo ' straight from nodejs.org, checksum-verified.'`,
+ `echo ''`,
+ ...nodeSteps,
+ `echo ''`
+ );
+ } else if (rung.nodeMissing) {
lines.push(
`echo ' Node.js is not installed on this machine, so the usual npm'`,
`echo ' installer cannot run here.'`,
diff --git a/src/main/hive.ts b/src/main/hive.ts
index dd1c9d9c..5931ea8a 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -388,12 +388,15 @@ export class HiveManager {
* This dir is APPENDED to the agent's PATH (see pty.spawn), never prepended: a
* user who has their own node keeps their own version — we are strictly the
* fallback. Prepending would silently swap every agent's node for Electron's
- * (the v22 line at time of writing) underneath the user's own projects.
+ * (20.18.1 as of Electron 32.3.3) underneath the user's own projects.
*
* NOTE: `node` only — deliberately no `npm`/`npx`. Electron bundles the Node
* RUNTIME, not the npm CLI (which is ~12MB of JS we do not ship), so an `npm`
* wrapper here could only be a stub that fails confusingly. A missing `npm` is
- * the honest signal; see the missing-CLI ladder in index.ts, which detects it.
+ * the honest signal; the install ladder (main/cliInstall.ts) detects it and
+ * installs a REAL system Node — which brings npm with it. This shim is only the
+ * last resort for when that install could not run (offline, or a platform with
+ * no official installer).
*/
runtimeBinDir(): string | null {
const root = this.root();
diff --git a/src/main/index.ts b/src/main/index.ts
index 4074e384..b5fac95f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -57,6 +57,7 @@ import {
type AgentProvider
} from '../shared/agentProvider';
import { buildMissingCliScript, chooseInstallRung } from './cliInstall';
+import { detectNodeVersion, nodeIsUsable, resolveNodeInstaller } from './nodeInstall';
import {
CODEX_REMOTE_SOCKET_RELATIVE,
codexRemoteAliasPath,
@@ -1969,8 +1970,17 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
// The installer commands are `npm install -g …`. Probe for npm the same way
// we probe for the engine CLI, so a no-Node machine gets the node-free rung
// (or an honest manual hint) instead of watching `npm: not found` scroll by.
- const npmAvailable = ptyManager.isCommandAvailable('npm');
- const rung = chooseInstallRung(installInfoForProvider(provider), npmAvailable);
+ // An npm whose Node is BELOW the floor counts as unavailable: founder rule
+ // (2026-08-07) is "their Node newer than ours → leave it alone; absent or
+ // older → install the latest stable for them".
+ const npmAvailable =
+ ptyManager.isCommandAvailable('npm') &&
+ nodeIsUsable(detectNodeVersion(ptyManager.commandPath('node')));
+ // Only reach the network when we actually need to (npm missing/too old);
+ // resolveNodeInstaller is timeout-bounded and returns null offline, which
+ // simply drops the ladder to the native/manual rung.
+ const nodeInstaller = npmAvailable ? null : await resolveNodeInstaller();
+ const rung = chooseInstallRung(installInfoForProvider(provider), npmAvailable, nodeInstaller);
const res = ptyManager.spawn(
{
id: opts.id,
@@ -1978,7 +1988,7 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
command: bin,
cols: opts.cols,
rows: opts.rows,
- shellScript: buildMissingCliScript(bin, provider, npmAvailable)
+ shellScript: buildMissingCliScript(bin, provider, npmAvailable, process.platform, nodeInstaller)
},
owner
);
diff --git a/src/main/nodeInstall.ts b/src/main/nodeInstall.ts
new file mode 100644
index 00000000..56a5f2ed
--- /dev/null
+++ b/src/main/nodeInstall.ts
@@ -0,0 +1,224 @@
+/**
+ * Installing Node.js itself, so a machine with nothing on it can still run agents.
+ *
+ * Founder decision (2026-08-07), superseding the earlier "never auto-install a
+ * system Node" constraint: by DEFAULT we install the real thing — latest stable
+ * (LTS) Node + the npm that ships with it — into the user's system. Electron's
+ * bundled Node stays as a last-resort fallback only (see hive.runtimeBinDir).
+ *
+ * The user has to type their password: every official installer writes outside the
+ * home directory. That happens VISIBLY in the same terminal as every other
+ * installer in this app — we never elevate silently.
+ *
+ * Because we run an installer as root, the download is CHECKSUM-VERIFIED against
+ * nodejs.org's own SHASUMS256.txt before anything executes. A mismatch aborts.
+ *
+ * Nothing here imports electron: the URL/artifact/script logic is all pure, so it
+ * is testable without booting an app.
+ */
+
+/** Lowest Node major we consider usable. Below this we offer the upgrade; at or
+ * above it we leave the user's own install completely alone — an existing,
+ * working toolchain is never "upgraded" out from under them. Chosen as Electron's
+ * own bundled line, i.e. the floor we already know every code path tolerates. */
+export const NODE_FLOOR_MAJOR = 20;
+
+const DIST = 'https://nodejs.org/dist';
+
+export interface NodeDistEntry {
+ version: string; // 'v24.19.0'
+ lts: false | string; // false | 'Krypton'
+ npm?: string;
+}
+
+export interface NodeInstaller {
+ version: string; // 'v24.19.0'
+ npmVersion?: string;
+ file: string; // 'node-v24.19.0.pkg'
+ url: string;
+ sha256: string;
+ kind: 'pkg' | 'msi' | 'tar';
+}
+
+/** Major version of `v24.19.0` / `24.19.0`, or null if unparseable. */
+export function nodeMajor(version: string | null | undefined): number | null {
+ const m = /^v?(\d+)\./.exec((version ?? '').trim());
+ return m ? Number(m[1]) : null;
+}
+
+/** Whether the user's own Node is good enough to be left alone. */
+export function nodeIsUsable(version: string | null | undefined): boolean {
+ const major = nodeMajor(version);
+ return major !== null && major >= NODE_FLOOR_MAJOR;
+}
+
+type VersionProbe = (nodePath: string) => string;
+
+const execNodeVersion: VersionProbe = (nodePath) =>
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ require('node:child_process')
+ .execFileSync(nodePath, ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
+
+/** `node --version` from the binary the user's PATH actually resolves (see
+ * pty.commandPath). Null when node is absent or the probe fails at all — both
+ * mean "we cannot vouch for this runtime", which routes into the install rung
+ * rather than silently assuming it is fine. */
+export function detectNodeVersion(
+ nodePath: string | null | undefined,
+ probe: VersionProbe = execNodeVersion
+): string | null {
+ if (!nodePath) return null;
+ try {
+ const out = (probe(nodePath) || '').trim();
+ return /^v?\d+\./.test(out) ? out : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Newest LTS in nodejs.org's index.json. The index is newest-first, and `lts` is
+ * the codename (or false), so the first truthy one is the latest stable line.
+ * We deliberately do NOT take index[0] — that is the current/odd release, which
+ * is not what "latest stable" means to a user who just wants things to work. */
+export function pickLatestLts(index: NodeDistEntry[]): NodeDistEntry | null {
+ return index.find((e) => e && e.lts) ?? null;
+}
+
+/** The installer artifact for a platform/arch.
+ *
+ * Names are derived here but VALIDATED against SHASUMS256.txt by the caller —
+ * index.json's `files` array is not trustworthy for this: it lists no
+ * `win-arm64-msi` even though `node-<v>-arm64.msi` is published, and its
+ * `osx-x64-pkg` entry actually denotes the single UNIVERSAL `node-<v>.pkg`.
+ *
+ * Linux has no official installer package — only tarballs — so it gets the
+ * tar kind, unpacked into /usr/local. */
+export function nodeArtifactFor(
+ version: string,
+ platform: string,
+ arch: string
+): { file: string; kind: NodeInstaller['kind'] } | null {
+ if (platform === 'darwin') return { file: `node-${version}.pkg`, kind: 'pkg' };
+ if (platform === 'win32') {
+ const a = arch === 'arm64' ? 'arm64' : 'x64';
+ return { file: `node-${version}-${a}.msi`, kind: 'msi' };
+ }
+ if (platform === 'linux') {
+ const a = arch === 'arm64' ? 'arm64' : arch === 'x64' ? 'x64' : null;
+ if (!a) return null;
+ return { file: `node-${version}-linux-${a}.tar.xz`, kind: 'tar' };
+ }
+ return null;
+}
+
+/** Pull one file's digest out of a SHASUMS256.txt body ("<sha> <file>" lines). */
+export function shaFor(shasums: string, file: string): string | null {
+ for (const line of shasums.split('\n')) {
+ const m = /^([0-9a-f]{64})\s+(\S+)\s*$/.exec(line.trim());
+ if (m && m[2] === file) return m[1];
+ }
+ return null;
+}
+
+export const distUrl = (version: string, file: string): string => `${DIST}/${version}/${file}`;
+
+type Fetcher = (url: string) => Promise<{ ok: boolean; text: () => Promise<string> }>;
+
+/** This runs INSIDE a spawn, so it must never hang the launch: an unreachable
+ * nodejs.org has to fail fast and drop the ladder to its next rung. */
+const timedFetch: Fetcher = (url) =>
+ fetch(url, { signal: AbortSignal.timeout(6000) }) as unknown as ReturnType<Fetcher>;
+
+/** Resolve the exact installer to run on THIS machine, checksum included.
+ * Returns null on any failure (offline, unsupported platform, artifact not in
+ * SHASUMS256) — callers then fall back down the ladder rather than guessing. */
+export async function resolveNodeInstaller(
+ platform: string = process.platform,
+ arch: string = process.arch,
+ fetchImpl: Fetcher = timedFetch
+): Promise<NodeInstaller | null> {
+ try {
+ const indexRes = await fetchImpl(`${DIST}/index.json`);
+ if (!indexRes.ok) return null;
+ const index = JSON.parse(await indexRes.text()) as NodeDistEntry[];
+ const lts = pickLatestLts(index);
+ if (!lts) return null;
+
+ const artifact = nodeArtifactFor(lts.version, platform, arch);
+ if (!artifact) return null;
+
+ const shaRes = await fetchImpl(`${DIST}/${lts.version}/SHASUMS256.txt`);
+ if (!shaRes.ok) return null;
+ const sha256 = shaFor(await shaRes.text(), artifact.file);
+ // No digest → we would be running an unverified installer as root. Refuse.
+ if (!sha256) return null;
+
+ return {
+ version: lts.version,
+ npmVersion: lts.npm,
+ file: artifact.file,
+ url: distUrl(lts.version, artifact.file),
+ sha256,
+ kind: artifact.kind
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** The visible install script: download → VERIFY → install, aborting on any step.
+ *
+ * POSIX form is newline-separated statements for `$SHELL -lc`. Windows form is
+ * ONE `&`-chained cmd.exe line with NO double quotes — it is wrapped verbatim in
+ * `cmd /d /s /c "<script>"`, where a single embedded quote would end the command
+ * line early and execute the remainder as garbage. */
+export function buildNodeInstallScript(installer: NodeInstaller, platform: string): string[] {
+ const { version, url, sha256, file } = installer;
+
+ if (platform === 'win32') {
+ // certutil is the only hashing tool guaranteed present; `findstr` does the
+ // compare because cmd has no string equality on command output. msiexec's
+ // own UAC prompt is the elevation — we never call it silently.
+ const f = `%TEMP%\\${file}`;
+ return [
+ `echo Downloading Node.js ${version} ^(official installer^)...`,
+ `curl -fSL ${url} -o ${f}`,
+ `if errorlevel 1 exit /b 1`,
+ `echo Verifying checksum...`,
+ `certutil -hashfile ${f} SHA256 | findstr /i /c:${sha256} >nul`,
+ `if errorlevel 1 (echo [x] CHECKSUM MISMATCH - refusing to install ^& exit /b 1)`,
+ `echo Installing - approve the Windows prompt if it appears...`,
+ `msiexec /i ${f} /passive /norestart`,
+ `if errorlevel 1 exit /b 1`,
+ `set PATH=%ProgramFiles%\\nodejs;%PATH%`
+ ];
+ }
+
+ // macOS ships `shasum`; Linux ships `sha256sum`. Neither ships both.
+ const verify = platform === 'darwin'
+ ? `echo "${sha256} $__f" | shasum -a 256 -c - >/dev/null`
+ : `echo "${sha256} $__f" | sha256sum -c - >/dev/null`;
+ const install = platform === 'darwin'
+ ? `sudo installer -pkg "$__f" -target /`
+ // No official Linux package — the tarball IS the distribution. --strip-components
+ // drops the versioned top dir so bin/ lands directly in /usr/local/bin.
+ : `sudo tar -xJf "$__f" -C /usr/local --strip-components=1`;
+
+ return [
+ `echo ' Downloading Node.js ${version} (official installer)...'`,
+ `__tmp=$(mktemp -d)`,
+ `__f=$__tmp/${file}`,
+ `curl -fSL --progress-bar ${url} -o "$__f" || { echo ' [x] Download failed.'; exit 1; }`,
+ `echo ' Verifying checksum...'`,
+ `${verify} || { echo ' [x] CHECKSUM MISMATCH - refusing to install.'; rm -rf "$__tmp"; exit 1; }`,
+ `echo ''`,
+ `echo ' Installing Node.js. Enter your password if prompted -'`,
+ `echo ' the official installer writes outside your home directory.'`,
+ `echo ''`,
+ `${install} || { echo ' [x] Node install failed.'; rm -rf "$__tmp"; exit 1; }`,
+ `rm -rf "$__tmp"`,
+ // The shell that is running this script captured PATH before node existed.
+ `PATH=/usr/local/bin:$PATH`,
+ `export PATH`
+ ];
+}
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 7683f0a8..589f0f2a 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -167,6 +167,15 @@ export class PtyManager {
return this.resolveCommand(command).found;
}
+ /** The absolute path a bare command resolves to for THIS user, or null when it
+ * isn't installed. Same resolution + cache as spawn(), so a caller that probes
+ * a binary (e.g. `node --version`, to decide whether it is too old to keep)
+ * inspects exactly the executable an agent would have run. */
+ commandPath(command: string): string | null {
+ const r = this.resolveCommand(command);
+ return r.found ? r.path : null;
+ }
+
/** Session cache of SUCCESSFUL command resolutions. Each miss costs a full
* interactive-shell launch (`$SHELL -ilc which …` sources the user's whole
* zshrc — nvm/asdf init is routinely ~1s) run synchronously on the main
diff --git a/test/node-install.test.cjs b/test/node-install.test.cjs
new file mode 100644
index 00000000..affa7fac
--- /dev/null
+++ b/test/node-install.test.cjs
@@ -0,0 +1,235 @@
+/**
+ * The system-Node auto-installer.
+ *
+ * Founder decision (2026-08-07) reversed the earlier "never auto-install a system
+ * Node" rule: on a machine with no usable Node we install the REAL thing (latest
+ * LTS + the npm it ships with), and only then run `npm install -g <cli>`. These
+ * tests pin the parts that are dangerous to get wrong — we hand a script to a
+ * shell that will run an installer as root — without touching the network:
+ * `resolveNodeInstaller` takes an injectable fetch, and every other function is pure.
+ */
+const test = require('node:test');
+const assert = require('node:assert');
+const load = require('./load-ts.cjs');
+
+const {
+ NODE_FLOOR_MAJOR, nodeMajor, nodeIsUsable, detectNodeVersion,
+ pickLatestLts, nodeArtifactFor, shaFor, distUrl,
+ resolveNodeInstaller, buildNodeInstallScript
+} = load('src/main/nodeInstall.ts');
+const { chooseInstallRung, buildMissingCliScript } = load('src/main/cliInstall.ts');
+
+const SHA = 'a'.repeat(64);
+const SHA2 = 'b'.repeat(64);
+
+/** The shape nodejs.org/dist/index.json actually returns: NEWEST FIRST, with the
+ * odd/current release on top and `lts` being a codename or literal false. */
+const INDEX = [
+ { version: 'v26.7.0', lts: false, npm: '11.20.0' },
+ { version: 'v25.4.1', lts: false, npm: '11.18.0' },
+ { version: 'v24.19.0', lts: 'Krypton', npm: '11.17.0' },
+ { version: 'v22.20.0', lts: 'Jod', npm: '10.9.3' }
+];
+
+function fakeFetch(map) {
+ return async (url) => {
+ if (!(url in map)) return { ok: false, text: async () => '' };
+ return { ok: true, text: async () => map[url] };
+ };
+}
+
+const OK_FETCH = fakeFetch({
+ 'https://nodejs.org/dist/index.json': JSON.stringify(INDEX),
+ 'https://nodejs.org/dist/v24.19.0/SHASUMS256.txt':
+ `${SHA} node-v24.19.0.pkg\n${SHA2} node-v24.19.0-x64.msi\n${SHA} node-v24.19.0-linux-x64.tar.xz\n`
+});
+
+// ── version gate ────────────────────────────────────────────────────────────
+
+test('a Node at or above the floor is left alone; below it is not', () => {
+ assert.equal(nodeMajor('v24.19.0'), 24);
+ assert.equal(nodeMajor('20.18.1'), 20);
+ assert.equal(nodeMajor('rubbish'), null);
+ assert.equal(nodeIsUsable(`v${NODE_FLOOR_MAJOR}.0.0`), true);
+ assert.equal(nodeIsUsable(`v${NODE_FLOOR_MAJOR - 1}.99.99`), false);
+ // Absent / unparseable must NOT read as usable — that is the whole gate.
+ assert.equal(nodeIsUsable(null), false);
+ assert.equal(nodeIsUsable(''), false);
+});
+
+test('detectNodeVersion returns null rather than guessing when the probe fails', () => {
+ assert.equal(detectNodeVersion('/usr/bin/node', () => 'v24.19.0\n'), 'v24.19.0');
+ assert.equal(detectNodeVersion(null, () => 'v24.19.0'), null);
+ assert.equal(detectNodeVersion('/usr/bin/node', () => { throw new Error('ENOENT'); }), null);
+ // Garbage on stdout is not a version. Treating it as one would skip the install.
+ assert.equal(detectNodeVersion('/usr/bin/node', () => 'command not found'), null);
+});
+
+// ── picking what to download ────────────────────────────────────────────────
+
+test('latest STABLE means newest LTS, never index[0] (the current/odd release)', () => {
+ assert.equal(pickLatestLts(INDEX).version, 'v24.19.0');
+ assert.notEqual(pickLatestLts(INDEX).version, INDEX[0].version);
+ assert.equal(pickLatestLts([{ version: 'v26.7.0', lts: false }]), null);
+});
+
+test('artifact names match what nodejs.org actually publishes', () => {
+ // macOS ships ONE universal .pkg — there is no -x64/-arm64 variant.
+ assert.deepEqual(nodeArtifactFor('v24.19.0', 'darwin', 'arm64'), { file: 'node-v24.19.0.pkg', kind: 'pkg' });
+ assert.deepEqual(nodeArtifactFor('v24.19.0', 'darwin', 'x64'), { file: 'node-v24.19.0.pkg', kind: 'pkg' });
+ assert.deepEqual(nodeArtifactFor('v24.19.0', 'win32', 'arm64'), { file: 'node-v24.19.0-arm64.msi', kind: 'msi' });
+ assert.deepEqual(nodeArtifactFor('v24.19.0', 'win32', 'x64'), { file: 'node-v24.19.0-x64.msi', kind: 'msi' });
+ assert.deepEqual(nodeArtifactFor('v24.19.0', 'linux', 'x64'), { file: 'node-v24.19.0-linux-x64.tar.xz', kind: 'tar' });
+ // Unsupported: no artifact rather than a URL that 404s mid-install.
+ assert.equal(nodeArtifactFor('v24.19.0', 'linux', 'mips'), null);
+ assert.equal(nodeArtifactFor('v24.19.0', 'aix', 'ppc64'), null);
+});
+
+test('shaFor matches the exact file, not a prefix of another entry', () => {
+ const body = `${SHA} node-v24.19.0.pkg\n${SHA2} node-v24.19.0-x64.msi\n`;
+ assert.equal(shaFor(body, 'node-v24.19.0.pkg'), SHA);
+ assert.equal(shaFor(body, 'node-v24.19.0-x64.msi'), SHA2);
+ assert.equal(shaFor(body, 'node-v24.19.0-arm64.msi'), null);
+ assert.equal(distUrl('v24.19.0', 'node-v24.19.0.pkg'), 'https://nodejs.org/dist/v24.19.0/node-v24.19.0.pkg');
+});
+
+test('resolveNodeInstaller returns the LTS artifact with its real digest', async () => {
+ const got = await resolveNodeInstaller('darwin', 'arm64', OK_FETCH);
+ assert.equal(got.version, 'v24.19.0');
+ assert.equal(got.npmVersion, '11.17.0');
+ assert.equal(got.file, 'node-v24.19.0.pkg');
+ assert.equal(got.url, 'https://nodejs.org/dist/v24.19.0/node-v24.19.0.pkg');
+ assert.equal(got.sha256, SHA);
+ assert.equal(got.kind, 'pkg');
+});
+
+test('resolveNodeInstaller refuses rather than running an unverified installer', async () => {
+ // Artifact published but absent from SHASUMS256 → no digest → no install.
+ assert.equal(await resolveNodeInstaller('win32', 'arm64', OK_FETCH), null);
+ // Offline / 5xx on either fetch.
+ assert.equal(await resolveNodeInstaller('darwin', 'arm64', fakeFetch({})), null);
+ assert.equal(await resolveNodeInstaller('darwin', 'arm64', async () => { throw new Error('ENETDOWN'); }), null);
+ // Unsupported platform never reaches the network at all.
+ assert.equal(await resolveNodeInstaller('sunos', 'x64', OK_FETCH), null);
+});
+
+// ── the script we hand to a root-capable shell ──────────────────────────────
+
+const INSTALLER = {
+ version: 'v24.19.0', npmVersion: '11.17.0', file: 'node-v24.19.0.pkg',
+ url: 'https://nodejs.org/dist/v24.19.0/node-v24.19.0.pkg', sha256: SHA, kind: 'pkg'
+};
+const WIN_INSTALLER = { ...INSTALLER, file: 'node-v24.19.0-x64.msi', kind: 'msi',
+ url: 'https://nodejs.org/dist/v24.19.0/node-v24.19.0-x64.msi' };
+
+test('every posix install script verifies the checksum BEFORE it elevates', () => {
+ for (const platform of ['darwin', 'linux']) {
+ const script = buildNodeInstallScript(
+ platform === 'darwin' ? INSTALLER : { ...INSTALLER, file: 'node-v24.19.0-linux-x64.tar.xz', kind: 'tar' },
+ platform
+ ).join('\n');
+ const verifyAt = script.indexOf(SHA);
+ const elevateAt = script.indexOf('sudo ');
+ assert.ok(verifyAt > -1, `${platform}: digest never checked`);
+ assert.ok(elevateAt > -1, `${platform}: never installs`);
+ assert.ok(verifyAt < elevateAt, `${platform}: elevates before verifying`);
+ // A mismatch must ABORT on its OWN line, not warn and carry on into sudo.
+ // (Asserted per-line: a regex spanning to some later `exit 1` passes even
+ // when the mismatch branch only prints — which is the bug that matters.)
+ const mismatch = script.split('\n').find((l) => l.includes('CHECKSUM MISMATCH'));
+ assert.ok(mismatch, `${platform}: no mismatch branch at all`);
+ assert.ok(/exit 1/.test(mismatch), `${platform}: mismatch warns but continues: ${mismatch}`);
+ assert.ok(script.indexOf('CHECKSUM MISMATCH') < elevateAt, `${platform}: mismatch checked after sudo`);
+ // The download must fail loudly too, on its own line.
+ const dl = script.split('\n').find((l) => l.includes('curl -fSL'));
+ assert.ok(dl && /exit 1/.test(dl), `${platform}: a failed download falls through: ${dl}`);
+ }
+});
+
+test('posix script uses the hashing tool that platform actually ships', () => {
+ const mac = buildNodeInstallScript(INSTALLER, 'darwin').join('\n');
+ const lin = buildNodeInstallScript({ ...INSTALLER, kind: 'tar' }, 'linux').join('\n');
+ assert.match(mac, /shasum -a 256 -c -/);
+ assert.ok(!/sha256sum/.test(mac), 'macOS does not ship sha256sum');
+ assert.match(lin, /sha256sum -c -/);
+ assert.ok(!/shasum -a 256/.test(lin), 'most linux images do not ship shasum');
+ assert.match(mac, /sudo installer -pkg/);
+ assert.match(lin, /sudo tar -xJf/);
+ // The running shell captured PATH before node existed — it must be re-pointed.
+ assert.match(mac, /PATH=\/usr\/local\/bin:\$PATH/);
+});
+
+test('the Windows install script survives cmd /d /s /c quoting', () => {
+ const parts = buildNodeInstallScript(WIN_INSTALLER, 'win32');
+ const line = parts.join(' & ');
+ // Wrapped verbatim in `cmd /d /s /c "<script>"` — one embedded quote truncates it.
+ assert.ok(!line.includes('"'), 'double quote would end the command line early');
+ assert.ok(!line.includes('\n'), 'must stay a single line');
+ // Literal ampersands inside a parenthesized block have to be escaped.
+ assert.ok(!/[^^]&(?!\s)/.test(line.replace(/ & /g, ' ')), 'unescaped & inside a block');
+ assert.match(line, /certutil -hashfile .* SHA256 \| findstr \/i \/c:a{64}/);
+ assert.match(line, /msiexec \/i .* \/passive \/norestart/);
+ assert.ok(line.indexOf(SHA) < line.indexOf('msiexec'), 'elevates before verifying');
+});
+
+// ── the ladder ──────────────────────────────────────────────────────────────
+
+test('a usable npm is untouched — no Node install is ever spliced in', () => {
+ for (const provider of ['claude', 'codex', 'opencode', 'copilot']) {
+ const rung = chooseInstallRung(
+ { command: 'npm install -g x', nativeCommand: 'curl x | bash', label: 'X' }, true, INSTALLER
+ );
+ assert.equal(rung.kind, 'npm');
+ assert.equal(rung.nodeMissing, false);
+ const s = buildMissingCliScript(provider, provider, true, 'darwin', INSTALLER);
+ assert.ok(!s.includes('nodejs.org'), `${provider}: offered a Node install to a machine that has one`);
+ assert.ok(!s.includes('sudo'), `${provider}: asked for a password it does not need`);
+ }
+});
+
+test('no usable npm + a resolvable installer → node-then-npm, ABOVE the native rung', () => {
+ // Claude Code is the only provider with a node-free native installer, so it is
+ // the one case where the two rungs compete. Founder ruled: fix the machine.
+ const info = { command: 'npm install -g @anthropic-ai/claude-code', nativeCommand: 'curl -fsSL https://claude.ai/install.sh | bash', label: 'Claude Code' };
+ const rung = chooseInstallRung(info, false, INSTALLER);
+ assert.equal(rung.kind, 'node-then-npm');
+ assert.equal(rung.command, info.command);
+ assert.equal(rung.nodeMissing, true);
+});
+
+test('node-then-npm installs Node first, then the CLI with it', () => {
+ const s = buildMissingCliScript('claude', 'claude', false, 'darwin', INSTALLER);
+ const nodeAt = s.indexOf('sudo installer -pkg');
+ const cliAt = s.lastIndexOf('npm install -g');
+ assert.ok(nodeAt > -1, 'no Node install');
+ assert.ok(cliAt > nodeAt, 'CLI install must come after Node lands');
+ assert.match(s, /Installing Node v24\.19\.0 \(\+ npm\) first/);
+ // The Node script exits non-zero on failure, so the npm line is unreachable
+ // unless Node actually installed — that is what makes the ordering safe.
+ const mismatch = s.split('\n').find((l) => l.includes('CHECKSUM MISMATCH'));
+ assert.ok(mismatch && /exit 1/.test(mismatch), `mismatch must abort before npm: ${mismatch}`);
+});
+
+test('no installer resolvable (offline/unsupported) falls back, never fabricates one', () => {
+ const info = { command: 'npm install -g @anthropic-ai/claude-code', nativeCommand: 'curl -fsSL https://claude.ai/install.sh | bash', label: 'Claude Code' };
+ assert.equal(chooseInstallRung(info, false, null).kind, 'native');
+ assert.equal(chooseInstallRung(info, false, undefined).kind, 'native');
+ // A provider with no native installer and no Node → manual hint, runs nothing.
+ const bare = { command: 'npm install -g @openai/codex', label: 'Codex' };
+ const manual = chooseInstallRung(bare, false, null);
+ assert.equal(manual.kind, 'manual');
+ assert.equal(manual.command, undefined);
+ const s = buildMissingCliScript('codex', 'codex', false, 'darwin', null);
+ for (const line of s.split('\n')) {
+ const t = line.trim();
+ if (t) assert.match(t, /^(echo |if |fi$|else$)/, `manual rung EXECUTED: ${t}`);
+ }
+});
+
+test('the Windows node-then-npm script is still one quote-free line', () => {
+ const s = buildMissingCliScript('claude', 'claude', false, 'win32', WIN_INSTALLER);
+ assert.ok(!s.includes('\n'), 'must stay a single line');
+ assert.ok(!s.includes('"'), 'double quote would end the command line early');
+ assert.ok(s.indexOf('msiexec') < s.lastIndexOf('npm install -g'), 'Node must land before the CLI install');
+ assert.match(s, /set PATH=%ProgramFiles%\\nodejs;%PATH%/);
+});