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
fix(onboarding): improve policy onboarding for global installs (#1416)
Michael D'Angelo14c706bab403
diff --git a/README.md b/README.mdindex d95f8be41..1b7768e27 100644--- a/README.md+++ b/README.md@@ -34,17 +34,16 @@ which must be on your `PATH`. If `cs` already resolves to another tool, use`codex-security` instead. If npm stops with an `EEXIST` error for `cs`, use`npx @openai/codex-security` without a global installation.-From your repository directory, optionally draft security guidance before your-first scan:+From your repository, optionally [draft a `SECURITY.md`](#generate-securitymd)+that explains what counts as a security issue in your project:```bashcs policy .```-The command saves a draft outside the checkout. Review the proposed diff and-notes, edit the draft as needed, then copy it to the displayed `Policy target`-so future scans use it. Generating the draft alone does not install it.-Skip this step to keep an existing policy or scan without one.+The draft is saved outside your repository. Review the diff and notes, edit the+draft, then copy only `SECURITY.md` to the **Policy target** shown. Skip this step+to keep your current policy or scan without one.Run your scan from the repository directory:@@ -121,16 +120,29 @@ validation, severity classification, owner suggestions, and result handling.## Generate SECURITY.md-Draft security guidance for a repository or one of its components:+Use `policy` to draft a new `SECURITY.md` or update an existing one. Use `--path`+to select a component:```bashcs policy .cs policy . --path services/api --knowledge-base architecture.md```-The command saves a draft outside the checkout. Review it before installing it-as guidance for future scans. See the [policy guide](sdk/typescript/docs/cli.md#generate-a-security-policy)-for supporting documents and SDK usage.+The command saves its draft outside the repository and leaves existing files+unchanged. Review the diff and notes, edit the draft, then copy only `SECURITY.md`+to the displayed **Policy target**. Keep the saved architecture and threat-model+documents outside the repository.++Scans already use root and component `SECURITY.md` files. Keep your current policy+if it needs no changes. When updating it, preserve its vulnerability-reporting+instructions. If the command says the policy is already up to date, no copy is+needed.++Files at `.github/SECURITY.md` or `docs/SECURITY.md` often contain reporting+instructions. Preserve them when drafting a policy; those locations do not+automatically provide repository-wide scan guidance. See the+[policy guide](sdk/typescript/docs/cli.md#generate-a-security-policy) for policy+locations, unanswered questions, saved artifacts, and SDK usage.## Save and export threat modelsdiff --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 8de208a01..5136feb1c 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@@ -1885,6 +1885,12 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].permissionProfile,},);+ assert.equal(+ workerLaunch.args.some((arg) =>+ arg.startsWith("permissions.codex_security_policy"),+ ),+ false,+ );assert.equal(workerLaunch.environment!.CODEX_SECURITY_KNOWLEDGE_BASE,workerConfigurations[index].knowledgePath,diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex ff23f23b3..7196c9f52 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -400,17 +400,16 @@ After [installing the CLI](#install-the-cli), sign in if needed:cs login```-From your repository directory, optionally draft security guidance before scanning:+From your repository, optionally [draft a `SECURITY.md`](#generate-a-security-policy)+that explains what counts as a security issue in your project:```bashcs policy .```-The command saves a draft outside the checkout. Review the proposed diff and-notes, edit the draft as needed, then copy it to the displayed `Policy target`-so future scans use it. Generating the draft alone does not install it.-Skip this step to keep an existing policy or scan without one. See-[Generate a security policy](#generate-a-security-policy) for details.+The draft is saved outside your repository. Review the diff and notes, edit the+draft, then copy only `SECURITY.md` to the **Policy target** shown. Skip this step+to keep your current policy or scan without one.Then scan the repository:@@ -435,16 +434,20 @@ scans, custom validation, imports, patching, and integrations.### Generate a security policy-To draft guidance for a selected path:+Use `policy` to draft a new `SECURITY.md` or update an existing one. To select a+component:```bashcs policy . --path services/api```-The SDK provides `generatePolicy()`,-`preflightPolicy()`, and `previewPolicy()`. See+Existing files stay unchanged until you review and copy the draft to the+**Policy target** shown. Scans already use root and component policies; you can+keep them without generating new ones.++The SDK provides `generatePolicy()`, `preflightPolicy()`, and `previewPolicy()`. See[policy generation](docs/cli.md#generate-a-security-policy) for SDK examples,-headless use, artifacts, and review requirements.+policy locations and reporting instructions, headless use, and saved artifacts.### Exports and CIdiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex f24b614ab..c11e715fd 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -165,55 +165,78 @@ reasoning-summary configuration.## Generate a security policy-`policy` drafts `SECURITY.md` guidance for later scans. Review the draft before-copying it into the checkout; the command saves it outside the repository.+Use `policy` to draft or update `SECURITY.md` before a scan. The policy describes+the project's security boundaries and what should count as a finding. This step+is optional: you can scan with an existing policy or without one.++From the repository root, run:```bashcodex-security policy .+```++The command saves a draft outside the repository and leaves existing files+unchanged. In a terminal, it asks about facts the source cannot establish and+shows the proposed diff.++1. Read the saved `SECURITY.md`, diff, and **Review notes**. Edit the draft as+ needed. Preserve reporting instructions and confirm exclusions, accepted+ risks, and severity decisions with the project owner.+2. If you choose to use the draft, copy only the reviewed `SECURITY.md` to the+ displayed **Policy target**. Keep the supporting documents outside the+ repository.+3. Run `codex-security scan .`. The scan reads the policy from the repository.++If you reject the draft, skip the copy and scan with your existing policy or+without one. If the command reports that `SECURITY.md` is already up to date, no+copy is needed; review any notes and continue to the scan.++You can leave answers blank during generation. Keep unresolved decisions+explicit in any policy you adopt, or scan without adopting the draft while you+resolve them. Regenerate if relevant source or neighboring policies changed+during generation.++### Existing policies and components++If your existing root or component `SECURITY.md` already describes the relevant+security boundaries, scan with it directly. To propose an update, use `policy .`+for the root policy or select a component:++```bashcodex-security policy . --path services/api-codex-security policy . --knowledge-base architecture.md --model gpt-5.6-terra --effort high-codex-security policy . --dry-run --json```-The repository defaults to the current directory. `--path` selects a component,-which inherits policies from its Git root, with the closest policy taking-precedence. Targets and links stay within the checkout and outside Git metadata.-Inherited policies may refer to ancestor `SECURITY.md` files or the checkout's-`.github/SECURITY.md` and `docs/SECURITY.md`; they cannot widen a component's scope.-Linked worktrees and initialized submodules use their own roots. For a separate-Git directory, set `core.worktree` to the checkout's absolute path; use-`git worktree repair` for moved linked worktrees.+This drafts `services/api/SECURITY.md`, whether or not that file already exists.+The repository defaults to the current directory. A component inherits policies+from its Git root, with the closest policy taking precedence. Inherited policies+may refer to ancestor `SECURITY.md` files or the checkout's `.github/SECURITY.md`+and `docs/SECURITY.md`; they cannot widen the component's scope.-Generation describes the system, builds a threat model, then drafts the policy.-In a terminal it asks about facts the source cannot establish and previews the-diff. `--headless` skips questions; unanswered questions remain in review notes.-The command uses scan authentication and read-only access to the selected source.-It denies Git metadata and sibling-component access, disables network, web, apps,-and MCP, and uses only Codex's core shell environment. Knowledge-base text stays-in private review artifacts during generation and is removed afterward.+A `.github/SECURITY.md` or `docs/SECURITY.md` often describes how to report+vulnerabilities. Keep those instructions: these files do not automatically+provide repository-wide scan guidance. Use a root `SECURITY.md` for that guidance,+or a component `SECURITY.md` for guidance specific to that directory. Before+replacing the policy target, check whether either reporting file links to it;+the replacement can affect their guidance too.-| Invocation | Result |-| ---------------------------- | --------------------------------------------------------- |-| `policy .` | Generate documents, ask questions, and preview the draft. |-| `policy . --headless --json` | Generate without prompts; return paths and review notes. |-| `policy . --format md` | Generate and write the draft to stdout. |-| `policy . --dry-run --json` | Check local inputs without calling Codex. |+### Generation options and saved files-Generation currently fails on Unix directories with non-UTF-8 names. On macOS,-the bundled runtime does not fully enforce write restrictions under `/tmp`-(including `/private/tmp`); keep source and artifacts elsewhere when read-only-enforcement is required. See the-[upstream sandbox issue](https://github.com/openai/codex/issues/32395).+Generation describes the system, builds a threat model, then drafts the policy.+Add context with `--knowledge-base`:-### Review the draft+```bash+codex-security policy . --knowledge-base architecture.md+```-Preserve reporting instructions and obtain owner approval for exclusions,-accepted risks, and severity decisions. Check linked `.github/SECURITY.md` and-`docs/SECURITY.md` files: installing the draft can affect their guidance too.-Regenerate if relevant source or neighboring policies changed during generation.+| Invocation | Result |+| ---------------------------- | -------------------------------------------------------- |+| `policy . --headless --json` | Generate without prompts; return paths and review notes. |+| `policy . --format md` | Generate and write the draft to stdout. |+| `policy . --dry-run --json` | Check local inputs without calling Codex. |-Use an empty output directory outside every enclosing checkout and its Git-metadata, or keep the default location in the Codex Security state directory:+`--headless` leaves unanswered questions in the review notes. By default, files+go in the Codex Security state directory. To choose a location, use an empty+directory outside every enclosing checkout and its Git metadata:```bashcodex-security policy . --path services/api --headless \@@ -237,6 +260,24 @@ completed-draft manifest is written. A preview failure reports saved paths.with `ok: false`. If a stage cannot inspect required evidence, generation stopsand keeps completed documents. Fix the problem and retry in a new directory.+### Source access and restrictions++The command uses scan authentication and read-only access to the selected source.+It denies Git metadata and sibling-component access, disables network, web, apps,+and MCP, and uses only Codex's core shell environment. Knowledge-base text stays+in private review artifacts during generation and is removed afterward.++Targets and links stay within the checkout and outside Git metadata. Linked+worktrees and initialized submodules use their own roots. For a separate Git+directory, set `core.worktree` to the checkout's absolute path; use+`git worktree repair` for moved linked worktrees.++Generation currently fails on Unix directories with non-UTF-8 names. On macOS,+the bundled runtime does not fully enforce write restrictions under `/tmp`+(including `/private/tmp`); keep source and artifacts elsewhere when read-only+enforcement is required. See the+[upstream sandbox issue](https://github.com/openai/codex/issues/32395).+### Generate a policy from TypeScript```tsdiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 801006670..ab1365b8e 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -196,6 +196,7 @@ import {codexSecurityCredentialHome,codexSecurityHasStoredFileCredentials,codexSecurityStateDirectory,+ codexExecutableReadPaths,createIsolatedHome,executablePathForSpawn,expandHome,@@ -1029,6 +1030,10 @@ export class CodexSecurity {runtime.plugin.pluginRoot,...(knowledgeBase === null ? [] : [knowledgeBase.path]),].filter((path, index, roots) => roots.indexOf(path) === index);+ const policyFilesystem = policyFilesystemPermissions(+ inputs.gitMetadataPaths,+ await codexExecutableReadPaths(this.#codexCommand().command),+ );const { codex } = await this.#createSessionCodex(session,"policy",@@ -1044,12 +1049,10 @@ export class CodexSecurity {options.auth,undefined,policyCodexConfig(session.sessionConfig),- inputs.gitMetadataPaths.length === 0- ? []- : [- // CLI override keys split on dots, so keep paths inside the TOML value.- `permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystemPermissions(inputs.gitMetadataPaths))}`,- ],+ [+ // CLI override keys split on dots, so keep paths inside the TOML value.+ `permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystem)}`,+ ],);const reportCost = (current: Readonly<ScanCost>): void => {const total = addScanCosts(accumulatedCost, current);@@ -4734,10 +4737,13 @@ export function scanRuntimeCodexConfig(function policyFilesystemPermissions(gitMetadataPaths: readonly string[] = [],+ codexPaths: readonly string[] = [],): JsonObject {return {":minimal": "read",":workspace_roots": "read",+ // Linux's sandbox re-executes Codex, including installations outside /usr.+ ...Object.fromEntries(codexPaths.map((path) => [path, { ".": "read" }])),// A scoped "." keeps native permission paths literal, including glob characters....Object.fromEntries(gitMetadataPaths.map((path) => [path, { ".": "deny" }]),diff --git a/sdk/typescript/src/cli-help.ts b/sdk/typescript/src/cli-help.tsindex 4a59a4777..e8fd7424d 100644--- a/sdk/typescript/src/cli-help.ts+++ b/sdk/typescript/src/cli-help.ts@@ -268,30 +268,33 @@ export function formatCliHelp(text: string, columns = 80): string {);if (command === "") {sections.push(- "Get started:\n" +- " codex-security login\n\n" ++ [+ "Get started:",+ " codex-security login",+ "",wrap(- "In your repository, optionally draft SECURITY.md:",+ "In your repository, draft SECURITY.md (optional):",width," "," ",- ) +- "\n codex-security policy .\n" ++ ),+ " codex-security policy .",wrap(- "Review and edit the draft, then copy it to the displayed Policy target.",+ "Review the diff and notes. Edit the draft, then copy only SECURITY.md to the Policy target shown.",width," "," ",- ) +- "\n" ++ ),wrap(- "Skip this step to keep an existing policy or scan without one.",+ "Skip this step to keep your existing policy or scan without one.",width," "," ",- ) +- "\n\n codex-security scan .\n" ++ ),+ "",+ " codex-security scan ."," codex-security findings",+ ].join("\n"),);} else if (examples) {sections.push(examples);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex f03cf43d1..c730def12 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -3336,7 +3336,7 @@ export async function main(},}).command("policy", {- description: "Draft SECURITY.md guidance for review.",+ description: "Draft SECURITY.md for review.",destructive: true,mcp: false,args: z.object({@@ -3367,11 +3367,11 @@ export async function main(headless: z.boolean().default(false)- .describe("Skip owner questions and authentication prompts."),+ .describe("Skip questions and sign-in prompts."),dryRun: z.boolean().default(false)- .describe("Validate local generation inputs without starting Codex."),+ .describe("Check inputs without generating a policy."),auth: SKILL_AUTH_OPTION,...MODEL_OPTIONS.shape,provider: PROVIDER_OPTION.describe(@@ -3387,7 +3387,9 @@ export async function main({ args: { repository: "." }, options: { path: "services/api" } },],hint:- "Save a draft for review:\n" ++ "Review the diff and notes. Edit the draft, then copy only SECURITY.md to the Policy target shown.\n" ++ "Your existing policy stays unchanged until you replace it.\n\n" ++ "Save a draft without answering questions:\n" +" codex-security policy . --headless --output-dir /path/outside/repository/policy --json",output: z.union([z.record(z.string(), z.unknown()), z.string()])diff --git a/sdk/typescript/src/codex-sdk-environment.ts b/sdk/typescript/src/codex-sdk-environment.tsindex a1436d411..38a59508e 100644--- a/sdk/typescript/src/codex-sdk-environment.ts+++ b/sdk/typescript/src/codex-sdk-environment.ts@@ -43,13 +43,20 @@ export function resolveBundledCodexExecutable(const platform = process.platform === "android" ? "linux" : process.platform;const packageName = `@openai/codex-${platform}-${process.arch}`;let packageJson: string;+ let legacyVendor = false;try {- codexPackageJson ??= createRequire(import.meta.url).resolve(- "@openai/codex/package.json",- );- packageJson = createRequire(codexPackageJson).resolve(- `${packageName}/package.json`,- );+ const selectedPackageJson =+ codexPackageJson ??+ createRequire(import.meta.url).resolve("@openai/codex/package.json");+ try {+ packageJson = createRequire(selectedPackageJson).resolve(+ `${packageName}/package.json`,+ );+ } catch (error) {+ if (codexPackageJson === undefined) throw error;+ packageJson = selectedPackageJson;+ legacyVendor = true;+ }} catch (error) {throw new PluginBootstrapError(`The bundled Codex executable could not be resolved from ${packageName}. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,@@ -57,15 +64,17 @@ export function resolveBundledCodexExecutable();}const vendor = join(dirname(packageJson), "vendor");- const target = readdirSync(vendor, { withFileTypes: true }).find((entry) =>- entry.isDirectory(),- );- const command = join(- vendor,- target?.name ?? "",- "bin",- process.platform === "win32" ? "codex.exe" : "codex",+ const architecture = process.arch === "arm64" ? "aarch64" : "x86_64";+ const legacyTarget = `${architecture}-${platform === "darwin" ? "apple-darwin" : platform === "win32" ? "pc-windows-msvc" : "unknown-linux-musl"}`;+ const target = readdirSync(vendor, { withFileTypes: true }).find(+ (entry) =>+ entry.isDirectory() && (!legacyVendor || entry.name === legacyTarget),);+ const targetRoot = join(vendor, target?.name ?? "");+ const binaryName = process.platform === "win32" ? "codex.exe" : "codex";+ let command = join(targetRoot, "bin", binaryName);+ if (codexPackageJson !== undefined && !existsSync(command))+ command = join(targetRoot, "codex", binaryName);if (target === undefined || !existsSync(command)) {throw new PluginBootstrapError(`The ${packageName} package does not contain the Codex executable. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 8c4395c0a..475e63d06 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -2699,6 +2699,34 @@ export function resolveCodexCommand(return { command: resolveBundledCodexExecutable() };}+export async function codexExecutableReadPaths(+ command: string,+): Promise<string[]> {+ const executable = await realpath(command);+ const packageJson = resolve(dirname(executable), "..", "package.json");+ try {+ const metadata = JSON.parse(await readFile(packageJson, "utf8"));+ if (+ metadata?.name !== "@openai/codex" ||+ typeof metadata.bin?.codex !== "string"+ )+ return [executable];+ const launcher = await realpath(+ resolve(dirname(packageJson), metadata.bin.codex),+ );+ if (launcher !== executable) return [executable];+ } catch {+ // A custom executable need not belong to a readable, valid npm package.+ return [executable];+ }++ // npm's entrypoint launches a native binary, which Linux re-executes in the sandbox.+ return [+ executable,+ await realpath(resolveBundledCodexExecutable(packageJson)),+ ];+}+export function executablePathForSpawn(command: string): string {if (process.platform !== "win32" || !win32.isAbsolute(command))return command;diff --git a/sdk/typescript/src/security-policy-cli.ts b/sdk/typescript/src/security-policy-cli.tsindex 26e1ae751..457dccbb0 100644--- a/sdk/typescript/src/security-policy-cli.ts+++ b/sdk/typescript/src/security-policy-cli.ts@@ -45,8 +45,8 @@ export interface PolicyCommandDependencies {}const STAGES: Record<SecurityPolicyStage, string> = {- architecture: "[1/3] Understanding the system and its security boundaries",- threat_model: "[2/3] Building the source-backed threat model",+ architecture: "[1/3] Reading the source",+ threat_model: "[2/3] Writing the threat model",policy: "[3/3] Drafting SECURITY.md",};@@ -122,7 +122,7 @@ export async function runPolicyCommand(signal: AbortSignal,) => {write(- "A few details could change this policy. Leave an answer blank to keep it unresolved.",+ "Answer what you know; leave other answers blank for later review.",);const answers: string[] = [];for (const question of questions) {@@ -162,7 +162,7 @@ export async function runPolicyCommand(...(draft.reviewNotes.length === 0? []: [- "\nOwner review:",+ "\nReview notes:",...draft.reviewNotes.map((note) => `- ${display(note)}`),]),].join("\n");@@ -177,7 +177,7 @@ export async function runPolicyCommand(write(`Threat model: ${display(draft.threatModelPath)}`);if (changed)write(- "No repository files changed. Review the saved SECURITY.md before copying it into the repository.",+ "No repository files changed. Review the draft, then copy only SECURITY.md to the Policy target shown.",);}const seconds = Math.max(0, (dependencies.now() - started) / 1000);diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.tsindex 829c8fdbe..a4b695a3a 100644--- a/sdk/typescript/tests-ts/api-policy.test.ts+++ b/sdk/typescript/tests-ts/api-policy.test.ts@@ -4,6 +4,7 @@ import {mkdir,readFile,readdir,+ realpath,rm,symlink,writeFile,@@ -18,6 +19,7 @@ import type {import Ajv, { type AnySchema } from "ajv";import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";import { parse as parseToml } from "smol-toml";+import { scanRuntimeCodexConfig } from "../src/api.js";import {InvalidTargetError,OutputDirectoryNotEmptyError,@@ -56,12 +58,14 @@ async function setup(secureOutput?: (path: string) => Promise<void>;surface?: "cli" | "sdk";config?: Record<string, unknown>;+ environment?: NodeJS.ProcessEnv;} = {},) {const f = await fixture();const codexHome = join(f.root, "codex-home");await mkdir(codexHome);const runtime = preparedRuntime(codexHome);+ Object.assign(runtime.environment, options.environment);const createCodex = mock((_config: CodexOptions) => {return {startThread: (threadOptions: ThreadOptions) => {@@ -92,7 +96,10 @@ async function setup(const security = new InternalSecurity(options.config ?? {},{- environment: { CODEX_SECURITY_STATE_DIR: join(f.root, "state") },+ environment: {+ CODEX_SECURITY_STATE_DIR: join(f.root, "state"),+ ...options.environment,+ },prepareRuntime: async () => {options.onPrepare?.();return runtime;@@ -152,6 +159,147 @@ async function* events(}describe("CodexSecurity policy API", () => {+ test.each([+ "bundled",+ "symlink",+ "custom-malformed-metadata",+ "custom-null-metadata",+ "custom-missing-bin",+ "custom-directory-metadata",+ ...(process.platform === "win32"+ ? []+ : [+ "npm",+ "npm-vendor",+ "npm-linked",+ "npm-vendor-linked",+ "npm-legacy",+ "npm-vendor-legacy",+ ]),+ ])(+ "grants only the selected runtime files to policy turns (%s)",+ async (installation) => {+ const executable = await realpath(+ runtime.resolveCodexCommand({}).command,+ );+ const runtimeFixture = await fixture();+ let selected = join(+ runtimeFixture.root,+ process.platform === "win32" ? "codex.exe" : "codex",+ );+ let readPaths = [executable];+ if (installation === "symlink")+ await symlink(executable, selected, "file");+ if (installation.startsWith("custom")) {+ const packageRoot = join(runtimeFixture.root, "custom");+ selected = join(+ packageRoot,+ "bin",+ process.platform === "win32" ? "codex.exe" : "codex",+ );+ await mkdir(dirname(selected), { recursive: true });+ await writeFile(selected, "synthetic native executable\n");+ const packageJson = join(packageRoot, "package.json");+ if (installation === "custom-directory-metadata")+ await mkdir(packageJson);+ else+ await writeFile(+ packageJson,+ installation === "custom-malformed-metadata"+ ? "{"+ : installation === "custom-null-metadata"+ ? "null"+ : JSON.stringify({ name: "@openai/codex" }),+ );+ readPaths = [await realpath(selected)];+ }+ if (installation.startsWith("npm")) {+ const modules = join(runtimeFixture.root, "node_modules", "@openai");+ const packageRoot = installation.endsWith("-linked")+ ? join(runtimeFixture.root, "linked-codex")+ : join(modules, "codex");+ selected = join(packageRoot, "bin", "codex.js");+ await mkdir(dirname(selected), { recursive: true });+ await writeFile(selected, "#!/usr/bin/env node\n");+ await writeFile(+ join(packageRoot, "package.json"),+ JSON.stringify({+ name: "@openai/codex",+ bin: { codex: "bin/codex.js" },+ }),+ );+ const platformPackage = `codex-${process.platform}-${process.arch}`;+ const nativeRoot = installation.startsWith("npm-vendor")+ ? packageRoot+ : join(+ installation.endsWith("-linked")+ ? join(packageRoot, "node_modules", "@openai")+ : modules,+ platformPackage,+ );+ const architecture = process.arch === "arm64" ? "aarch64" : "x86_64";+ const target = `${architecture}-${process.platform === "darwin" ? "apple-darwin" : "unknown-linux-musl"}`;+ const native = join(+ nativeRoot,+ "vendor",+ target,+ installation.endsWith("-legacy") ? "codex" : "bin",+ "codex",+ );+ await mkdir(dirname(native), { recursive: true });+ await writeFile(native, "synthetic native executable\n");+ if (installation.startsWith("npm-vendor"))+ await mkdir(join(nativeRoot, "vendor", "a-different-platform"));+ if (!installation.startsWith("npm-vendor"))+ await writeFile(+ join(nativeRoot, "package.json"),+ JSON.stringify({ name: `@openai/${platformPackage}` }),+ );+ readPaths = [await realpath(selected), await realpath(native)];+ }+ const f = await setup({+ ...(installation !== "bundled"+ ? { environment: { CODEX_CLI_PATH: selected } }+ : {}),+ });+ const sharedConfigPath = join(f.runtime.codexHome, "config.toml");+ await writeCodexConfig(sharedConfigPath, scanRuntimeCodexConfig({}));+ const sharedConfig = await readFile(sharedConfigPath, "utf8");++ await f.security.generatePolicy(f.repository, { outputDir: f.outputDir });++ const overrides = f.configuration()!.configOverrides!;+ expect(overrides).toHaveLength(1);+ expect(parseToml(overrides[0]!)).toEqual({+ permissions: {+ codex_security_policy: {+ filesystem: {+ ":minimal": "read",+ ":workspace_roots": "read",+ ...Object.fromEntries(+ readPaths.map((path) => [path, { ".": "read" }]),+ ),+ },+ },+ },+ });+ expect(f.threads).toHaveLength(3);+ for (const thread of f.threads) {+ for (const path of readPaths)+ expect(thread.additionalDirectories).not.toContain(dirname(path));+ expect(thread.additionalDirectories).not.toContain(f.runtime.codexHome);+ expect(thread.approvalPolicy).toBe("never");+ expect(thread.networkAccessEnabled).toBe(false);+ }+ if (installation !== "bundled")+ expect(f.configuration()!.codexPathOverride).toBe(+ runtime.executablePathForSpawn(selected),+ );+ expect(await readFile(sharedConfigPath, "utf8")).toBe(sharedConfig);+ await f.security.close();+ },+ );+test("requires private output before starting a policy turn", async () => {const onOutputDirReady = mock();const secured = mock(async (_path: string) => {diff --git a/sdk/typescript/tests-ts/cli-help.test.ts b/sdk/typescript/tests-ts/cli-help.test.tsindex cd909bbf7..f867afd82 100644--- a/sdk/typescript/tests-ts/cli-help.test.ts+++ b/sdk/typescript/tests-ts/cli-help.test.ts@@ -67,6 +67,9 @@ describe("CLI help", () => {for (const command of ["login", "policy .", "scan .", "findings"]) {expect(text).toContain(` codex-security ${command}`);}+ expect(text.indexOf("codex-security policy .")).toBeLessThan(+ text.indexOf("codex-security scan ."),+ );expect(text).toContain("<command> --help");});diff --git a/sdk/typescript/tests-ts/cli-policy.test.ts b/sdk/typescript/tests-ts/cli-policy.test.tsindex b606680f4..a99c9da2c 100644--- a/sdk/typescript/tests-ts/cli-policy.test.ts+++ b/sdk/typescript/tests-ts/cli-policy.test.ts@@ -497,7 +497,7 @@ describe("policy CLI", () => {expect(input).toHaveBeenCalledTimes(1);expect(stderr.text()).toContain("--- /dev/null");expect(stderr.text()).toContain("+Requests must be authorized");- expect(stderr.text()).toContain("Owner review:");+ expect(stderr.text()).toContain("Review notes:");expect(stderr.text()).toContain("No repository files changed");expect(await readFile(join(f.outputDir, "SECURITY.md"), "utf8")).toBe(POLICY,