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

refactor(cli): reuse scan setup across commands (#510)

mldangelo-oai65993d375f27
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 9cd6feb8c..8abdb37b5 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -164,6 +164,7 @@ const distFiles = new Set(
"auth",
"bulk-scan-discovery",
"cli",
+ "codex-prompt",
"config",
"contract",
"cost",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index a498b213b..9b72f890c 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -31,6 +31,11 @@ import {
logout as codexLogout,
type AccountStatus,
} from "./auth.js";
+import {
+ jsonForPrompt,
+ pluginPythonCommand,
+ shellEnvironmentReference,
+} from "./codex-prompt.js";
import {
EXTERNAL_CODEX_PROVIDERS,
isExternalModelProvider,
@@ -58,8 +63,6 @@ import {
CodexSecurityError,
IncompleteScanError,
OutputDirectoryError,
- OutputInsideProtectedRootError,
- type ProtectedScanPathKind,
errorMessage,
safeErrorMessage,
ScanCostLimitExceededError,
@@ -103,8 +106,9 @@ import {
pluginExecutionEnvironment,
planOutputArchive,
prepareOutputDir,
- preparePersistentScanRoot,
+ preparePersistentOutputRoot,
requireModelSafeOutputDir,
+ requireOutputOutsideRepository,
resolveCodexCommand,
resolvePluginPath,
resolvePluginPython,
@@ -548,7 +552,11 @@ export class CodexSecurity {
const scanOutputRoot =
requestedOutput === null &&
this.#dependencies.prepareOutputDir === undefined
- ? await preparePersistentScanRoot(stateDirectory, basename(repo))
+ ? await preparePersistentOutputRoot(
+ stateDirectory,
+ "scans",
+ basename(repo),
+ )
: temporaryRoot;
if (scanOutputRoot !== undefined) {
requireOutputOutsideRepository(
@@ -937,12 +945,7 @@ export class CodexSecurity {
approvalPolicy,
});
const serializedPaths =
- normalized.kind === "paths"
- ? JSON.stringify(normalized.paths)
- .replaceAll("\u0085", "\\u0085")
- .replaceAll("\u2028", "\\u2028")
- .replaceAll("\u2029", "\\u2029")
- : null;
+ normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
checkOpen();
if (serializedPaths !== null && targetPathsFile !== null) {
await writeFile(targetPathsFile, `${serializedPaths}\n`, {
@@ -2542,7 +2545,7 @@ function scanPrompt(
additionalPrompt?: string,
enforceCostLimit = false,
): string {
- const python = `${process.platform === "win32" ? "& " : ""}${shellEnvironmentReference("PYTHON")}`;
+ const python = pluginPythonCommand();
return [
`Use the installed $codex-security:${skillName} skill at ${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", `/skills/${skillName}/SKILL.md`)}.`,
"Run this Codex Security scan non-interactively.",
@@ -2619,11 +2622,6 @@ function scanPrompt(
].join("\n");
}
-function shellEnvironmentReference(name: string, suffix = ""): string {
- const prefix = process.platform === "win32" ? "$env:" : "$";
- return `"${prefix}${name}${suffix}"`;
-}
-
function skillNameFor(target: NormalizedTarget, mode: ScanMode): string {
if (target.kind === "refs" || target.kind === "working_tree")
return "security-diff-scan";
@@ -3203,31 +3201,6 @@ async function pluginSupportsIsolatedDeepScanConfig(
);
}
-function requireOutputOutsideRepository(
- repository: string,
- outputDirectory: string,
- pathKind: ProtectedScanPathKind = "output",
-): void {
- const outputRelative = relative(repository, outputDirectory);
- const repositoryRelative = relative(outputDirectory, repository);
- if (
- outputRelative === "" ||
- (outputRelative !== ".." &&
- !outputRelative.startsWith(`..${sep}`) &&
- !isAbsolute(outputRelative)) ||
- (pathKind === "output" &&
- repositoryRelative !== ".." &&
- !repositoryRelative.startsWith(`..${sep}`) &&
- !isAbsolute(repositoryRelative))
- ) {
- throw new OutputInsideProtectedRootError(
- outputDirectory,
- repository,
- pathKind,
- );
- }
-}
-
function throwIfAborted(signal?: AbortSignal, scanDir = ""): void {
if (!signal?.aborted) return;
if (signal.reason instanceof ScanCostLimitExceededError) throw signal.reason;
diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.ts
index 197e4a424..c5c42410a 100644
--- a/sdk/typescript/src/bulk-scan-discovery.ts
+++ b/sdk/typescript/src/bulk-scan-discovery.ts
@@ -54,12 +54,21 @@ interface GitHubRepositoriesResponse {
export interface BulkScanPrompt {
isInteractive(): boolean;
write(value: string): void;
- confirm(question: string, defaultValue?: boolean): Promise<boolean>;
- input(question: string, defaultValue?: string): Promise<string>;
+ confirm(
+ question: string,
+ defaultValue?: boolean,
+ signal?: AbortSignal,
+ ): Promise<boolean>;
+ input(
+ question: string,
+ defaultValue?: string,
+ signal?: AbortSignal,
+ ): Promise<string>;
select<Value extends string>(
question: string,
options: readonly { label: string; value: Value; short?: string }[],
presentation?: { header?: string },
+ signal?: AbortSignal,
): Promise<Value>;
}
@@ -326,7 +335,7 @@ async function validateWizardOutput(outputDir: string): Promise<void> {
}
function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {
- const context = () => {
+ const context = (signal?: AbortSignal) => {
const stream = new Writable({
write(chunk: Buffer, _encoding, callback) {
output.write(chunk.toString("utf8"));
@@ -337,7 +346,7 @@ function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {
configurable: true,
get: () => output.columns,
});
- return { input: stdin, output: stream };
+ return { input: stdin, output: stream, signal };
};
return {
@@ -345,11 +354,11 @@ function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {
write: (value) => {
output.write(value);
},
- confirm: (message, defaultValue = false) =>
- confirm({ message, default: defaultValue }, context()),
- input: (message, defaultValue) =>
- input({ message, default: defaultValue }, context()),
- select: (message, options, presentation) =>
+ confirm: (message, defaultValue = false, signal) =>
+ confirm({ message, default: defaultValue }, context(signal)),
+ input: (message, defaultValue, signal) =>
+ input({ message, default: defaultValue }, context(signal)),
+ select: (message, options, presentation, signal) =>
search(
{
message,
@@ -374,7 +383,7 @@ function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {
...(short === undefined ? {} : { short }),
})),
},
- context(),
+ context(signal),
),
};
}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 495cecd45..001efa4b4 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -125,7 +125,12 @@ import type {
ScanWorkerPhase,
ScanWorkerStatus,
} from "./worker-progress.js";
-import { DiffTarget, type ScanMode, type ScanTarget } from "./targets.js";
+import {
+ abortable,
+ DiffTarget,
+ type ScanMode,
+ type ScanTarget,
+} from "./targets.js";
import {
BUNDLED_PLUGIN_VERSION,
checkForUpdate,
@@ -141,7 +146,7 @@ const PROGRESS_REFRESH_MILLISECONDS = 1_000;
const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
const WINDOWS_LOCAL_DEVICE_ROOT =
/^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
-const SCAN_HISTORY_OUTPUT_OPTION =
+const OUTPUT_OPTION =
/^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
const HIDE_CURSOR = "\u001B[?25l";
const SHOW_CURSOR = "\u001B[?25h";
@@ -714,7 +719,7 @@ interface CliDependencies {
prepareAuthenticationHome?: (
environment: NodeJS.ProcessEnv,
) => Promise<string>;
- hasStoredChatGPTSignIn?: () => Promise<boolean>;
+ hasStoredChatGPTSignIn?: (signal?: AbortSignal) => Promise<boolean>;
scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;
publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;
publishScan?: typeof publishScan;
@@ -749,7 +754,8 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
prepareAuthenticationHome: prepareCodexSecurityCredentialHome,
checkForUpdate: (signal) =>
checkForUpdate({ environment: process.env, signal }),
- hasStoredChatGPTSignIn: async () => {
+ hasStoredChatGPTSignIn: async (signal) => {
+ signal?.throwIfAborted();
const environment = Object.fromEntries(
Object.entries(process.env).filter(
([name]) =>
@@ -759,10 +765,14 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
);
const command = resolveCodexCommand(environment);
if (existsSync(codexSecurityCredentialHome(process.env))) {
- const dedicatedStatus = await accountStatus(command, {
- ...environment,
- CODEX_HOME: await prepareCodexSecurityCredentialHome(process.env),
- });
+ const dedicatedStatus = await accountStatus(
+ command,
+ {
+ ...environment,
+ CODEX_HOME: await prepareCodexSecurityCredentialHome(process.env),
+ },
+ signal,
+ );
if (
dedicatedStatus.authenticated &&
/\bchatgpt\b/iu.test(dedicatedStatus.details)
@@ -770,7 +780,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
return true;
}
}
- const ambientStatus = await accountStatus(command, environment);
+ const ambientStatus = await accountStatus(command, environment, signal);
return (
ambientStatus.authenticated && /\bchatgpt\b/iu.test(ambientStatus.details)
);
@@ -1207,7 +1217,7 @@ export async function main(
result === undefined ||
format !== "toon" ||
output.isTTY !== true ||
- argv.some((argument) => SCAN_HISTORY_OUTPUT_OPTION.test(argument))
+ argv.some((argument) => OUTPUT_OPTION.test(argument))
) {
return result;
}
@@ -1863,7 +1873,7 @@ export async function main(
format === "toon" &&
!formatExplicit &&
!options.dryRun &&
- !argv.some((argument) => SCAN_HISTORY_OUTPUT_OPTION.test(argument))
+ !argv.some((argument) => OUTPUT_OPTION.test(argument))
) {
renderedPublication = renderPublicationSummary(
result,
@@ -2123,7 +2133,7 @@ export async function main(
if (
!options.dryRun &&
format === "toon" &&
- !argv.some((argument) => SCAN_HISTORY_OUTPUT_OPTION.test(argument))
+ !argv.some((argument) => OUTPUT_OPTION.test(argument))
) {
return;
}
@@ -3636,12 +3646,81 @@ function diagnosticValue(value: unknown): string {
);
}
+async function chooseInteractiveAuthentication(
+ options: {
+ auth: ScanAuthMode | undefined;
+ provider: unknown;
+ command: "scan" | "policy";
+ signal: AbortSignal;
+ },
+ errorOutput: Writable,
+ dependencies: CliDependencies,
+): Promise<ScanAuthMode | undefined> {
+ const { auth, provider, signal } = options;
+ if (
+ errorOutput.isTTY !== true ||
+ isExternalModelProvider(provider) ||
+ (auth !== undefined && auth !== "auto")
+ )
+ return auth;
+ const authentication = scanAuthentication(
+ dependencies.environment,
+ auth,
+ provider,
+ );
+ if (authentication.method !== "api_key") return auth;
+ const prompt =
+ dependencies.scanAuthenticationPrompt ??
+ createBulkScanDiscoveryDependencies({
+ output: errorOutput,
+ now: dependencies.now,
+ currentDirectory: dependencies.currentDirectory,
+ }).prompt;
+ const hasStoredSignIn = dependencies.hasStoredChatGPTSignIn;
+ if (
+ !prompt.isInteractive() ||
+ hasStoredSignIn === undefined ||
+ !(await abortable(() => hasStoredSignIn(signal), signal))
+ )
+ return auth;
+ const source = authentication.source;
+ try {
+ errorOutput.write(
+ `Both a ChatGPT sign-in and an API key from ${source} are available.\n`,
+ );
+ } catch {}
+ return await abortable(
+ () =>
+ prompt.select<ScanAuthMode>(
+ options.command === "scan"
+ ? "How would you like to authenticate this scan?"
+ : "How would you like to authenticate policy generation?",
+ [
+ { label: "ChatGPT subscription", value: "chatgpt" },
+ { label: `API key from ${source}`, value: "api-key" },
+ ],
+ undefined,
+ signal,
+ ),
+ signal,
+ );
+}
+
async function runScan(
arguments_: ScanArguments,
errorOutput: Writable,
dependencies: CliDependencies,
interactive = true,
): Promise<ScanOutcome> {
+ return await withTerminalErrorsHandled(errorOutput, () =>
+ executeScan(arguments_, errorOutput, dependencies, interactive),
+ );
+}
+
+async function withTerminalErrorsHandled<T>(
+ errorOutput: Writable,
+ operation: () => Promise<T>,
+): Promise<T> {
const observeTerminalErrors =
typeof errorOutput.on === "function" &&
typeof errorOutput.off === "function";
@@ -3650,12 +3729,7 @@ async function runScan(
errorOutput.on?.("error", ignoreTerminalError);
}
try {
- return await executeScan(
- arguments_,
- errorOutput,
- dependencies,
- interactive,
- );
+ return await operation();
} finally {
if (observeTerminalErrors) {
try {
@@ -3802,50 +3876,25 @@ async function executeScan(
};
({ model: effectiveModel, reasoningEffort: effectiveReasoningEffort } =
scanModelConfiguration(effectiveConfiguration));
- let auth = arguments_.auth;
const provider = scanModelProvider(effectiveConfiguration);
+ const auth =
+ !arguments_.dryRun && interactive
+ ? await chooseInteractiveAuthentication(
+ {
+ auth: arguments_.auth,
+ provider,
+ command: "scan",
+ signal: preparationAbortController.signal,
+ },
+ errorOutput,
+ dependencies,
+ )
+ : arguments_.auth;
selectedAuthentication = scanAuthentication(
dependencies.environment,
auth,
provider,
);
- if (
- !isExternalModelProvider(provider) &&
- (auth === undefined || auth === "auto") &&
- !arguments_.dryRun &&
- interactive &&
- errorOutput.isTTY === true &&
- selectedAuthentication.method === "api_key"
- ) {
- const prompt =
- dependencies.scanAuthenticationPrompt ??
- createBulkScanDiscoveryDependencies({
- output: errorOutput,
- now: dependencies.now,
- currentDirectory: dependencies.currentDirectory,
- }).prompt;
- if (
- prompt.isInteractive() &&
- (await dependencies.hasStoredChatGPTSignIn?.()) === true
- ) {
- const source = selectedAuthentication.source;
- errorOutput.write(
- `Both a ChatGPT sign-in and an API key from ${source} are available.\n`,
- );
- auth = await prompt.select<ScanAuthMode>(
- "How would you like to authenticate this scan?",
- [
- { label: "ChatGPT subscription", value: "chatgpt" },
- { label: `API key from ${source}`, value: "api-key" },
- ],
- );
- selectedAuthentication = scanAuthentication(
- dependencies.environment,
- auth,
- provider,
- );
- }
- }
diagnostic("scan.configuration", {
cli_version: VERSION,
bundled_plugin_version: BUNDLED_PLUGIN_VERSION,
diff --git a/sdk/typescript/src/codex-prompt.ts b/sdk/typescript/src/codex-prompt.ts
new file mode 100644
index 000000000..47b830a08
--- /dev/null
+++ b/sdk/typescript/src/codex-prompt.ts
@@ -0,0 +1,15 @@
+export function shellEnvironmentReference(name: string, suffix = ""): string {
+ const prefix = process.platform === "win32" ? "$env:" : "$";
+ return `"${prefix}${name}${suffix}"`;
+}
+
+export function pluginPythonCommand(): string {
+ return `${process.platform === "win32" ? "& " : ""}${shellEnvironmentReference("PYTHON")}`;
+}
+
+export function jsonForPrompt(value: unknown): string {
+ return JSON.stringify(value)
+ .replaceAll("\u0085", "\\u0085")
+ .replaceAll("\u2028", "\\u2028")
+ .replaceAll("\u2029", "\\u2029");
+}
diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.ts
index 53d67c7ff..7a1988166 100644
--- a/sdk/typescript/src/errors.ts
+++ b/sdk/typescript/src/errors.ts
@@ -37,6 +37,18 @@ export class PluginBootstrapError extends CodexSecurityError {}
export class PluginPythonUnavailableError extends PluginBootstrapError {}
export class InvalidTargetError extends CodexSecurityError {}
export class OutputDirectoryError extends CodexSecurityError {}
+export class OutputDirectoryNotEmptyError extends OutputDirectoryError {
+ public constructor(
+ public readonly directory: string,
+ operation: "scan" | "policy" = "scan",
+ ) {
+ super(
+ operation === "policy"
+ ? `Policy output directory is not empty: ${directory}. Choose a new or empty directory.`
+ : `Scan output directory is not empty: ${directory}. To keep the existing results and start a new scan, add --archive-existing.`,
+ );
+ }
+}
export type ProtectedScanPathKind = "output" | "temporary" | "runtime";
export class OutputInsideProtectedRootError extends OutputDirectoryError {
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 609aa88d7..7ce3e3b0e 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -30,6 +30,7 @@ export {
IncompleteScanError,
InvalidTargetError,
OutputDirectoryError,
+ OutputDirectoryNotEmptyError,
OutputInsideProtectedRootError,
PluginBootstrapError,
PluginPythonUnavailableError,
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index e370454bc..81b2a2379 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -22,7 +22,16 @@ import {
} from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { createRequire } from "node:module";
-import { basename, dirname, extname, join, relative, resolve } from "node:path";
+import {
+ basename,
+ dirname,
+ extname,
+ isAbsolute,
+ join,
+ relative,
+ resolve,
+ sep,
+} from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
@@ -33,8 +42,11 @@ import { parse } from "smol-toml";
import {
CodexSecurityError,
OutputDirectoryError,
+ OutputDirectoryNotEmptyError,
+ OutputInsideProtectedRootError,
PluginBootstrapError,
PluginPythonUnavailableError,
+ type ProtectedScanPathKind,
errorMessage,
} from "./errors.js";
import type { JsonObject } from "./config.js";
@@ -1268,18 +1280,53 @@ export async function preserveCodexSecurityPluginRegistration(
};
}
-export async function preparePersistentScanRoot(
+export function requireOutputOutsideRepository(
+ repository: string,
+ outputDirectory: string,
+ pathKind: ProtectedScanPathKind = "output",
+): void {
+ const outputRelative = relative(repository, outputDirectory);
+ const repositoryRelative = relative(outputDirectory, repository);
+ if (
+ outputRelative === "" ||
+ (outputRelative !== ".." &&
+ !outputRelative.startsWith(`..${sep}`) &&
+ !isAbsolute(outputRelative)) ||
+ (pathKind === "output" &&
+ repositoryRelative !== ".." &&
+ !repositoryRelative.startsWith(`..${sep}`) &&
+ !isAbsolute(repositoryRelative))
+ ) {
+ throw new OutputInsideProtectedRootError(
+ outputDirectory,
+ repository,
+ pathKind,
+ );
+ }
+}
+
+export function requireOutputOutsideRepositories(
+ repositories: readonly string[],
+ outputDirectory: string,
+ pathKind: ProtectedScanPathKind = "output",
+): void {
+ for (const repository of repositories)
+ requireOutputOutsideRepository(repository, outputDirectory, pathKind);
+}
+
+export async function preparePersistentOutputRoot(
stateDirectory: string,
+ category: "scans" | "policies",
repositoryName: string,
): Promise<string> {
await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
let root = await realpath(stateDirectory);
- for (const directory of ["scans", safePrefix(repositoryName)]) {
+ for (const directory of [category, safePrefix(repositoryName)]) {
root = join(root, directory);
await mkdir(root, { recursive: true, mode: 0o700 });
if (!(await lstat(root)).isDirectory()) {
throw new OutputDirectoryError(
- `Persistent scan output must use real directories: ${root}`,
+ `Persistent ${category === "scans" ? "scan" : "policy"} output must use real directories: ${root}`,
);
}
}
@@ -1398,9 +1445,7 @@ export async function validateOutputDir(
);
}
if (!archiveExisting && (await readdir(path)).length !== 0) {
- throw new OutputDirectoryError(
- `Scan output directory is not empty: ${path}. To keep the existing results and start a new scan, add --archive-existing.`,
- );
+ throw new OutputDirectoryNotEmptyError(path);
}
requirePrivateOutputDirectory(metadata, path);
await requireSecureOutputAncestry(path);
diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts
index f13858af2..5c8ab0888 100644
--- a/sdk/typescript/src/targets.ts
+++ b/sdk/typescript/src/targets.ts
@@ -456,7 +456,7 @@ function isolatedGitEnvironment(
return environment;
}
-async function abortable<T>(
+export async function abortable<T>(
operation: () => Promise<T>,
signal?: AbortSignal,
): Promise<T> {
@@ -465,16 +465,18 @@ async function abortable<T>(
return await new Promise<T>((resolvePromise, reject) => {
const onAbort = (): void => reject(abortReason(signal));
signal.addEventListener("abort", onAbort, { once: true });
- void operation().then(
- (value) => {
- signal.removeEventListener("abort", onAbort);
- resolvePromise(value);
- },
- (error: unknown) => {
- signal.removeEventListener("abort", onAbort);
- reject(error);
- },
- );
+ void Promise.resolve()
+ .then(operation)
+ .then(
+ (value) => {
+ signal.removeEventListener("abort", onAbort);
+ resolvePromise(value);
+ },
+ (error: unknown) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ },
+ );
});
}
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 032bd1ca8..e88d3391d 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -20,6 +20,7 @@ import {
import {
capture,
dependencies as cliDependencies,
+ FakeSignals,
fakePreflight,
fakeResult,
} from "./cli-fixtures.js";
@@ -506,6 +507,47 @@ describe("CLI authentication", () => {
}
});
+ test("cancels sign-in discovery and authentication prompts before starting a scan", async () => {
+ for (const stage of ["status", "prompt"] as const) {
+ const signals = new FakeSignals();
+ const signalName = stage === "status" ? "SIGTERM" : "SIGINT";
+ let observedSignal: AbortSignal | undefined;
+ let initialized = false;
+ const deps = dependencies({
+ signals,
+ environment: { OPENAI_API_KEY: "synthetic-private-key" },
+ });
+ deps.createSecurity = () => {
+ initialized = true;
+ throw new Error("must not initialize a cancelled scan");
+ };
+ const interrupt = <Value>(signal?: AbortSignal): Promise<Value> => {
+ observedSignal = signal;
+ signals.emit(signalName);
+ return new Promise(() => {});
+ };
+ deps.hasStoredChatGPTSignIn = (signal) =>
+ stage === "status" ? interrupt<boolean>(signal) : Promise.resolve(true);
+ deps.scanAuthenticationPrompt = {
+ isInteractive: () => true,
+ select: <Value extends string>(
+ _message: string,
+ _options: readonly { label: string; value: Value }[],
+ _presentation?: { header?: string },
+ signal?: AbortSignal,
+ ) => interrupt<Value>(signal),
+ };
+
+ expect(
+ await main(["scan"], capture().stream, capture(true).stream, deps),
+ ).toBe(signalName === "SIGTERM" ? 143 : 130);
+ expect(observedSignal?.aborted).toBe(true);
+ expect(initialized).toBe(false);
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+ }
+ });
+
test("does not hide or relabel a failed ChatGPT login", async () => {
const stdout = capture();
const stderr = capture();
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index c46a8f9b3..20e2035bb 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -61,7 +61,7 @@ import {
isPythonPathCandidate,
planOutputArchive,
prepareCodexSecurityCredentialHome,
- preparePersistentScanRoot,
+ preparePersistentOutputRoot,
requirePrivateCredentialHome,
requirePrivateCredentialFile,
requirePrivateOutputDirectory,
@@ -3560,8 +3560,9 @@ describe("runtime directories and plugin Python boundary", () => {
CODEX_SECURITY_STATE_DIR: join(root, "explicit-state"),
}),
).toBe(join(root, "explicit-state"));
- const scanRoot = await preparePersistentScanRoot(
+ const scanRoot = await preparePersistentOutputRoot(
join(root, "state"),
+ "scans",
"repository with spaces",
);
expect(scanRoot).toBe(
@@ -3578,7 +3579,11 @@ describe("runtime directories and plugin Python boundary", () => {
process.platform === "win32" ? "junction" : "dir",
);
expect(
- await preparePersistentScanRoot(linkedState, "linked repository"),
+ await preparePersistentOutputRoot(
+ linkedState,
+ "scans",
+ "linked repository",
+ ),
).toBe(join(root, "state", "scans", "linked-repository"));
});
@@ -3601,7 +3606,7 @@ describe("runtime directories and plugin Python boundary", () => {
);
await expect(
- preparePersistentScanRoot(state, "repository"),
+ preparePersistentOutputRoot(state, "scans", "repository"),
).rejects.toThrow("Persistent scan output must use real directories");
expect(await readdir(external)).toEqual([]);
}