fix(security): harden plugin/hook npm installs
This commit is contained in:
@@ -4,7 +4,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import * as tar from "tar";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as skillScanner from "../security/skill-scanner.js";
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
@@ -52,6 +52,10 @@ afterEach(() => {
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("installPluginFromArchive", () => {
|
||||
it("installs into ~/.openclaw/extensions and uses unscoped id", async () => {
|
||||
const stateDir = makeTempDir();
|
||||
@@ -487,3 +491,72 @@ describe("installPluginFromDir", () => {
|
||||
expect(opts?.cwd).toBe(res.targetDir);
|
||||
});
|
||||
});
|
||||
|
||||
describe("installPluginFromNpmSpec", () => {
|
||||
it("uses --ignore-scripts for npm pack and cleans up temp dir", async () => {
|
||||
const workDir = makeTempDir();
|
||||
const stateDir = makeTempDir();
|
||||
const pkgDir = path.join(workDir, "package");
|
||||
fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(pkgDir, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "@openclaw/voice-call",
|
||||
version: "0.0.1",
|
||||
openclaw: { extensions: ["./dist/index.js"] },
|
||||
}),
|
||||
"utf-8",
|
||||
);
|
||||
fs.writeFileSync(path.join(pkgDir, "dist", "index.js"), "export {};", "utf-8");
|
||||
|
||||
const extensionsDir = path.join(stateDir, "extensions");
|
||||
fs.mkdirSync(extensionsDir, { recursive: true });
|
||||
|
||||
const { runCommandWithTimeout } = await import("../process/exec.js");
|
||||
const run = vi.mocked(runCommandWithTimeout);
|
||||
|
||||
let packTmpDir = "";
|
||||
const packedName = "voice-call-0.0.1.tgz";
|
||||
run.mockImplementation(async (argv, opts) => {
|
||||
if (argv[0] === "npm" && argv[1] === "pack") {
|
||||
packTmpDir = String(opts?.cwd ?? "");
|
||||
await packToArchive({ pkgDir, outDir: packTmpDir, outName: packedName });
|
||||
return { code: 0, stdout: `${packedName}\n`, stderr: "", signal: null, killed: false };
|
||||
}
|
||||
throw new Error(`unexpected command: ${argv.join(" ")}`);
|
||||
});
|
||||
|
||||
const { installPluginFromNpmSpec } = await import("./install.js");
|
||||
const result = await installPluginFromNpmSpec({
|
||||
spec: "@openclaw/voice-call@0.0.1",
|
||||
extensionsDir,
|
||||
logger: { info: () => {}, warn: () => {} },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
|
||||
const packCalls = run.mock.calls.filter(
|
||||
(c) => Array.isArray(c[0]) && c[0][0] === "npm" && c[0][1] === "pack",
|
||||
);
|
||||
expect(packCalls.length).toBe(1);
|
||||
const packCall = packCalls[0];
|
||||
if (!packCall) {
|
||||
throw new Error("expected npm pack call");
|
||||
}
|
||||
const [argv, options] = packCall;
|
||||
expect(argv).toEqual(["npm", "pack", "@openclaw/voice-call@0.0.1", "--ignore-scripts"]);
|
||||
expect(options?.env).toMatchObject({ NPM_CONFIG_IGNORE_SCRIPTS: "true" });
|
||||
|
||||
expect(packTmpDir).not.toBe("");
|
||||
expect(fs.existsSync(packTmpDir)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects non-registry npm specs", async () => {
|
||||
const { installPluginFromNpmSpec } = await import("./install.js");
|
||||
const result = await installPluginFromNpmSpec({ spec: "github:evil/evil" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) {
|
||||
return;
|
||||
}
|
||||
expect(result.error).toContain("unsupported npm spec");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
resolveArchiveKind,
|
||||
resolvePackedRootDir,
|
||||
} from "../infra/archive.js";
|
||||
import { validateRegistryNpmSpec } from "../infra/npm-registry-spec.js";
|
||||
import { runCommandWithTimeout } from "../process/exec.js";
|
||||
import * as skillScanner from "../security/skill-scanner.js";
|
||||
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
|
||||
@@ -334,37 +335,41 @@ export async function installPluginFromArchive(params: {
|
||||
}
|
||||
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-plugin-"));
|
||||
const extractDir = path.join(tmpDir, "extract");
|
||||
await fs.mkdir(extractDir, { recursive: true });
|
||||
|
||||
logger.info?.(`Extracting ${archivePath}…`);
|
||||
try {
|
||||
await extractArchive({
|
||||
archivePath,
|
||||
destDir: extractDir,
|
||||
const extractDir = path.join(tmpDir, "extract");
|
||||
await fs.mkdir(extractDir, { recursive: true });
|
||||
|
||||
logger.info?.(`Extracting ${archivePath}…`);
|
||||
try {
|
||||
await extractArchive({
|
||||
archivePath,
|
||||
destDir: extractDir,
|
||||
timeoutMs,
|
||||
logger,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: `failed to extract archive: ${String(err)}` };
|
||||
}
|
||||
|
||||
let packageDir = "";
|
||||
try {
|
||||
packageDir = await resolvePackedRootDir(extractDir);
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) };
|
||||
}
|
||||
|
||||
return await installPluginFromPackageDir({
|
||||
packageDir,
|
||||
extensionsDir: params.extensionsDir,
|
||||
timeoutMs,
|
||||
logger,
|
||||
mode,
|
||||
dryRun: params.dryRun,
|
||||
expectedPluginId: params.expectedPluginId,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: `failed to extract archive: ${String(err)}` };
|
||||
} finally {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
|
||||
let packageDir = "";
|
||||
try {
|
||||
packageDir = await resolvePackedRootDir(extractDir);
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) };
|
||||
}
|
||||
|
||||
return await installPluginFromPackageDir({
|
||||
packageDir,
|
||||
extensionsDir: params.extensionsDir,
|
||||
timeoutMs,
|
||||
logger,
|
||||
mode,
|
||||
dryRun: params.dryRun,
|
||||
expectedPluginId: params.expectedPluginId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function installPluginFromDir(params: {
|
||||
@@ -468,43 +473,51 @@ export async function installPluginFromNpmSpec(params: {
|
||||
const dryRun = params.dryRun ?? false;
|
||||
const expectedPluginId = params.expectedPluginId;
|
||||
const spec = params.spec.trim();
|
||||
if (!spec) {
|
||||
return { ok: false, error: "missing npm spec" };
|
||||
const specError = validateRegistryNpmSpec(spec);
|
||||
if (specError) {
|
||||
return { ok: false, error: specError };
|
||||
}
|
||||
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-npm-pack-"));
|
||||
logger.info?.(`Downloading ${spec}…`);
|
||||
const res = await runCommandWithTimeout(["npm", "pack", spec], {
|
||||
timeoutMs: Math.max(timeoutMs, 300_000),
|
||||
cwd: tmpDir,
|
||||
env: { COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" },
|
||||
});
|
||||
if (res.code !== 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `npm pack failed: ${res.stderr.trim() || res.stdout.trim()}`,
|
||||
};
|
||||
}
|
||||
try {
|
||||
logger.info?.(`Downloading ${spec}…`);
|
||||
const res = await runCommandWithTimeout(["npm", "pack", spec, "--ignore-scripts"], {
|
||||
timeoutMs: Math.max(timeoutMs, 300_000),
|
||||
cwd: tmpDir,
|
||||
env: {
|
||||
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
|
||||
NPM_CONFIG_IGNORE_SCRIPTS: "true",
|
||||
},
|
||||
});
|
||||
if (res.code !== 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `npm pack failed: ${res.stderr.trim() || res.stdout.trim()}`,
|
||||
};
|
||||
}
|
||||
|
||||
const packed = (res.stdout || "")
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean)
|
||||
.pop();
|
||||
if (!packed) {
|
||||
return { ok: false, error: "npm pack produced no archive" };
|
||||
}
|
||||
const packed = (res.stdout || "")
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean)
|
||||
.pop();
|
||||
if (!packed) {
|
||||
return { ok: false, error: "npm pack produced no archive" };
|
||||
}
|
||||
|
||||
const archivePath = path.join(tmpDir, packed);
|
||||
return await installPluginFromArchive({
|
||||
archivePath,
|
||||
extensionsDir: params.extensionsDir,
|
||||
timeoutMs,
|
||||
logger,
|
||||
mode,
|
||||
dryRun,
|
||||
expectedPluginId,
|
||||
});
|
||||
const archivePath = path.join(tmpDir, packed);
|
||||
return await installPluginFromArchive({
|
||||
archivePath,
|
||||
extensionsDir: params.extensionsDir,
|
||||
timeoutMs,
|
||||
logger,
|
||||
mode,
|
||||
dryRun,
|
||||
expectedPluginId,
|
||||
});
|
||||
} finally {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export async function installPluginFromPath(params: {
|
||||
|
||||
Reference in New Issue
Block a user