Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(cli): identify local plugin and knowledge-base failures (#463)

mldangelo-oaic9455f0bbf8b
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index a2b3dd67d..7b5d770c6 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -39,6 +39,10 @@ are unavailable when reading saved activity or attaching scan logs to feedback,
scans whose original session is compressed cannot resume. Plain `.jsonl` logs
work on all supported runtimes.
+`LocalPluginBootstrapError` identifies local plugin setup failures and extends
+`PluginBootstrapError`, so existing catches keep working. Knowledge-base
+preparation errors use `ConfigurationError`; wrapped diagnostics remain in `cause`.
+
## Authentication
Sign in with ChatGPT:
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 1774c4820..c84252d62 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -150,6 +150,7 @@ import {
AuthenticationRequiredError,
ConfigurationError,
InvalidTargetError,
+ LocalPluginBootstrapError,
OutputDirectoryError,
OutputInsideProtectedRootError,
PluginPythonUnavailableError,
@@ -9035,6 +9036,7 @@ function isLocalScanFailure(error: unknown): boolean {
error instanceof InvalidTargetError ||
error instanceof OutputDirectoryError ||
error instanceof ConfigurationError ||
+ error instanceof LocalPluginBootstrapError ||
error instanceof PluginPythonUnavailableError
) {
return true;
diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.ts
index 78ed49ca8..30cc5ad5e 100644
--- a/sdk/typescript/src/errors.ts
+++ b/sdk/typescript/src/errors.ts
@@ -46,6 +46,7 @@ export class DeduplicationReviewError extends CodexSecurityError {
export class ConfigurationError extends CodexSecurityError {}
export class AuthenticationRequiredError extends CodexSecurityError {}
export class PluginBootstrapError extends CodexSecurityError {}
+export class LocalPluginBootstrapError extends PluginBootstrapError {}
export class PluginPythonUnavailableError extends PluginBootstrapError {}
export class SandboxUnavailableError extends CodexSecurityError {}
export class InvalidTargetError extends CodexSecurityError {}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 54666eec0..52bbe9376 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -93,6 +93,7 @@ export {
DeduplicationReviewError,
IncompleteScanError,
InvalidTargetError,
+ LocalPluginBootstrapError,
OutputDirectoryError,
OutputDirectoryNotEmptyError,
OutputInsideProtectedRootError,
diff --git a/sdk/typescript/src/knowledge-base.ts b/sdk/typescript/src/knowledge-base.ts
index 5e5e6d56a..2df9c138b 100644
--- a/sdk/typescript/src/knowledge-base.ts
+++ b/sdk/typescript/src/knowledge-base.ts
@@ -12,6 +12,7 @@ import {
import { tmpdir } from "node:os";
import { basename, extname, join, resolve } from "node:path";
import { unzipSync } from "fflate";
+import { ConfigurationError, errorMessage } from "./errors.js";
import { expandHome } from "./runtime.js";
import {
gitMarkerRoot,
@@ -45,79 +46,86 @@ export async function readKnowledgeBaseSnapshot(
paths: readonly string[],
signal?: AbortSignal,
): Promise<KnowledgeBaseSnapshot> {
- const sources = new Set<string>();
- const documents = new Set<string>();
+ try {
+ const sources = new Set<string>();
+ const documents = new Set<string>();
- for (const requested of paths) {
- signal?.throwIfAborted();
- if (!requested.trim())
- throw new Error("Knowledge base paths cannot be empty.");
- const path = resolve(expandHome(requested));
- const metadata = await lstat(path);
- if (metadata.isSymbolicLink()) {
- throw new Error(`Knowledge base paths cannot be symbolic links: ${path}`);
- }
- if (!metadata.isFile() && !metadata.isDirectory()) {
- throw new Error(
- `Knowledge base path is not a file or directory: ${path}`,
- );
- }
+ for (const requested of paths) {
+ signal?.throwIfAborted();
+ if (!requested.trim())
+ throw new Error("Knowledge base paths cannot be empty.");
+ const path = resolve(expandHome(requested));
+ const metadata = await lstat(path);
+ if (metadata.isSymbolicLink()) {
+ throw new Error(
+ `Knowledge base paths cannot be symbolic links: ${path}`,
+ );
+ }
+ if (!metadata.isFile() && !metadata.isDirectory()) {
+ throw new Error(
+ `Knowledge base path is not a file or directory: ${path}`,
+ );
+ }
- const source = await realpath(path);
- const selected = metadata.isDirectory()
- ? (await discover(source, signal)).sort()
- : [source];
- if (selected.length === 0) {
- throw new Error(
- `Knowledge base directory contains no supported documents: ${path}`,
- );
- }
- for (const document of selected) {
- documents.add(document);
+ const source = await realpath(path);
+ const selected = metadata.isDirectory()
+ ? (await discover(source, signal)).sort()
+ : [source];
+ if (selected.length === 0) {
+ throw new Error(
+ `Knowledge base directory contains no supported documents: ${path}`,
+ );
+ }
+ for (const document of selected) {
+ documents.add(document);
+ }
+ sources.add(source);
}
- sources.add(source);
- }
- const extracted: Record<string, string> = {};
- let index = 0;
- for (const document of documents) {
- signal?.throwIfAborted();
- const metadata = await lstat(document);
- if (process.platform !== "win32" && (metadata.mode & 0o444) === 0) {
- throw new Error(`Knowledge base document is not readable: ${document}`);
- }
- const bytes = await readFile(document, {
- flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
- signal,
- });
- const extension = extname(document).toLowerCase();
- const text =
- extension === ".pdf"
- ? await extractPdf(document, bytes)
- : extension === ".docx"
- ? extractDocx(document, bytes)
- : decodeText(document, bytes);
- if ((extension === ".pdf" || extension === ".docx") && !text.trim()) {
- throw new Error(
- `Knowledge base document contains no extractable text: ${document}`,
- );
+ const extracted: Record<string, string> = {};
+ let index = 0;
+ for (const document of documents) {
+ signal?.throwIfAborted();
+ const metadata = await lstat(document);
+ if (process.platform !== "win32" && (metadata.mode & 0o444) === 0) {
+ throw new Error(`Knowledge base document is not readable: ${document}`);
+ }
+ const bytes = await readFile(document, {
+ flag: constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
+ signal,
+ });
+ const extension = extname(document).toLowerCase();
+ const text =
+ extension === ".pdf"
+ ? await extractPdf(document, bytes)
+ : extension === ".docx"
+ ? extractDocx(document, bytes)
+ : decodeText(document, bytes);
+ if ((extension === ".pdf" || extension === ".docx") && !text.trim()) {
+ throw new Error(
+ `Knowledge base document contains no extractable text: ${document}`,
+ );
+ }
+ const name = `${index}-${basename(document)}.txt`;
+ // The prefix and suffix can exceed the filesystem's 255-byte name limit.
+ const filename = Buffer.byteLength(name) > 255 ? `${index}.txt` : name;
+ extracted[filename] = text;
+ index++;
}
- const name = `${index}-${basename(document)}.txt`;
- // The prefix and suffix can exceed the filesystem's 255-byte name limit.
- const filename = Buffer.byteLength(name) > 255 ? `${index}.txt` : name;
- extracted[filename] = text;
- index++;
- }
- return {
- sources: [...sources],
- protectedRoots: await Promise.all(
- [...sources].map(
- async (source) =>
- (await gitMarkerRoot(source, signal, "outermost")) ?? source,
+ return {
+ sources: [...sources],
+ protectedRoots: await Promise.all(
+ [...sources].map(
+ async (source) =>
+ (await gitMarkerRoot(source, signal, "outermost")) ?? source,
+ ),
),
- ),
- documents: extracted,
- };
+ documents: extracted,
+ };
+ } catch (error) {
+ if (signal?.aborted || error instanceof ConfigurationError) throw error;
+ throw new ConfigurationError(errorMessage(error), { cause: error });
+ }
}
export async function prepareKnowledgeBase(
@@ -125,41 +133,46 @@ export async function prepareKnowledgeBase(
signal?: AbortSignal,
directory?: string,
): Promise<PreparedKnowledgeBase> {
- const snapshot =
- "documents" in input
- ? input
- : await readKnowledgeBaseSnapshot(input, signal);
- const protectedRoots =
- snapshot.protectedRoots === undefined
- ? await Promise.all(
- snapshot.sources.map(
- async (source) =>
- (await gitMarkerRoot(source, signal, "outermost")) ?? source,
- ),
- )
- : [...snapshot.protectedRoots];
- const path = await mkdtemp(
- join(directory ?? tmpdir(), "codex-security-knowledge-"),
- );
try {
- for (const [filename, text] of Object.entries(snapshot.documents)) {
- signal?.throwIfAborted();
- await writeFile(join(path, filename), text, {
- encoding: "utf8",
- mode: 0o600,
- signal,
- });
+ const snapshot =
+ "documents" in input
+ ? input
+ : await readKnowledgeBaseSnapshot(input, signal);
+ const protectedRoots =
+ snapshot.protectedRoots === undefined
+ ? await Promise.all(
+ snapshot.sources.map(
+ async (source) =>
+ (await gitMarkerRoot(source, signal, "outermost")) ?? source,
+ ),
+ )
+ : [...snapshot.protectedRoots];
+ const path = await mkdtemp(
+ join(directory ?? tmpdir(), "codex-security-knowledge-"),
+ );
+ try {
+ for (const [filename, text] of Object.entries(snapshot.documents)) {
+ signal?.throwIfAborted();
+ await writeFile(join(path, filename), text, {
+ encoding: "utf8",
+ mode: 0o600,
+ signal,
+ });
+ }
+ } catch (error) {
+ await rm(path, { recursive: true, force: true });
+ throw error;
}
+ return {
+ path,
+ sources: [...snapshot.sources],
+ protectedRoots,
+ cleanup: () => rm(path, { recursive: true, force: true }),
+ };
} catch (error) {
- await rm(path, { recursive: true, force: true });
- throw error;
+ if (signal?.aborted || error instanceof ConfigurationError) throw error;
+ throw new ConfigurationError(errorMessage(error), { cause: error });
}
- return {
- path,
- sources: [...snapshot.sources],
- protectedRoots,
- cleanup: () => rm(path, { recursive: true, force: true }),
- };
}
/** @internal Read the same extracted document text used by scans. */
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 88012cb57..20d3607da 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -55,6 +55,7 @@ import {
OutputDirectoryNotEmptyError,
OutputInsideProtectedRootError,
PluginBootstrapError,
+ LocalPluginBootstrapError,
PluginPythonUnavailableError,
type ProtectedScanPathKind,
SandboxUnavailableError,
@@ -2562,26 +2563,32 @@ export async function resolvePluginPath(
workspace: string,
signal?: AbortSignal,
): Promise<string> {
- if (pluginPath === undefined) {
- return await bundledPluginRoot();
- }
+ try {
+ if (pluginPath === undefined) {
+ return await bundledPluginRoot();
+ }
- const path = resolve(expandHome(pluginPath));
- const metadata = await lstat(path).catch(() => null);
- if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
- return await extractPluginZip(
- path,
- join(workspace, "extracted-plugin"),
- signal,
+ const path = resolve(expandHome(pluginPath));
+ const metadata = await lstat(path).catch(() => null);
+ if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
+ return await extractPluginZip(
+ path,
+ join(workspace, "extracted-plugin"),
+ signal,
+ );
+ }
+ if (metadata?.isDirectory()) {
+ throwIfSignalAborted(signal);
+ return await validatePluginRoot(path);
+ }
+ throw new PluginBootstrapError(
+ `Plugin path must be a directory or ZIP: ${path}`,
);
+ } catch (error) {
+ if (signal?.aborted || error instanceof LocalPluginBootstrapError)
+ throw error;
+ throw new LocalPluginBootstrapError(errorMessage(error), { cause: error });
}
- if (metadata?.isDirectory()) {
- throwIfSignalAborted(signal);
- return await validatePluginRoot(path);
- }
- throw new PluginBootstrapError(
- `Plugin path must be a directory or ZIP: ${path}`,
- );
}
export async function createMarketplace(
@@ -2589,20 +2596,26 @@ export async function createMarketplace(
pluginRoot: string,
signal?: AbortSignal,
): Promise<string> {
- throwIfSignalAborted(signal);
- const root = await realpath(pluginRoot);
- const marketplace = join(codexHome, "sdk-marketplace");
- const pluginDestination = join(marketplace, "plugins", PLUGIN_NAME);
- await copyPluginTree(root, pluginDestination, signal);
- const projection = await legacyPluginProjection(pluginDestination, signal);
- for (const [path, file] of projection?.files ?? []) {
- const destination = join(pluginDestination, path);
- await mkdir(dirname(destination), { recursive: true });
- await writeFile(destination, file.contents, { mode: file.mode, signal });
- if (file.mode !== undefined) await chmod(destination, file.mode);
+ try {
+ throwIfSignalAborted(signal);
+ const root = await realpath(pluginRoot);
+ const marketplace = join(codexHome, "sdk-marketplace");
+ const pluginDestination = join(marketplace, "plugins", PLUGIN_NAME);
+ await copyPluginTree(root, pluginDestination, signal);
+ const projection = await legacyPluginProjection(pluginDestination, signal);
+ for (const [path, file] of projection?.files ?? []) {
+ const destination = join(pluginDestination, path);
+ await mkdir(dirname(destination), { recursive: true });
+ await writeFile(destination, file.contents, { mode: file.mode, signal });
+ if (file.mode !== undefined) await chmod(destination, file.mode);
+ }
+ await writeMarketplaceManifest(marketplace, signal);
+ return marketplace;
+ } catch (error) {
+ if (signal?.aborted || error instanceof LocalPluginBootstrapError)
+ throw error;
+ throw new LocalPluginBootstrapError(errorMessage(error), { cause: error });
}
- await writeMarketplaceManifest(marketplace, signal);
- return marketplace;
}
async function writeMarketplaceManifest(
@@ -2814,7 +2827,14 @@ export async function bootstrapPlugin(
): Promise<PluginInstall> {
const root = await realpath(pluginRoot);
const { name, version } = await pluginMetadata(root);
- const projection = await legacyPluginProjection(root, options.signal);
+ const projection = await legacyPluginProjection(root, options.signal).catch(
+ (error: unknown) => {
+ if (options.signal?.aborted) throw error;
+ throw new LocalPluginBootstrapError(errorMessage(error), {
+ cause: error,
+ });
+ },
+ );
const marketplace = join(codexHome, "sdk-marketplace");
throwIfSignalAborted(options.signal);
const command =
@@ -2826,7 +2846,7 @@ export async function bootstrapPlugin(
const run = options.runCodex ?? runPluginCommand;
const existing = await lstat(marketplace).catch(nullIfMissingFileError);
if (existing !== null && !existing.isDirectory()) {
- throw new PluginBootstrapError(
+ throw new LocalPluginBootstrapError(
`Codex Security plugin marketplace path must be a directory: ${marketplace}`,
);
}
@@ -3079,18 +3099,21 @@ export async function pluginMetadata(
}
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
} catch (error) {
- throw new PluginBootstrapError(`Invalid Codex plugin directory: ${root}`, {
- cause: error,
- });
+ throw new LocalPluginBootstrapError(
+ `Invalid Codex plugin directory: ${root}`,
+ {
+ cause: error,
+ },
+ );
}
if (!isRecord(manifest) || manifest["name"] !== PLUGIN_NAME) {
- throw new PluginBootstrapError(
+ throw new LocalPluginBootstrapError(
"Plugin manifest must have name 'codex-security'.",
);
}
const version = manifest["version"];
if (typeof version !== "string" || version.trim().length === 0) {
- throw new PluginBootstrapError(
+ throw new LocalPluginBootstrapError(
"Plugin manifest must have a non-empty version.",
);
}
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index ec4bcbd0f..35566518e 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -22,6 +22,8 @@ import type {
import {
BUNDLED_PLUGIN_VERSION,
CodexSecurityError,
+ LocalPluginBootstrapError,
+ PluginBootstrapError,
DiffTarget,
InvalidTargetError,
OutputDirectoryError,
@@ -139,6 +141,45 @@ async function multiscanInventory(root: string): Promise<void> {
}
describe("CLI", () => {
+ test("preserves typed local plugin failure origin and diagnostic details", async () => {
+ const cause = new Error("Synthetic plugin preparation detail.");
+ const localFailure = new LocalPluginBootstrapError(
+ "Synthetic plugin preparation failed.",
+ { cause },
+ );
+ const installerFailure = new PluginBootstrapError(
+ "Synthetic plugin connection failed.",
+ );
+ expect(localFailure).toBeInstanceOf(PluginBootstrapError);
+ expect(localFailure.cause).toBe(cause);
+ expect(installerFailure).not.toBeInstanceOf(LocalPluginBootstrapError);
+ for (const [failure, classification] of [
+ [localFailure, "local"],
+ [installerFailure, "network_error"],
+ ] as const) {
+ for (const format of ["json", "jsonl"] as const) {
+ const { stdout, stderr, runCli } = createCliTest(main);
+ const deps = dependencies({
+ onRun: () => {
+ throw failure;
+ },
+ });
+ expect(
+ await runCli(["scan", ".", "--verbose", "--format", format], deps),
+ ).toBe(2);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ status: "failed",
+ code: "SCAN_FAILED",
+ });
+ expect(stderr.text()).toContain(failure.message);
+ expect(stderr.text()).toContain(
+ `scan.failed classification="${classification}"`,
+ );
+ expect(JSON.parse(stdout.text()).message).toContain(failure.message);
+ }
+ }
+ });
+
test("passes the safety identifier as a per-scan option", async () => {
const onTurn = mock<(repository: string, options: unknown) => void>();
const stderr = captureCli(main, "stderr");
diff --git a/sdk/typescript/tests-ts/knowledge-base.test.ts b/sdk/typescript/tests-ts/knowledge-base.test.ts
index ab049b7d8..71eff27be 100644
--- a/sdk/typescript/tests-ts/knowledge-base.test.ts
+++ b/sdk/typescript/tests-ts/knowledge-base.test.ts
@@ -14,7 +14,11 @@ import * as os from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, spyOn, test } from "bun:test";
import { strToU8, zipSync } from "fflate";
-import { prepareKnowledgeBase } from "../src/knowledge-base.js";
+import { ConfigurationError } from "../src/errors.js";
+import {
+ prepareKnowledgeBase,
+ readKnowledgeBaseSnapshot,
+} from "../src/knowledge-base.js";
import { expandHome } from "../src/runtime.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -489,6 +493,52 @@ describe("scan knowledge bases", () => {
expect(documents).toContain("Authentication\nReview sessions\n");
});
+ test.each([
+ ["preparation", prepareKnowledgeBase],
+ ["snapshot extraction", readKnowledgeBaseSnapshot],
+ ] as const)(
+ "preserves the local origin and cause of document parser failures during %s",
+ async (_name, prepare) => {
+ const root = await temporaryDirectory();
+ const source = join(root, "network-security.pdf");
+ await writeFile(source, pdf("Network design"));
+ const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
+ const cause = new Error("Synthetic parser failure.");
+ const parser = spyOn(pdfjs, "getDocument").mockImplementation(() => {
+ throw cause;
+ });
+
+ try {
+ const prepared = prepare([source]);
+ await expect(prepared).rejects.toBeInstanceOf(ConfigurationError);
+ await expect(prepared).rejects.toMatchObject({
+ message: `Cannot extract text from knowledge base PDF: ${source}`,
+ cause: { cause },
+ });
+ } finally {
+ parser.mockRestore();
+ }
+ },
+ );
+
+ test("preserves the local origin and cause when snapshot staging fails", async () => {
+ const root = await temporaryDirectory();
+ const parent = join(root, "not-a-directory");
+ await writeFile(parent, "synthetic occupied path");
+ const prepared = prepareKnowledgeBase(
+ {
+ sources: [],
+ protectedRoots: [],
+ documents: { "0.txt": "Synthetic knowledge" },
+ },
+ undefined,
+ parent,
+ );
+ await expect(prepared).rejects.toBeInstanceOf(ConfigurationError);
+ await expect(prepared).rejects.toMatchObject({ cause: expect.any(Error) });
+ expect(await readFile(parent, "utf8")).toBe("synthetic occupied path");
+ });
+
test.each([
["&#x110000;", "&#x110000;"],
["&#1114112;", "&#1114112;"],
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index a39b36904..aa4797625 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -53,7 +53,9 @@ import {
createMarketplace,
extractPluginZip,
importAmbientAuth,
+ LocalPluginBootstrapError,
pluginExecutionEnvironment,
+ pluginMetadata,
PluginBootstrapError,
PluginPythonUnavailableError,
prepareOutputDir,
@@ -839,17 +841,46 @@ describe("plugin runtime preparation", () => {
}
});
+ test("preserves the local origin of plugin selection and manifest failures", async () => {
+ const root = await temporaryDirectory();
+ const workspace = join(root, "workspace");
+ const source = await plugin(root);
+ await mkdir(workspace);
+ await expect(
+ resolvePluginPath(join(root, "network-plugin"), workspace),
+ ).rejects.toBeInstanceOf(LocalPluginBootstrapError);
+
+ const cause = new Error("Synthetic manifest read failure.");
+ const manifestRead = spyOn(fsPromises, "readFile").mockRejectedValue(cause);
+ try {
+ for (const operation of [
+ () => pluginMetadata(source),
+ () => resolvePluginPath(source, workspace),
+ ]) {
+ const result = operation();
+ await expect(result).rejects.toBeInstanceOf(LocalPluginBootstrapError);
+ await expect(result).rejects.toMatchObject({
+ message: `Invalid Codex plugin directory: ${source}`,
+ cause,
+ });
+ }
+ } finally {
+ manifestRead.mockRestore();
+ }
+ });
+
test("honors cancellation while staging a configured plugin directory", async () => {
const root = await temporaryDirectory();
const workspace = join(root, "bootstrap");
await mkdir(workspace);
const source = await plugin(root);
const controller = new AbortController();
- controller.abort(new DOMException("canceled", "AbortError"));
+ const reason = new DOMException("canceled", "AbortError");
+ controller.abort(reason);
await expect(
resolvePluginPath(source, workspace, controller.signal),
- ).rejects.toMatchObject({ name: "AbortError" });
+ ).rejects.toBe(reason);
expect(existsSync(join(workspace, "selected-plugin"))).toBe(false);
});
@@ -878,6 +909,63 @@ describe("plugin runtime preparation", () => {
).toBeDefined();
});
+ test("keeps local marketplace failures separate from installer failures", async () => {
+ const root = await temporaryDirectory();
+ const selected = await plugin(root);
+ const home = join(root, "home");
+ const marketplace = join(home, "sdk-marketplace");
+ const installationFailure = new PluginBootstrapError(
+ "Codex plugin bootstrap failed: network ECONNRESET",
+ );
+ let installerCalls = 0;
+ const options = {
+ codexCommand: { command: join(root, "codex") },
+ environment: {},
+ runCodex: async () => {
+ installerCalls += 1;
+ throw installationFailure;
+ },
+ };
+
+ await mkdir(home);
+ await writeFile(marketplace, "local fixture");
+ await expect(
+ bootstrapPlugin(home, selected, options),
+ ).rejects.toBeInstanceOf(LocalPluginBootstrapError);
+ await rm(marketplace);
+
+ await writeFile(join(selected, ".mcp.json"), "network failure");
+ const malformed = await bootstrapPlugin(home, selected, options).catch(
+ (error: unknown) => error,
+ );
+ expect(malformed).toBeInstanceOf(LocalPluginBootstrapError);
+ const failure = malformed as LocalPluginBootstrapError;
+ expect(failure.cause).toBeInstanceOf(SyntaxError);
+ expect(failure.message).toBe((failure.cause as Error).message);
+ await rm(join(selected, ".mcp.json"));
+
+ const cause = new PluginBootstrapError(
+ "Plugin projection failed for a local network directory.",
+ );
+ const copy = spyOn(fsPromises, "cp").mockRejectedValue(cause);
+ try {
+ const result = bootstrapPlugin(home, selected, options);
+ await expect(result).rejects.toBeInstanceOf(LocalPluginBootstrapError);
+ await expect(result).rejects.toMatchObject({
+ message: cause.message,
+ cause,
+ });
+ } finally {
+ copy.mockRestore();
+ }
+ expect(installerCalls).toBe(0);
+
+ await expect(bootstrapPlugin(home, selected, options)).rejects.toBe(
+ installationFailure,
+ );
+ expect(installerCalls).toBe(1);
+ });
+
test.each([
"shell",
"shell with root",
@@ -1433,7 +1521,7 @@ ${directNode ? "}" : ""}
).toBe(false);
});
- test("extracts a plugin in one top-level directory", async () => {
+ test("extracts a plugin in one top-level directory and preserves manifest failures", async () => {
const root = await temporaryDirectory();
const archive = join(root, "plugin.zip");
await writeFile(
@@ -1446,6 +1534,35 @@ ${directNode ? "}" : ""}
);
const extracted = await extractPluginZip(archive, join(root, "extracted"));
expect(extracted).toBe(join(root, "extracted", "release"));
+
+ const cause = new Error("Synthetic manifest read failure.");
+ const originalReadFile = fsPromises.readFile;
+ const manifestRead = spyOn(fsPromises, "readFile").mockImplementation(((
+ ...args: Parameters<typeof originalReadFile>
+ ) => {
+ if (
+ args[1] === "utf8" &&
+ String(args[0]).endsWith(join(".codex-plugin", "plugin.json"))
+ ) {
+ return Promise.reject(cause);
+ }
+ return Reflect.apply(originalReadFile, fsPromises, args);
+ }) as typeof originalReadFile);
+ try {
+ for (const operation of [
+ () => extractPluginZip(archive, join(root, "failed-extract")),
+ () => resolvePluginPath(archive, join(root, "bootstrap")),
+ ]) {
+ const result = operation();
+ await expect(result).rejects.toBeInstanceOf(LocalPluginBootstrapError);
+ await expect(result).rejects.toMatchObject({
+ message: expect.stringContaining("Invalid Codex plugin directory:"),
+ cause,
+ });
+ }
+ } finally {
+ manifestRead.mockRestore();
+ }
});
test("decodes flag-clear ZIP filenames with the legacy CP437 encoding", async () => {