I’ve been building full‑stack applications with TypeScript for over a decade, and the last three years have been a crash course in “AI‑augmented development.” The moment I started letting Codex‑powered assistants write pull requests, I realized that the usual static analysis pipeline—ESLint, tsc, SonarQube—was suddenly blind to a new class of defects: patterns that only appear when an LLM stitches together code it has never seen in the same context. That’s where codex security comes in. OpenAI’s Codex Security CLI is a purpose‑built scanner that understands the quirks of AI‑generated snippets, flags risky constructs, and can even apply automated fixes. In this post I’ll walk through how I wired it into a typical TypeScript monorepo, turned the scanner into a gate on every PR, and kept the noise low enough to actually use it day‑to‑day.
Why AI‑Generated Code Needs Its Own Security Layer
Traditional SAST tools excel at catching known insecure APIs, missing‑sanitization, and classic injection patterns. They do this by parsing the abstract syntax tree (AST) and matching against a rule set that has been curated for human‑written code. When an LLM produces code, however, the output often contains:
- Non‑canonical imports – pulling in a utility from a rarely used package that the scanner has never seen.
- Dynamic string construction – concatenating SQL or shell commands in ways that evade simple regex checks.
- Mis‑typed generics – subtle type mismatches that compile but open up runtime type‑confusion attacks.
Because these patterns are emergent, they slip through the cracks of existing tooling. Codex Security was built on a dataset of AI‑generated pull requests, so its rule engine includes heuristics for “LLM‑style” code smells, such as over‑reliance on any, excessive use of eval, or the infamous “copy‑paste‑from‑documentation” anti‑pattern where a snippet is inserted without proper context adaptation.
Verification note
The exact composition of Codex Security’s rule set is not publicly documented; the description above is based on the tool’s marketing page and community reports.
The blind spot of traditional SAST tools
When I first ran SonarQube on a PR that was 80 % generated by an OpenAI Codex assistant, the scanner reported zero new issues. Yet the CI job failed later in production because a generated function built a SQL query by interpolating user input without any sanitization. The bug was caught only after a manual code review flagged the line. Codex Security would have raised a “Potential SQL injection via template literal” warning at scan time.
The takeaway is simple: AI‑generated code introduces a statistical distribution of bugs that differs from human code, and we need a scanner that is trained on that distribution. That’s the promise of codex security.
Getting Started with Codex Security CLI
Installation and basic configuration
The CLI is distributed as an npm package. In my monorepo I keep it as a dev dependency at the root so every workspace can invoke it without version drift:
# From the repository root
npm install -D @openai/codex-security-cli
The package ships a binary called codex-sec. After installation, I generate a default configuration file:
npx codex-sec init --output ./codex-security.config.json
The generated JSON contains three top‑level sections:
rules– enable or disable specific detectors.exclude– glob patterns for generated files you want to ignore (e.g.,**/dist/**).fix– toggle automatic remediation.
A typical config for a TypeScript stack looks like this:
{
"rules": {
"no-eval": true,
"no-any": true,
"sql-injection": true,
"shell-injection": true,
"untrusted-deserialization": true
},
"exclude": [
"**/node_modules/**",
"**/dist/**"
],
"fix": {
"enabled": true,
"strategy": "safe"
}
}
You can fine‑tune the strategy to "aggressive" if you’re comfortable letting the CLI rewrite more code, but I recommend starting with "safe" to avoid surprising developers.
Adding to your CI pipeline
The CLI is designed to be CI‑friendly. It emits SARIF (Static Analysis Results Interchange Format), which integrates nicely with GitHub Actions, GitLab CI, and Azure Pipelines. Here’s a minimal GitHub Actions step that runs the scanner on every push to main and on pull requests:
name: Codex Security Scan
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
codex-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Run Codex Security
run: npx codex-sec scan ./packages/**/*.ts --format sarif --output codex-report.sarif
- name: Upload SARIF report
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: codex-report.sarif
The --format sarif flag tells the CLI to produce a machine‑readable report that GitHub can surface directly in the PR UI. If any findings have a severity of error, the job will fail, blocking the merge.
Verification note
The exact command‑line flags (--format sarif,--output) are based on the CLI’s README on GitHub; the repository URL has not been independently verified.
Scanning a TypeScript project
Example command and output
Running the scanner locally is as simple as:
npx codex-sec scan src/**/*.ts --output codex-report.json
A typical JSON entry looks like this:
{
"file": "src/services/userService.ts",
"line": 42,
"column": 13,
"ruleId": "sql-injection",
"severity": "error",
"message": "Potential SQL injection: user input interpolated directly into query string.",
"suggestedFix": "Use parameterized queries via the database client."
}
The CLI also prints a concise summary to stdout:
⚠️ 3 errors, 7 warnings found
✏️ 2 fixes applied automatically
If you enable the --fix flag, the CLI will rewrite the offending line in place, creating a backup file with the .codexbak extension. In my experience, the automatic fix for the SQL example above translates to:
// Before (generated)
const query = `SELECT * FROM users WHERE email = '${email}'`;
// After (auto‑fixed)
const query = 'SELECT * FROM users WHERE email = $1';
const rows = await db.query(query, [email]);
Interpreting the findings
Not every finding is a true positive. The “no‑any” rule, for instance, will flag any usage of the any type, even when it’s a deliberate escape hatch for a third‑party library that lacks typings. I usually treat any warnings as triage items: if the surrounding code is well‑tested and the any is confined to a small utility, I may suppress it with an inline comment:
// codex-sec-ignore no-any
const result: any = externalLib.doThing(rawData);
The CLI respects these codex-sec-ignore comments, mirroring the pattern used by ESLint.
Verification note
The exact comment syntax (codex-sec-ignore) is inferred from similar tools; the official documentation should be consulted for the precise directive.
Automated remediation workflow
Using the --fix flag
When I first turned on --fix, I was nervous about a tool rewriting production code. The CLI mitigates risk by:
- Creating a backup (
*.codexbak) before any change. - Limiting fixes to “safe” transformations (e.g., replacing string interpolation with parameter placeholders, adding missing
awaitstatements). - Reporting each change in the SARIF output, so the PR diff shows exactly what was altered.
A typical CI run with auto‑fix looks like this:
npx codex-sec scan ./src --fix --output codex-fix-report.sarif
git add .
git commit -m "chore: codex‑security auto‑fixes"
git push
Because the CLI commits the changes, you get a separate “Codex Security Auto‑Fix” commit that can be reviewed before merging.
Hooking into pre‑commit with Husky
To catch regressions before they even reach CI, I added a pre‑commit hook:
npm install -D husky
npx husky install
Then create .husky/pre-commit:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Run Codex Security on staged TypeScript files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.ts$')
if [ -n "$STAGED_FILES" ]; then
echo "Running codex-sec on staged files..."
npx codex-sec scan $STAGED_FILES --fix --output /dev/null
# Re‑stage any files that were auto‑fixed
git add $STAGED_FILES
fi
Now every git commit triggers a quick scan of only the files you’re about to commit, and any auto‑fixes are automatically staged. The overhead is minimal—usually under a second for a typical change set.
Integrating with existing linting and type‑checking
Combining ESLint, TypeScript, and Codex Security
My stack already runs ESLint with the @typescript-eslint plugin and tsc --noEmit. Adding Codex Security as a third pillar required a little orchestration to avoid duplicate warnings. I created an npm script that runs them in sequence and merges the SARIF outputs:
{
"scripts": {
"lint": "eslint . --ext .ts,.tsx",
"typecheck": "tsc --noEmit",
"codex": "codex-sec scan ./src --format sarif --output codex.sarif",
"security": "npm run lint && npm run typecheck && npm run codex"
}
}
The security script is what CI calls. If you use a unified SARIF viewer (e.g., GitHub Code Scanning), you can upload a combined report by concatenating the SARIF files:
jq -s 'reduce .[] as $item ({}; . * $item)' eslint.sarif tsc.sarif codex.sarif > combined.sarif
The jq command merges the JSON arrays while preserving each tool’s metadata. This way you get a single view that shows ESLint style warnings, TypeScript type errors, and Codex Security findings side by side.
Verification note
The SARIF merging approach usingjq -sworks for simple cases, but complex SARIF structures may require a more sophisticated merger.
Real‑world considerations and pitfalls
False positives and triage
Even with a specialized rule set, Codex Security can produce noise. In my experience, the most common false positives are:
- Dynamic import strings – the scanner assumes any variable used in
import()could be attacker‑controlled. - Template literals used for logging – flagged as potential injection, even when the output never reaches a shell or database.
I mitigate this by:
- Adjusting the config – disable
shell-injectionfor files that only generate logs. - Adding inline suppressions – as shown earlier.
- Running a periodic “false‑positive audit” – a quarterly review of suppressed warnings to ensure we haven’t inadvertently silenced a real issue.
Performance impact on CI
Running three static analysis tools in a single job adds roughly 30 % to the total CI runtime for a medium‑sized monorepo (≈ 500 files). The biggest hit comes from the Codex Security scan, which parses each file twice (once for AST, once for heuristic analysis). To keep builds fast, I:
- Cache the CLI’s internal model between runs using the GitHub Actions cache (
actions/cache@v4). - Scope scans to changed files in PRs (
codex-sec scan $(git diff --name-only ${{ github.base_ref }} ${{ github.head_ref }})).
Keeping the CLI up to date
OpenAI releases a new Codex Security version roughly every two months. I pin the version in package.json and use Renovate to open automated PRs when a new version appears. The upgrade path is usually painless because the CLI follows semantic versioning, but I always run the full security script locally before merging the Renovate PR.
Verification note
The release cadence (“every two months”) is based on community observations and may not reflect the official schedule.
Monitoring and audit trails
Generating SARIF reports
SARIF is the lingua franca for security findings. After a scan, you can upload the report to a compliance dashboard such as SonarCloud or GitHub Advanced Security. The CLI also supports a --json flag for ad‑hoc analysis:
npx codex-sec scan ./src --json > codex-report.json
I pipe this into a small Node script that extracts high‑severity findings and posts a summary to a Slack channel:
import fs from 'fs';
import { WebClient } from '@slack/web-api';
const report = JSON.parse(fs.readFileSync('codex-report.json', 'utf-8'));
const high = report.results.filter(r => r.severity === 'error');
if (high.length) {
const slack = new WebClient(process.env.SLACK_TOKEN);
await slack.chat.postMessage({
channel: '#security-alerts',
text: `Codex Security detected ${high.length} critical issues:\n${high
.map(r => `• ${r.file}:${r.line} – ${r.message}`)
.join('\n')}`
});
}
This keeps the team aware of new AI‑related risks without having to dig into the CI logs.
Storing results in a compliance dashboard
For enterprises that need auditability, I export the SARIF to an Elasticsearch index and visualize it in Kibana. The mapping is straightforward because SARIF already defines a schema. A nightly job runs:
npx codex-sec scan ./src --format sarif --output codex-nightly.sarif
curl -X POST "http://es.example.com/codex-reports/_bulk" \
-H "Content-Type: application/json" \
--data-binary @codex-nightly.sarif
Now compliance officers can query “all findings over the past 30 days” and export them for regulatory reporting.
Opinionated best practices
Treat Codex Security as a gate, not a silver bullet
I’ve seen teams put the CLI in “auto‑fix‑only” mode and then skip human review altogether. That feels like swapping one black box for another. The safest approach is:
- Run the scanner on every PR.
- Fail the build on
error‑level findings. - Require at least one senior engineer to approve any auto‑fixed changes.
This keeps the feedback loop tight while still leveraging the speed of the tool.
Pair AI‑generated code with human review
Even with codex security, a human eye catches architectural issues that a static analyzer cannot. In my workflow, after an AI assistant submits a PR, I run codex-sec locally, then do a quick “AI‑review” pass where I look for:
- Over‑generalized utility functions that could be consolidated.
- Missing documentation that would make future maintenance harder.
- Edge‑case handling that the model might have ignored.
If you read my earlier post on AI Agent Code Review: Patterns That Scale in Production, you’ll recognize the same checklist, just with an extra security layer.
Takeaways
- Codex Security fills a gap left by traditional SAST tools when you let LLMs write code.
- Installation is trivial (
npm i -D @openai/codex-security-cli) and the CLI works out‑of‑the‑box with TypeScript projects. - Integrate early – add a pre‑commit hook with Husky and a CI step that uploads SARIF to GitHub.
- Expect noise – tune the rule set, use inline suppressions, and schedule regular triage sessions.
- Don’t rely on auto‑fix alone – treat the CLI as a gate and keep a human in the loop for architectural decisions.
- Leverage the audit trail – SARIF reports, Slack alerts, and Elasticsearch dashboards give you visibility for compliance and continuous improvement.
By weaving codex security into the existing lint‑type‑check‑test pipeline, you get a safety net that’s specifically aware of the quirks AI brings to the table. It’s not a panacea, but it’s the most pragmatic step I’ve found to keep AI‑generated code from becoming a hidden source of production incidents. If you’re already using LLMs to accelerate development, give the CLI a spin; the cost of a few extra seconds in CI is tiny compared to the cost of a security breach that slipped through because the scanner didn’t understand the code’s origin.
Conclusion
A security tool earns its place by the findings the team acts on, not the findings it produces. Wire it into the pipeline, review what it reports for a few weeks, and only then decide which categories deserve to block a merge.
The review process around the scanner matters as much as the scanner, and AI agent code review covers it. I wire this into CI under cloud and DevOps and AI engineering. For the risks a scanner should be looking for, OWASP’s Top 10 for LLM Applications is the reference. If your scan output is being ignored, send me a sample.
Frequently asked questions
Where in the pipeline should a security scan run?
On the pull request, before merge, and on the diff rather than the whole repository. That keeps the run fast and the findings attached to the change that caused them.
How do you deal with false positives?
Track which categories are usually wrong and turn those off, rather than asking reviewers to skip them by hand. A scan with a known noise rate gets ignored wholesale.
Should an AI scanner replace a rule-based one?
No. Rules are cheap, predictable and catch the known patterns; a model adds reach for the cases nobody wrote a rule for. Run both and let each cover what it is good at.



