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(windows): preserve PowerShell environment and activity paths (#634)

faizan-oaic64fddceeb5e
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 7848ccb07..5cdf25f7b 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -51,6 +51,7 @@ import {
classifyConnectionFailure,
CodexSecurity,
createSecurityInternal,
+ environmentValue,
listRepositoryFindings,
SCAN_AUTH_MODES,
scanAuthentication,
@@ -1342,7 +1343,10 @@ export async function runCodexSkillCommand(
processEnvironment: NodeJS.ProcessEnv = process.env,
input?: string,
): Promise<number> {
- const configuredHome = processEnvironment["CODEX_HOME"];
+ const configuredHome =
+ process.platform === "win32"
+ ? environmentValue(processEnvironment, "CODEX_HOME")
+ : processEnvironment["CODEX_HOME"];
const environment = { ...processEnvironment };
for (const name of Object.keys(environment)) {
if (name.toUpperCase() === "CODEX_HOME") delete environment[name];
diff --git a/sdk/typescript/src/scan-activity.ts b/sdk/typescript/src/scan-activity.ts
index bf6c3dcf3..4cd377b9e 100644
--- a/sdk/typescript/src/scan-activity.ts
+++ b/sdk/typescript/src/scan-activity.ts
@@ -117,6 +117,20 @@ export function scanActivityFromEvent(
function displayCommand(command: string): string {
const normalized = command.replaceAll(/\s+/gu, " ").trim();
+ const powershell =
+ process.platform === "win32"
+ ? /^(?:"([^"]+)"|([^\s"'|;&<>]+))\s+(?:-NoProfile\s+)?-Command\s+(['"])(.*)\3$/iu.exec(
+ normalized,
+ )
+ : null;
+ if (
+ powershell !== null &&
+ /(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/iu.test(
+ powershell[1] ?? powershell[2]!,
+ )
+ ) {
+ return powershell[4]!;
+ }
const match =
/^(?:\/(?:usr\/)?bin\/)?(?:zsh|bash|sh)\s+-[a-z]*c[a-z]*\s+(['"])(.*)$/u.exec(
normalized,
@@ -358,13 +372,17 @@ function commandRepositoryPaths(command: string, repository: string): string[] {
const repositoryPrefix = repository.replaceAll("\\", "/").replace(/\/$/u, "");
for (const token of command.match(SHELL_TOKEN) ?? []) {
let value = token;
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
+ const singleQuoted = value.startsWith("'") && value.endsWith("'");
+ if ((value.startsWith('"') && value.endsWith('"')) || singleQuoted) {
value = value.slice(1, -1);
}
value = value.replaceAll('\\"', '"').replaceAll("\\", "/");
+ if (process.platform === "win32" && !singleQuoted) {
+ value = value.replace(
+ /^\$(?:env:CODEX_SECURITY_REPOSITORY|\{env:CODEX_SECURITY_REPOSITORY\})\//iu,
+ "$CODEX_SECURITY_REPOSITORY/",
+ );
+ }
for (const prefix of [
"$CODEX_SECURITY_REPOSITORY/",
"${CODEX_SECURITY_REPOSITORY}/",
diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.ts
index d50d151ae..6a9c036a7 100644
--- a/sdk/typescript/tests-ts/cli-skills.test.ts
+++ b/sdk/typescript/tests-ts/cli-skills.test.ts
@@ -997,6 +997,46 @@ describe("CLI skill commands", () => {
expect(stderr.text()).toBe("");
});
+ test("preserves the selected Codex home from copied Windows environments", async () => {
+ const configuredHome = "./synthetic home with spaces";
+ const source = `
+process.stdout.write(JSON.stringify({
+ type: "item.completed",
+ item: {
+ type: "agent_message",
+ text: JSON.stringify({
+ home: process.env.CODEX_HOME ?? null,
+ homeKeys: Object.keys(process.env).filter((name) => name.toUpperCase() === "CODEX_HOME"),
+ other: process.env.SYNTHETIC_OTHER,
+ }),
+ },
+}) + "\\n");
+`;
+ for (const name of ["CODEX_HOME", "codex_home", "Codex_Home"]) {
+ const environment = Object.freeze({
+ [name]: configuredHome,
+ SYNTHETIC_OTHER: "preserved",
+ });
+ const stdout = capture();
+ const stderr = capture();
+ expect(
+ await runCodexSkillCommand(
+ ["-e", source],
+ { command: "validate", stdout: stdout.stream, stderr: stderr.stream },
+ { command: process.execPath },
+ environment,
+ ),
+ ).toBe(0);
+ const selected = process.platform === "win32" || name === "CODEX_HOME";
+ expect(JSON.parse(stdout.text())).toEqual({
+ home: selected ? resolve(configuredHome) : null,
+ homeKeys: selected ? ["CODEX_HOME"] : [],
+ other: "preserved",
+ });
+ expect(stderr.text()).toBe("");
+ }
+ });
+
test("extracts the final skill response without exposing intermediate events", async () => {
async function* events(): AsyncGenerator<Buffer> {
yield Buffer.from(
diff --git a/sdk/typescript/tests-ts/scan-activity.test.ts b/sdk/typescript/tests-ts/scan-activity.test.ts
index c45d64e1b..21399ba5f 100644
--- a/sdk/typescript/tests-ts/scan-activity.test.ts
+++ b/sdk/typescript/tests-ts/scan-activity.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
+import { shellEnvironmentReference } from "../src/codex-prompt.js";
import {
scanActivitiesFromEvent,
scanActivityFromEvent,
@@ -146,11 +147,71 @@ describe("scan activity", () => {
});
});
+ test("unwraps native PowerShell command events and persisted worker commands", () => {
+ const script =
+ 'Get-Content -LiteralPath "$env:CODEX_SECURITY_REPOSITORY/example.txt"';
+ for (const launcher of [
+ '"C:\\\\tools\\\\pwsh.exe" -NoProfile',
+ '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoProfile',
+ '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoProfile',
+ "PowerShell.EXE -noprofile",
+ "pwsh",
+ ]) {
+ const command = `${launcher} -Command '${script}'`;
+ const expected = {
+ description: process.platform === "win32" ? script : command,
+ paths: process.platform === "win32" ? ["example.txt"] : [],
+ };
+ for (const type of ["item.started", "item.completed"] as const) {
+ expect(
+ scanActivityFromEvent(
+ commandEvent(type, command),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject(expected);
+ }
+ expect(
+ scanActivityFromSessionEvent(
+ sessionEvent({
+ type: "function_call",
+ name: "exec_command",
+ call_id: "worker-command-1",
+ arguments: JSON.stringify({ cmd: command }),
+ }),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject(expected);
+ }
+ });
+
+ test("preserves inner PowerShell literals when removing the shell launcher", () => {
+ for (const [script, quote] of [
+ ["Write-Output '$env:CODEX_SECURITY_REPOSITORY/example.txt'", '"'],
+ ['Write-Output "`$env:CODEX_SECURITY_REPOSITORY/example.txt"', "'"],
+ ]) {
+ const command = `pwsh -NoProfile -Command ${quote}${script}${quote}`;
+ expect(
+ scanActivityFromEvent(
+ commandEvent("item.started", command),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject({
+ description: process.platform === "win32" ? script : command,
+ paths: [],
+ });
+ }
+ });
+
test("does not remove a shell that is part of the actual command", () => {
for (const command of [
"/bin/zsh -i",
"/bin/zsh -lc unquoted-script",
"echo '/bin/zsh -lc'",
+ "pwsh -NoProfile",
+ "pwsh -File 'example.ps1'",
+ "pwsh -EncodedCommand 'ZQB4AGEAbQBwAGwAZQA='",
+ "other.exe -Command 'example'",
+ "echo 'pwsh -Command'",
]) {
expect(
scanActivityFromEvent(
@@ -204,6 +265,79 @@ describe("scan activity", () => {
).toMatchObject({ paths: ["routes/login page.ts"] });
});
+ test("recognizes repository paths generated for the current shell", () => {
+ const command = `${process.platform === "win32" ? "Get-Content -LiteralPath" : "cat"} ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY", "/src/app.ts")}`;
+ expect(
+ scanActivityFromEvent(
+ commandEvent("item.started", command),
+ process.platform === "win32" ? "C:\\code\\project" : "/code/project",
+ ),
+ ).toMatchObject({ paths: ["src/app.ts"] });
+ });
+
+ test("recognizes Windows PowerShell repository environment references", () => {
+ for (const [argument, path] of [
+ ["$env:CODEX_SECURITY_REPOSITORY/src/app.ts", "src/app.ts"],
+ ['"$env:CODEX_SECURITY_REPOSITORY\\src\\app page.ts"', "src/app page.ts"],
+ ['"${env:CODEX_SECURITY_REPOSITORY}/src/app.ts"', "src/app.ts"],
+ ['"$Env:Codex_Security_Repository\\src\\App.ts"', "src/App.ts"],
+ ['"${ENV:codex_security_repository}\\src\\App.ts"', "src/App.ts"],
+ ]) {
+ const command = `Get-Content -LiteralPath ${argument}`;
+ const paths = process.platform === "win32" ? [path] : [];
+ expect(
+ scanActivityFromEvent(
+ commandEvent("item.started", command),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject({ paths });
+ expect(
+ scanActivityFromSessionEvent(
+ sessionEvent({
+ type: "function_call",
+ name: "exec_command",
+ call_id: "worker-command-1",
+ arguments: JSON.stringify({ cmd: command }),
+ }),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject({ paths });
+ }
+ });
+
+ test("does not mistake PowerShell literals or other variables for repository paths", () => {
+ for (const argument of [
+ "'$env:CODEX_SECURITY_REPOSITORY/src/app.ts'",
+ "'${env:CODEX_SECURITY_REPOSITORY}/src/app.ts'",
+ '"`$env:CODEX_SECURITY_REPOSITORY/src/app.ts"',
+ '"$env:CODEX_SECURITY_REPOSITORY_BACKUP/src/app.ts"',
+ '"${env:CODEX_SECURITY_REPOSITORY_BACKUP}/src/app.ts"',
+ '"$env:CODEX_SECURITY_PLUGIN_ROOT/skills/security-scan/SKILL.md"',
+ '"prefix$env:CODEX_SECURITY_REPOSITORY/src/app.ts"',
+ '"$env:CODEX_SECURITY_REPOSITORY/../credentials.json"',
+ '"${env:CODEX_SECURITY_REPOSITORY}\\src\\..\\..\\credentials.json"',
+ ]) {
+ expect(
+ scanActivityFromEvent(
+ commandEvent("item.started", `Get-Content -LiteralPath ${argument}`),
+ "C:\\code\\project",
+ ),
+ ).toMatchObject({ paths: [] });
+ }
+ });
+
+ test("keeps POSIX environment names case-sensitive", () => {
+ expect(
+ scanActivityFromEvent(
+ commandEvent(
+ "item.started",
+ 'cat "$codex_security_repository/src/app.ts" "${Codex_Security_Repository}/src/app.ts"',
+ ),
+ "/code/project",
+ ),
+ ).toMatchObject({ paths: [] });
+ });
+
test("cleans escaped quotes from real wrapped scan commands", () => {
expect(
scanActivityFromEvent(