mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
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:
@@ -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 });
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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)}`);
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user