Skip to content

Commit 3af5ae1

Browse files
committed
fix(plugins): load source artifacts without losing credential targets
Use the canonical plugin loader for source and built public artifacts, retire transformed module dependencies with their cache generation, and report broken contracts during source credential-reference generation. Fixes #132153
1 parent 64f9e13 commit 3af5ae1

16 files changed

Lines changed: 297 additions & 264 deletions

‎docs/reference/secretref-credential-surface.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Scope:
1616

1717
The lists below are generated from the source target registry and checked against `docs/reference/secretref-user-supplied-credentials-matrix.json` in CI; do not hand-edit entries.
1818

19+
Source generation fails if a present channel secret-contract artifact cannot load, rather than publishing an incomplete list. A plugin without that optional artifact contributes no channel targets. This generation check does not change runtime SecretRef owner-isolation behavior.
20+
1921
## Supported credentials
2022

2123
### `openclaw.json` targets (`secrets configure` + `secrets apply` + `secrets audit`)

‎src/plugins/native-module-require.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { pathToFileURL } from "node:url";
77
import { afterEach, beforeAll, describe, expect, it } from "vitest";
88
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
99
import {
10-
clearNativeRequireJavaScriptModuleCache,
10+
clearPluginModuleRequireCache,
1111
isJavaScriptModulePath,
1212
tryNativeRequireJavaScriptModule,
1313
} from "./native-module-require.js";
@@ -207,7 +207,7 @@ describe("tryNativeRequireJavaScriptModule", () => {
207207
});
208208

209209
fs.writeFileSync(modulePath, 'module.exports = { marker: "after" };\n', "utf8");
210-
clearNativeRequireJavaScriptModuleCache(modulePath);
210+
clearPluginModuleRequireCache(modulePath);
211211

212212
expect(tryNativeRequireJavaScriptModule(modulePath, { allowWindows: true })).toEqual({
213213
ok: true,
@@ -227,7 +227,7 @@ describe("tryNativeRequireJavaScriptModule", () => {
227227
});
228228

229229
fs.writeFileSync(helperPath, 'module.exports = { marker: "after" };\n', "utf8");
230-
clearNativeRequireJavaScriptModuleCache(modulePath, { dependencyRoot: dir });
230+
clearPluginModuleRequireCache(modulePath, { dependencyRoot: dir });
231231

232232
expect(tryNativeRequireJavaScriptModule(modulePath, { allowWindows: true })).toEqual({
233233
ok: true,

‎src/plugins/native-module-require.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,14 +91,11 @@ export function tryNativeRequireJavaScriptModule(
9191
}
9292
}
9393

94-
/** Clears a native-loaded module and dependency subtree under the plugin dependency root. */
95-
export function clearNativeRequireJavaScriptModuleCache(
94+
/** Clears native and source-transformed modules within the plugin dependency root. */
95+
export function clearPluginModuleRequireCache(
9696
modulePath: string,
9797
options: { dependencyRoot?: string } = {},
9898
): void {
99-
if (!isJavaScriptModulePath(modulePath)) {
100-
return;
101-
}
10299
try {
103100
const resolved = nodeRequire.resolve(modulePath);
104101
clearRequireCacheSubtree(
@@ -107,7 +104,7 @@ export function clearNativeRequireJavaScriptModuleCache(
107104
new Set(),
108105
);
109106
} catch {
110-
// Best-effort lifecycle cleanup: unresolved paths were not native-loaded.
107+
// Best-effort lifecycle cleanup: unresolved paths were not loaded.
111108
}
112109
}
113110

‎src/plugins/plugin-module-loader-cache.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -935,10 +935,10 @@ describe("plugin module cache generation cleanup", () => {
935935
{ boundaryRoot: "/repo/dist/extensions", dependencyRoot: "/repo/dist" },
936936
{ boundaryRoot: "/repo/installed/demo", dependencyRoot: "/repo/installed/demo" },
937937
])("evicts native dependencies under $dependencyRoot for $boundaryRoot", async (params) => {
938-
const clearNativeRequireJavaScriptModuleCache = vi.fn();
938+
const clearPluginModuleRequireCache = vi.fn();
939939
vi.doMock("./native-module-require.js", async (importOriginal) => ({
940940
...(await importOriginal<typeof import("./native-module-require.js")>()),
941-
clearNativeRequireJavaScriptModuleCache,
941+
clearPluginModuleRequireCache,
942942
}));
943943
const { recordPluginModuleRoot } = await importPluginModuleLoader(
944944
"./plugin-module-loader-cache.js?scope=lifecycle-disposal",
@@ -949,7 +949,7 @@ describe("plugin module cache generation cleanup", () => {
949949

950950
resetPluginCache();
951951

952-
expect(clearNativeRequireJavaScriptModuleCache).toHaveBeenCalledWith(modulePath, {
952+
expect(clearPluginModuleRequireCache).toHaveBeenCalledWith(modulePath, {
953953
dependencyRoot: params.dependencyRoot,
954954
});
955955
expect(getPluginCache()).not.toBe(previous);

‎src/plugins/plugin-module-loader-cache.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { openRootFileSync } from "../infra/boundary-file-read.js";
88
import { sameFileIdentity } from "../infra/fs-safe-advanced.js";
99
import { toSafeImportPath } from "../shared/import-specifier.js";
1010
import {
11-
clearNativeRequireJavaScriptModuleCache,
11+
clearPluginModuleRequireCache,
1212
tryNativeRequireJavaScriptModule,
1313
} from "./native-module-require.js";
1414
import {
@@ -133,7 +133,7 @@ function retainModuleLifecycle(cache: ReturnType<typeof getPluginCache>): void {
133133
path.basename(extensionsDir) === "extensions" && path.basename(distDir) === "dist"
134134
? distDir
135135
: rootDir;
136-
clearNativeRequireJavaScriptModuleCache(modulePath, { dependencyRoot });
136+
clearPluginModuleRequireCache(modulePath, { dependencyRoot });
137137
}
138138
};
139139
}

‎src/plugins/public-surface-loader.test.ts‎

Lines changed: 66 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
// Verifies plugin public surface loading and fallback behavior.
22
import fs from "node:fs";
33
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
45
import { importFreshModule } from "openclaw/plugin-sdk/test-fixtures";
56
import { afterEach, describe, expect, it, vi } from "vitest";
67
import { createTempDirTracker } from "../../test/helpers/temp-dir.js";
78
import { MissingPublicSurfaceError } from "../plugin-sdk/facade-loader.js";
9+
import { spawnNodeEvalSync } from "../test-utils/node-process.js";
810
import { withMockedWindowsPlatform } from "../test-utils/vitest-spies.js";
911
import { resetPluginCache } from "./plugin-cache.js";
1012

@@ -32,7 +34,6 @@ afterEach(() => {
3234
vi.doUnmock("./bundled-dir.js");
3335
vi.doUnmock("./native-module-require.js");
3436
vi.doUnmock("./public-surface-runtime.js");
35-
vi.doUnmock("node:module");
3637
if (originalBundledPluginsDir === undefined) {
3738
delete process.env.OPENCLAW_BUNDLED_PLUGINS_DIR;
3839
} else {
@@ -131,45 +132,74 @@ describe("bundled plugin public surface loader", () => {
131132
});
132133
});
133134

134-
it("prefers source require for bundled source public artifacts when a ts require hook exists", async () => {
135-
const createJiti = vi.fn(() => vi.fn(() => ({ marker: "jiti-should-not-run" })));
136-
vi.doMock("jiti", () => ({
137-
createJiti,
138-
}));
139-
const requireLoader = Object.assign(
140-
vi.fn(() => ({ marker: "source-require-ok" })),
135+
it("loads import-only dependencies under tsx and shares source artifacts for one cache generation", () => {
136+
const tempRoot = tempDirs.make("openclaw-public-surface-source-");
137+
const bundledPluginsDir = path.join(tempRoot, "extensions");
138+
const pluginRoot = path.join(bundledPluginsDir, "demo");
139+
const dependencyRoot = path.join(pluginRoot, "node_modules", "import-only-fixture");
140+
const modulePath = path.join(pluginRoot, "secret-contract-api.ts");
141+
const dependencyPath = path.join(dependencyRoot, "index.js");
142+
fs.mkdirSync(dependencyRoot, { recursive: true });
143+
fs.writeFileSync(
144+
path.join(dependencyRoot, "package.json"),
145+
JSON.stringify({ type: "module", exports: { node: { import: "./index.js" } } }),
146+
);
147+
fs.writeFileSync(dependencyPath, 'export const marker = "original";\n');
148+
fs.writeFileSync(path.join(tempRoot, "shared.cjs"), "module.exports = {};\n");
149+
fs.writeFileSync(
150+
modulePath,
151+
'export { marker } from "import-only-fixture";\nexport { default as shared } from "../../shared.cjs";\n',
152+
);
153+
154+
const moduleUrl = (relativePath: string) =>
155+
JSON.stringify(pathToFileURL(path.join(process.cwd(), relativePath)).href);
156+
const result = spawnNodeEvalSync(
157+
`
158+
import assert from "node:assert/strict";
159+
import fs from "node:fs";
160+
import { createRequire } from "node:module";
161+
import { loadBundledPluginPublicArtifactModuleSync, loadPluginPublicArtifactModuleSync } from ${moduleUrl("src/plugins/public-surface-loader.ts")};
162+
import { loadFacadeModuleAtLocationSync } from ${moduleUrl("src/plugin-sdk/facade-loader.ts")};
163+
import { clearPluginMetadataLifecycleCaches } from ${moduleUrl("src/plugins/plugin-metadata-lifecycle.ts")};
164+
assert.equal(typeof createRequire(import.meta.url).extensions[".ts"], "function");
165+
const load = () => loadBundledPluginPublicArtifactModuleSync({ dirName: "demo", artifactBasename: "secret-contract-api.js" });
166+
const first = load();
167+
assert.equal(first.marker, "original");
168+
assert.equal(load(), first);
169+
assert.equal(loadPluginPublicArtifactModuleSync({ pluginRoot: ${JSON.stringify(pluginRoot)}, artifactBasename: "secret-contract-api.js" }), first);
170+
assert.equal(loadFacadeModuleAtLocationSync({ location: { modulePath: ${JSON.stringify(modulePath)}, boundaryRoot: ${JSON.stringify(pluginRoot)} }, trackedPluginId: "demo" }), first);
171+
fs.writeFileSync(${JSON.stringify(dependencyPath)}, 'export const marker = "replacement";\\n');
172+
assert.equal(load(), first);
173+
clearPluginMetadataLifecycleCaches();
174+
const replacement = load();
175+
assert.notEqual(replacement, first);
176+
assert.equal(replacement.marker, "replacement");
177+
assert.equal(replacement.shared, first.shared);
178+
console.log("source artifact import, identity, and lifecycle verified");
179+
`,
141180
{
142-
extensions: {
143-
".ts": vi.fn(),
181+
imports: [pathToFileURL(path.join(process.cwd(), "scripts/tsx.mjs")).href],
182+
timeout: 30_000,
183+
env: {
184+
PATH: process.env.PATH,
185+
SystemRoot: process.env.SystemRoot,
186+
HOME: tempRoot,
187+
USERPROFILE: tempRoot,
188+
TMPDIR: tempRoot,
189+
TMP: tempRoot,
190+
TEMP: tempRoot,
191+
VITEST: "true",
192+
OPENCLAW_STATE_DIR: path.join(tempRoot, "state"),
193+
OPENCLAW_BUNDLED_PLUGINS_DIR: bundledPluginsDir,
194+
OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR: "1",
195+
JITI_FS_CACHE: "0",
144196
},
145197
},
146198
);
147-
vi.doMock("node:module", async () => {
148-
const actual = await vi.importActual<typeof import("node:module")>("node:module");
149-
return Object.assign({}, actual, {
150-
createRequire: vi.fn(() => requireLoader),
151-
});
152-
});
153-
154-
const publicSurfaceLoader = await importFreshModule<
155-
typeof import("./public-surface-loader.js")
156-
>(import.meta.url, "./public-surface-loader.js?scope=source-require-fast-path");
157-
const tempRoot = tempDirs.make("openclaw-public-surface-loader-");
158-
const bundledPluginsDir = path.join(tempRoot, "extensions");
159-
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = bundledPluginsDir;
160-
161-
const modulePath = path.join(bundledPluginsDir, "demo", "secret-contract-api.ts");
162-
fs.mkdirSync(path.dirname(modulePath), { recursive: true });
163-
fs.writeFileSync(modulePath, 'export const marker = "source-require-ok";\n', "utf8");
164-
165-
expect(
166-
publicSurfaceLoader.loadBundledPluginPublicArtifactModuleSync<{ marker: string }>({
167-
dirName: "demo",
168-
artifactBasename: "secret-contract-api.js",
169-
}).marker,
170-
).toBe("source-require-ok");
171-
expect(requireLoader).toHaveBeenCalledWith(fs.realpathSync(modulePath));
172-
expect(createJiti).not.toHaveBeenCalled();
199+
expect(result.error).toBeUndefined();
200+
expect(result.stderr).toBe("");
201+
expect(result.status).toBe(0);
202+
expect(result.stdout.trim()).toBe("source artifact import, identity, and lifecycle verified");
173203
});
174204

175205
it("keeps bundled dist public artifacts on the native path", async () => {

‎src/plugins/public-surface-loader.ts‎

Lines changed: 6 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// Loads documented plugin public surfaces while preserving lazy boundaries.
2-
import { createRequire } from "node:module";
32
import path from "node:path";
43
import { fileURLToPath } from "node:url";
54
import { MissingPublicSurfaceError } from "../plugin-sdk/facade-loader.js";
@@ -14,41 +13,18 @@ import {
1413
resolveBundledPluginPublicSurfacePath,
1514
resolvePluginRootPublicSurfacePath,
1615
} from "./public-surface-runtime.js";
17-
import { resolvePluginLoaderTryNative, resolveLoaderPackageRoot } from "./sdk-alias.js";
16+
import { resolveLoaderPackageRoot } from "./sdk-alias.js";
1817

1918
const OPENCLAW_PACKAGE_ROOT =
2019
resolveLoaderPackageRoot({
2120
modulePath: fileURLToPath(import.meta.url),
2221
moduleUrl: import.meta.url,
2322
}) ?? fileURLToPath(new URL("../..", import.meta.url));
24-
const sourceArtifactRequire = createRequire(import.meta.url);
2523
type PublicSurfaceLocation = {
2624
modulePath: string;
2725
boundaryRoot: string;
2826
};
2927

30-
function isSourceArtifactPath(modulePath: string): boolean {
31-
switch (path.extname(modulePath).toLowerCase()) {
32-
case ".ts":
33-
case ".tsx":
34-
case ".mts":
35-
case ".cts":
36-
case ".mtsx":
37-
case ".ctsx":
38-
return true;
39-
default:
40-
return false;
41-
}
42-
}
43-
44-
function canUseSourceArtifactRequire(params: { modulePath: string; tryNative: boolean }): boolean {
45-
return (
46-
!params.tryNative &&
47-
isSourceArtifactPath(params.modulePath) &&
48-
typeof sourceArtifactRequire.extensions?.[".ts"] === "function"
49-
);
50-
}
51-
5228
function createResolutionKey(params: { dirName: string; artifactBasename: string }): string {
5329
const bundledPluginsDir = resolveBundledPluginsDir();
5430
return `${params.dirName}::${params.artifactBasename}::${bundledPluginsDir ? path.resolve(bundledPluginsDir) : "<default>"}`;
@@ -92,21 +68,16 @@ function resolvePublicSurfaceLocation(params: {
9268
return resolved;
9369
}
9470

95-
function getModuleLoader(modulePath: string) {
96-
return getCachedPluginModuleLoader({
71+
function loadPublicSurfaceModule(modulePath: string): unknown {
72+
// A TS require hook can force import-only dependencies through CommonJS resolution.
73+
// Keep source transforms and built-artifact native loading on the same canonical owner.
74+
const load = getCachedPluginModuleLoader({
9775
modulePath,
9876
importerUrl: import.meta.url,
9977
preferBuiltDist: true,
10078
loaderFilename: import.meta.url,
10179
});
102-
}
103-
104-
function loadPublicSurfaceModule(modulePath: string): unknown {
105-
const tryNative = resolvePluginLoaderTryNative(modulePath, { preferBuiltDist: true });
106-
if (canUseSourceArtifactRequire({ modulePath, tryNative })) {
107-
return sourceArtifactRequire(modulePath);
108-
}
109-
return getModuleLoader(modulePath)(modulePath);
80+
return load(modulePath);
11081
}
11182

11283
function loadValidatedPublicSurfaceModule(params: {

0 commit comments

Comments
 (0)