Skip to content

Commit ba91ae4

Browse files
committed
fix(plugins): preserve npm-pack install transactions
1 parent a0c5502 commit ba91ae4

2 files changed

Lines changed: 145 additions & 1 deletion

File tree

‎src/plugins/install-npm-pack.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
loadPluginInstallRuntime,
2626
resolveEffectiveInstallMode,
2727
} from "./install-shared.js";
28+
import { copyPluginInstallTransactionRequest } from "./install-transaction.js";
2829
import {
2930
PLUGIN_INSTALL_ERROR_CODE,
3031
type InstallPluginResult,
@@ -232,7 +233,9 @@ export async function installPluginFromNpmPackArchive(
232233
? "install"
233234
: targetMode;
234235

235-
const result = await installPluginFromManagedNpmRoot({
236+
const managedNpmParams = copyPluginInstallTransactionRequest<
237+
Parameters<typeof installPluginFromManagedNpmRoot>[0]
238+
>(params, {
236239
dangerouslyForceUnsafeInstall: params.dangerouslyForceUnsafeInstall,
237240
onInstallPolicyWarning: params.onInstallPolicyWarning,
238241
trustedSourceLinkedOfficialInstall: params.trustedSourceLinkedOfficialInstall,
@@ -278,6 +281,7 @@ export async function installPluginFromNpmPackArchive(
278281
npmResolution,
279282
...(driftResult.integrityDrift ? { integrityDrift: driftResult.integrityDrift } : {}),
280283
});
284+
const result = await installPluginFromManagedNpmRoot(managedNpmParams);
281285
emitSuccessfulPluginInstallSecurityEvent(result, {
282286
dryRun,
283287
mode: policyMode,

‎src/plugins/install.npm-spec.test.ts‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Covers npm spec parsing for plugin install inputs.
22
import fs from "node:fs";
3+
import os from "node:os";
34
import path from "node:path";
45
import { pathToFileURL } from "node:url";
56
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -8,6 +9,7 @@ import {
89
mockNpmViewMetadataResult,
910
} from "../test-utils/npm-spec-install-test-helpers.js";
1011
import {
12+
resolveDefaultPluginNpmDir,
1113
resolvePluginNpmGenerationProjectDir,
1214
resolvePluginNpmProjectDir,
1315
resolvePluginNpmProjectsDir,
@@ -20,6 +22,7 @@ import { createSyncSuiteTempRootTracker } from "./test-helpers/fs-fixtures.js";
2022

2123
const runCommandWithTimeoutMock = vi.fn();
2224
const resolveOpenClawPackageRootSyncMock = vi.fn();
25+
const persistPluginInstallMock = vi.fn();
2326

2427
vi.mock("../process/exec.js", () => ({
2528
runCommandWithTimeout: (...args: unknown[]) => runCommandWithTimeoutMock(...args),
@@ -30,10 +33,16 @@ vi.mock("../infra/openclaw-root.js", () => ({
3033
resolveOpenClawPackageRootSyncMock(...args),
3134
}));
3235

36+
vi.mock("./install-persistence.js", async (importOriginal) => ({
37+
...(await importOriginal<typeof import("./install-persistence.js")>()),
38+
persistPluginInstall: (...args: unknown[]) => persistPluginInstallMock(...args),
39+
}));
40+
3341
vi.resetModules();
3442

3543
const { installPluginFromNpmPackArchive, installPluginFromNpmSpec, PLUGIN_INSTALL_ERROR_CODE } =
3644
await import("./install.js");
45+
const { installManagedPluginSource } = await import("./management-service.js");
3746
const { classifyNpmManagedOverrideCompatibilityError } =
3847
await import("./install-managed-npm-state.js");
3948

@@ -619,6 +628,7 @@ afterAll(() => {
619628
beforeEach(() => {
620629
runCommandWithTimeoutMock.mockReset();
621630
resolveOpenClawPackageRootSyncMock.mockReset();
631+
persistPluginInstallMock.mockReset();
622632
const hostRoot = suiteTempRootTracker.makeTempDir();
623633
fs.writeFileSync(
624634
path.join(hostRoot, "package.json"),
@@ -820,6 +830,136 @@ describe("installPluginFromNpmSpec", () => {
820830
expect(stagedArchiveContents).toBe("fixture pack contents");
821831
});
822832

833+
it.each([
834+
{ settlement: "rollback" as const, persistenceFails: true },
835+
{ settlement: "commit" as const, persistenceFails: false },
836+
])(
837+
"$settlement settles a forced npm-pack replacement only after persistence",
838+
async ({ persistenceFails }) => {
839+
const root = suiteTempRootTracker.makeTempDir();
840+
const env = { HOME: root, OPENCLAW_STATE_DIR: path.join(root, "state") };
841+
vi.stubEnv("HOME", root);
842+
vi.stubEnv("OPENCLAW_STATE_DIR", env.OPENCLAW_STATE_DIR);
843+
const npmRoot = resolveDefaultPluginNpmDir(env);
844+
const packageName = "@openclaw/pack-transaction";
845+
const archiveAPath = path.join(root, "pack-transaction-a.tgz");
846+
const archiveBPath = path.join(root, "pack-transaction-b.tgz");
847+
const metadata = {
848+
packageName,
849+
version: "1.0.0",
850+
pluginId: "pack-transaction",
851+
npmRoot,
852+
integrity: "sha512-pack-transaction",
853+
shasum: "packtransactionsha",
854+
packTarballName: "openclaw-pack-transaction-1.0.0.tgz",
855+
};
856+
const snapshot = {
857+
config: {},
858+
baseHash: "base-hash",
859+
writeOptions: {
860+
expectedConfigPath: path.join(root, "openclaw.json"),
861+
includeFileHashesForWrite: {},
862+
includeFileTargetsForWrite: {},
863+
},
864+
};
865+
fs.writeFileSync(archiveAPath, "archive A", "utf8");
866+
fs.writeFileSync(archiveBPath, "archive B", "utf8");
867+
868+
let durableSourcePath: string | undefined;
869+
let custodyPresentDuringPersistence = false;
870+
const custodyDirs: string[] = [];
871+
const mkdtemp = fs.promises.mkdtemp.bind(fs.promises);
872+
const mkdtempSpy = vi
873+
.spyOn(fs.promises, "mkdtemp")
874+
.mockImplementation(async (prefix: string) => {
875+
const dir = await mkdtemp(prefix);
876+
if (
877+
prefix.startsWith(path.join(os.tmpdir(), "openclaw-npm-plugin-rollback-")) ||
878+
prefix.startsWith(path.join(os.tmpdir(), "openclaw-npm-pack-archive-"))
879+
) {
880+
custodyDirs.push(dir);
881+
}
882+
return dir;
883+
});
884+
885+
const installArchive = async (archivePath: string, mode: "install" | "update") =>
886+
await installManagedPluginSource({
887+
request: { source: "npm-pack", archivePath, mode },
888+
snapshot,
889+
env,
890+
});
891+
892+
try {
893+
persistPluginInstallMock.mockImplementation(async (params: unknown) => {
894+
const install = (params as { install: { sourcePath?: string } }).install;
895+
durableSourcePath = install.sourcePath;
896+
return {};
897+
});
898+
mockNpmViewAndInstallMany([
899+
{ ...metadata, packArchivePath: archiveAPath, indexJs: 'export const generation = "A";' },
900+
]);
901+
const initialInstall = await installArchive(archiveAPath, "install");
902+
if (!initialInstall.ok) {
903+
throw new Error(initialInstall.error);
904+
}
905+
906+
mockNpmViewAndInstallMany([
907+
{ ...metadata, packArchivePath: archiveAPath, indexJs: 'export const generation = "A";' },
908+
]);
909+
const generationInstall = await installArchive(archiveAPath, "update");
910+
if (!generationInstall.ok || !generationInstall.targetDir) {
911+
throw new Error(
912+
generationInstall.ok
913+
? "npm-pack install did not return a target"
914+
: generationInstall.error,
915+
);
916+
}
917+
const packageDir = generationInstall.targetDir;
918+
const generationRoot = path.resolve(packageDir, "../../..");
919+
const treeA = readTextFileTree(generationRoot);
920+
expect(fs.readFileSync(path.join(packageDir, "dist", "index.js"), "utf8")).toContain('"A"');
921+
expect(durableSourcePath).toBe(archiveAPath);
922+
923+
custodyDirs.length = 0;
924+
const persistenceConflict = new Error("config changed during npm-pack install");
925+
persistPluginInstallMock.mockImplementation(async (params: unknown) => {
926+
const install = (params as { install: { sourcePath?: string } }).install;
927+
expect(fs.readFileSync(path.join(packageDir, "dist", "index.js"), "utf8")).toContain(
928+
'"B"',
929+
);
930+
custodyPresentDuringPersistence =
931+
custodyDirs.length >= 2 && custodyDirs.every((dir) => fs.existsSync(dir));
932+
if (persistenceFails) {
933+
throw persistenceConflict;
934+
}
935+
durableSourcePath = install.sourcePath;
936+
return {};
937+
});
938+
mockNpmViewAndInstallMany([
939+
{ ...metadata, packArchivePath: archiveBPath, indexJs: 'export const generation = "B";' },
940+
]);
941+
942+
const replacement = installArchive(archiveBPath, "update");
943+
if (persistenceFails) {
944+
await expect(replacement).rejects.toBe(persistenceConflict);
945+
expect(readTextFileTree(generationRoot)).toEqual(treeA);
946+
expect(durableSourcePath).toBe(archiveAPath);
947+
} else {
948+
await expect(replacement).resolves.toMatchObject({ ok: true });
949+
expect(fs.readFileSync(path.join(packageDir, "dist", "index.js"), "utf8")).toContain(
950+
'"B"',
951+
);
952+
expect(durableSourcePath).toBe(archiveBPath);
953+
}
954+
expect(custodyPresentDuringPersistence).toBe(true);
955+
expect(custodyDirs.length).toBeGreaterThanOrEqual(2);
956+
expect(custodyDirs.every((dir) => !fs.existsSync(dir))).toBe(true);
957+
} finally {
958+
mkdtempSpy.mockRestore();
959+
}
960+
},
961+
);
962+
823963
it("rejects npm pack archive metadata with traversal package names", async () => {
824964
const stateDir = suiteTempRootTracker.makeTempDir();
825965
const npmRoot = path.join(stateDir, "npm");

0 commit comments

Comments
 (0)