Skip to content

Commit 7f842da

Browse files
authored
fix(plugins): restrict npm project cleanup to owned roots (#124608)
* fix(plugins): validate npm project root ownership Restrict recursive managed npm project deletion to canonical ordinary or exact generation roots. Preserve noncanonical sibling roots while retaining package-leaf cleanup and valid generation lifecycle behavior.\n\nFixes #123972 * fix(plugins): reject substituted npm project roots * fix(plugins): pin managed npm root identity * fix(plugins): revalidate npm package removals * fix(plugins): validate npm cleanup descendants * fix(plugins): reject npm cleanup symlink aliases * fix(plugins): bind npm cleanup to planned root kind
1 parent 51964c1 commit 7f842da

7 files changed

Lines changed: 693 additions & 87 deletions

‎src/plugins/install-paths.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Resolves plugin install paths for local and package sources.
22
import { createHash } from "node:crypto";
3+
import { lstatSync, realpathSync } from "node:fs";
34
import path from "node:path";
5+
import { resolvePathViaExistingAncestorSync } from "../infra/boundary-path.js";
46
import {
57
resolveSafeInstallDir,
68
safeDirName,
@@ -124,12 +126,69 @@ export function resolvePluginNpmProjectDir(params: {
124126

125127
const PLUGIN_NPM_GENERATION_PROJECT_SEPARATOR = "__openclaw-generation__";
126128
const PLUGIN_NPM_GENERATION_KEY_HASH_CHARS = 16;
129+
const PLUGIN_NPM_GENERATION_KEY_DIR_NAME_PATTERN = new RegExp(
130+
`^g-[a-f0-9]{${PLUGIN_NPM_GENERATION_KEY_HASH_CHARS}}$`,
131+
"u",
132+
);
127133

128134
/** Resolves the managed npm artifact-generation project directory prefix for a package. */
129135
export function resolvePluginNpmGenerationProjectDirPrefix(packageName: string): string {
130136
return `${encodePluginNpmProjectDirName(packageName)}${PLUGIN_NPM_GENERATION_PROJECT_SEPARATOR}`;
131137
}
132138

139+
/** Checks that a managed path preserves its npm-root-relative real path. */
140+
export function isPluginNpmManagedPath(params: {
141+
managedPath: string;
142+
npmDir?: string;
143+
allowMissing?: boolean;
144+
}): boolean {
145+
const npmDir = path.resolve(params.npmDir ?? resolveDefaultPluginNpmDir());
146+
const managedPath = path.resolve(params.managedPath);
147+
try {
148+
return (
149+
lstatSync(npmDir).isDirectory() &&
150+
path.relative(npmDir, managedPath) ===
151+
path.relative(
152+
realpathSync(npmDir),
153+
params.allowMissing
154+
? resolvePathViaExistingAncestorSync(managedPath)
155+
: realpathSync(managedPath),
156+
)
157+
);
158+
} catch {
159+
return false;
160+
}
161+
}
162+
163+
/** Checks whether a project directory has the exact managed shape owned by a package. */
164+
export function isPluginNpmProjectDir(params: {
165+
packageName: string;
166+
projectDir: string;
167+
npmDir?: string;
168+
}): boolean {
169+
const npmDir = path.resolve(params.npmDir ?? resolveDefaultPluginNpmDir());
170+
const projectDir = path.resolve(params.projectDir);
171+
if (path.dirname(projectDir) !== path.resolve(resolvePluginNpmProjectsDir(npmDir))) {
172+
return false;
173+
}
174+
if (!isPluginNpmManagedPath({ managedPath: projectDir, npmDir })) {
175+
return false;
176+
}
177+
const packageDir = path.join(projectDir, "node_modules", ...params.packageName.split("/"));
178+
if (!isPluginNpmManagedPath({ managedPath: packageDir, npmDir, allowMissing: true })) {
179+
return false;
180+
}
181+
if (projectDir === path.resolve(resolvePluginNpmProjectDir(params))) {
182+
return true;
183+
}
184+
const projectName = path.basename(projectDir);
185+
const generationPrefix = resolvePluginNpmGenerationProjectDirPrefix(params.packageName);
186+
return (
187+
projectName.startsWith(generationPrefix) &&
188+
PLUGIN_NPM_GENERATION_KEY_DIR_NAME_PATTERN.test(projectName.slice(generationPrefix.length))
189+
);
190+
}
191+
133192
/** Encodes a package generation fingerprint into a compact project directory suffix. */
134193
function encodePluginNpmGenerationKeyDirName(generationKey: string): string {
135194
const digest = createHash("sha256").update(generationKey).digest("hex");

‎src/plugins/install-persistence.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ describe("persistPluginInstall", () => {
403403
kind: "npm",
404404
npmRoot: previousProjectRoot,
405405
packageName: "@openclaw/codex",
406+
rootKind: "isolated-project",
406407
},
407408
},
408409
});
Lines changed: 89 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,50 @@
11
import fs from "node:fs";
2-
import os from "node:os";
32
import path from "node:path";
43
import { afterEach, describe, expect, it } from "vitest";
54
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
6-
import { resolvePluginNpmGenerationProjectDir } from "./install-paths.js";
5+
import {
6+
resolvePluginNpmGenerationProjectDir,
7+
resolvePluginNpmProjectDir,
8+
} from "./install-paths.js";
79
import { RETAINED_MANAGED_NPM_KEEP_FILES_REASON } from "./managed-npm-retention-contract.js";
8-
9-
const retentionTempDirs = useAutoCleanupTempDirTracker(afterEach);
1010
import {
1111
cleanupRetainedManagedNpmInstallGenerations,
1212
hasRetainedManagedNpmInstallMarker,
1313
markRetainedManagedNpmInstall,
1414
} from "./managed-npm-retention.js";
1515

16+
const retentionTempDirs = useAutoCleanupTempDirTracker(afterEach);
17+
1618
describe("managed npm retention", () => {
17-
it("cleans retired generations while preserving the active install root", async () => {
18-
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-retention-"));
19-
const npmDir = path.join(stateDir, "npm");
20-
const packageName = "@openclaw/codex";
21-
const oldProjectRoot = resolvePluginNpmGenerationProjectDir({
22-
npmDir,
23-
packageName,
24-
generationKey: "codex-v1",
25-
});
26-
const activeProjectRoot = resolvePluginNpmGenerationProjectDir({
27-
npmDir,
28-
packageName,
29-
generationKey: "codex-v2",
30-
});
31-
const oldPackageDir = path.join(oldProjectRoot, "node_modules", "@openclaw", "codex");
32-
const activePackageDir = path.join(activeProjectRoot, "node_modules", "@openclaw", "codex");
33-
fs.mkdirSync(oldPackageDir, { recursive: true });
34-
fs.mkdirSync(activePackageDir, { recursive: true });
35-
await markRetainedManagedNpmInstall({
36-
packageDir: oldPackageDir,
37-
pluginId: "codex",
38-
reason: "test-retired-generation",
39-
});
19+
it.each(["ordinary", "generation"] as const)(
20+
"cleans a retired %s project while preserving the active install root",
21+
async (layout) => {
22+
const stateDir = retentionTempDirs.make("openclaw-retention-");
23+
const npmDir = path.join(stateDir, "npm");
24+
const packageName = "@openclaw/codex";
25+
const oldProjectRoot =
26+
layout === "ordinary"
27+
? resolvePluginNpmProjectDir({ npmDir, packageName })
28+
: resolvePluginNpmGenerationProjectDir({
29+
npmDir,
30+
packageName,
31+
generationKey: "codex-v1",
32+
});
33+
const activeProjectRoot = resolvePluginNpmGenerationProjectDir({
34+
npmDir,
35+
packageName,
36+
generationKey: "codex-v2",
37+
});
38+
const oldPackageDir = path.join(oldProjectRoot, "node_modules", "@openclaw", "codex");
39+
const activePackageDir = path.join(activeProjectRoot, "node_modules", "@openclaw", "codex");
40+
fs.mkdirSync(oldPackageDir, { recursive: true });
41+
fs.mkdirSync(activePackageDir, { recursive: true });
42+
await markRetainedManagedNpmInstall({
43+
packageDir: oldPackageDir,
44+
pluginId: "codex",
45+
reason: "test-retired-generation",
46+
});
4047

41-
try {
4248
await expect(
4349
cleanupRetainedManagedNpmInstallGenerations({
4450
npmDir,
@@ -48,13 +54,11 @@ describe("managed npm retention", () => {
4854
expect(fs.existsSync(oldProjectRoot)).toBe(false);
4955
expect(fs.existsSync(activeProjectRoot)).toBe(true);
5056
expect(hasRetainedManagedNpmInstallMarker(activePackageDir)).toBe(false);
51-
} finally {
52-
fs.rmSync(stateDir, { recursive: true, force: true });
53-
}
54-
});
57+
},
58+
);
5559

5660
it("cleans retained packages from the legacy shared npm root", async () => {
57-
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-retention-"));
61+
const stateDir = retentionTempDirs.make("openclaw-retention-");
5862
const npmDir = path.join(stateDir, "npm");
5963
const packageDir = path.join(npmDir, "node_modules", "@openclaw", "codex");
6064
fs.mkdirSync(packageDir, { recursive: true });
@@ -64,17 +68,55 @@ describe("managed npm retention", () => {
6468
reason: "test-legacy-generation",
6569
});
6670

67-
try {
68-
await expect(
69-
cleanupRetainedManagedNpmInstallGenerations({
70-
npmDir,
71-
}),
72-
).resolves.toBe(1);
73-
expect(fs.existsSync(packageDir)).toBe(false);
74-
expect(hasRetainedManagedNpmInstallMarker(packageDir)).toBe(false);
75-
} finally {
76-
fs.rmSync(stateDir, { recursive: true, force: true });
77-
}
71+
await expect(
72+
cleanupRetainedManagedNpmInstallGenerations({
73+
npmDir,
74+
}),
75+
).resolves.toBe(1);
76+
expect(fs.existsSync(packageDir)).toBe(false);
77+
expect(hasRetainedManagedNpmInstallMarker(packageDir)).toBe(false);
78+
});
79+
80+
it("preserves a noncanonical project root even when it has a retained marker", async () => {
81+
const stateDir = retentionTempDirs.make("openclaw-retention-noncanonical-");
82+
const npmDir = path.join(stateDir, "npm");
83+
const projectRoot = path.join(npmDir, "projects", "noncanonical-sibling");
84+
const packageDir = path.join(projectRoot, "node_modules", "@openclaw", "codex");
85+
const siblingFile = path.join(projectRoot, "must-remain.txt");
86+
fs.mkdirSync(packageDir, { recursive: true });
87+
fs.writeFileSync(siblingFile, "preserve me", "utf8");
88+
await markRetainedManagedNpmInstall({
89+
packageDir,
90+
pluginId: "codex",
91+
reason: "test-retired-generation",
92+
});
93+
94+
await expect(cleanupRetainedManagedNpmInstallGenerations({ npmDir })).resolves.toBe(0);
95+
expect(fs.readFileSync(siblingFile, "utf8")).toBe("preserve me");
96+
});
97+
98+
it("does not follow a substituted managed projects directory", async () => {
99+
const stateDir = retentionTempDirs.make("openclaw-retention-symlink-");
100+
const npmDir = path.join(stateDir, "npm");
101+
const outsideProjectsDir = retentionTempDirs.make("openclaw-retention-outside-");
102+
fs.mkdirSync(npmDir, { recursive: true });
103+
fs.symlinkSync(outsideProjectsDir, path.join(npmDir, "projects"), "dir");
104+
const projectRoot = resolvePluginNpmProjectDir({
105+
npmDir,
106+
packageName: "@openclaw/codex",
107+
});
108+
const packageDir = path.join(projectRoot, "node_modules", "@openclaw", "codex");
109+
const sentinel = path.join(projectRoot, "must-remain.txt");
110+
fs.mkdirSync(packageDir, { recursive: true });
111+
fs.writeFileSync(sentinel, "preserve me", "utf8");
112+
await markRetainedManagedNpmInstall({
113+
packageDir,
114+
pluginId: "codex",
115+
reason: "test-retired-generation",
116+
});
117+
118+
await expect(cleanupRetainedManagedNpmInstallGenerations({ npmDir })).resolves.toBe(0);
119+
expect(fs.readFileSync(sentinel, "utf8")).toBe("preserve me");
78120
});
79121

80122
it.each(["project", "legacy"] as const)(
@@ -98,13 +140,9 @@ describe("managed npm retention", () => {
98140
reason: RETAINED_MANAGED_NPM_KEEP_FILES_REASON,
99141
});
100142

101-
try {
102-
await expect(cleanupRetainedManagedNpmInstallGenerations({ npmDir })).resolves.toBe(0);
103-
expect(fs.existsSync(packageDir)).toBe(true);
104-
expect(hasRetainedManagedNpmInstallMarker(packageDir)).toBe(true);
105-
} finally {
106-
fs.rmSync(stateDir, { recursive: true, force: true });
107-
}
143+
await expect(cleanupRetainedManagedNpmInstallGenerations({ npmDir })).resolves.toBe(0);
144+
expect(fs.existsSync(packageDir)).toBe(true);
145+
expect(hasRetainedManagedNpmInstallMarker(packageDir)).toBe(true);
108146
},
109147
);
110148
});

‎src/plugins/managed-npm-retention.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import fs from "node:fs";
33
import path from "node:path";
44
import { isRecord } from "@openclaw/normalization-core/record-coerce";
55
import { safePathSegmentHashed } from "../infra/install-safe-path.js";
6-
import { resolveDefaultPluginNpmDir, resolvePluginNpmProjectsDir } from "./install-paths.js";
6+
import {
7+
isPluginNpmProjectDir,
8+
resolveDefaultPluginNpmDir,
9+
resolvePluginNpmProjectsDir,
10+
} from "./install-paths.js";
711
import { RETAINED_MANAGED_NPM_KEEP_FILES_REASON } from "./managed-npm-retention-contract.js";
812
import { listManagedPluginNpmRootsSync } from "./npm-project-roots.js";
913

@@ -152,6 +156,25 @@ function listManagedNpmPackageDirs(npmRoot: string): string[] {
152156
});
153157
}
154158

159+
function isOwnedManagedNpmProject(params: {
160+
markerNames: ReadonlySet<string>;
161+
npmDir: string;
162+
projectRoot: string;
163+
}): boolean {
164+
return listManagedNpmPackageDirs(params.projectRoot).some((packageDir) => {
165+
const info = resolveRetainedManagedNpmInstallPackageInfo(packageDir);
166+
return Boolean(
167+
info &&
168+
params.markerNames.has(path.basename(info.markerPath)) &&
169+
isPluginNpmProjectDir({
170+
npmDir: params.npmDir,
171+
packageName: info.packageName,
172+
projectDir: params.projectRoot,
173+
}),
174+
);
175+
});
176+
}
177+
155178
async function cleanupRetainedLegacyNpmPackages(params: {
156179
npmRoot: string;
157180
activeInstallPaths: string[];
@@ -221,6 +244,11 @@ export async function cleanupRetainedManagedNpmInstallGenerations(
221244
markerPreservesPackageFiles(path.join(markerDir, entry.name)),
222245
) ||
223246
!isPathEqualOrInside(projectsDir, projectRoot) ||
247+
!isOwnedManagedNpmProject({
248+
markerNames: new Set(markerEntries.map((entry) => entry.name)),
249+
npmDir,
250+
projectRoot,
251+
}) ||
224252
activeInstallPaths.some((installPath) => isPathEqualOrInside(projectRoot, installPath))
225253
) {
226254
continue;

‎src/plugins/management-service.install-compensation.test.ts‎

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import fs from "node:fs/promises";
2-
import os from "node:os";
32
import path from "node:path";
4-
import { beforeEach, describe, expect, it, vi } from "vitest";
5-
import { resolveDefaultPluginNpmDir, resolvePluginNpmProjectDir } from "./install-paths.js";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import {
6+
resolveDefaultPluginNpmDir,
7+
resolvePluginNpmGenerationProjectDir,
8+
resolvePluginNpmProjectDir,
9+
} from "./install-paths.js";
10+
11+
const compensationTempDirs = useAutoCleanupTempDirTracker(afterEach);
612

713
const mocks = vi.hoisted(() => ({
814
applyUninstall: vi.fn(),
@@ -104,19 +110,27 @@ describe("managed plugin install compensation", () => {
104110
expect(mocks.applyUninstall).toHaveBeenCalledWith({ target: targetDir });
105111
});
106112

107-
it("removes a planner-validated isolated npm project after persistence conflicts", async () => {
108-
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-managed-npm-conflict-"));
109-
const env = { HOME: home };
110-
const packageName = "@openclaw/demo";
111-
const npmRoot = resolvePluginNpmProjectDir({
112-
npmDir: resolveDefaultPluginNpmDir(env),
113-
packageName,
114-
});
115-
const targetDir = path.join(npmRoot, "node_modules", "@openclaw", "demo");
116-
const packArchive = path.join(npmRoot, "_openclaw-pack-archives", "demo.tgz");
117-
const conflict = new Error("config changed during npm plugin install");
113+
it.each([
114+
{ name: "ordinary", generationKey: undefined },
115+
{ name: "generation", generationKey: "demo-v2" },
116+
])(
117+
"removes a planner-validated $name npm project after persistence conflicts",
118+
async (fixture) => {
119+
const home = compensationTempDirs.make("openclaw-managed-npm-conflict-");
120+
const env = { HOME: home };
121+
const packageName = "@openclaw/demo";
122+
const npmDir = resolveDefaultPluginNpmDir(env);
123+
const npmRoot = fixture.generationKey
124+
? resolvePluginNpmGenerationProjectDir({
125+
npmDir,
126+
packageName,
127+
generationKey: fixture.generationKey,
128+
})
129+
: resolvePluginNpmProjectDir({ npmDir, packageName });
130+
const targetDir = path.join(npmRoot, "node_modules", "@openclaw", "demo");
131+
const packArchive = path.join(npmRoot, "_openclaw-pack-archives", "demo.tgz");
132+
const conflict = new Error("config changed during npm plugin install");
118133

119-
try {
120134
await fs.mkdir(targetDir, { recursive: true });
121135
await fs.mkdir(path.dirname(packArchive), { recursive: true });
122136
await fs.writeFile(packArchive, "packed plugin");
@@ -148,13 +162,11 @@ describe("managed plugin install compensation", () => {
148162

149163
expect(mocks.applyUninstall).toHaveBeenCalledWith({
150164
target: npmRoot,
151-
cleanup: { kind: "npm", npmRoot, packageName },
165+
cleanup: { kind: "npm", npmRoot, packageName, rootKind: "isolated-project" },
152166
});
153167
await expect(fs.access(npmRoot)).rejects.toMatchObject({ code: "ENOENT" });
154-
} finally {
155-
await fs.rm(home, { recursive: true, force: true });
156-
}
157-
});
168+
},
169+
);
158170

159171
it("never deletes an operator-owned source when link persistence fails", async () => {
160172
const env = { HOME: "/tmp/openclaw-managed-link-conflict-home" };

0 commit comments

Comments
 (0)