OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(imports)!: require opt-in for external import workflows (#1863)
Michael D'Angelob2c818907a41
diff --git a/compose.runner.yaml b/compose.runner.yamlindex a22eed985..ed0ec4afc 100644--- a/compose.runner.yaml+++ b/compose.runner.yaml@@ -11,6 +11,7 @@ services:environment:CODEX_API_KEY:CODEX_SECURITY_EMBEDDINGS_URL:+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:CODEX_SECURITY_GIT_HOST:GH_TOKEN:GITHUB_TOKEN:diff --git a/compose.yaml b/compose.yamlindex 08c843e5f..f6445d6b7 100644--- a/compose.yaml+++ b/compose.yaml@@ -13,6 +13,7 @@ services:environment:CODEX_API_KEY:CODEX_SECURITY_EMBEDDINGS_URL:+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:CODEX_SECURITY_GIT_HOST:GH_TOKEN:GITHUB_TOKEN:diff --git a/docker/verify-container-compose.sh b/docker/verify-container-compose.shindex b188addfa..5a3679d06 100644--- a/docker/verify-container-compose.sh+++ b/docker/verify-container-compose.sh@@ -5,20 +5,20 @@ set -euo pipefail# Resolve the environment on the host; these checks need no running container.for compose_file in compose.yaml compose.runner.yaml; doendpoint="https://embeddings.example.com/custom/v1/embeddings?api-version=synthetic"- CODEX_SECURITY_EMBEDDINGS_URL="$endpoint" \+ CODEX_SECURITY_EMBEDDINGS_URL="$endpoint" CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1 \docker compose --env-file /dev/null -f "$compose_file" config --format json |jq --exit-status --arg endpoint "$endpoint" \- '.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == $endpoint' > /dev/null+ '.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == $endpoint and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == "1"' > /dev/null- env -u CODEX_SECURITY_EMBEDDINGS_URL \+ env -u CODEX_SECURITY_EMBEDDINGS_URL -u CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS \docker compose --env-file /dev/null -f "$compose_file" config --format json |jq --exit-status \- '.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == null' > /dev/null+ '.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == null and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == null' > /dev/null- CODEX_SECURITY_EMBEDDINGS_URL="" \+ CODEX_SECURITY_EMBEDDINGS_URL="" CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS="" \docker compose --env-file /dev/null -f "$compose_file" config --format json |jq --exit-status \- '.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == ""' > /dev/null+ '.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == "" and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == ""' > /dev/nulldonemkdir -p results statediff --git a/docs/scanner-imports/endor.md b/docs/scanner-imports/endor.mdindex 233efb7cb..5e3c10480 100644--- a/docs/scanner-imports/endor.md+++ b/docs/scanner-imports/endor.md@@ -1,5 +1,8 @@# Import Endor Labs findings+Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.+See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally).+Use authenticated `endorctl` to export complete native Finding JSON through the[official CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api).Scope the export to one project and context, omit `--field-mask`, and usediff --git a/docs/scanner-imports/semgrep.md b/docs/scanner-imports/semgrep.mdindex 8f98ae958..ae71b7376 100644--- a/docs/scanner-imports/semgrep.md+++ b/docs/scanner-imports/semgrep.md@@ -1,5 +1,8 @@# Import Semgrep Code findings+Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.+See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally).+Prefer native **Semgrep Code/SAST CLI or CI JSON** for this reader. It preservesthe scanner's original severity and source evidence. Self-contained SARIF 2.1.0is a compatibility path. Both formats may be plain or gzip-compressed.diff --git a/docs/scanner-imports/snyk.md b/docs/scanner-imports/snyk.mdindex f6c732c07..7b113a354 100644--- a/docs/scanner-imports/snyk.md+++ b/docs/scanner-imports/snyk.md@@ -1,5 +1,8 @@# Snyk Open Source imports+Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.+See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally).+Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)to collect a fresh workspace scan. The existing[`publish findings` command](../../sdk/typescript/docs/cli.md#import-snyk-open-source-findings)diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.jsonindex b732d5b28..6cabc05a0 100644--- a/plugins/codex-security/.mcp.json+++ b/plugins/codex-security/.mcp.json@@ -38,6 +38,7 @@"PYTHONUTF8","CODEX_SECURITY_PYTHON_COMMAND","CODEX_SECURITY_GIT",+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS","CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",diff --git a/plugins/codex-security/mcp-app/helpers-main.ts b/plugins/codex-security/mcp-app/helpers-main.tsindex db1b24405..b412c3633 100644--- a/plugins/codex-security/mcp-app/helpers-main.ts+++ b/plugins/codex-security/mcp-app/helpers-main.ts@@ -66,10 +66,14 @@ function runHelper(): void {"Usage: store-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload.entries containing finding and embedding records; payload.repositoryId is optional.","list-stored-findings":"Usage: list-stored-findings\nReads a JSON object from stdin with an absolute stateDirectory, positive payload.limit and non-negative payload.offset.",- "store-external-findings":- "Usage: store-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload containing repository, provider, sourceKey and findings with source_finding_id and evidence.",- "list-external-findings":- "Usage: list-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository; payload.id optionally selects one external finding.",+ ...(process.env.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS === "1"+ ? {+ "store-external-findings":+ "Usage: store-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload containing repository, provider, sourceKey and findings with source_finding_id and evidence.",+ "list-external-findings":+ "Usage: list-external-findings\nReads a JSON object from stdin with an absolute stateDirectory and payload.repository; payload.id optionally selects one external finding.",+ }+ : {}),"find-potential-duplicates":"Usage: find-potential-duplicates\nReads a JSON object from stdin with an absolute stateDirectory, payload.findingId and payload.scope containing either repositoryId or allRepositories: true.","store-dedupe-groups":diff --git a/plugins/codex-security/mcp-app/src/workbench/commands.ts b/plugins/codex-security/mcp-app/src/workbench/commands.tsindex 8d610db3b..c91b9704f 100644--- a/plugins/codex-security/mcp-app/src/workbench/commands.ts+++ b/plugins/codex-security/mcp-app/src/workbench/commands.ts@@ -27,6 +27,14 @@ export async function workbenchCommand(input: string,scanId?: string,): Promise<unknown> {+ if (+ (command === "store-external-findings" ||+ command === "list-external-findings") &&+ process.env.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS !== "1"+ )+ throw new Error(+ "External findings imports are disabled. Set CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1 to enable them.",+ );const request = parseJson(input) as {stateDirectory: string;payload: unknown;diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.tsindex f439485e9..c8d324a34 100644--- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts+++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts@@ -65,7 +65,7 @@ const profileIndex = process.argv.indexOf('--profile');const profileContents = profileIndex === -1 ? undefined : readFileSync(join(process.env.CODEX_HOME, process.argv[profileIndex + 1] + '.config.toml'), 'utf8');const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;-const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));+const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));const toolProbe = stdin.includes('CAPTURE_SYNTHETIC_RG') ? spawnSync('rg', ['--version'], { encoding: 'utf8' }) : undefined;if (toolProbe && toolProbe.status !== 0) throw toolProbe.error ?? new Error(toolProbe.stderr);const pythonProbe = stdin.includes('CAPTURE_SYNTHETIC_PYTHON') ? spawnSync(process.env.PYTHON, ['-I', '-c', 'import json,os,sys; print(json.dumps([sys.prefix,os.environ.get("LD_LIBRARY_PATH")]))'], { encoding: 'utf8' }) : undefined;@@ -148,8 +148,51 @@ export function workerGitEnvironment(root: string) {};}+export function workerRuntimeEnvironment(root: string, virtualenv?: string) {+ return {+ PATH: [+ virtualenv === undefined+ ? path.join(root, "runner-tools")+ : path.join(virtualenv, "bin"),+ path.dirname(process.execPath),+ ].join(path.delimiter),+ HOME: path.join(root, "home"),+ PYTHON:+ virtualenv === undefined+ ? path.join(root, "tools", "python3")+ : "python3",+ PYTHONUTF8: "1",+ LD_LIBRARY_PATH:+ (process.env.LD_LIBRARY_PATH === undefined+ ? ""+ : process.env.LD_LIBRARY_PATH + path.delimiter) ++ path.join(root, "libraries"),+ DYLD_LIBRARY_PATH: path.join(root, "dylibs"),+ DYLD_FALLBACK_LIBRARY_PATH: path.join(root, "fallback-libraries"),+ CODEX_SECURITY_STATE_DIR: path.join(root, "state"),+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+ RUNNER_TRACKING_ID: "synthetic-worker-job",+ };+}++export const externalImports: {+ inherited: string | undefined;+ override?: string;+}[] = [+ { inherited: undefined },+ { inherited: "1" },+ { inherited: "0" },+ { inherited: "0", override: "1" },+ { inherited: "1", override: "0" },+ { inherited: "" },+];+export function workerScanEnvironment(root: string, index: number) {+ const { override } = externalImports[index];return {+ ...(override === undefined+ ? {}+ : { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: override }),HOME: path.join(root, `scan home ${index}`),PATH: path.join(root, `scan tools ${index}`),NODE_OPTIONS: `--stack-trace-limit=${20 + index}`,diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex de39b3e53..e8482a8b6 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1,7 +1,9 @@import { testArtifactStartupTimeoutClassification } from "./deep_scan_startup_cases.ts";import {workerGitEnvironment,+ workerRuntimeEnvironment,workerScanEnvironment,+ externalImports,expectedGitEnvironment,restoreEnv,} from "./support/fake-codex-source.ts";@@ -1196,29 +1198,10 @@ async function testOpenAiCredentialsReachWorker() {true,entry.accountResult ?? noAccount,);- const runtimeEnvironment = {- PATH: [- virtualenv === undefined- ? path.join(fixture.root, "runner-tools")- : path.join(virtualenv, "bin"),- path.dirname(process.execPath),- ].join(path.delimiter),- HOME: path.join(fixture.root, "home"),- PYTHON:- virtualenv === undefined- ? path.join(fixture.root, "tools", "python3")- : "python3",- PYTHONUTF8: "1",- LD_LIBRARY_PATH:- (process.env.LD_LIBRARY_PATH === undefined- ? ""- : process.env.LD_LIBRARY_PATH + path.delimiter) +- path.join(fixture.root, "libraries"),- DYLD_LIBRARY_PATH: path.join(fixture.root, "dylibs"),- DYLD_FALLBACK_LIBRARY_PATH: path.join(fixture.root, "fallback-libraries"),- CODEX_SECURITY_STATE_DIR: path.join(fixture.root, "state"),- RUNNER_TRACKING_ID: "synthetic-worker-job",- };+ const runtimeEnvironment = workerRuntimeEnvironment(+ fixture.root,+ virtualenv,+ );const previousEnvironment = ["OPENAI_API_KEY","CODEX_API_KEY",@@ -1463,6 +1446,7 @@ async function testWorkerRuntimeSettings() {"CODEX_SECURITY_PLUGIN_ROOT","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH","CODEX_SECURITY_KNOWLEDGE_BASE",+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS","OPENAI_API_KEY","CODEX_API_KEY","SYNTHETIC_GATEWAY_KEY",@@ -1980,6 +1964,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,await Promise.all(executors.map((executor, index) => {// Snapshot each scan environment independently.+ restoreEnv(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS",+ externalImports[index].inherited,+ );process.env.CODEX_MCP_NODE_PATH = nodePaths[index];Object.assign(process.env, temporaryEnvironments[index]);process.env.CODEX_SECURITY_STATE_DIR = path.join(@@ -2101,6 +2089,16 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].knowledgePath,);const invocation = await readJson(workerLaunch.markerPath);+ assert.equal(+ invocation.runtimeEnvironment+ .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS,+ externalImports[index].override ??+ externalImports[index].inherited,+ );+ assert.equal(+ process.env.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS,+ externalImports.at(-1)!.inherited,+ );if (process.platform === "win32" &&configuration === "" &&diff --git a/plugins/codex-security/mcp-app/tests/test_external_imports_gate.ts b/plugins/codex-security/mcp-app/tests/test_external_imports_gate.tsnew file mode 100644index 000000000..738c7cf8d--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_external_imports_gate.ts@@ -0,0 +1,149 @@+import assert from "node:assert/strict";+import { execFile, spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { after, test } from "node:test";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";+import { importSource } from "./import-module.ts";+import { createTemporaryDirectories } from "./support/temporary-directories.ts";++const { workbenchCommand } = (await importSource(+ "src/workbench/commands.ts",+)) as typeof import("../src/workbench/commands.ts");+const temporary = createTemporaryDirectories(true);+after(() => temporary.cleanup());+const flag = "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS";+const commands = ["store-external-findings", "list-external-findings"];+const helper = fileURLToPath(+ new URL(+ "../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs",+ import.meta.url,+ ),+);++function helperEnvironment(value?: string): NodeJS.ProcessEnv {+ const environment = Object.fromEntries(+ Object.entries(process.env).filter(([name]) => name.toUpperCase() !== flag),+ );+ if (value !== undefined) environment[flag] = value;+ return environment;+}++test("direct external commands require opt-in before parsing input or creating state", async (t) => {+ const previous = process.env[flag];+ t.after(() => {+ if (previous === undefined) delete process.env[flag];+ else process.env[flag] = previous;+ });+ const stateDirectory = join(+ await temporary.create("external-gate-direct-"),+ "state",+ );+ const input = JSON.stringify({ stateDirectory, payload: {} });+ for (const value of [undefined, "0", "true"]) {+ if (value === undefined) delete process.env[flag];+ else process.env[flag] = value;+ for (const command of commands) {+ await assert.rejects(+ workbenchCommand(command, input),+ /CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1/,+ );+ await assert.rejects(+ workbenchCommand(command, "not JSON"),+ /CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1/,+ );+ }+ assert.equal(existsSync(stateDirectory), false);+ }+});++test("disabled bundled helpers omit external commands and do not create state", async () => {+ const stateDirectory = join(+ await temporary.create("external-gate-disabled-"),+ "state",+ );+ for (const value of [undefined, "0", "true"]) {+ for (const command of commands) {+ const result = spawnSync(process.execPath, [helper, command], {+ env: helperEnvironment(value),+ input: JSON.stringify({ stateDirectory, payload: {} }),+ encoding: "utf8",+ });+ assert.equal(result.status, 2, result.stderr);+ assert.equal(result.stdout, "");+ assert.ok(result.stderr.includes("store-findings"));+ for (const hidden of commands)+ assert.equal(result.stderr.includes(hidden), false);+ }+ assert.equal(existsSync(stateDirectory), false);+ }+ const { stdout } = await promisify(execFile)(+ process.execPath,+ [helper, "store-findings", "--help"],+ { env: helperEnvironment(), timeout: 30_000 },+ );+ assert.ok(stdout.startsWith("Usage: store-findings"));+});++test("opted-in bundled helpers expose help, store and read external evidence", async () => {+ const root = await temporary.create("external-gate-enabled-");+ const stateDirectory = join(root, "state");+ const repository = join(root, "synthetic-repository");+ const payload = {+ repository,+ provider: "synthetic-scanner",+ sourceKey: "synthetic-project",+ findings: [+ {+ source_finding_id: "finding-one",+ evidence: { title: "Synthetic finding" },+ },+ ],+ };+ for (const command of commands) {+ // Open stdin must not delay an enabled help request.+ const { stdout } = await promisify(execFile)(+ process.execPath,+ [helper, command, "--help"],+ { env: helperEnvironment("1"), timeout: 30_000 },+ );+ assert.ok(stdout.startsWith(`Usage: ${command}`));+ }+ for (const command of commands) {+ const result = spawnSync(process.execPath, [helper, command], {+ env: helperEnvironment("1"),+ input: JSON.stringify({ stateDirectory, payload }),+ encoding: "utf8",+ });+ assert.equal(result.status, 0, result.stderr);+ const stored = JSON.parse(result.stdout);+ assert.equal(stored.findings.length, 1);+ assert.deepEqual(stored.findings[0].evidence, payload.findings[0].evidence);+ assert.equal(stored.findings[0].assessment.state, "not_assessed");+ }+ const disabled = spawnSync(+ process.execPath,+ [helper, "list-external-findings"],+ {+ env: helperEnvironment(),+ input: JSON.stringify({ stateDirectory, payload: { repository } }),+ encoding: "utf8",+ },+ );+ assert.equal(disabled.status, 2, disabled.stderr);+ const database = new DatabaseSync(join(stateDirectory, "workbench.sqlite3"), {+ readOnly: true,+ });+ try {+ assert.equal(+ database+ .prepare("SELECT COUNT(*) AS total FROM external_source_reports")+ .get()!.total,+ 1,+ );+ } finally {+ database.close();+ }+});diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.tsindex ca3e596fd..b8b514bcb 100644--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts@@ -87,6 +87,7 @@ assert.deepEqual("PYTHONUTF8","CODEX_SECURITY_PYTHON_COMMAND","CODEX_SECURITY_GIT",+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS","CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.mdindex 2a939ec63..12b476a4d 100644--- a/plugins/codex-security/skills/publish-findings/SKILL.md+++ b/plugins/codex-security/skills/publish-findings/SKILL.md@@ -1,10 +1,12 @@---name: publish-findings-description: Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs findings, GitHub code-scanning alerts or GHSA advisories, or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles, Snyk Open Source and Semgrep Code SARIF, endorctl SARIF, saved GitHub JSON/JSONL, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.+description: Disabled by default; requires user opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs findings, GitHub code-scanning alerts or GHSA advisories, or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles, Snyk Open Source and Semgrep Code SARIF, endorctl SARIF, saved GitHub JSON/JSONL, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.---# Publish external findings+Before acquiring or importing findings, check for `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` in the command environment. If it is unset or has another value, stop and ask the user to enable imports.+Use the installed `codex-security publish findings` command for preview and import. Select `--to local` for the local workbench or `--to cloud` for Cloud. The command owns source mapping, persistence, and Cloud authentication and retries. Do not implement another store or uploader or put credentials in command arguments.## Select the evidencediff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex d86b2159b..a0d6b59aa 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -644,6 +644,14 @@ grant Cloud access. See [Cloud publication](docs/cli.md#publish-findings-to-cloufor setup and review steps, or [Linear publication](docs/cli.md#publish-completed-scans-to-linear)for issue creation.+External vendor imports are opt-in. Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`+to enable `publish findings`, `findings imported`, `import github-advisories`, and+the SDK's external publication, local import/readback, and advisory acquisition+APIs. They are disabled otherwise; CLI commands are hidden from help and schemas.+SDK callers can supply the flag through the existing per-call+`dependencies.environment`. Pure normalizers and file readers remain available.+This does not affect scan publishing or the existing GitHub alert collector.+The SDK also exposes `prepareExternalPublication(file, options)` for supportedvendor exports and `prepareNormalizedExternalPublication(findings, options)` fornormalized external evidence from any provider in the Cloud import contract.diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex d8d480380..5bf692c18 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -939,26 +939,27 @@ For filesystem and approval behavior, see the### Environment variables-| Variable | Effect |-| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |-| `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan credentials; the first takes precedence. |-| `CODEX_SECURITY_STATE_DIR` | Private history, database, and default artifacts. |-| `CODEX_SECURITY_PROJECT_CONFIG` | Selected project file; `-c` overrides it. |-| `CODEX_HOME` | Ambient Codex home; default `~/.codex`. |-| `CODEX_CLI_PATH` | Codex executable for login, setup, scans, and workers. |-| `PYTHON` | Python interpreter unless an explicit option overrides it. |-| `CODEX_SECURITY_LOG_LEVEL` | CLI diagnostics; `debug` enables verbose output. |-| `LOG_LEVEL` | Fallback if `CODEX_SECURITY_LOG_LEVEL` is unset or blank. |-| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default publication destination. |-| `CODEX_SECURITY_LINEAR_API_KEY` | Linear personal API key. |-| `CODEX_SECURITY_CLOUD_BASE_URL` | Cloud API root for discovery, imports, and scan publication. Defaults to `https://chatgpt.com/backend-api/aardvark`. |-| `CODEX_SECURITY_CLOUD_WEB_URL` | Cloud app URL for repository links when an alternate deployment serves its UI separately. |-| `CODEX_SECURITY_EMBEDDINGS_URL` | Local dedupe and findings service embeddings endpoint. |-| `GH_HOST` | GitHub Enterprise host for bulk discovery. |-| `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Disable interactive update notices. |-| `CODEX_SECURITY_NPM_REGISTRY`, `npm_config_registry`, `NPM_CONFIG_REGISTRY` | Update registry, in precedence order. |-| `CI` | Disable interactive update notices. |-| `NO_COLOR`, `TERM` | Disable colored history when `NO_COLOR` is defined or `TERM=dumb`. |+| Variable | Effect |+| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |+| `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan credentials; the first takes precedence. |+| `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS` | Set to `1` to enable vendor finding imports, imported-findings readback, and GitHub advisory acquisition; disabled otherwise. |+| `CODEX_SECURITY_STATE_DIR` | Private history, database, and default artifacts. |+| `CODEX_SECURITY_PROJECT_CONFIG` | Selected project file; `-c` overrides it. |+| `CODEX_HOME` | Ambient Codex home; default `~/.codex`. |+| `CODEX_CLI_PATH` | Codex executable for login, setup, scans, and workers. |+| `PYTHON` | Python interpreter unless an explicit option overrides it. |+| `CODEX_SECURITY_LOG_LEVEL` | CLI diagnostics; `debug` enables verbose output. |+| `LOG_LEVEL` | Fallback if `CODEX_SECURITY_LOG_LEVEL` is unset or blank. |+| `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default publication destination. |+| `CODEX_SECURITY_LINEAR_API_KEY` | Linear personal API key. |+| `CODEX_SECURITY_CLOUD_BASE_URL` | Cloud API root for discovery, imports, and scan publication. Defaults to `https://chatgpt.com/backend-api/aardvark`. |+| `CODEX_SECURITY_CLOUD_WEB_URL` | Cloud app URL for repository links when an alternate deployment serves its UI separately. |+| `CODEX_SECURITY_EMBEDDINGS_URL` | Local dedupe and findings service embeddings endpoint. |+| `GH_HOST` | GitHub Enterprise host for bulk discovery. |+| `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Disable interactive update notices. |+| `CODEX_SECURITY_NPM_REGISTRY`, `npm_config_registry`, `NPM_CONFIG_REGISTRY` | Update registry, in precedence order. |+| `CI` | Disable interactive update notices. |+| `NO_COLOR`, `TERM` | Disable colored history when `NO_COLOR` is defined or `TERM=dumb`. |Custom Codex executables need thread source attribution for `exec` and`app-server` (Codex 0.149.1+). On Windows, use a native `.exe` or `.com`;@@ -1267,6 +1268,24 @@ Supply the validation prompt again when rerunning.## Import vendor findings locally+External finding imports are disabled by default. Opt in for the current shell:++```bash+export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1+```++In PowerShell, use `$env:CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS = '1'`.+Only `1` enables the feature. Without it, `publish findings`, `findings imported`,+and `import github-advisories` are absent from command help and schemas and cannot+run. The SDK's external publication, local import/readback, and advisory+acquisition APIs require the same flag in their effective environment. An explicit+`dependencies.environment` is used instead of the process environment. Pure+normalizers and file readers remain available as library utilities.++This flag does not affect `publish scan`, `publish check`, `scan import`, or the+existing `import github` alert collector. Disabling it retains previously imported+records; enable it again to read them with `findings imported`.+Prefer the provider's supported native JSON from its CLI, plugin, or API. Nativereports can retain details omitted by SARIF. Use SARIF or CSV as compatibilityinputs only for providers and report profiles that support them. A JSON API@@ -2366,6 +2385,9 @@ installation fails. The installer respects `core.hooksPath`.## Import GitHub findings locally or to Cloud+Local and Cloud ingestion require the [external-import opt-in](#import-vendor-findings-locally).+The existing alert collector remains available without it.+Acquire code-scanning findings with the existing `import github` collector andsave its complete JSON output. In Codex, the official[GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github)@@ -2457,6 +2479,8 @@ import file directly. Read records with `listLocalExternalFindings({ repository### Import GHSA advisories separately+Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` before using this command or its SDK API.+**Importing a GHSA advisory does not establish an installed dependency orapplicability to the destination repository.** Repository advisories aredisclosures maintained by a repository; global advisories describe affecteddiff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex 53deeee0b..02a7682e3 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -33,6 +33,7 @@ const distModules = ["external-findings-publish","external-import-contract","external-import-models",+ "external-imports-feature","endor-findings","wiz-csv","wiz-findings",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 1a983ee7e..da617c055 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -156,6 +156,7 @@ import {ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";+import { forwardExternalImportSetting } from "./external-imports-feature.js";import {knowledgeBaseProtectedRoots,prepareKnowledgeBase,@@ -6258,11 +6259,13 @@ function standaloneFindingForPrompt(finding: string | object): string {function definedEnvironment(environment: ProcessEnvironment,): Record<string, string> {- return Object.fromEntries(+ const child = Object.fromEntries(Object.entries(environment).filter((entry): entry is [string, string] => entry[1] !== undefined,),);+ forwardExternalImportSetting(environment, child);+ return child;}function withoutCodexHome(diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.tsindex a1439c1c3..b53100933 100644--- a/sdk/typescript/src/auth.ts+++ b/sdk/typescript/src/auth.ts@@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";import { homedir } from "node:os";import { join, resolve } from "node:path";import { parse } from "smol-toml";+import { forwardExternalImportSetting } from "./external-imports-feature.js";import type { JsonObject } from "./config.js";import {CodexSecurityError,@@ -37,12 +38,14 @@ export function environmentEntry(export function withoutOpenAiApiKeys<Value>(environment: Record<string, Value>,): Record<string, Value> {- return Object.fromEntries(+ const child = Object.fromEntries(Object.entries(environment).filter(([name]) =>!["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),),);+ forwardExternalImportSetting(environment, child);+ return child;}/** @internal */diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 6d74e42f9..dcc891b30 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -114,6 +114,10 @@ import {type ExternalPublicationResult,} from "./external-findings-publish.js";import { prepareLocalExternalImport } from "./external-findings-import.js";+import {+ externalImportsDisabledMessage,+ externalImportsEnabled,+} from "./external-imports-feature.js";import { listLocalExternalFindings } from "./external-findings-local.js";import { EXTERNAL_FINDINGS_READERS } from "./external-findings-read.js";import type { ExternalFindings } from "./external-findings.js";@@ -378,6 +382,19 @@ const execFile = promisify(execFileCallback);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 FRAMEWORK_ACTIONS = new Set([+ "--llms",+ "--llms-full",+ "--mcp",+ "--update",+ "--incur-update-check",+]);+const FRAMEWORK_VALUE_OPTIONS = new Set([+ "--format",+ "--filter-output",+ "--token-limit",+ "--token-offset",+]);const OUTPUT_OPTION =/^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;const HIDE_CURSOR = "\u001B[?25l";@@ -1902,6 +1919,7 @@ export async function main(errorOutput: Writable = process.stderr,dependencies: CliDependencies = DEFAULT_DEPENDENCIES,): Promise<number> {+ const importsEnabled = externalImportsEnabled(dependencies.environment);const remediationOperation =argv[0] === "patch"? "patch"@@ -2326,53 +2344,60 @@ export async function main();},});- findingFeedback.command("imported", {- description: "List imported vendor evidence for a local repository.",- mcp: false,- args: z.object({- repository: z- .string()- .optional()- .describe("Local repository to inspect (default: current directory)."),- }),- output: z.record(z.string(), z.unknown()).optional(),- async run({ args, format, error: incurError }) {- const controller = new AbortController();- const removeSignals = listenForAbort(dependencies, controller);- try {- const repository = resolveCliPath(- dependencies.currentDirectory(),- args.repository ?? ".",- );- const findings = await (- dependencies.listLocalExternalFindings ?? listLocalExternalFindings- )(- { repository },- { environment: dependencies.environment, signal: controller.signal },- );- return { repository, findings };- } catch (error) {- if (controller.signal.aborted) {- exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;- if (- argv.includes("--full-output") &&- (format === "json" || format === "jsonl")- ) {- structuredError = true;- return incurError({- code: "FINDINGS_READ_FAILED",- message: diagnosticValue(error),- exitCode,- });+ if (importsEnabled) {+ findingFeedback.command("imported", {+ description: "List imported vendor evidence for a local repository.",+ mcp: false,+ args: z.object({+ repository: z+ .string()+ .optional()+ .describe(+ "Local repository to inspect (default: current directory).",+ ),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, format, error: incurError }) {+ const controller = new AbortController();+ const removeSignals = listenForAbort(dependencies, controller);+ try {+ const repository = resolveCliPath(+ dependencies.currentDirectory(),+ args.repository ?? ".",+ );+ const findings = await (+ dependencies.listLocalExternalFindings ?? listLocalExternalFindings+ )(+ { repository },+ {+ environment: dependencies.environment,+ signal: controller.signal,+ },+ );+ return { repository, findings };+ } catch (error) {+ if (controller.signal.aborted) {+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;+ if (+ argv.includes("--full-output") &&+ (format === "json" || format === "jsonl")+ ) {+ structuredError = true;+ return incurError({+ code: "FINDINGS_READ_FAILED",+ message: diagnosticValue(error),+ exitCode,+ });+ }+ return;}- return;+ throw error;+ } finally {+ removeSignals();}- throw error;- } finally {- removeSignals();- }- },- });+ },+ });+ }const scanHistory = Cli.create("scans", {description: "Review saved scans (default: list).",})@@ -3515,268 +3540,270 @@ export async function main(});},});- publication.command("findings", {- description:- "Preview and import selected Wiz, Snyk, Semgrep Code, Endor, or GitHub findings locally or to Cloud.",- hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",- destructive: true,- mcp: false,- args: z.object({- file: z- .string()- .describe(- "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",- ),- }),- options: z.object({- to: z.enum(["cloud", "local"]).describe("Import destination (required)."),- repository: optionValue("--repository").describe(- "Local repository path for --to local; authorized repository ID or URL for --to cloud.",- ),- provider: z- .enum(EXTERNAL_FINDINGS_READERS)- .describe("Provider that produced these findings."),- sourceRepositoryUrl: optionValue("--source-repository-url")- .optional()- .describe(- "Required for Semgrep: source repository URL, checked against the Cloud destination or configured local Git remotes.",- ),- sourceKey: optionValue("--source-key").describe(- "Stable vendor tenant and finding namespace; not a project selection filter.",- ),- dryRun: z- .boolean()- .default(false)- .describe(- "Read and preview the destination and findings without storing them.",+ let disabledImportInvocation = false;+ function registerFindingPublication() {+ publication.command("findings", {+ description:+ "Preview and import selected Wiz, Snyk, Semgrep Code, Endor, or GitHub findings locally or to Cloud.",+ hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",+ destructive: true,+ mcp: false,+ args: z.object({+ file: z+ .string()+ .describe(+ "Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV.",+ ),+ }),+ options: z.object({+ to: z+ .enum(["cloud", "local"])+ .describe("Import destination (required)."),+ repository: optionValue("--repository").describe(+ "Local repository path for --to local; authorized repository ID or URL for --to cloud.",),- yes: z- .boolean()- .default(false)- .describe(- "Confirm publication of the previewed input without a terminal prompt.",+ provider: z+ .enum(EXTERNAL_FINDINGS_READERS)+ .describe("Provider that produced these findings."),+ sourceRepositoryUrl: optionValue("--source-repository-url")+ .optional()+ .describe(+ "Required for Semgrep: source repository URL, checked against the Cloud destination or configured local Git remotes.",+ ),+ sourceKey: optionValue("--source-key").describe(+ "Stable vendor tenant and finding namespace; not a project selection filter.",),- }),- output: z.record(z.string(), z.unknown()).optional(),- async run({ args, options, format, formatExplicit, error: incurError }) {- return await withTerminalErrorsHandled(errorOutput, async () => {- const writeDiagnostic = (message: string): void =>- notify(() => errorOutput.write(message));- if (- argv.includes("--full-output") &&- format !== "json" &&- format !== "jsonl"- ) {- structuredError = true;- exitCode = 2;- return incurError({- code: "INVALID_ARGUMENTS",- message:- "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",- exitCode,- });- }- const controller = new AbortController();- const removeSignals = listenForAbort(dependencies, controller);- const structured = formatExplicit && format !== "toon";- const humanSummary =- format === "toon" &&- !formatExplicit &&- !argv.some((argument) => OUTPUT_OPTION.test(argument));- const confirmImport = async (- preview: ExternalFindings,- showPreview: () => void,- ): Promise<boolean> => {- if (options.yes) return true;- const prompt =- dependencies.externalPublicationPrompt ??- createTerminalPrompt(errorOutput);- const local = options.to === "local";- if (!prompt.isInteractive())- throw new CodexSecurityError(- `${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`,+ dryRun: z+ .boolean()+ .default(false)+ .describe(+ "Read and preview the destination and findings without storing them.",+ ),+ yes: z+ .boolean()+ .default(false)+ .describe(+ "Confirm publication of the previewed input without a terminal prompt.",+ ),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, options, format, formatExplicit, error: incurError }) {+ return await withTerminalErrorsHandled(errorOutput, async () => {+ const writeDiagnostic = (message: string): void =>+ notify(() => errorOutput.write(message));+ const machineFormat = format === "json" || format === "jsonl";+ if (argv.includes("--full-output") && !machineFormat) {+ structuredError = true;+ exitCode = 2;+ return incurError({+ code: "INVALID_ARGUMENTS",+ message:+ "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",+ exitCode,+ });+ }+ const controller = new AbortController();+ const removeSignals = listenForAbort(dependencies, controller);+ const structured = formatExplicit && format !== "toon";+ const humanSummary =+ format === "toon" &&+ !formatExplicit &&+ !argv.some((argument) => OUTPUT_OPTION.test(argument));+ const confirmImport = async (+ preview: ExternalFindings,+ showPreview: () => void,+ ): Promise<boolean> => {+ if (options.yes) return true;+ const prompt =+ dependencies.externalPublicationPrompt ??+ createTerminalPrompt(errorOutput);+ const local = options.to === "local";+ if (!prompt.isInteractive())+ throw new CodexSecurityError(+ `${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`,+ );+ if (structured) showPreview();+ const action = local+ ? `Store these ${preview.findings.length} findings locally`+ : `Publish these ${preview.findings.length} findings`;+ return prompt.confirm(+ `${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`,+ false,+ controller.signal,);- if (structured) showPreview();- const action = local- ? `Store these ${preview.findings.length} findings locally`- : `Publish these ${preview.findings.length} findings`;- return prompt.confirm(- `${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`,- false,- controller.signal,- );- };- let lastProgress = "";- const onProgress = (event: ExternalPublicationProgress) => {- if (errorOutput.isTTY !== true) return;- const step = event.total- ? Math.floor((event.completed * 10) / event.total)- : 0;- const key = `${event.phase}:${step}`;- if (key === lastProgress) return;- lastProgress = key;- const labels = {- reading: "Reading selected findings",- discovering: "Checking Cloud account and repository",- preparing: "Preparing findings",- waiting: "Waiting for publication access",- uploading: "Acknowledged findings",- verifying: "Verifying source records",};- writeDiagnostic(- `${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`,- );- };- try {- if (options.to === "local") {- const prepared = await (- dependencies.prepareLocalExternalImport ??- prepareLocalExternalImport- )(+ let lastProgress = "";+ const onProgress = (event: ExternalPublicationProgress) => {+ if (errorOutput.isTTY !== true) return;+ const step = event.total+ ? Math.floor((event.completed * 10) / event.total)+ : 0;+ const key = `${event.phase}:${step}`;+ if (key === lastProgress) return;+ lastProgress = key;+ const labels = {+ reading: "Reading selected findings",+ discovering: "Checking Cloud account and repository",+ preparing: "Preparing findings",+ waiting: "Waiting for publication access",+ uploading: "Acknowledged findings",+ verifying: "Verifying source records",+ };+ writeDiagnostic(+ `${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`,+ );+ };+ try {+ if (!importsEnabled)+ throw new CodexSecurityError(externalImportsDisabledMessage);+ if (options.to === "local") {+ const prepared = await (+ dependencies.prepareLocalExternalImport ??+ prepareLocalExternalImport+ )(+ resolveCliPath(dependencies.currentDirectory(), args.file),+ {+ ...options,+ repository: resolveCliPath(+ dependencies.currentDirectory(),+ options.repository,+ ),+ },+ {+ environment: dependencies.environment,+ signal: controller.signal,+ },+ );+ const { preview } = prepared;+ const showPreview = () => {+ writeDiagnostic(+ `Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`,+ );+ for (const excluded of preview.excluded)+ writeDiagnostic(+ `Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,+ );+ for (const finding of preview.findings.slice(0, 5))+ writeDiagnostic(+ ` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,+ );+ writeDiagnostic(+ `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`,+ );+ };+ if (!structured) showPreview();+ if (options.dryRun) {+ if (humanSummary)+ renderedOutput = "Dry run complete. No findings stored.\n";+ return { ...preview, dryRun: true };+ }+ if (!(await confirmImport(preview, showPreview))) {+ if (humanSummary) renderedOutput = "No findings stored.\n";+ return { imported: false, preview };+ }+ const result = await prepared.import();+ if (result.excluded.length > 0) exitCode = 1;+ const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;+ if (humanSummary) renderedOutput = summary;+ else if (!structured) writeDiagnostic(summary);+ return { ...result };+ }+ const prepared = await prepareExternalPublication(resolveCliPath(dependencies.currentDirectory(), args.file),- {- ...options,- repository: resolveCliPath(- dependencies.currentDirectory(),- options.repository,- ),- },+ options,{environment: dependencies.environment,+ fetch: dependencies.cloudFetch,signal: controller.signal,+ onProgress,},);const { preview } = prepared;const showPreview = () => {writeDiagnostic(- `Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`,+ `Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`,);+ if (preview.cloudUrl)+ writeDiagnostic(+ `Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`,+ );for (const excluded of preview.excluded)writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,);+ writeDiagnostic(+ `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`,+ );+ const severities = new Map<string, number>();+ for (const finding of preview.findings)+ severities.set(+ finding.evidence.severity,+ (severities.get(finding.evidence.severity) ?? 0) + 1,+ );+ writeDiagnostic(+ `Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`,+ );for (const finding of preview.findings.slice(0, 5))writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,);+ if (preview.findings.length > 5)+ writeDiagnostic(+ `Showing 5 of ${preview.findings.length} findings.\n`,+ );writeDiagnostic(- `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`,+ "Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n",);};if (!structured) showPreview();if (options.dryRun) {if (humanSummary)- renderedOutput = "Dry run complete. No findings stored.\n";+ renderedOutput = "Dry run complete. No findings uploaded.\n";return { ...preview, dryRun: true };}if (!(await confirmImport(preview, showPreview))) {- if (humanSummary) renderedOutput = "No findings stored.\n";- return { imported: false, preview };+ if (humanSummary) renderedOutput = "No findings published.\n";+ return { published: false, preview };}- const result = await prepared.import();- if (result.excluded.length > 0) exitCode = 1;- const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;- if (humanSummary) renderedOutput = summary;- else if (!structured) writeDiagnostic(summary);+ const result = await prepared.publish();+ if (result.status === "partial") exitCode = 1;+ if (humanSummary)+ renderedOutput = renderExternalPublicationSummary(result);+ else if (!structured)+ writeDiagnostic(renderExternalPublicationSummary(result));return { ...result };- }- const prepared = await prepareExternalPublication(- resolveCliPath(dependencies.currentDirectory(), args.file),- options,- {- environment: dependencies.environment,- fetch: dependencies.cloudFetch,- signal: controller.signal,- onProgress,- },- );- const { preview } = prepared;- const showPreview = () => {- writeDiagnostic(- `Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`,- );- if (preview.cloudUrl)- writeDiagnostic(- `Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`,- );- for (const excluded of preview.excluded)- writeDiagnostic(- `Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`,- );- writeDiagnostic(- `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`,- );- const severities = new Map<string, number>();- for (const finding of preview.findings)- severities.set(- finding.evidence.severity,- (severities.get(finding.evidence.severity) ?? 0) + 1,- );- writeDiagnostic(- `Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`,- );- for (const finding of preview.findings.slice(0, 5))- writeDiagnostic(- ` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,- );- if (preview.findings.length > 5)- writeDiagnostic(- `Showing 5 of ${preview.findings.length} findings.\n`,- );- writeDiagnostic(- "Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n",+ } catch (error) {+ if (argv.includes("--full-output") && machineFormat)+ failedResultOutput = {+ format,+ code: "IMPORT_FAILED",+ message: diagnosticValue(error),+ };+ reportPublicationError(+ diagnosticValue(error),+ controller.signal.aborted ? controller.signal.reason : undefined,);- };- if (!structured) showPreview();- if (options.dryRun) {- if (humanSummary)- renderedOutput = "Dry run complete. No findings uploaded.\n";- return { ...preview, dryRun: true };- }- if (!(await confirmImport(preview, showPreview))) {- if (humanSummary) renderedOutput = "No findings published.\n";- return { published: false, preview };- }- const result = await prepared.publish();- if (result.status === "partial") exitCode = 1;- if (humanSummary)- renderedOutput = renderExternalPublicationSummary(result);- else if (!structured)- writeDiagnostic(renderExternalPublicationSummary(result));- return { ...result };- } catch (error) {- if (- argv.includes("--full-output") &&- (format === "json" || format === "jsonl")- )- failedResultOutput = {- format,- code: "IMPORT_FAILED",- message: diagnosticValue(error),- };- reportPublicationError(- diagnosticValue(error),- controller.signal.aborted ? controller.signal.reason : undefined,- );- if (error instanceof ExternalPublicationError) {- if (humanSummary)- renderedOutput = renderExternalPublicationSummary(error.result);- return { ...error.result };+ if (error instanceof ExternalPublicationError) {+ if (humanSummary)+ renderedOutput = renderExternalPublicationSummary(error.result);+ return { ...error.result };+ }+ const failure = { status: "failed", error: diagnosticValue(error) };+ if (+ machineFormat &&+ !argv.includes("--full-output") &&+ argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument))+ )+ filteredScanFailure = { format, data: failure };+ return structured ? failure : undefined;+ } finally {+ removeSignals();}- const failure = { status: "failed", error: diagnosticValue(error) };- if (- (format === "json" || format === "jsonl") &&- !argv.includes("--full-output") &&- argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument))- )- filteredScanFailure = { format, data: failure };- return structured ? failure : undefined;- } finally {- removeSignals();- }- });- },- });+ });+ },+ });+ }+ if (importsEnabled) registerFindingPublication();publication.command("check", {description:"Check saved scan history and Linear access without creating issues.",@@ -3809,10 +3836,12 @@ export async function main(},});const imports = Cli.create("import", {- description: "Read GitHub code scanning alerts and security advisories.",+ description: importsEnabled+ ? "Read GitHub code scanning alerts and security advisories."+ : "Read GitHub code scanning alerts.",}).command("github", {description: "Read GitHub code scanning alerts without changing GitHub.",- hint: "Save complete --format json output for publish findings --provider github. This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.",+ hint: `${importsEnabled ? "Save complete --format json output for publish findings --provider github. " : ""}This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.`,destructive: false,mcp: false,args: z.object({@@ -3890,101 +3919,106 @@ export async function main(}},});- imports.command("github-advisories", {- description: "Read GitHub security advisories without changing GitHub.",- hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",- destructive: false,- mcp: false,- args: z.object({- repository: z- .string()- .min(1)- .describe(- "Source repository, or target context for global IDs, in OWNER/REPO form.",- ),- }),- options: z.object({- githubAdvisory: z- .array(- optionValue("--github-advisory").regex(- /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu,- "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",+ function registerGitHubAdvisories() {+ imports.command("github-advisories", {+ description: "Read GitHub security advisories without changing GitHub.",+ hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",+ destructive: false,+ mcp: false,+ args: z.object({+ repository: z+ .string()+ .min(1)+ .describe(+ "Source repository, or target context for global IDs, in OWNER/REPO form.",+ ),+ }),+ options: z.object({+ githubAdvisory: z+ .array(+ optionValue("--github-advisory").regex(+ /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu,+ "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form.",+ ),+ )+ .default([])+ .describe(+ "Exact GHSA ID; repeat to select a subset. Required for global advisories.",+ ),+ githubAdvisorySource: z+ .enum(["repository", "global"])+ .default("repository")+ .describe(+ "Advisory API to read; global requires exact IDs and never lists the database.",+ ),+ githubState: z+ .enum(GITHUB_ADVISORY_STATES)+ .default("published")+ .describe(+ "Repository advisory list state; omit when selecting exact GHSA IDs.",),+ }),+ output: z+ .array(+ z.object({+ source: z.literal("github-security-advisory"),+ selection: z.enum(["repository", "global"]),+ repository: z.string(),+ githubHost: z.string(),+ ghsaId: z.string(),+ url: z.string(),+ advisory: z.record(z.string(), z.unknown()),+ }),)- .default([])- .describe(- "Exact GHSA ID; repeat to select a subset. Required for global advisories.",- ),- githubAdvisorySource: z- .enum(["repository", "global"])- .default("repository")- .describe(- "Advisory API to read; global requires exact IDs and never lists the database.",- ),- githubState: z- .enum(GITHUB_ADVISORY_STATES)- .default("published")- .describe(- "Repository advisory list state; omit when selecting exact GHSA IDs.",- ),- }),- output: z- .array(- z.object({- source: z.literal("github-security-advisory"),- selection: z.enum(["repository", "global"]),- repository: z.string(),- githubHost: z.string(),- ghsaId: z.string(),- url: z.string(),- advisory: z.record(z.string(), z.unknown()),- }),- )- .optional(),- async run({ args, options, error: incurError }) {- const controller = new AbortController();- const removeSignals = listenForAbort(dependencies, controller);- try {- return await (- dependencies.importGitHubAdvisories ?? importGitHubAdvisories- )(- {- repository: args.repository,- advisoryIds: options.githubAdvisory,- source: options.githubAdvisorySource,- state: options.githubState,- signal: controller.signal,- },- {- environment: dependencies.environment,- currentDirectory: dependencies.currentDirectory(),- },- );- } catch (error) {- const signal = controller.signal.reason;- if (signal === "SIGINT" || signal === "SIGTERM") {- exitCode = signal === "SIGINT" ? 130 : 143;- errorOutput.write(- `codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`,+ .optional(),+ async run({ args, options, error: incurError }) {+ const controller = new AbortController();+ const removeSignals = listenForAbort(dependencies, controller);+ try {+ if (!importsEnabled)+ throw new CodexSecurityError(externalImportsDisabledMessage);+ return await (+ dependencies.importGitHubAdvisories ?? importGitHubAdvisories+ )(+ {+ repository: args.repository,+ advisoryIds: options.githubAdvisory,+ source: options.githubAdvisorySource,+ state: options.githubState,+ signal: controller.signal,+ },+ {+ environment: dependencies.environment,+ currentDirectory: dependencies.currentDirectory(),+ },);- } else {- exitCode = 2;- errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);- }- if (argv.includes("--full-output")) {- structuredError = true;- return incurError({- code: "GITHUB_IMPORT_FAILED",- message: diagnosticValue(error),- exitCode,- });+ } catch (error) {+ const signal = controller.signal.reason;+ if (signal === "SIGINT" || signal === "SIGTERM") {+ exitCode = signal === "SIGINT" ? 130 : 143;+ errorOutput.write(+ `codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`,+ );+ } else {+ exitCode = 2;+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);+ }+ if (argv.includes("--full-output")) {+ structuredError = true;+ return incurError({+ code: "GITHUB_IMPORT_FAILED",+ message: diagnosticValue(error),+ exitCode,+ });+ }+ return undefined;+ } finally {+ removeSignals();}- return undefined;- } finally {- removeSignals();- }- },- });+ },+ });+ }+ if (importsEnabled) registerGitHubAdvisories();const infoOutput = z.object({sdkVersion: z.string(),bundledPluginVersion: z.string(),@@ -3999,7 +4033,7 @@ export async function main(configuration: z.record(z.string(), z.unknown()),});- const cli = Cli.create("codex-security", {+ const cliOptions: Cli.create.Options = {aliases: ["cs"],description: "Find, review, and fix security issues in your code.",version: VERSION,@@ -4009,7 +4043,8 @@ export async function main(instructions:"Use info for read-only SDK metadata. Scans and other state-changing commands are CLI-only because the MCP transport cannot cancel active commands.",},- })+ };+ const cli = Cli.create("codex-security", cliOptions).command("policy", {description: "Draft SECURITY.md for review.",destructive: true,@@ -6589,7 +6624,7 @@ export async function main(});const commands = Cli.toCommands.get(cli)!;- const valueOptions = cliValueOptions(commands);+ let valueOptions = cliValueOptions(commands);function isScanImportCommand(argv: readonly string[]): boolean {const commandIndex = cliCommandIndex(argv);return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";@@ -6736,6 +6771,42 @@ export async function main(command === "publish" ||command === "import";const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;+ if (+ command === "import" &&+ (subcommand === "github" || subcommand === "github-advisories") &&+ frameworkFlags.rawCollector+ ) {+ // Incur's skill-sync notice turns a saved collector array into an object.+ cliOptions.sync = false;+ }+ if (+ !importsEnabled &&+ ((command === "publish" && subcommand === "findings") ||+ (command === "findings" && subcommand === "imported") ||+ (command === "import" && subcommand === "github-advisories"))+ ) {+ if (+ process.env["COMPLETE"] ||+ argv.some((value) => FRAMEWORK_ACTIONS.has(value))+ ) {+ return externalImportsDisabledMessage;+ }+ if (!argv.includes("--version")) {+ if (+ argv.includes("--schema") ||+ (command !== "publish" &&+ (command !== "import" || !argv.includes("--full-output")))+ ) {+ return externalImportsDisabledMessage;+ }+ disabledImportInvocation = true;+ // This route only formats a disabled command; it is not an installed skill.+ cliOptions.sync = false;+ if (command === "publish") registerFindingPublication();+ else registerGitHubAdvisories();+ valueOptions = cliValueOptions(commands);+ }+ }if (command === "info") {for (let index = 0; index < argv.length; index += 1) {const argument = argv[index]!;@@ -6812,8 +6883,20 @@ export async function main() {return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;}+ if (disabledImportInvocation && frameworkFlags.hideDisabledRoute)+ return externalImportsDisabledMessage;}argv = normalizeScanImportArguments(defaultListCommand(argv));+ const frameworkArgv = argv.flatMap((argument) => {+ const separator = argument.indexOf("=");+ if (+ separator < 0 ||+ !FRAMEWORK_VALUE_OPTIONS.has(argument.slice(0, separator))+ )+ return [argument];+ return [argument.slice(0, separator), argument.slice(separator + 1)];+ });+ const frameworkFlags = frameworkOutputFlags(frameworkArgv);const policyFullOutput =argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");const argumentError = validateCliArguments(argv, positionals);@@ -6931,24 +7014,12 @@ export async function main(let notice: UpdateNotice | undefined;try {- await cli.serve(- argv.flatMap((argument) => {- if (- !/^--(?:format|filter-output|token-limit|token-offset)=/u.test(- argument,- )- )- return [argument];- const separator = argument.indexOf("=");- return [argument.slice(0, separator), argument.slice(separator + 1)];- }),- {- stdout: frameworkCapture.stream.write,- exit: (code) => {- frameworkExit = code;- },+ await cli.serve(frameworkArgv, {+ stdout: frameworkCapture.stream.write,+ exit: (code) => {+ frameworkExit = code;},- );+ });if (pendingUpdate !== undefined) {notice = await Promise.race([pendingUpdate, undefined]);}@@ -6990,6 +7061,10 @@ export async function main(} catch {}}if (frameworkExit !== undefined) {+ if (disabledImportInvocation && exitCode === 0) {+ reportPublicationError(externalImportsDisabledMessage, undefined);+ return exitCode;+ }if (policyFullOutput || structuredError) {if (exitCode === 0) exitCode = 2;} else {@@ -7324,15 +7399,35 @@ async function prepareScanArgumentsFromRecipe(};}+function frameworkOutputFlags(argv: readonly string[]) {+ let hideDisabledRoute = false;+ let fullOutput = false;+ let rawCollector = false;+ for (let index = 0; index < argv.length; index++) {+ const value = argv[index]!;+ if (+ FRAMEWORK_ACTIONS.has(value) ||+ value === "--schema" ||+ value === "--help" ||+ value === "-h"+ )+ hideDisabledRoute = true;+ if (value === "--full-output") fullOutput = true;+ if (value === "--json") rawCollector = true;+ if (FRAMEWORK_VALUE_OPTIONS.has(value)) {+ const operand = argv[++index];+ if (value === "--format")+ rawCollector =+ operand === "json" || operand === "jsonl" || operand === "yaml";+ }+ }+ return { hideDisabledRoute, rawCollector: rawCollector && !fullOutput };+}+function cliValueOptions(commands: NonNullable<ReturnType<typeof Cli.toCommands.get>>,): Set<string> {- const options = new Set([- "--format",- "--filter-output",- "--token-limit",- "--token-offset",- ]);+ const options = new Set(FRAMEWORK_VALUE_OPTIONS);for (const command of commands.values()) {if ("_group" in command) {for (const option of cliValueOptions(command.commands))diff --git a/sdk/typescript/src/external-findings-import.ts b/sdk/typescript/src/external-findings-import.tsindex c350472a3..3975eb5b7 100644--- a/sdk/typescript/src/external-findings-import.ts+++ b/sdk/typescript/src/external-findings-import.ts@@ -12,6 +12,7 @@ import {type LocalExternalImportDependencies,} from "./external-findings-local.js";import { abortable } from "./targets.js";+import { requireExternalImports } from "./external-imports-feature.js";/** Read an installed vendor format and prepare it for the local workbench. */export async function prepareLocalExternalImport(@@ -20,6 +21,7 @@ export async function prepareLocalExternalImport(dependencies: LocalExternalImportDependencies = {},) {dependencies.signal?.throwIfAborted();+ requireExternalImports(dependencies.environment);const parsed = await abortable(() => readExternalFindings(path, options, "local"),dependencies.signal,@@ -54,8 +56,10 @@ export async function prepareLocalExternalImport(})),];}+ const { environment, ...workbench } = dependencies;return prepareNormalizedLocalImport(parsed.findings, normalizedOptions, {- ...dependencies,+ ...workbench,+ environment,sourceRepositories: [...(dependencies.sourceRepositories ?? []),...sourceRepositories,diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex cf863e53d..8fefd5fc8 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -3,6 +3,10 @@ import { dirname, isAbsolute, join, resolve, sep } from "node:path";import { isNumberObject } from "node:util/types";import { environmentEntry } from "./auth.js";import { CodexSecurityError } from "./errors.js";+import {+ forwardExternalImportSetting,+ requireExternalImports,+} from "./external-imports-feature.js";import type {ExternalFindings,ExternalSourceRepository,@@ -425,9 +429,10 @@ async function localContext(mode: "import" | "read" = "import",) {dependencies.signal?.throwIfAborted();- const environment = workbenchEnvironment(- dependencies.environment ?? process.env,- );+ const selected = dependencies.environment ?? process.env;+ const environment = workbenchEnvironment(selected);+ forwardExternalImportSetting(selected, environment);+ requireExternalImports(environment);const path = expandHome(selectedRepository, environment);const repository =mode === "read"@@ -481,6 +486,7 @@ export async function prepareNormalizedLocalImport(dependencies: LocalExternalImportDependencies = {},): Promise<PreparedLocalExternalImport> {dependencies.signal?.throwIfAborted();+ requireExternalImports(dependencies.environment);requireIdentity(options.sourceKey, "Source key");const current = structuredClone(input);const identities = new Set<string>();@@ -592,6 +598,8 @@ export async function listLocalExternalFindings(selection: { repository: string; id?: string },dependencies: LocalExternalImportDependencies = {},): Promise<StoredExternalFinding[]> {+ dependencies.signal?.throwIfAborted();+ requireExternalImports(dependencies.environment);if (selection.id !== undefined) requireIdentity(selection.id, "Finding id");const { repository, options } = await localContext(selection.repository,diff --git a/sdk/typescript/src/external-findings-publish.ts b/sdk/typescript/src/external-findings-publish.tsindex 5f5b83daf..37cc62ae8 100644--- a/sdk/typescript/src/external-findings-publish.ts+++ b/sdk/typescript/src/external-findings-publish.ts@@ -19,6 +19,7 @@ import {DEFAULT_CLOUD_BASE_URL,} from "./cloud-endpoint.js";import { CodexSecurityError } from "./errors.js";+import { requireExternalImports } from "./external-imports-feature.js";import {codexSecurityStateDirectory,createWindowsOutputDirectory,@@ -350,6 +351,7 @@ export async function prepareExternalPublication(options: ExternalPublicationOptions,dependencies: ExternalPublicationDependencies = {},): Promise<PreparedExternalPublication> {+ requireExternalImports(dependencies.environment);const parsed = await readExternalFindings(path, options);const normalizedOptions = {...options,@@ -374,6 +376,7 @@ export async function prepareNormalizedExternalPublication(options: NormalizedExternalPublicationOptions,dependencies: ExternalPublicationDependencies = {},): Promise<PreparedExternalPublication> {+ requireExternalImports(dependencies.environment);// Validation adds Cloud defaults; leave the caller's objects unchanged.const current = structuredClone(input);// structuredClone preserves aliases. Detach every raw record before adding@@ -444,6 +447,7 @@ async function preparePublicationInput(}progress({ phase: "discovering", completed: 0 });const environment = dependencies.environment ?? process.env;+ requireExternalImports(environment);const apiBaseUrl = cloudBaseUrl(environment);const cloudApiUrl = `${apiBaseUrl}/external`;// Validate the configured return destination before authentication or uploads.diff --git a/sdk/typescript/src/external-imports-feature.ts b/sdk/typescript/src/external-imports-feature.tsnew file mode 100644index 000000000..190212fa0--- /dev/null+++ b/sdk/typescript/src/external-imports-feature.ts@@ -0,0 +1,59 @@+import { CodexSecurityError } from "./errors.js";++const flag = "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS";+export const externalImportsDisabledMessage = `External findings imports are disabled. Set ${flag}=1 to enable them.`;++function externalImportSetting<Value>(environment: Record<string, Value>) {+ const exact = environment[flag];+ if (process.platform !== "win32") return { key: flag, value: exact };+ // A scan can override a case-insensitive process.env with its own spelling.+ function callerDeclares(key: string): boolean {+ for (+ let owner: object | null = environment;+ owner && owner !== process.env;+ owner = Object.getPrototypeOf(owner)+ ) {+ if (Object.hasOwn(owner, key)) return true;+ }+ return false;+ }+ if (exact !== undefined && callerDeclares(flag))+ return { key: flag, value: exact };+ // Node includes enumerable prototype keys and sorts competing spellings.+ const keys: string[] = [];+ for (const name in environment) {+ if (name.toUpperCase() === flag) keys.push(name);+ }+ keys.sort();+ const key = keys.find(callerDeclares) ?? keys[0];+ if (key !== undefined)+ return { key, value: key === flag ? exact : environment[key] };+}++export function externalImportsEnabled(+ environment: NodeJS.ProcessEnv = process.env,+): boolean {+ return externalImportSetting(environment)?.value === "1";+}++/** Preserve the selected flag while copying a caller's environment for a child. */+export function forwardExternalImportSetting<Value>(+ source: Record<string, Value | undefined>,+ child: Record<string, Value>,+): void {+ const selected = externalImportSetting(source);+ if (selected === undefined) return;+ if (process.platform === "win32") {+ for (const name of Object.keys(child)) {+ if (name !== selected.key && name.toUpperCase() === flag)+ delete child[name];+ }+ }+ if (selected.value !== undefined) child[selected.key] = selected.value;+}++export function requireExternalImports(environment?: NodeJS.ProcessEnv): void {+ if (!externalImportsEnabled(environment)) {+ throw new CodexSecurityError(externalImportsDisabledMessage);+ }+}diff --git a/sdk/typescript/src/github-advisories.ts b/sdk/typescript/src/github-advisories.tsindex 403d5bd71..6391c1f4e 100644--- a/sdk/typescript/src/github-advisories.ts+++ b/sdk/typescript/src/github-advisories.ts@@ -1,5 +1,6 @@import type { Octokit } from "@octokit/core";import { CodexSecurityError, errorMessage } from "./errors.js";+import { requireExternalImports } from "./external-imports-feature.js";import { createAuthenticatedGitHub } from "./github.js";export const GITHUB_ADVISORY_STATES = [@@ -51,6 +52,8 @@ export async function importGitHubAdvisories(dependencies: GitHubAdvisoryImportDependencies = {},): Promise<ImportedGitHubAdvisory[]> {options.signal?.throwIfAborted();+ const environment = dependencies.environment ?? process.env;+ requireExternalImports(environment);const repository = options.repository.trim();const parts = /^([a-z0-9_.-]+)\/([a-z0-9_.-]+)$/iu.exec(repository);if (!parts || parts.slice(1).some((part) => /^\.{1,2}$/u.test(part)))@@ -87,7 +90,6 @@ export async function importGitHubAdvisories(throw new CodexSecurityError("--github-state only filters repository lists; omit it when selecting exact GHSA IDs.",);- const environment = dependencies.environment ?? process.env;const host =options.githubHost?.trim() ??(environment["GH_HOST"]?.trim() || "github.com");diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 4c4f465fe..e34f74337 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -1,3 +1,4 @@+import { forwardExternalImportSetting } from "./external-imports-feature.js";import { executablePathForSpawn } from "./executable-path.js";export { executablePathForSpawn } from "./executable-path.js";import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";@@ -3152,12 +3153,14 @@ export function pluginExecutionEnvironment(python: string,environment: ProcessEnvironment = process.env,): ProcessEnvironment {- return {+ const child = {...pythonUtf8Environment(environment),PYTHON: python,CODEX_SECURITY_PYTHON_COMMAND: python,CODEX_CLI_PATH: resolveCodexCommand(environment).command,};+ forwardExternalImportSetting(environment, child);+ return child;}export function environmentWithGit(diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.tsindex 21f3ebf31..af46fc3ce 100644--- a/sdk/typescript/tests-ts/api-credentials.test.ts+++ b/sdk/typescript/tests-ts/api-credentials.test.ts@@ -1,5 +1,5 @@import { requestMetadata } from "./support/request-metadata.js";-import { nodeCommand } from "./support/shell.js";+import { nodeCommand, runCommand } from "./support/shell.js";import { existsSync } from "node:fs";import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";import { join, relative } from "node:path";@@ -451,11 +451,28 @@ describe("CodexSecurity orchestration", () => {let scansStarted = 0;const deepScanConfigPaths = new Set<string>();const concurrentScans = Promise.withResolvers<void>();+ const inheritedOptIn = Object.defineProperty(+ {},+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS",+ { value: "1", enumerable: false, writable: true },+ );const clients = await Promise.all(- [0, 1].map(async (index) => {+ [+ {},+ {+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:+ process.platform === "win32" ? undefined : "0",+ Codex_Security_Enable_External_Imports: "1",+ },+ ].map(async (overrides, index) => {const scanDir = join(root, `parallel-scan-${index}`);await mkdir(scanDir, { mode: 0o700 });+ const environment: NodeJS.ProcessEnv = Object.assign(+ Object.create(inheritedOptIn),+ { CODEX_HOME: ambientHome, CODEX_SECURITY_STATE_DIR: stateDirectory },+ overrides,+ );return new TestClient({pluginPath: PLUGIN_ROOT,@@ -464,10 +481,7 @@ describe("CodexSecurity orchestration", () => {},},{- environment: {- CODEX_HOME: ambientHome,- CODEX_SECURITY_STATE_DIR: stateDirectory,- },+ environment,resolvePluginPython: async () => "/managed/python",prepareOutputDir: async () => scanDir,repositoryRevision: async () => "deadbeef",@@ -500,6 +514,15 @@ describe("CodexSecurity orchestration", () => {workers: index + 2,});await concurrentScans.promise;+ const child = await runCommand(+ nodeCommand().command,+ ["-p", "process.env.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS"],+ { env: options.env },+ );+ expect(child.status, child.stderr).toBe(0);+ expect(child.stdout.trim()).toBe(+ String(environment["CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS"]),+ );const after = parseToml(await readFile(deepScanConfigPath!, "utf8"),);@@ -518,7 +541,11 @@ describe("CodexSecurity orchestration", () => {const results = await Promise.allSettled(clients.map((client, index) =>client- .run(repository, { mode: "deep", workers: index + 2 })+ .run(repository, {+ mode: "deep",+ workers: index + 2,+ auth: index === 0 ? "chatgpt" : "auto",+ }).finally(concurrentScans.resolve),),);diff --git a/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts b/sdk/typescript/tests-ts/cli-external-imports-feature.test.tsnew file mode 100644index 000000000..3f4437552--- /dev/null+++ b/sdk/typescript/tests-ts/cli-external-imports-feature.test.ts@@ -0,0 +1,344 @@+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { expect, mock, test } from "bun:test";+import { main } from "../src/cli.js";+import { VERSION } from "../src/version.js";+import {+ removeTemporaryDirectory,+ temporaryDirectory,+} from "./support/temporary-directories.js";+import { dependencies } from "./cli-fixtures.js";+import { createCliTest } from "./support/cli-run.js";+import { importedAlert } from "./support/github-import-fixtures.js";+import { runTestInSubprocess } from "./support/test-subprocess.js";++const commands = [+ ["publish", "findings"],+ ["findings", "imported"],+ ["import", "github-advisories"],+];++const publishLocal = [+ "publish",+ "findings",+ "selected.json",+ "--to",+ "local",+ "--repository",+ ".",+ "--provider",+ "wiz",+ "--source-key",+ "synthetic/findings",+ "--yes",+];++for (const value of [undefined, "", "0", "true"]) {+ test(`external commands are absent from discovery without opt-in (${String(value)})`, async () => {+ const environment = { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: value };+ for (const [group, command] of commands) {+ const cli = createCliTest(main);+ expect(+ await cli.runCli([group!, "--help"], dependencies({ environment })),+ ).toBe(0);+ expect(cli.stdout.text()).not.toMatch(+ new RegExp(`^\\s+${command}\\s`, "m"),+ );+ const schema = createCliTest(main);+ expect(+ await schema.runCli(+ [group!, command!, "--schema"],+ dependencies({ environment }),+ ),+ ).not.toBe(0);+ }+ const github = createCliTest(main);+ expect(+ await github.runCli(+ ["import", "github", "--help"],+ dependencies({ environment }),+ ),+ ).toBe(0);+ expect(github.stdout.text()).not.toContain("publish findings");+ });+}++test("disabled commands distinguish discovery requests from filter values", async () => {+ const deps = dependencies({ environment: {} });+ for (const flag of ["--schema", "--llms-full", "--help"]) {+ const cli = createCliTest(main);+ expect(+ await cli.runCli(+ [+ "--filter-output",+ `--token-limit=${flag}`,+ "publish",+ "findings",+ "--json",+ ],+ deps,+ ),+ ).toBe(2);+ expect(cli.stdout.text()).toBe("");+ expect(cli.stderr.text()).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ }+ const filtered = createCliTest(main);+ expect(+ await filtered.runCli(+ [+ ...publishLocal,+ "--filter-output=--schema",+ "--full-output",+ "--format=json",+ ],+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(filtered.stdout.text()).error.code).toBe("IMPORT_FAILED");+});++test("disabled commands cannot invoke import, storage, or publication handlers", async () => {+ const unexpected = mock(async () => {+ throw new Error("Unexpected import handler");+ });+ const deps = {+ ...dependencies({+ environment: {},+ importGitHubAdvisories: unexpected,+ onWorkbench: unexpected,+ }),+ prepareLocalExternalImport: unexpected,+ listLocalExternalFindings: unexpected,+ cloudFetch: unexpected,+ };+ for (const command of [+ publishLocal,+ [+ "publish",+ "findings",+ "selected.json",+ "--to",+ "cloud",+ "--repository",+ "example/project",+ "--provider",+ "snyk",+ "--source-key",+ "synthetic/findings",+ "--yes",+ ],+ ["findings", "imported", "."],+ ["import", "github-advisories", "example/project"],+ ]) {+ const cli = createCliTest(main);+ expect(await cli.runCli(command, deps)).not.toBe(0);+ expect(cli.stderr.text()).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ if (command[0] === "publish") {+ for (const [flags, diagnostic] of [+ [["--unknown", "--json"], cli.stderr.text()],+ [+ ["extra.json", "--json"],+ "Unexpected positional argument for publish findings.",+ ],+ [+ ["--source-key", "--dry-run", "--json"],+ "Missing value for flag: --source-key",+ ],+ ] as const) {+ const rejected = createCliTest(main);+ expect(await rejected.runCli([...command, ...flags], deps)).toBe(2);+ expect(rejected.stdout.text()).toBe("");+ expect(rejected.stderr.text()).toContain(diagnostic);+ }+ for (const [flags, result] of [+ [["--format=yaml"], /^status: failed$/m],+ [["--format", "md"], /\|\s*status\s*\|\s*failed\s*\|/],+ [["--format", "json", "--format", "yaml"], /^status: failed$/m],+ ] as const) {+ const formatted = createCliTest(main);+ expect(await formatted.runCli([...command, ...flags], deps)).toBe(2);+ expect(formatted.stdout.text()).toMatch(result);+ expect(formatted.stdout.text()).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ }+ for (const format of ["json", "jsonl"]) {+ const formatted = createCliTest(main);+ expect(+ await formatted.runCli(+ [...command, "--format", format, "--full-output"],+ deps,+ ),+ ).toBe(2);+ const message = expect.stringContaining(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ expect(JSON.parse(formatted.stdout.text())).toMatchObject({+ ok: false,+ error: { code: "IMPORT_FAILED", message },+ data: { status: "failed", error: message },+ });+ }+ const unsupported = createCliTest(main);+ expect(+ await unsupported.runCli(+ [...command, "--format", "json", "--format", "yaml", "--full-output"],+ deps,+ ),+ ).toBe(2);+ expect(unsupported.stdout.text()).toContain("INVALID_ARGUMENTS");+ } else if (command[1] === "github-advisories") {+ for (const format of [undefined, "json", "jsonl", "yaml", "md", "toon"]) {+ const formatted = createCliTest(main);+ expect(+ await formatted.runCli(+ [+ ...command,+ "--full-output",+ ...(format === undefined ? [] : ["--format", format]),+ ],+ deps,+ ),+ ).toBe(2);+ if (format === "json" || format === "jsonl") {+ expect(JSON.parse(formatted.stdout.text())).toMatchObject({+ ok: false,+ error: { code: "GITHUB_IMPORT_FAILED" },+ });+ } else {+ expect(formatted.stdout.text()).toContain("GITHUB_IMPORT_FAILED");+ }+ expect(formatted.stdout.text()).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ }+ }+ }+ expect(unexpected).not.toHaveBeenCalled();+});++const installedSkills =+ "installed skills preserve import errors and collector output";+test(installedSkills, async () => {+ if (runTestInSubprocess(import.meta.path, installedSkills)) return;+ const root = await temporaryDirectory("disabled-import-skills-");+ const entry = fileURLToPath(new URL("../src/cli.ts", import.meta.url));+ const run = (...args: string[]) =>+ spawnSync(process.execPath, [entry, ...args], {+ cwd: root,+ env: {+ ...process.env,+ COMPLETE: "",+ HOME: root,+ USERPROFILE: root,+ CODEX_HOME: root,+ XDG_DATA_HOME: root,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0",+ CODEX_SECURITY_NO_UPDATE_NOTICE: "1",+ },+ encoding: "utf8",+ });+ try {+ expect(run("skills", "add", "--no-global").status).toBe(0);+ for (const args of [+ [...publishLocal, "--json"],+ [+ "import",+ "github-advisories",+ "example/project",+ "--json",+ "--full-output",+ ],+ ]) {+ const result = run(...args);+ expect(result.status).toBe(2);+ expect(result.stdout).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ expect(result.stdout).not.toContain("Skills are out of date");+ }++ process.env["XDG_DATA_HOME"] = root;+ const alerts = [importedAlert()];+ const deps = dependencies({+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },+ importGitHubAlerts: async () => alerts,+ });+ const args = ["import", "github", "example/project", "--json"];+ const full = createCliTest(main);+ expect(await full.runCli([...args, "--full-output"], deps)).toBe(0);+ expect(JSON.parse(full.stdout.text())).toMatchObject({+ data: alerts,+ meta: { cta: { description: "Skills are out of date:" } },+ });+ const plain = createCliTest(main);+ expect(await plain.runCli(args, deps)).toBe(0);+ expect(JSON.parse(plain.stdout.text())).toEqual(alerts);+ const yaml = createCliTest(main);+ expect(await yaml.runCli([...args, "--format=yaml"], deps)).toBe(0);+ expect(Bun.YAML.parse(yaml.stdout.text())).toEqual(alerts);+ } finally {+ await removeTemporaryDirectory(root);+ }+});++test("opt-in exposes the commands per invocation without affecting concurrent disabled discovery", async () => {+ await Promise.all(+ [true, false].map(async (enabled) => {+ const environment = {+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: enabled ? "1" : "0",+ };+ for (const [group, command] of commands) {+ const version = createCliTest(main);+ expect(+ await version.runCli(+ [group!, command!, "--version", "--json"],+ dependencies({ environment }),+ ),+ ).toBe(0);+ expect(version.stdout.text()).toBe(`${VERSION}\n`);+ expect(version.stderr.text()).toBe("");+ const cli = createCliTest(main);+ expect(+ await cli.runCli([group!, "--help"], dependencies({ environment })),+ ).toBe(0);+ expect(+ new RegExp(`^\\s+${command}\\s`, "m").test(cli.stdout.text()),+ ).toBe(enabled);+ if (enabled) {+ const help = createCliTest(main);+ expect(+ await help.runCli(+ [group!, command!, "--schema"],+ dependencies({ environment }),+ ),+ ).toBe(0);+ }+ }+ }),+ );+});++test("established scan publishing, status, scan import, and GitHub collection stay available", async () => {+ for (const command of [+ ["publish", "scan"],+ ["publish", "check"],+ ["scan", "import"],+ ["import", "github"],+ ]) {+ const cli = createCliTest(main);+ expect(+ await cli.runCli(+ [...command, "--help"],+ dependencies({ environment: {} }),+ ),+ ).toBe(0);+ expect(cli.stdout.text()).toContain(+ `Usage: codex-security ${command.join(" ")} `,+ );+ }+});diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.tsindex 87dd448e1..c9e6f4322 100644--- a/sdk/typescript/tests-ts/cli-local-import.test.ts+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts@@ -11,9 +11,23 @@ import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterEach, expect, test } from "bun:test";import { main } from "../src/cli.js";-import { dependencies, FakeSignals } from "./cli-fixtures.js";+import {+ dependencies as cliDependencies,+ FakeSignals,+} from "./cli-fixtures.js";import { createCliTest } from "./support/cli-run.js";+const dependencies: typeof cliDependencies = (options = {}) => {+ const result = cliDependencies(options);+ return {+ ...result,+ environment: {+ ...result.environment,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+ },+ };+};+const roots: string[] = [];afterEach(async () => {await Promise.all(diff --git a/sdk/typescript/tests-ts/direct-deep-scan.test.ts b/sdk/typescript/tests-ts/direct-deep-scan.test.tsindex 25437155a..7385fc61e 100644--- a/sdk/typescript/tests-ts/direct-deep-scan.test.ts+++ b/sdk/typescript/tests-ts/direct-deep-scan.test.ts@@ -62,6 +62,7 @@ writeFileSync(process.env.SYNTHETIC_RECEIPT, JSON.stringify({request, argv: process.argv.slice(2), key: process.env.CODEX_API_KEY,execPath: process.execPath, bun: process.versions.bun,awsProfile: process.env.AWS_PROFILE, snapshot: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ externalImports: process.env.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS,}));if (process.env.SYNTHETIC_WAIT === '1') {lines.once('close', () => { writeFileSync(process.env.SYNTHETIC_RECEIPT + '.stopped', 'stopped'); process.exit(0); });@@ -80,7 +81,7 @@ if (process.env.SYNTHETIC_WAIT === '1') {test("isolates direct engine credentials and runtime snapshots across concurrent scans", async () => {const { root, pluginRoot } = await fixture();const events = await Promise.all(- ["first", "second"].map(async (name) => {+ ["first", "second", "unset", "mixed-case"].map(async (name) => {const scanDir = join(root, name);const receipt = join(root, `${name}.json`);await mkdir(scanDir);@@ -95,6 +96,14 @@ test("isolates direct engine credentials and runtime snapshots across concurrent"private-snapshot.toml",),AWS_PROFILE: `profile-${name}`,+ ...(name === "mixed-case"+ ? { Codex_Security_Enable_External_Imports: "1" }+ : name === "unset"+ ? {}+ : {+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:+ name === "first" ? "1" : "0",+ }),};const before = { ...environment };const collected = [];@@ -120,6 +129,18 @@ test("isolates direct engine credentials and runtime snapshots across concurrent}))collected.push(event);const saved = JSON.parse(await readFile(receipt, "utf8"));+ assert.equal(+ saved.externalImports,+ name === "mixed-case"+ ? process.platform === "win32"+ ? "1"+ : undefined+ : name === "first"+ ? "1"+ : name === "second"+ ? "0"+ : undefined,+ );assert.partialDeepStrictEqual(saved, {key: `synthetic-key-${name}`,awsProfile: `profile-${name}`,diff --git a/sdk/typescript/tests-ts/external-findings-import.test.ts b/sdk/typescript/tests-ts/external-findings-import.test.tsindex e9a192acd..0cc68f18d 100644--- a/sdk/typescript/tests-ts/external-findings-import.test.ts+++ b/sdk/typescript/tests-ts/external-findings-import.test.ts@@ -8,6 +8,84 @@ import { listLocalExternalFindings } from "../src/external-findings-local.js";import { readVendorFindings } from "../src/wiz-findings.js";import { localFindingsFixture } from "./external-findings-local-helpers.js";+test("requires opt-in before reading the source file", async () => {+ const fixture = await localFindingsFixture();+ try {+ const environment: NodeJS.ProcessEnv = { ...fixture.environment };+ delete environment["CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS"];+ let workbenchCalls = 0;+ await expect(+ prepareLocalExternalImport(+ join(fixture.root, "missing-findings.json"),+ {+ repository: fixture.repository,+ provider: "wiz",+ sourceKey: "example-project/main",+ },+ {+ environment,+ runWorkbench: async () => {+ workbenchCalls++;+ throw new Error("Disabled imports must not access the workbench");+ },+ },+ ),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ expect(workbenchCalls).toBe(0);+ await expect(access(fixture.stateDirectory)).rejects.toThrow();+ } finally {+ await fixture.dispose();+ }+});++test("a file import rechecks the selected workbench opt-in after reading", async () => {+ const f = await localFindingsFixture();+ try {+ const file = join(f.root, "report.json");+ await writeFile(+ file,+ JSON.stringify([+ {+ source_finding_id: "example",+ evidence: { title: "Example finding", severity: "high" },+ },+ ]),+ );+ const selection = {+ repository: f.repository,+ provider: "wiz" as const,+ sourceKey: "example",+ };+ class Workbench {+ get environment() {+ return { ...f.environment, HOME: f.root, USERPROFILE: f.root };+ }+ }+ const prepared = await prepareLocalExternalImport(+ file,+ { ...selection, repository: "~/repository" },+ new Workbench(),+ );+ expect(prepared.preview.repository).toBe(f.repository);++ const dependencies = { environment: { ...f.environment } };+ const pending = prepareLocalExternalImport(file, selection, dependencies);+ const disabledState = join(f.root, "disabled-state");+ dependencies.environment = {+ ...f.environment,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0",+ CODEX_SECURITY_STATE_DIR: disabledState,+ };+ await expect(pending).rejects.toThrow(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ await expect(access(f.stateDirectory)).rejects.toThrow();+ await expect(access(disabledState)).rejects.toThrow();+ } finally {+ await f.dispose();+ }+});+test("cancels preparation while the source file read is pending", async () => {const fixture = await localFindingsFixture();try {diff --git a/sdk/typescript/tests-ts/external-findings-local-helpers.ts b/sdk/typescript/tests-ts/external-findings-local-helpers.tsindex a4b2f36a1..61b099b6d 100644--- a/sdk/typescript/tests-ts/external-findings-local-helpers.ts+++ b/sdk/typescript/tests-ts/external-findings-local-helpers.ts@@ -25,7 +25,16 @@ export async function localFindingsFixture(options: { remote?: string } = {}) {root,repository,stateDirectory,- environment: { ...process.env, CODEX_SECURITY_STATE_DIR: stateDirectory },+ environment: {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([name]) =>+ name.toUpperCase() !== "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS",+ ),+ ),+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",+ },dispose: () => rm(root, { recursive: true, force: true }),};}diff --git a/sdk/typescript/tests-ts/external-findings-local-limits.test.ts b/sdk/typescript/tests-ts/external-findings-local-limits.test.tsindex 1111e7337..cf7a6a7d2 100644--- a/sdk/typescript/tests-ts/external-findings-local-limits.test.ts+++ b/sdk/typescript/tests-ts/external-findings-local-limits.test.ts@@ -293,7 +293,7 @@ test("local SQLite preserves each oversized evidence field and Cloud rejects eacprepareNormalizedExternalPublication({ read: 1, findings: [input], excluded: [] },options,- { credentials },+ { ...dependencies, credentials },),).rejects.toThrow();}@@ -339,7 +339,7 @@ test.each(["wiz", "endor"] as const)(prepareNormalizedExternalPublication({ read: 1, findings: prepared.preview.findings, excluded: [] },options,- { credentials },+ { ...dependencies, credentials },),).rejects.toThrow("512");expect(credentials).not.toHaveBeenCalled();diff --git a/sdk/typescript/tests-ts/external-findings-local.test.ts b/sdk/typescript/tests-ts/external-findings-local.test.tsindex ebcee431c..fcf1a57ec 100644--- a/sdk/typescript/tests-ts/external-findings-local.test.ts+++ b/sdk/typescript/tests-ts/external-findings-local.test.ts@@ -70,6 +70,133 @@ function input(): ExternalFindings {const source = { provider: "snyk" as const, sourceKey: "example-project/main" };describe("local normalized scanner findings", () => {+ test("requires opt-in before resolving repositories or accessing the workbench", async () => {+ const { root, stateDirectory, environment } = await fixture();+ const disabledEnvironment: NodeJS.ProcessEnv = { ...environment };+ delete disabledEnvironment["CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS"];+ const repository = join(root, "missing-repository");+ let workbenchCalls = 0;+ const dependencies = {+ environment: disabledEnvironment,+ runWorkbench: async () => {+ workbenchCalls++;+ throw new Error("Disabled imports must not access the workbench");+ },+ };+ await expect(+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source },+ dependencies,+ ),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ await expect(+ listLocalExternalFindings({ repository }, dependencies),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ expect(workbenchCalls).toBe(0);+ expect(existsSync(stateDirectory)).toBe(false);+ });++ test("requires opt-in from the workbench selected during normalization", async () => {+ const { root, repository, stateDirectory, environment } = await fixture();+ const disabledState = join(root, "disabled-state");+ const dependencies = { environment };+ const data = input();+ const finding = data.findings[0]!;+ const evidence = finding.evidence;+ Object.defineProperty(finding, "evidence", {+ enumerable: true,+ get() {+ dependencies.environment = {+ ...environment,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0",+ CODEX_SECURITY_STATE_DIR: disabledState,+ };+ return evidence;+ },+ });+ await expect(+ prepareNormalizedLocalImport(+ data,+ { repository, ...source },+ dependencies,+ ).then((prepared) => prepared.import()),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ expect(existsSync(disabledState)).toBe(false);+ expect(existsSync(stateDirectory)).toBe(false);+ });++ test("forwards an inherited opt-in to store and read helpers while an overlapping import stays disabled", async () => {+ const { root, repository, stateDirectory, environment } = await fixture();+ const { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS, ...settings } = environment;+ const enabledEnvironment = Object.assign(+ Object.create({+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS,+ get CODEX_SECURITY_CLOUD_WEB_URL() {+ throw new Error("A local import does not use the Cloud endpoint");+ },+ }),+ settings,+ );+ const disabledState = join(root, "disabled-state");+ const disabledEnvironment = {+ ...environment,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0",+ CODEX_SECURITY_STATE_DIR: disabledState,+ };+ const [enabled, disabled] = await Promise.allSettled([+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source },+ { environment: enabledEnvironment },+ ).then((prepared) => prepared.import()),+ prepareNormalizedLocalImport(+ input(),+ { repository, ...source },+ {+ environment: disabledEnvironment,+ },+ ).then((prepared) => prepared.import()),+ ]);+ if (enabled.status !== "fulfilled") throw enabled.reason;+ expect(enabled.value.counts).toEqual({+ created: 2,+ updated: 0,+ unchanged: 0,+ });+ expect(disabled.status).toBe("rejected");+ if (disabled.status !== "rejected")+ throw new Error("Disabled import succeeded");+ expect(disabled.reason.message).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ const [readback, blockedRead] = await Promise.allSettled([+ listLocalExternalFindings(+ { repository },+ { environment: enabledEnvironment },+ ),+ listLocalExternalFindings(+ { repository },+ { environment: disabledEnvironment },+ ),+ ]);+ expect(readback.status).toBe("fulfilled");+ if (readback.status !== "fulfilled") throw readback.reason;+ expect(+ new Map(readback.value.map((finding) => [finding.id, finding])),+ ).toEqual(+ new Map(enabled.value.findings.map((finding) => [finding.id, finding])),+ );+ expect(blockedRead.status).toBe("rejected");+ if (blockedRead.status !== "rejected")+ throw new Error("Disabled read succeeded");+ expect(blockedRead.reason.message).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ expect(existsSync(join(stateDirectory, "workbench.sqlite3"))).toBe(true);+ expect(existsSync(disabledState)).toBe(false);+ });+test("persists sparse evidence through the native helper and reads it in a separate process", async () => {const { repository, stateDirectory, environment } = await fixture();const normalized = input();diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.tsindex 57d278b12..b7d0604cb 100644--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts@@ -61,6 +61,113 @@ const normalized = (id = "vendor-1", severity = "high") => ({},});+for (const value of [undefined, "", "0", "true", " 1 "]) {+ test(`external publication stays disabled without exact opt-in (${JSON.stringify(value)})`, async () => {+ const root = await mkdtemp(join(tmpdir(), "external-import-disabled-"));+ cleanups.push(() => rm(root, { recursive: true, force: true }));+ const state = join(root, "state");+ let sideEffects = 0;+ const disabled = {+ environment: {+ CODEX_SECURITY_STATE_DIR: state,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: value,+ },+ credentials: async () => {+ sideEffects++;+ throw new Error("Unexpected credential read");+ },+ fetch: async () => {+ sideEffects++;+ throw new Error("Unexpected Cloud request");+ },+ };+ // The missing path would fail differently if the file reader ran first.+ await expect(+ prepareExternalPublication(join(root, "missing.json"), options, disabled),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ await expect(+ prepareNormalizedExternalPublication(+ { read: 0, findings: [], excluded: [] },+ options,+ disabled,+ ),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ expect(sideEffects).toBe(0);+ await expect(readdir(state)).rejects.toThrow("ENOENT");+ });+}++test("concurrent external publications use their own opt-in environments", async () => {+ const f = await fixture();+ const parsed = await readVendorFindings(f.file);+ let disabledSideEffects = 0;+ const disabled = {+ ...f.deps,+ environment: {+ ...f.environment,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0",+ },+ credentials: async () => {+ disabledSideEffects++;+ throw new Error("Unexpected credential read");+ },+ fetch: async () => {+ disabledSideEffects++;+ throw new Error("Unexpected Cloud request");+ },+ };+ const results = await Promise.allSettled([+ prepareExternalPublication(f.file, options, f.deps),+ prepareExternalPublication(f.file, options, disabled),+ prepareNormalizedExternalPublication(parsed, options, f.deps),+ prepareNormalizedExternalPublication(parsed, options, disabled),+ ]);+ expect(results.map((result) => result.status)).toEqual([+ "fulfilled",+ "rejected",+ "fulfilled",+ "rejected",+ ]);+ for (const result of results) {+ if (result.status === "fulfilled") {+ expect(result.value.preview.findings).toHaveLength(1);+ } else {+ expect(String(result.reason)).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ }+ }+ expect(disabledSideEffects).toBe(0);+ expect(f.posts).toHaveLength(0);+});++for (const provider of ["wiz", "snyk"] as const) {+ test(`${provider} publication rechecks the selected Cloud opt-in after reading`, async () => {+ const { snykSarif } = await import("./support/snyk-import-fixtures.js");+ const f =+ provider === "snyk" ? await fixture(snykSarif()) : await fixture();+ let credentialReads = 0;+ const dependencies = {+ ...f.deps,+ environment: { ...f.environment },+ credentials: async () => {+ credentialReads++;+ throw new Error("Unexpected credential read");+ },+ };+ const pending = prepareExternalPublication(+ f.file,+ { ...options, provider },+ dependencies,+ );+ dependencies.environment.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS = "0";+ await expect(pending).rejects.toThrow(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ expect(credentialReads).toBe(0);+ });+}+test("Wiz's gzip JSON report retains finding identity, evidence and repository locations", async () => {const report = {id: "vendor-report-1",@@ -159,6 +266,7 @@ async function fixture(await writeFile(file, JSON.stringify(records));const environment = {...process.env,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",CODEX_HOME: join(root, "credentials"),CODEX_SECURITY_STATE_DIR: join(root, "state"),};@@ -3771,3 +3879,49 @@ test("Endor source repository binding preserves immutable requests across a repoexpect(f.posts).toHaveLength(posted);expect(input).toEqual(original);});++test("publication rejects malformed options without writing findings", async () => {+ const f = await fixture();+ const missingSourceKey = [+ ...f.command.slice(1, f.command.indexOf("--source-key") + 1),+ "--dry-run",+ "--yes",+ ];+ for (const flags of [+ ["--json"],+ ["--json", "--filter-output", "--token-limit"],+ ["--filter-output", "--to"],+ ]) {+ const cli = createCliTest(main);+ expect(+ await cli.runCli(["publish", ...flags, ...missingSourceKey], f.cliDeps),+ ).toBe(2);+ expect(cli.stderr.text()).toContain("Missing value for flag");+ }+ const extraArguments = createCliTest(main);+ expect(+ await extraArguments.runCli(+ [+ "--filter-output",+ "--token-limit",+ ...f.command,+ "--yes",+ "extra-1",+ "extra-2",+ ],+ f.cliDeps,+ ),+ ).toBe(2);+ expect(extraArguments.stderr.text()).toContain(+ "Unexpected positional argument",+ );+ const preview = createCliTest(main);+ expect(+ await preview.runCli(+ ["--json", ...f.command, "--dry-run", "--yes"],+ f.cliDeps,+ ),+ ).toBe(0);+ expect(JSON.parse(preview.stdout.text())).toMatchObject({ dryRun: true });+ expect(f.posts).toHaveLength(0);+});diff --git a/sdk/typescript/tests-ts/external-imports-feature.test.ts b/sdk/typescript/tests-ts/external-imports-feature.test.tsnew file mode 100644index 000000000..c0a778058--- /dev/null+++ b/sdk/typescript/tests-ts/external-imports-feature.test.ts@@ -0,0 +1,94 @@+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { expect, test } from "bun:test";++test.each(["win32", "linux", "darwin"])(+ "external import opt-in follows %s environment key semantics",+ (platform) => {+ const result = spawnSync(+ process.execPath,+ [+ "-e",+ `+const { strict: assert } = await import("node:assert");+const { importGitHubAdvisories } = await import(process.argv[2]);+Object.defineProperty(process, "platform", { value: process.argv[1] });+const flag = "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS";+const environments = [+ { Codex_Security_Enable_External_Imports: "1" },+ { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },+ { Codex_Security_Enable_External_Imports: "0" },+ { Codex_Security_Enable_External_Imports: "true" },+ { Codex_Security_Enable_External_Imports: "1", CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: undefined },+ { codex_security_enable_external_imports: "1", Codex_Security_Enable_External_Imports: "0" },+ { codex_security_enable_external_imports: "0", Codex_Security_Enable_External_Imports: "1" },+ Object.create({ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" }),+ Object.assign(Object.create({ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0" }), {+ Codex_Security_Enable_External_Imports: "1",+ }),+ Object.defineProperty({}, flag, { value: "1" }),+ Object.defineProperty({ [flag.toLowerCase()]: "1" }, flag, { value: "0" }),+ Object.defineProperty({ [flag.toLowerCase()]: "1" }, flag, { value: undefined }),+ {},+];+async function importAdvisories(environment) {+ let requests = 0;+ try {+ const advisories = await importGitHubAdvisories(+ { repository: "example/project" },+ { environment, createGitHub: async () => ({ request: async () => {+ requests++;+ return { data: [], headers: {} };+ } }) },+ );+ return { enabled: true, advisories, requests };+ } catch (error) {+ return { enabled: false, message: error.message, requests };+ }+}+const results = await Promise.all(environments.map(importAdvisories));+if (process.platform === "win32") {+ const mixed = "Codex_Security_Enable_External_Imports";+ for (const name of Object.keys(process.env)) if (name.toUpperCase() === flag) delete process.env[name];+ for (const hostKey of [flag, mixed, flag.toLowerCase()]) {+ for (const own of ["0", "1"]) {+ process.env[hostKey] = own === "0" ? "1" : "0";+ const overlay = Object.create(process.env, { [mixed]: { value: own, enumerable: true } });+ assert.equal((await importAdvisories(overlay)).requests, Number(own), hostKey);+ }+ delete process.env[hostKey];+ }+}+console.log(JSON.stringify(results));+`,+ platform,+ fileURLToPath(new URL("../src/github-advisories.ts", import.meta.url)),+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ const enabled = { enabled: true, advisories: [], requests: 1 };+ const disabled = {+ enabled: false,+ message: expect.stringContaining(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ ),+ requests: 0,+ };+ expect(JSON.parse(result.stdout)).toEqual([+ platform === "win32" ? enabled : disabled,+ enabled,+ disabled,+ disabled,+ disabled,+ disabled,+ platform === "win32" ? enabled : disabled,+ enabled,+ disabled,+ enabled,+ disabled,+ platform === "win32" ? enabled : disabled,+ disabled,+ ]);+ },+);diff --git a/sdk/typescript/tests-ts/github-advisories.test.ts b/sdk/typescript/tests-ts/github-advisories.test.tsindex 5f7030d15..1fb8894c8 100644--- a/sdk/typescript/tests-ts/github-advisories.test.ts+++ b/sdk/typescript/tests-ts/github-advisories.test.ts@@ -9,6 +9,8 @@ import { dependencies, FakeSignals } from "./cli-fixtures.js";import { captureCli, runCapturedCli } from "./support/cli-run.js";import { importedAdvisory } from "./support/github-import-fixtures.js";+const enabledEnvironment = { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" };+function client(respond: (url: URL) => Response): Octokit {return new Octokit({auth: "SYNTHETIC_ADVISORY_TOKEN",@@ -27,6 +29,48 @@ function client(respond: (url: URL) => Response): Octokit {});}+test.each(["repository", "global"] as const)(+ "%s advisory imports require opt-in before GitHub authentication",+ async (source) => {+ const createGitHub = mock(async () => client(() => Response.json([])));+ await expect(+ importGitHubAdvisories(+ {+ repository: "example/project",+ source,+ advisoryIds: [importedAdvisory().ghsaId],+ },+ { environment: {}, createGitHub },+ ),+ ).rejects.toThrow("CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1");+ expect(createGitHub).not.toHaveBeenCalled();+ },+);++test("concurrent advisory imports keep opt-in scoped to each call", async () => {+ const advisory = importedAdvisory();+ const createGitHub = mock(async () =>+ client(() => Response.json([advisory.advisory])),+ );+ const [enabled, disabled] = await Promise.allSettled([+ importGitHubAdvisories(+ { repository: "example/project" },+ { environment: enabledEnvironment, createGitHub },+ ),+ importGitHubAdvisories(+ { repository: "example/project" },+ { environment: {}, createGitHub },+ ),+ ]);+ expect(enabled).toEqual({ status: "fulfilled", value: [advisory] });+ expect(disabled.status).toBe("rejected");+ if (disabled.status === "rejected")+ expect(disabled.reason.message).toContain(+ "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1",+ );+ expect(createGitHub).toHaveBeenCalledTimes(1);+});+test("repository advisory lists default to published and paginate cursors with full evidence", async () => {const paths: string[] = [];const github = client((url) => {@@ -47,7 +91,7 @@ test("repository advisory lists default to published and paginate cursors with f});const imported = await importGitHubAdvisories({ repository: "example/project" },- { createGitHub: async () => github },+ { environment: enabledEnvironment, createGitHub: async () => github },);expect(paths).toHaveLength(2);expect(new URL(paths[1]!).searchParams.get("after")).toBe("cursor-2");@@ -68,7 +112,7 @@ test("global advisory selection uses only explicit deduplicated IDs and preservesource: "global",advisoryIds: [selected.ghsaId.toLowerCase(), selected.ghsaId],},- { createGitHub: async () => github },+ { environment: enabledEnvironment, createGitHub: async () => github },);expect(paths).toEqual([`/advisories/${selected.ghsaId}`]);expect(imported).toEqual([selected]);@@ -86,7 +130,7 @@ test("explicit repository IDs allow private drafts without listing other advisor});const imported = await importGitHubAdvisories({ repository: "example/project", advisoryIds: [selected.ghsaId] },- { createGitHub: async () => github },+ { environment: enabledEnvironment, createGitHub: async () => github },);expect(imported[0]!.advisory).toEqual(draft);});@@ -96,7 +140,7 @@ test("global crawl and misleading exact-ID state filters fail before GitHub authawait expect(importGitHubAdvisories({ repository: "example/project", source: "global" },- { createGitHub },+ { environment: enabledEnvironment, createGitHub },),).rejects.toThrow("explicit GHSA IDs");await expect(@@ -106,7 +150,7 @@ test("global crawl and misleading exact-ID state filters fail before GitHub authadvisoryIds: [importedAdvisory().ghsaId],state: "draft",},- { createGitHub },+ { environment: enabledEnvironment, createGitHub },),).rejects.toThrow("only filters repository lists");expect(createGitHub).not.toHaveBeenCalled();@@ -125,7 +169,7 @@ test("a later advisory page failure returns no incomplete selection", async () =await expect(importGitHubAdvisories({ repository: "example/project" },- { createGitHub: async () => github },+ { environment: enabledEnvironment, createGitHub: async () => github },),).rejects.toThrow("rate limited");});@@ -147,6 +191,7 @@ test("GitHub advisory CLI exposes separate selection defaults and exact public I"json",],dependencies({+ environment: enabledEnvironment,importGitHubAdvisories: async (value) => {options = value;return [importedAdvisory("global")];@@ -165,7 +210,7 @@ test("GitHub advisory CLI exposes separate selection defaults and exact public Iexpect(await schema.run(["import", "github-advisories", "--schema", "--format", "json"],- dependencies(),+ dependencies({ environment: enabledEnvironment }),),).toBe(0);expect(JSON.parse(schema.text())).toMatchObject({@@ -185,6 +230,7 @@ test("advisory CLI cancellation removes handlers and preserves its exit code", amain,["import", "github-advisories", "example/project"],dependencies({+ environment: enabledEnvironment,signals,importGitHubAdvisories: async ({ signal }) => {signals.emit("SIGINT");@@ -225,6 +271,7 @@ for (const format of ["--full-output",],dependencies({+ environment: enabledEnvironment,signals,importGitHubAdvisories: async ({ signal }) => {if (failure === "error")diff --git a/sdk/typescript/tests-ts/github-findings.test.ts b/sdk/typescript/tests-ts/github-findings.test.tsindex 7901ed477..62d1fe566 100644--- a/sdk/typescript/tests-ts/github-findings.test.ts+++ b/sdk/typescript/tests-ts/github-findings.test.ts@@ -305,6 +305,7 @@ test("real GitHub readers and mappings preserve explicit ports in repository evi},});const dependency = {+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },createGitHub: async (selectedHost: string) => {expect(selectedHost).toBe(host);return github;diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex cae6ac713..1d9f35902 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -2973,6 +2973,7 @@ for await (const line of createInterface({ input: process.stdin })) {};const parentEnvironment = pluginExecutionEnvironment(process.execPath, {PATH: "",+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",...(process.env["SystemRoot"] === undefined? {}: { SystemRoot: process.env["SystemRoot"] }),@@ -2991,6 +2992,9 @@ for await (const line of createInterface({ input: process.stdin })) {expect(workerEnvironment["CODEX_CLI_PATH"]).toBe(resolveCodexCommand().command,);+ expect(workerEnvironment["CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS"]).toBe(+ "1",+ );expect(workerEnvironment["PYTHONUTF8"]).toBe("1");expect(workerEnvironment["CODEX_SECURITY_PYTHON_COMMAND"]).toBe(process.execPath,@@ -3010,6 +3014,25 @@ for await (const line of createInterface({ input: process.stdin })) {expect(nestedCodex.stdout).toMatch(/^codex-cli\s+\d/u);});+ test("forwards the external import setting to the plugin helper", () => {+ const flag = "CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS";+ const node = Bun.which("node")!;+ const environment: NodeJS.ProcessEnv = Object.assign(+ Object.create({ [flag]: "1" }),+ { CODEX_CLI_PATH: node, SystemRoot: process.env["SystemRoot"] },+ );+ const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");+ const run = () =>+ spawnSync(node, [helper, "list-external-findings", "--help"], {+ env: pluginExecutionEnvironment(node, environment),+ }).status;++ expect(run()).toBe(0);+ environment[flag] = undefined;+ environment["Codex_Security_Enable_External_Imports"] = "1";+ expect(run()).toBe(2);+ });+test("preserves an explicit Codex executable override for nested workers", () => {const configured = join(tmpdir(),diff --git a/sdk/typescript/tests-ts/wiz-findings.test.ts b/sdk/typescript/tests-ts/wiz-findings.test.tsindex 9ad9f1efc..73d2e8354 100644--- a/sdk/typescript/tests-ts/wiz-findings.test.ts+++ b/sdk/typescript/tests-ts/wiz-findings.test.ts@@ -489,6 +489,7 @@ async function cloudFixture(payload: unknown) {const f = await fixture(payload);const environment = {...process.env,+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",CODEX_HOME: join(f.root, "login"),CODEX_SECURITY_STATE_DIR: join(f.root, "state"),};@@ -1740,6 +1741,7 @@ test("Node resumes the same uncertain publication across locales and Unicode keyconst prepared = await prepareExternalPublication(${JSON.stringify(f.file)}, ${JSON.stringify(f.options)}, {environment: ${JSON.stringify({+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",CODEX_HOME: f.environment.CODEX_HOME,CODEX_SECURITY_STATE_DIR: f.environment.CODEX_SECURITY_STATE_DIR,})},