fix(plugins): validate Codex companion launch metadata

This commit is contained in:
morluto
2026-10-14 01:23:15 +08:00
parent b7dabdbc4f
commit a85bfed8dc
15 changed files with 315 additions and 99 deletions
-6
View File
@@ -1,6 +0,0 @@
/** Exact host argv for a pinned registry package's MCP entry point. */
export function packageRunnerCommand(
runner: "npx" | "bunx",
packageSpecifier: string,
platform: NodeJS.Platform,
): readonly string[];
-16
View File
@@ -1,16 +0,0 @@
/** Host argv shared by setup registrations and the source-only plugin launcher. */
export const packageRunnerCommand = (runner, packageSpecifier, platform) => {
if (runner !== "npx" && runner !== "bunx")
throw new Error("Unsupported package runner");
// Windows cmd.exe consumes these tokens itself. Package registrations use
// exact registry references, never shell expressions or arbitrary operands.
if (!/^[@A-Za-z0-9_./+-]+$/u.test(packageSpecifier))
throw new Error("Package runner requires a shell-safe registry reference");
const command =
runner === "npx"
? ["npx", "-y", packageSpecifier, "mcp"]
: ["bunx", packageSpecifier, "mcp"];
// npm's .cmd shim is not a native executable. Disable cmd AutoRun, matching
// the setup registration policy, and keep all dynamic values out of syntax.
return platform === "win32" ? ["cmd.exe", "/d", "/c", ...command] : command;
};
+37 -9
View File
@@ -8,10 +8,31 @@ const PLUGIN_MANIFEST_PATHS = [
".claude-plugin/plugin.json",
".codex-plugin/plugin.json",
];
const PLUGIN_PACKAGE_NAME = "rea-agents";
const pluginManifestSchema = versionSchema.extend({
const inlinePluginManifestSchema = versionSchema.extend({
mcpServers: z.object({
rea: z.object({ args: z.array(z.string()) }),
rea: z.object({
command: z.literal("node"),
args: z.tuple([
z.literal("${CLAUDE_PLUGIN_ROOT}/scripts/plugin-mcp-launcher.mjs"),
z.string(),
]),
}),
}),
});
const codexPluginManifestSchema = versionSchema.extend({
mcpServers: z.literal("./.mcp.json"),
});
const codexServerConfigSchema = z.object({
mcpServers: z.object({
rea: z.object({
command: z.literal("node"),
args: z.tuple([
z.literal("./scripts/plugin-mcp-launcher.mjs"),
z.string(),
]),
cwd: z.literal("."),
startup_timeout_sec: z.number().int().positive(),
}),
}),
});
const sectionsSchema = z.object({
@@ -203,9 +224,16 @@ async function validateCandidate(git, sha, version, commits) {
// previous server, so both are version authority like server.json.
const launches = [];
for (const path of PLUGIN_MANIFEST_PATHS) {
const manifest = await readJson(git, sha, path, pluginManifestSchema);
const manifest =
path === ".codex-plugin/plugin.json"
? await readJson(git, sha, path, codexPluginManifestSchema)
: await readJson(git, sha, path, inlinePluginManifestSchema);
versions.push([path, manifest.version]);
launches.push([path, manifest.mcpServers.rea.args[1]]);
const server =
path === ".codex-plugin/plugin.json"
? await readJson(git, sha, ".mcp.json", codexServerConfigSchema)
: manifest;
launches.push([path, server.mcpServers.rea.args[1]]);
}
// Catalogs are generated and checked from this candidate by the release job;
// they are not version authority stored in the immutable source tree.
@@ -228,13 +256,13 @@ async function validateCandidate(git, sha, version, commits) {
);
}
}
// Compare the whole specifier: a bare version would make npx fetch a
// package named after the release number.
const requiredLaunch = `${PLUGIN_PACKAGE_NAME}@${version}`;
// Plugin JSON stores only a scalar version. The launcher owns the fixed
// package name and constructs the complete registry specifier at runtime.
const requiredLaunch = version;
for (const [location, launched] of launches) {
if (launched !== requiredLaunch) {
throw new Error(
`${location}@${sha} launches ${launched ?? "no package"}; release branch requires ${requiredLaunch}.`,
`${location}@${sha} launches version ${launched ?? "no version"}; release branch requires ${requiredLaunch}.`,
);
}
}
+4 -4
View File
@@ -368,6 +368,7 @@ export function verifyReleaseNotes(raw, text, body) {
const VERSION_ONLY_PLUGIN_METADATA = new Set([
".claude-plugin/plugin.json",
".codex-plugin/plugin.json",
".mcp.json",
".claude-plugin/marketplace.json",
".agents/plugins/marketplace.json",
]);
@@ -390,10 +391,9 @@ function pluginMetadataWithoutVersions(path, text) {
}
if ("version" in manifest) manifest.version = "";
const launch = manifest.mcpServers?.rea?.args;
// Only the version after the last "@" is release-owned; a different package
// name changes what the plugin runs.
if (Array.isArray(launch) && typeof launch[1] === "string")
launch[1] = launch[1].replace(/@[^@/]*$/u, "@");
// Only the scalar pinned version is release-owned; the launcher owns the
// fixed package name and the executable/path remain product behavior.
if (Array.isArray(launch) && typeof launch[1] === "string") launch[1] = "";
return JSON.stringify(manifest);
}
+111 -10
View File
@@ -1,29 +1,29 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { access, mkdtemp, rm } from "node:fs/promises";
import { constants, tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { packageRunnerCommand } from "./lib/packageRunnerCommand.mjs";
import { packageRunnerCommand } from "../src/application/PackageRunnerCommand.mjs";
// The manifest owns this exact package pin; args[1] remains release-managed.
// Keep the package name at the launcher boundary so release automation updates
// only a scalar version in plugin JSON, never a compound package specifier.
// No build, dependency installation or ambient latest-version lookup is needed
// to run this bootstrap from a Git-installed plugin.
const [packageSpecifier, ...extra] = process.argv.slice(2);
const [version, ...extra] = process.argv.slice(2);
if (
extra.length !== 0 ||
!/^rea-agents@\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/u.test(
packageSpecifier ?? "",
)
!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/u.test(version ?? "")
) {
process.stderr.write(
"REA plugin requires one exact rea-agents@VERSION pin.\n",
);
process.exitCode = 1;
} else {
await launch(packageSpecifier);
await launch(`rea-agents@${version}`);
}
async function launch(packageSpecifier) {
@@ -71,12 +71,15 @@ async function launch(packageSpecifier) {
process.exitCode = 1;
return;
}
if (process.platform === "win32") {
await launchWindowsFallback(command, args, workingDirectory);
return;
}
const child = spawn(command, args, {
cwd: workingDirectory,
// A dedicated POSIX process group gives this launcher ownership of the
// package runner and any server it starts. Windows keeps direct-child
// signaling until a verified Job Object owner is available here.
detached: process.platform !== "win32",
// package runner and any server it starts.
detached: true,
stdio: "inherit",
shell: false,
});
@@ -134,6 +137,104 @@ async function launch(packageSpecifier) {
});
}
async function launchWindowsFallback(command, args, workingDirectory) {
let spawnOwnedProviderProcess;
try {
({ spawnOwnedProviderProcess } =
await import("../dist/process/ProviderProcess.js"));
} catch (cause) {
await rm(workingDirectory, { recursive: true }).catch(() => {});
process.stderr.write(
`REA plugin cannot safely launch a Windows fallback without the owned process supervisor: ${cause.message}\n`,
);
process.exitCode = 1;
return;
}
let owned;
try {
owned = await spawnOwnedProviderProcess({
command,
arguments: args,
runId: randomUUID(),
cwd: workingDirectory,
stdin: "pipe",
platform: "win32",
});
} catch (cause) {
await rm(workingDirectory, { recursive: true }).catch(() => {});
process.stderr.write(
`REA plugin could not start the owned Windows process tree: ${cause.message}\n`,
);
process.exitCode = 1;
return;
}
const child = owned.process;
child.stdout?.pipe(process.stdout);
child.stderr?.pipe(process.stderr);
if (child.stdin === null || child.stdin === undefined) {
const cleanup = await owned.cleanup?.();
if (cleanup?.cleaned === true)
await rm(workingDirectory, { recursive: true }).catch(() => {});
else
process.stderr.write(
`REA plugin retained its Windows process ownership directory at ${workingDirectory} because cleanup was not verified.\n`,
);
process.stderr.write(
"REA plugin Windows process supervisor did not provide protocol stdin.\n",
);
process.exitCode = 1;
return;
}
process.stdin.pipe(child.stdin);
let cleanupFailed = false;
let cleanupPromise;
const signals = new Map();
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
const forward = () => {
if (child.exitCode !== null || child.signalCode !== null) return;
cleanupPromise ??= owned
.cleanup?.()
.then((result) => {
if (!result.cleaned) {
cleanupFailed = true;
process.stderr.write(
`REA plugin could not verify Windows process-tree cleanup: ${result.reason}\n`,
);
}
})
.catch((cause) => {
cleanupFailed = true;
process.stderr.write(
`REA plugin Windows process-tree cleanup failed: ${cause.message}\n`,
);
});
};
signals.set(signal, forward);
process.on(signal, forward);
}
child.once("error", (cause) => {
process.stderr.write(
`REA plugin Windows process supervisor failed: ${cause.message}\n`,
);
process.exitCode = 1;
});
child.once("close", async (code) => {
for (const [signal, listener] of signals) process.off(signal, listener);
await cleanupPromise;
if (!cleanupFailed) {
try {
await rm(workingDirectory, { recursive: true });
} catch (cause) {
cleanupFailed = true;
process.stderr.write(
`REA plugin retained its working directory at ${workingDirectory}: ${cause.message}\n`,
);
}
}
process.exitCode = code === 0 && cleanupFailed ? 1 : (code ?? 1);
});
}
function isMissing(cause) {
return (
typeof cause === "object" &&
+7 -10
View File
@@ -73,25 +73,20 @@ export async function verifyPackagePack({ root, workspace }) {
);
const serverConfig = path.startsWith(".codex")
? JSON.parse(
(
await exec("tar", [
"-xOf",
tarball,
"package/.mcp.json",
])
).stdout,
(await exec("tar", ["-xOf", tarball, "package/.mcp.json"])).stdout,
)
: manifest;
const expectedArgs = [
`${path.startsWith(".claude") ? "${CLAUDE_PLUGIN_ROOT}/" : "./"}scripts/plugin-mcp-launcher.mjs`,
`${packedManifest.name}@${packedManifest.version}`,
packedManifest.version,
];
if (
manifest.version !== packedManifest.version ||
manifest.skills !== "./skills" ||
(path.startsWith(".codex")
? manifest.mcpServers !== "./.mcp.json" ||
serverConfig.mcpServers?.rea?.cwd !== "."
serverConfig.mcpServers?.rea?.cwd !== "." ||
serverConfig.mcpServers?.rea?.startup_timeout_sec !== 30
: false) ||
serverConfig.mcpServers?.rea?.command !== "node" ||
JSON.stringify(serverConfig.mcpServers?.rea?.args) !==
@@ -105,7 +100,9 @@ export async function verifyPackagePack({ root, workspace }) {
throw new Error("Packaged Codex MCP server declaration is missing");
for (const path of [
"scripts/plugin-mcp-launcher.mjs",
"scripts/lib/packageRunnerCommand.mjs",
"src/application/PackageRunnerCommand.mjs",
"src/application/PackageRunnerCommand.d.mts",
"dist/application/PackageRunnerCommand.mjs",
])
if (!packedFiles.includes(`package/${path}`))
throw new Error(