fix(cli): run global updates from the home directory (#8131)

* fix(cli): run global updates from the home directory

* fix(cli): skip self-updates inside package scripts and explain unsafe homes
This commit is contained in:
terencecho
2026-11-18 04:41:57 +00:00
committed by GitHub
parent dcdd340715
commit e99cd75b42
10 changed files with 259 additions and 23 deletions
+4
View File
@@ -2409,6 +2409,10 @@ prompting, `--yes, -y` upgrades a detected global install (otherwise it prints
the right `npx` command; an unattended run without `--yes` or `--check` exits 2),
and `--project [dir]` rewrites
`hyperframes@<version>` script pins in a project's `package.json`.
Foreground and background CLI updates run the global package manager from your home directory.
Run global CLI updates directly from your shell. An npm, pnpm, or Bun package script can pass project settings to its children, so the CLI skips self-installation in that context.
On POSIX systems, the home directory must belong to the effective user and allow writes only by its owner. If `sudo` retains a different user's home, the update reports the ownership mismatch. A skipped background install reports its reason on stderr.
`--check --json` returns:
```json
+7 -1
View File
@@ -4,6 +4,7 @@
// only spawn, the config file, the manifest fetch/disk and the registry are stubbed.
import { homeCliCommand } from "../utils/homeCliCommand.js";
import { homedir } from "node:os";
import { EventEmitter } from "node:events";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -131,6 +132,7 @@ beforeEach(() => {
}),
);
for (const name of [
"npm_lifecycle_event",
"HYPERFRAMES_PLUGIN_VERSION",
"HYPERFRAMES_SKIP_SKILLS",
"HYPERFRAMES_AGENT",
@@ -261,7 +263,11 @@ describe("hyperframes update (install)", () => {
expect(installs()).toHaveLength(1);
expect(installs()[0]).toMatchObject({ command: bin, args });
// The child's stdout goes to stderr: a --json stdout stays one parseable object.
expect(installs()[0]!.opts).toMatchObject({ shell: false, stdio: ["inherit", 2, 2] });
expect(installs()[0]!.opts).toMatchObject({
cwd: homedir(),
shell: false,
stdio: ["inherit", 2, 2],
});
expect(skillsAdds()).toHaveLength(1);
expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.8");
expect(json().updated).toMatchObject({
+3 -1
View File
@@ -185,7 +185,9 @@ function cliOutcomeLine(cli: UpdateOutcome["cli"]): string {
case "manual":
return c.warn(`CLI: run ${cli.command} (${cli.reason}).`);
case "failed":
return c.error(`CLI upgrade failed. Run: ${cli.command}`);
return c.error(
cli.reason ?? `CLI upgrade failed. From your home directory, run: ${cli.command}`,
);
default:
return c.success("CLI is up to date.");
}
+42 -1
View File
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { homedir } from "node:os";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* Pins the security-relevant contract of the `--yes` install path: the detected
@@ -8,8 +9,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
* in installerDetection.test.ts; this locks how it's executed.
*/
describe("runDetectedInstall", () => {
beforeEach(() => vi.stubEnv("npm_lifecycle_event", ""));
afterEach(() => {
vi.unstubAllEnvs();
vi.doUnmock("node:child_process");
vi.doUnmock("node:os");
vi.resetModules();
});
@@ -27,11 +31,48 @@ describe("runDetectedInstall", () => {
expect(execSpy).toHaveBeenCalledTimes(1);
expect(execSpy).toHaveBeenCalledWith("bun", ["add", "-g", "hyperframes@1.2.3"], {
cwd: homedir(),
stdio: "inherit",
shell: false,
});
});
it.each([
["", /home directory/],
["preview", /outside the package script/],
] as const)(
"reports why both foreground installs were skipped (package event %j)",
async (event, reason) => {
vi.stubEnv("npm_lifecycle_event", event);
const execSpy = vi.fn();
vi.doMock("node:child_process", () => ({ execFileSync: execSpy }));
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => ".",
}));
const { runDetectedInstall, upgradeRunningCli } = await import("./upgrade.js");
const { consumeCommandResult } = await import("../utils/commandResult.js");
const argv = process.argv;
try {
process.argv = [process.execPath, "/usr/local/lib/node_modules/hyperframes/dist/cli.js"];
expect(upgradeRunningCli("1.2.3")).toMatchObject({
status: "failed",
reason: expect.stringMatching(reason),
});
runDetectedInstall(
{ bin: "npm", args: ["install", "-g", "hyperframes@1.2.3"] },
"npm install -g hyperframes@1.2.3",
"1.2.3",
);
expect(consumeCommandResult().exitCode).toBe(1);
expect(execSpy).not.toHaveBeenCalled();
} finally {
process.argv = argv;
}
},
);
it("sets a non-zero exit code when the install fails, without throwing", async () => {
const execSpy = vi.fn(() => {
throw new Error("install boom");
+23 -6
View File
@@ -1,4 +1,4 @@
import { homeCliCommand } from "../utils/homeCliCommand.js";
import { globalInstallLocation, homeCliCommand } from "../utils/homeCliCommand.js";
import { setCommandExitCode } from "../utils/commandResult.js";
import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
@@ -170,17 +170,19 @@ export type CliUpgradeOutcome =
| { status: "unchanged"; version: string; command: string; reason: string }
| { status: "unverified"; command: string; reason: string }
| { status: "manual"; command: string; reason: string }
| { status: "failed"; command: string };
| { status: "failed"; command: string; reason?: string };
/** The version Homebrew's linked `hyperframes` reports, or null when it cannot be read. */
function brewInstalledVersion(): string | null {
function brewInstalledVersion(cwd: string): string | null {
try {
const prefix = execFileSync("brew", ["--prefix", "hyperframes"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: false,
}).trim();
const version = execFileSync(join(prefix, "bin", "hyperframes"), ["--version"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: false,
@@ -200,8 +202,13 @@ export function upgradeRunningCli(latest: string): CliUpgradeOutcome {
if (!isSafeVersion(latest)) return { status: "failed", command: NPX_LATEST };
const plan = upgradePlan(latest);
if ("manual" in plan) return { status: "manual", command: plan.manual, reason: plan.reason };
const location = globalInstallLocation();
if ("reason" in location)
return { status: "failed", command: plan.displayCmd, reason: location.reason };
const { cwd } = location;
try {
execFileSync(plan.invocation.bin, plan.invocation.args, {
cwd,
stdio: ["inherit", 2, 2],
shell: false,
});
@@ -209,7 +216,7 @@ export function upgradeRunningCli(latest: string): CliUpgradeOutcome {
return { status: "failed", command: plan.displayCmd };
}
// `brew upgrade` installs whatever the formula pins, which can lag npm, and exits 0 on a no-op.
const installed = plan.pinsVersion ? latest : brewInstalledVersion();
const installed = plan.pinsVersion ? latest : brewInstalledVersion(cwd);
const command = plan.displayCmd;
if (installed === null) {
return { status: "unverified", command, reason: "the installed version could not be read" };
@@ -327,16 +334,26 @@ export function runDetectedInstall(
displayCmd: string,
version: string,
): void {
const location = globalInstallLocation();
if ("reason" in location) {
clack.outro(c.dim(location.reason));
setCommandExitCode(1);
return;
}
console.log();
console.log(` ${c.dim("Running:")} ${c.accent(displayCmd)}`);
console.log();
try {
// shell:false — version is provably safe per isSafeVersion above; keep the
// no-shell call so future edits can't regress the injection surface.
execFileSync(invocation.bin, invocation.args, { stdio: "inherit", shell: false });
execFileSync(invocation.bin, invocation.args, {
cwd: location.cwd,
stdio: "inherit",
shell: false,
});
clack.outro(c.success(`Upgraded to v${version}`));
} catch {
clack.outro(c.dim("Install failed. Try running manually:"));
clack.outro(c.dim("Install failed. Retry from your home directory:"));
console.log(` ${c.accent(displayCmd)}`);
setCommandExitCode(1);
}
@@ -4,6 +4,7 @@ import {
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
utimesSync,
writeFileSync,
@@ -29,10 +30,17 @@ function setup(staleMs = 60_000) {
mkdirSync(runningDir);
const marker = join(dir, "installed");
const script = installerScript({
cwd: dir,
configFile: join(dir, "config.json"),
version: "9.9.9",
bin: process.execPath,
args: ["-e", `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "")`],
args: [
"-e",
`const fs = require("node:fs");
fs.writeFileSync(${JSON.stringify(marker)}, JSON.stringify({
cwd: process.cwd(), localConfig: fs.existsSync("bunfig.toml")
}));`,
],
runningDir,
pollMs: 50,
maxWaitMs: 60_000,
@@ -41,8 +49,8 @@ function setup(staleMs = 60_000) {
return { dir, runningDir, marker, script };
}
function start(args: string[]): ChildProcess {
const child = spawn(process.execPath, args, { stdio: "ignore" });
function start(args: string[], cwd?: string): ChildProcess {
const child = spawn(process.execPath, args, { cwd, stdio: "ignore" });
children.push(child);
return child;
}
@@ -74,6 +82,20 @@ function registerCli(runningDir: string): ChildProcess {
return cli;
}
it("runs the manager in the selected home even when the installer starts in a project", async () => {
const { dir, marker, script } = setup();
const project = join(dir, "project");
mkdirSync(project);
writeFileSync(join(project, "bunfig.toml"), "[install]\nexact = true\n");
await exited(start(["-e", script], project));
expect(JSON.parse(readFileSync(marker, "utf8"))).toEqual({
cwd: realpathSync(dir),
localConfig: false,
});
});
it("never replaces package files while a CLI process is running, then installs once it exits", async () => {
const { dir, runningDir, marker, script } = setup();
const cli = registerCli(runningDir);
@@ -64,7 +64,12 @@ async function patchAvailableAt(entry: string) {
}));
process.argv = [process.argv[0] ?? "node", entry];
for (const name of ["CI", "HYPERFRAMES_NO_AUTO_INSTALL", "HYPERFRAMES_NO_UPDATE_CHECK"]) {
for (const name of [
"CI",
"npm_lifecycle_event",
"HYPERFRAMES_NO_AUTO_INSTALL",
"HYPERFRAMES_NO_UPDATE_CHECK",
]) {
delete process.env[name];
}
Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
+88 -3
View File
@@ -1,7 +1,8 @@
// fallow-ignore-file code-duplication
import { execFileSync, spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { EventEmitter } from "node:events";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -91,6 +92,7 @@ function setupMocks(opts: {
// before the test runs. Critical for CI, where GitHub Actions always sets
// CI=true and would cause every scheduling assertion to fail false-negative.
// Tests that specifically want one of these set pass it via opts.env.
delete process.env["npm_lifecycle_event"];
delete process.env["CI"];
delete process.env["HYPERFRAMES_NO_AUTO_INSTALL"];
delete process.env["HYPERFRAMES_NO_UPDATE_CHECK"];
@@ -117,6 +119,7 @@ describe("scheduleBackgroundInstall", () => {
vi.doUnmock("./installerDetection.js");
vi.doUnmock("node:child_process");
vi.doUnmock("node:fs");
vi.doUnmock("node:os");
vi.resetModules();
});
@@ -129,12 +132,94 @@ describe("scheduleBackgroundInstall", () => {
const scheduled = scheduleBackgroundInstall("0.4.4", "0.4.3");
expect(scheduled).toBe(true);
expect(spawnSpy).toHaveBeenCalledOnce();
expect(spawnSpy).toHaveBeenCalledWith(
process.execPath,
expect.any(Array),
expect.objectContaining({ cwd: homedir(), detached: true }),
);
expect(writeSpy).toHaveBeenCalled();
expect(config.pendingUpdate?.version).toBe("0.4.4");
expect(config.pendingUpdate?.command).toBe("npm install -g hyperframes@0.4.4");
});
it.each(["missing", "relative", "file"] as const)(
"skips an install with a %s home directory",
async (kind) => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "bun", command: "bun add -g hyperframes@0.4.4" },
});
const homes = { missing: join(homedir(), "absent"), relative: ".", file: process.execPath };
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => homes[kind],
}));
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
},
);
it.skipIf(!process.geteuid).each([
["other-owner", "belongs to a different user"],
["group-writable", "allows writes by the group or other users"],
] as const)(
"explains a rejected %s home on stderr without writing in it",
async (kind, message) => {
const home = mkdtempSync(join(tmpdir(), "hf-update-home-"));
try {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
});
if (kind === "other-owner") {
vi.spyOn(process, "geteuid").mockReturnValue(process.geteuid!() + 1);
} else {
chmodSync(home, 0o775);
}
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => home,
}));
const stderr = vi.spyOn(process.stderr, "write").mockReturnValue(true);
const fs = await import("node:fs");
const logWrite = vi.spyOn(fs, "appendFileSync");
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(stderr).toHaveBeenCalledWith(expect.stringContaining(message));
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
expect(logWrite).not.toHaveBeenCalled();
} finally {
vi.restoreAllMocks();
rmSync(home, { recursive: true, force: true });
}
},
);
it("leaves no pending install when launched by a package script", async () => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "bun", command: "bun add -g hyperframes@0.4.4" },
env: { npm_lifecycle_event: "preview", npm_config_color: "always" },
});
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
});
it("clears the pending update if the installer cannot enter its working directory", async () => {
const { spawnSpy, config } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
});
const child = new EventEmitter();
spawnSpy.mockReturnValueOnce(child);
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
child.emit("error", new Error("ENOENT"));
expect(config.pendingUpdate).toBeUndefined();
});
it("schedules nothing from a CLI that could not put itself on record as running", async () => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
+24 -7
View File
@@ -25,6 +25,8 @@
import { spawn } from "node:child_process";
import { appendFileSync, mkdirSync, openSync } from "node:fs";
import { resolve } from "node:path";
import { globalInstallLocation } from "./homeCliCommand.js";
import { compareVersions } from "compare-versions";
import { withFileLock } from "../media-use/lib/config-lock.mjs";
import { readConfig, writeConfig } from "../telemetry/config.js";
@@ -73,6 +75,7 @@ function log(line: string): void {
}
export interface InstallerScriptOptions {
cwd: string;
configFile: string;
version: string;
bin: string;
@@ -144,7 +147,7 @@ export function installerScript(o: InstallerScriptOptions): string {
clearInterval(lockBeat);
if (ownsLock()) { try { fs.unlinkSync(INSTALL_LOCK); } catch (e) {} }
};
const install = () => execFile(BIN, ARGS, { windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => {
const install = () => execFile(BIN, ARGS, { cwd: ${JSON.stringify(o.cwd)}, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => {
withLock(() => {
let cfg = {};
try { cfg = JSON.parse(readFileSync(CFG, "utf-8")); } catch (e) { if (e.code !== "ENOENT") return; }
@@ -205,16 +208,18 @@ function launchDetachedInstall(
invocation: InstallInvocation,
displayCommand: string,
version: string,
cwd: string,
): void {
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
const configFile = seededConfigFile("config.json");
const nodeScript = installerScript({
configFile,
cwd,
configFile: resolve(configFile),
version,
bin: invocation.bin,
args: invocation.args,
runningDir: runningDir(),
runningDir: resolve(runningDir()),
pollMs: INSTALL_POLL_MS,
maxWaitMs: INSTALL_MAX_WAIT_MS,
staleMs: RUNNING_STALE_MS,
@@ -222,13 +227,19 @@ function launchDetachedInstall(
const out = openSync(logFile(), "a", 0o600);
const child = spawn(process.execPath, ["-e", nodeScript], {
cwd,
detached: true,
stdio: ["ignore", out, out],
windowsHide: true,
env: { ...process.env, HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_AUTO_INSTALL: "1" },
});
if (child.pid === undefined) {
// A vanished cwd makes spawn return without a pid and emit its error on the next tick.
child.once("error", (err) => log(`[error] ${err.message}`));
throw new Error("Detached installer did not start");
}
child.unref();
log(`[launch] pid=${child.pid ?? "?"} cmd=${displayCommand} version=${version}`);
log(`[launch] pid=${child.pid} cmd=${displayCommand} version=${version}`);
}
function isSilentUpgrade(latestVersion: string, currentVersion: string): boolean {
@@ -276,6 +287,14 @@ function backgroundInstaller(
export function scheduleBackgroundInstall(latestVersion: string, currentVersion: string): boolean {
if (isAutoInstallDisabled()) return false;
if (!isSilentUpgrade(latestVersion, currentVersion)) return false;
const installer = backgroundInstaller(latestVersion);
if (!installer) return false;
const location = globalInstallLocation();
if ("reason" in location) {
// The rejected home may be shared or belong to another user, so avoid opening a log in it.
process.stderr.write(` Skipping CLI auto-update: ${location.reason}\n`);
return false;
}
if (!registeredAsRunning()) {
log(
`[skip] ${latestVersion}: this CLI is not on record as running, so an install could replace it mid-run`,
@@ -283,8 +302,6 @@ export function scheduleBackgroundInstall(latestVersion: string, currentVersion:
return false;
}
const installer = backgroundInstaller(latestVersion);
if (!installer) return false;
const { installCommand, invocation } = installer;
const config = readConfig();
@@ -313,7 +330,7 @@ export function scheduleBackgroundInstall(latestVersion: string, currentVersion:
if (!writeConfig(config)) return false;
try {
launchDetachedInstall(invocation, installCommand, latestVersion);
launchDetachedInstall(invocation, installCommand, latestVersion, location.cwd);
return true;
} catch (err) {
log(`[error] spawn failed: ${String(err)}`);
+37
View File
@@ -1,3 +1,40 @@
import { accessSync, constants, statSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute } from "node:path";
type GlobalInstallLocation = { cwd: string } | { reason: string };
export function globalInstallLocation(): GlobalInstallLocation {
// Package scripts inherit project configuration and executable search paths from their manager.
if (process.env["npm_lifecycle_event"]) {
return {
reason: "Run the global CLI update directly from your shell, outside the package script.",
};
}
const unavailable = { reason: "The CLI update needs an accessible, absolute home directory." };
try {
const home = homedir();
if (!isAbsolute(home)) return unavailable;
const stat = statSync(home);
if (!stat.isDirectory()) return unavailable;
if (process.geteuid) {
if (stat.uid !== process.geteuid()) {
return {
reason:
"The home directory belongs to a different user. Run the update as the home owner, or use the effective user's own home directory.",
};
}
if ((stat.mode & 0o022) !== 0) {
return { reason: "The home directory allows writes by the group or other users." };
}
}
accessSync(home, constants.X_OK);
return { cwd: home };
} catch {
return unavailable;
}
}
/** Manual update commands are often copied from a project terminal. Start npm in the home folder. */
export function homeCliCommand(
release: string,