Skip to content

Commit 00d542d

Browse files
authored
fix(update): npm-hardened global updates no longer roll back
Closes #134177 ## What Problem This Solves Fixes an issue where operators with npm `ignore-scripts=true` could download an OpenClaw update successfully, but strict package verification rejected the retained lifecycle guard and left the old version active. ## Why This Change Was Made The staged npm install remains fully script-disabled, including for every dependency. Strict package verification runs before any lifecycle code. That boundary allows only the documented legacy guard from the exact `[email protected]` registry target. The shared owner then completes only OpenClaw's pending preinstall and postinstall work, and strict verification runs again before activation. npm keeps its package-scoped allowance when supported, packaged-dist verification stays strict, and no global script policy changes. The shipped `2026.8.1` postinstall predates the root lifecycle marker. The owner now finalizes that promoted marker only after both legacy scripts succeed. ## User Impact Managed npm updates work on hardened hosts without enabling lifecycle scripts for unrelated packages or weakening package verification. ## Evidence - Published `v2026.8.1` red: `2026.7.1 -> 2026.8.1` staged install exited 0, verification rejected `dist/openclaw-install-guard`, update exited 1, and `2026.7.1` stayed active. - Main red at `0e0b89663f945324a9a9698a58ff8019fe78da8a`: a varied real-npm `1.0.0 -> 2.2.0` update reproduced the same retained guard and rollback. - Exact-head green: the real published `[email protected]` package passed the narrow pre-lifecycle check, completed only its two lifecycle scripts, passed strict post-lifecycle verification, and activated `2026.8.1`. - Security anti-cheat: a guard plus another unexpected dist file runs no lifecycle script, performs no swap, and leaves the old version active. - CLI and owner tests: `node scripts/run-vitest.mjs src/cli/update-cli.test.ts src/infra/package-lifecycle.test.ts src/infra/package-update-steps.test.ts src/infra/package-update-steps.pnpm11-guard.test.ts` — 329 passed. - Formatting, focused Oxlint, conflict-marker, max-lines, assertion-safety, test-temp, and diff checks passed. - Production delta: `+57/-44`, net `+13`. The growth enforces verify-before-execute and strict verify-after-execute around the shipped legacy exception. Tests: `+77/-12`. GitHub CI owns build, typecheck, platform, and merge gates. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent ace8a13 commit 00d542d

4 files changed

Lines changed: 134 additions & 56 deletions

File tree

‎src/cli/update-cli.test.ts‎

Lines changed: 75 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { Command } from "commander";
99
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1010
import { PLUGIN_CAPABILITY_CONSENT_REQUIRED } from "../../packages/gateway-protocol/src/capability-consent-error-details.js";
1111
import { writePackageDistInventory } from "../../scripts/lib/package-dist-inventory.ts";
12+
import { LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH } from "../../scripts/lib/package-lifecycle-marker.mjs";
1213
import { createDeferred } from "../../test/helpers/promise.js";
1314
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
1415
import type { OpenClawConfig, ConfigFileSnapshot } from "../config/types.openclaw.js";
@@ -5049,25 +5050,27 @@ describe("update-cli", () => {
50495050
const tempDir = tempDirs.make("openclaw-update-staged-fail-");
50505051
const prefix = path.join(tempDir, "prefix");
50515052
const nodeModules = path.join(prefix, "lib", "node_modules");
5052-
const { pkgRoot } = await setupInstalledPackageAtNodeModules(nodeModules, "2026.4.20");
5053-
readPackageVersion.mockResolvedValue("2026.4.20");
5054-
primeNpmChannelTag("latest", "2026.4.25");
5053+
const { pkgRoot } = await setupInstalledPackageAtNodeModules(nodeModules, "2026.7.1");
5054+
readPackageVersion.mockResolvedValue("2026.7.1");
5055+
primeNpmChannelTag("latest", "2026.8.1");
50555056
mockNpmGlobalCommands(nodeModules, async (argv) => {
50565057
if (argv[0] === "npm" && argv[1] === "i" && argv.includes("--prefix")) {
50575058
const stagePrefix = argv[argv.indexOf("--prefix") + 1];
50585059
if (typeof stagePrefix !== "string") {
50595060
throw new Error("missing stage prefix");
50605061
}
50615062
const stageRoot = path.join(stagePrefix, "lib", "node_modules", "openclaw");
5062-
await writeOpenClawPackageFixture(stageRoot, "2026.4.25", {
5063+
await writeOpenClawPackageFixture(stageRoot, "2026.8.1", {
50635064
entrySource: "export {};\n",
50645065
inventory: true,
50655066
});
5066-
await fs.writeFile(
5067-
path.join(stageRoot, "dist", "stale-runtime.js"),
5068-
"export {};\n",
5069-
"utf-8",
5070-
);
5067+
await Promise.all([
5068+
fs.writeFile(
5069+
path.join(stageRoot, LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH),
5070+
"pending\n",
5071+
),
5072+
fs.writeFile(path.join(stageRoot, "dist", "stale-runtime.js"), "export {};\n", "utf-8"),
5073+
]);
50715074
}
50725075
});
50735076

@@ -5076,14 +5079,76 @@ describe("update-cli", () => {
50765079
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
50775080
expect(doctorCommandCall()).toBeUndefined();
50785081
expect(updateNpmInstalledPlugins).not.toHaveBeenCalled();
5082+
expect(
5083+
commandCalls().some(
5084+
([argv]) => argv[0] === process.execPath && argv[1]?.includes("/scripts/"),
5085+
),
5086+
).toBe(false);
50795087
await expect(fs.readFile(path.join(pkgRoot, "package.json"), "utf-8")).resolves.toContain(
5080-
'"version":"2026.4.20"',
5088+
'"version":"2026.7.1"',
50815089
);
50825090
const logs = getLogOutput();
50835091
expect(logs).toContain("global install verify");
50845092
expect(logs).toContain("unexpected packaged dist file dist/stale-runtime.js");
50855093
});
50865094

5095+
it("completes a suppressed npm lifecycle before activating the staged package", async () => {
5096+
const tempDir = tempDirs.make("openclaw-update-staged-lifecycle-");
5097+
const prefix = path.join(tempDir, "prefix");
5098+
const nodeModules = path.join(prefix, "lib", "node_modules");
5099+
const { pkgRoot } = await setupInstalledPackageAtNodeModules(nodeModules, "2026.7.1");
5100+
readPackageVersion.mockImplementation(async (packageRoot: string) =>
5101+
(await fs.readFile(path.join(packageRoot, "package.json"), "utf-8")).includes("2026.8.1")
5102+
? "2026.8.1"
5103+
: "2026.7.1",
5104+
);
5105+
primeNpmChannelTag("latest", "2026.8.1");
5106+
vi.mocked(resolveGatewayInstallEntrypoint).mockResolvedValue(
5107+
path.join(pkgRoot, "dist", "index.js"),
5108+
);
5109+
runPostCorePluginConvergenceSpy.mockResolvedValueOnce(postCoreConvergenceResult());
5110+
vi.mocked(runExec).mockResolvedValue({ stdout: "", stderr: "" });
5111+
mockNpmGlobalCommands(nodeModules, async (argv) => {
5112+
if (argv[0] === "npm" && argv[1] === "i" && argv.includes("--prefix")) {
5113+
const stagePrefix = requireValue(argv[argv.indexOf("--prefix") + 1], "staged prefix");
5114+
const stageRoot = path.join(stagePrefix, "lib", "node_modules", "openclaw");
5115+
await writeOpenClawPackageFixture(stageRoot, "2026.8.1", {
5116+
entrySource: "export {};\n",
5117+
inventory: true,
5118+
});
5119+
await fs.writeFile(
5120+
path.join(stageRoot, LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH),
5121+
"pending\n",
5122+
);
5123+
}
5124+
if (
5125+
argv[0] === process.execPath &&
5126+
argv[1]?.endsWith("preinstall-package-manager-warning.mjs")
5127+
) {
5128+
await fs.rm(
5129+
path.join(path.dirname(path.dirname(argv[1])), "dist", "openclaw-install-guard"),
5130+
);
5131+
}
5132+
return undefined;
5133+
});
5134+
5135+
await updateCommand({ yes: true, restart: false, json: true });
5136+
5137+
expect(defaultRuntime.exit).not.toHaveBeenCalledWith(1);
5138+
expect(lastWriteJsonCall()).toMatchObject({ status: "ok", after: { version: "2026.8.1" } });
5139+
expect(
5140+
commandCalls()
5141+
.filter(([argv]) => argv[0] === process.execPath && argv[1]?.includes("/scripts/"))
5142+
.map(([argv]) => path.basename(requireValue(argv[1], "lifecycle script"))),
5143+
).toEqual(["preinstall-package-manager-warning.mjs", "postinstall-bundled-plugins.mjs"]);
5144+
await expect(fs.readFile(path.join(pkgRoot, "package.json"), "utf-8")).resolves.toContain(
5145+
'"version":"2026.8.1"',
5146+
);
5147+
await expect(
5148+
fs.access(path.join(pkgRoot, LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH)),
5149+
).rejects.toMatchObject({ code: "ENOENT" });
5150+
});
5151+
50875152
it("runs old package doctors without fix mode when service ownership is unknown", async () => {
50885153
const tempDir = tempDirs.make("openclaw-update-package-");
50895154
const { nodeModules, pkgRoot, entryPath } = await setupInstalledPackageRoot(tempDir);

‎src/infra/package-lifecycle.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,12 @@ describe("package lifecycle completion", () => {
136136
await expect(fs.readFile(markerPath, "utf8")).resolves.toBe("pending\n");
137137
if (script.name === "preinstall") {
138138
await fs.rm(legacyGuardPath);
139-
} else {
140-
await fs.rm(markerPath);
141139
}
142140
},
143141
}),
144142
).resolves.toBe(true);
143+
await expect(fs.access(markerPath)).rejects.toMatchObject({ code: "ENOENT" });
144+
await expect(fs.access(legacyGuardPath)).rejects.toMatchObject({ code: "ENOENT" });
145145
});
146146
});
147147
});

‎src/infra/package-lifecycle.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ export async function completePendingPackageLifecycle(params: {
157157
if (!(await isPackageLifecyclePending(paths))) {
158158
return false;
159159
}
160+
const finalizePromotedLegacyMarker = !(await pathExists(paths.pending));
160161
// Promote the shipped 2026.8.1 dist guard before preinstall removes it.
161162
// Postinstall alone clears the canonical marker after all lifecycle work succeeds.
162163
await ensurePendingMarker(paths.pending);
@@ -166,6 +167,10 @@ export async function completePendingPackageLifecycle(params: {
166167
for (const script of PACKAGE_LIFECYCLE_SCRIPTS) {
167168
await runScript(script);
168169
}
170+
if (finalizePromotedLegacyMarker) {
171+
// v2026.8.1 postinstall predates this marker; finalize it after both scripts succeed.
172+
await fs.rm(paths.pending, { force: true });
173+
}
169174
if (await isPackageLifecyclePending(paths)) {
170175
throw new Error("OpenClaw package postinstall did not complete its lifecycle marker");
171176
}

‎src/infra/package-update-steps.ts‎

Lines changed: 52 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import { pathToFileURL } from "node:url";
6+
import { LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH } from "../../scripts/lib/package-lifecycle-marker.mjs";
67
import { resolveBunGlobalInstallOwner } from "./detect-package-manager.js";
78
import { formatErrorMessage } from "./errors.js";
89
import { pathExists } from "./fs-safe.js";
@@ -1101,49 +1102,6 @@ export async function runGlobalPackageUpdateSteps(params: {
11011102
return packageUpdateFailure(failedStep, null, [...steps, failedStep]);
11021103
}
11031104

1104-
if (
1105-
finalInstallStep.exitCode === 0 &&
1106-
!stagedInstall &&
1107-
params.installTarget.manager === "pnpm" &&
1108-
verificationPackageRoot
1109-
) {
1110-
let failedLifecycleStep: PackageUpdateStepResult | null = null;
1111-
try {
1112-
await completePendingPackageLifecycle({
1113-
packageRoot: verificationPackageRoot,
1114-
timeoutMs: params.timeoutMs,
1115-
runScript: async (script) => {
1116-
const lifecycleStep = await params.runStep({
1117-
name: `pnpm package ${script.name}`,
1118-
argv: [process.execPath, path.join(verificationPackageRoot, script.relativePath)],
1119-
cwd: verificationPackageRoot,
1120-
env: effectiveInstallEnv,
1121-
timeoutMs: params.timeoutMs,
1122-
});
1123-
steps.push(lifecycleStep);
1124-
if (lifecycleStep.exitCode !== 0) {
1125-
failedLifecycleStep = lifecycleStep;
1126-
throw new Error(lifecycleStep.stderrTail ?? `${lifecycleStep.name} failed`);
1127-
}
1128-
},
1129-
});
1130-
} catch (error) {
1131-
if (failedLifecycleStep) {
1132-
return packageUpdateFailure(failedLifecycleStep, verifiedPackageRoot, steps);
1133-
}
1134-
const lifecycleStep: PackageUpdateStepResult = {
1135-
name: "pnpm package lifecycle",
1136-
command: `complete ${verificationPackageRoot}`,
1137-
cwd: verificationPackageRoot,
1138-
durationMs: 0,
1139-
exitCode: 1,
1140-
stderrTail: formatErrorMessage(error),
1141-
};
1142-
steps.push(lifecycleStep);
1143-
return packageUpdateFailure(lifecycleStep, verifiedPackageRoot, steps);
1144-
}
1145-
}
1146-
11471105
let afterVersion: string | null = null;
11481106
if (finalInstallStep.exitCode === 0 && verificationPackageRoot) {
11491107
const candidateVersion = await readPackageVersion(verificationPackageRoot);
@@ -1154,11 +1112,61 @@ export async function runGlobalPackageUpdateSteps(params: {
11541112
params.packageName,
11551113
params.installSpec,
11561114
);
1157-
const verificationErrors = await collectInstalledGlobalPackageErrors({
1115+
let verificationErrors = await collectInstalledGlobalPackageErrors({
11581116
packageRoot: verificationPackageRoot,
11591117
expectedVersion,
11601118
expectedGitCheckout: params.expectedGitCheckout,
11611119
});
1120+
// v2026.8.1 alone shipped this pending marker inside the closed dist inventory.
1121+
const blockingVerificationErrors = verificationErrors.filter(
1122+
(error) =>
1123+
params.installSpec !== "[email protected]" ||
1124+
error !== `unexpected packaged dist file ${LEGACY_PACKAGE_INSTALL_GUARD_RELATIVE_PATH}`,
1125+
);
1126+
if (blockingVerificationErrors.length === 0) {
1127+
let failedLifecycleStep: PackageUpdateStepResult | null = null;
1128+
try {
1129+
const completedLifecycle = await completePendingPackageLifecycle({
1130+
packageRoot: verificationPackageRoot,
1131+
timeoutMs: params.timeoutMs,
1132+
runScript: async (script) => {
1133+
const lifecycleStep = await params.runStep({
1134+
name: `${params.installTarget.manager} package ${script.name}`,
1135+
argv: [process.execPath, path.join(verificationPackageRoot, script.relativePath)],
1136+
cwd: verificationPackageRoot,
1137+
env: effectiveInstallEnv,
1138+
timeoutMs: params.timeoutMs,
1139+
});
1140+
steps.push(lifecycleStep);
1141+
if (lifecycleStep.exitCode !== 0) {
1142+
failedLifecycleStep = lifecycleStep;
1143+
throw new Error(lifecycleStep.stderrTail ?? `${lifecycleStep.name} failed`);
1144+
}
1145+
},
1146+
});
1147+
if (completedLifecycle) {
1148+
verificationErrors = await collectInstalledGlobalPackageErrors({
1149+
packageRoot: verificationPackageRoot,
1150+
expectedVersion,
1151+
expectedGitCheckout: params.expectedGitCheckout,
1152+
});
1153+
}
1154+
} catch (error) {
1155+
if (failedLifecycleStep) {
1156+
return packageUpdateFailure(failedLifecycleStep, verifiedPackageRoot, steps);
1157+
}
1158+
const lifecycleStep: PackageUpdateStepResult = {
1159+
name: `${params.installTarget.manager} package lifecycle`,
1160+
command: `complete ${verificationPackageRoot}`,
1161+
cwd: verificationPackageRoot,
1162+
durationMs: 0,
1163+
exitCode: 1,
1164+
stderrTail: formatErrorMessage(error),
1165+
};
1166+
steps.push(lifecycleStep);
1167+
return packageUpdateFailure(lifecycleStep, verifiedPackageRoot, steps);
1168+
}
1169+
}
11621170
if (verificationErrors.length > 0) {
11631171
steps.push({
11641172
name: "global install verify",

0 commit comments

Comments
 (0)