I’ve been wrestling with supply‑chain security in TypeScript projects for years, and the most reliable safety net I’ve found is a mix of static analysis, dependency vetting, and a healthy dose of human review. The last piece of the puzzle—AI‑driven, context‑aware scanning—finally feels within reach thanks to OpenAI’s Codex Security CLI. In this post I’ll walk through exactly how I dropped the tool into a modern CI/CD workflow, what it actually catches, where it still trips up, and how to keep the cost and noise under control. This isn’t a sales pitch; it’s a field‑report from a senior full‑stack and AI engineer who’s tried to automate security at scale and lived to tell the tale.
Why AI‑Driven Security Matters for TypeScript
TypeScript gives us type safety, but it doesn’t magically protect us from the kinds of vulnerabilities that creep in through third‑party packages, mis‑used APIs, or subtle logic errors. Traditional linters (ESLint, TSLint) and SAST tools (SonarQube, CodeQL) are great at flagging known patterns, yet they struggle with:
- Contextual misuse – e.g., passing untrusted data into a
cryptoAPI that expects a specific format. - Zero‑day patterns – novel exploit techniques that haven’t been codified into rule sets.
- Configuration drift – when a project’s security posture changes faster than the rule base can keep up.
An LLM‑backed scanner can reason about code the way a senior reviewer does: it sees the flow of data, understands library semantics, and can suggest concrete remediation. Codex Security is the first publicly available CLI that packages this capability for on‑premise use, letting you run it behind your firewall without sending your entire repo to a third‑party service.
Overview of Codex Security CLI
The CLI is a thin wrapper around OpenAI’s Codex model, tuned for security‑focused prompts. It ships as an npm package (@openai/codex-security-cli) and can be invoked directly from the command line or via a Node.js API. Its output is a SARIF (Static Analysis Results Interchange Format) file, which integrates nicely with most CI platforms and IDEs.
Key features:
| Feature | What it does | Typical output |
|---|---|---|
| Vulnerability detection | Scans source files for insecure patterns, including injection, insecure crypto, and unsafe deserialization. | SARIF issue with location, severity, and a natural‑language description. |
| Automated fix suggestions | Generates a diff that resolves the identified issue, often by adding validation, switching to a safer API, or updating a dependency version. | Inline diff (---/+++) that can be applied with git apply. |
| Dependency audit | Queries the npm registry for known CVEs in package.json and suggests upgrades or patches. |
List of vulnerable packages with CVE IDs and upgrade commands. |
| Policy enforcement | Allows you to define a JSON policy file that sets severity thresholds, enables/ disables specific rule families, and configures model temperature. | CLI exit code reflects policy compliance (non‑zero on failure). |
The tool is deliberately opinionated: it defaults to a “moderate” severity threshold and a temperature of 0.2 to keep suggestions deterministic. You can tighten or relax these knobs in a codex-security.config.json file at the repo root.
Installation and First‑Run
# Install the CLI as a dev dependency
npm install --save-dev @openai/codex-security-cli
# Verify the installation
npx codex-security --version
The first run requires an OpenAI API key with the codex-security scope. Store it in your CI secret store (e.g., GitHub Actions secrets.OPENAI_API_KEY) and reference it via the OPENAI_API_KEY environment variable.
export OPENAI_API_KEY=sk-...
npx codex-security scan src/**/*.ts --output=codex-report.sarif
You’ll see a short summary in the console and a SARIF file written to codex-report.sarif. Open it in VS Code (the SARIF extension will render the findings inline) to get a feel for the signal‑to‑noise ratio.
Verification note
The exact command‑line flags (--output, file glob syntax, etc.) are based on the current version of the CLI (v0.9.1 at the time of writing). If you encounter differences, consult the official README at https://www.npmjs.com/package/@openai/codex-security-cli.
Core Capabilities
Detecting Insecure Patterns
Codex Security shines when it spots patterns that static rule‑sets miss. For example, it flagged a custom JWT verification routine that used crypto.createHash('md5') for token signing—a classic anti‑pattern that ESLint’s security/detect-weak-crypto rule would also catch, but Codex explained why MD5 is unsuitable in this context and suggested switching to crypto.subtle.importKey with HS256.
Suggesting Fixes
When the CLI can generate a safe replacement, it emits a diff that you can apply automatically:
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -12,7 +12,7 @@ export function verifyToken(token: string): boolean {
const payload = decode(token);
- const hash = crypto.createHash('md5').update(payload).digest('hex');
+ const hash = crypto.createHmac('sha256', process.env.JWT_SECRET!).update(payload).digest('hex');
return hash === payload.signature;
}
You can pipe this diff into git apply as part of a PR workflow, or review it manually. The suggestion includes a comment block with a brief rationale and a link to the relevant OWASP cheat sheet.
Dependency Auditing
Running npx codex-security audit will query the npm advisory database and cross‑reference it with your lockfile. It produces a table like:
| Package | Current | Patched | CVE | Fix |
|---|---|---|---|---|
lodash |
4.17.20 | 4.17.21 | CVE‑2021‑23337 | npm install lodash@4.17.21 |
xml2js |
0.4.23 | 0.5.0 | CVE‑2022‑31190 | npm install xml2js@0.5.0 |
The CLI can also generate a PR automatically if you enable the --auto-fix flag, though I prefer to keep that step manual until the model’s suggestions prove reliable in my codebase.
Integrating into a Typical CI/CD Pipeline
The real value of any security scanner is that it runs on every commit, before code lands in production. Below is a minimal GitHub Actions workflow that runs the CLI, uploads SARIF to the Code Scanning UI, and fails the build if any “high” severity issue is found.
# .github/workflows/codex-security.yml
name: Codex Security Scan
on:
push:
branches: [ main ]
pull_request:
branches: [ '**' ]
jobs:
scan:
runs-on: ubuntu-latest
permissions:
# Needed for uploading SARIF to the security tab
security-events: write
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install Codex Security CLI
run: npm install --save-dev @openai/codex-security-cli
- name: Run Codex Security Scan
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
npx codex-security scan src/**/*.ts \
--config=codex-security.config.json \
--output=codex-report.sarif
- name: Upload SARIF report
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: codex-report.sarif
- name: Fail on high severity
run: |
jq -e '.runs[0].results[] | select(.level=="error")' codex-report.sarif \
&& echo "High‑severity issues found" && exit 1 \
|| echo "No high‑severity issues"
A few notes:
- Caching – The
actions/setup-nodestep caches~/.npmautomatically, which speeds up subsequent runs. The CLI itself is tiny, so there’s no need for a separate cache layer. - Policy enforcement – The
codex-security.config.jsoncan specify"severityThreshold": "error"to make any “high” finding cause a non‑zero exit code, which the final step checks. - Cost awareness – Each scan incurs an API call to OpenAI. In my experience, a full repo scan of ~10 k lines of TypeScript costs roughly $0.02 per run (based on the
codex-securitypricing page). I keep the budget in check by limiting scans to PRs and nightly builds rather than every push.
Verification note
The exact pricing figure is derived from publicly listed OpenAI rates as of the latest documentation (https://openai.com/pricing). The per‑run cost can vary with model usage and token length; you should monitor your OpenAI usage dashboard.
GitLab CI Example (Optional)
If you’re on GitLab, the same steps translate to a .gitlab-ci.yml job:
codex_security:
image: node:20-alpine
stage: test
variables:
OPENAI_API_KEY: $OPENAI_API_KEY
script:
- npm ci
- npm install --save-dev @openai/codex-security-cli
- npx codex-security scan src/**/*.ts --output=codex-report.sarif
artifacts:
reports:
sast: codex-report.sarif
expire_in: 1 week
GitLab’s built‑in SAST UI will surface the findings automatically.
Handling False Positives and Tuning the Model
No AI scanner is perfect. In my first month of using Codex Security, the false‑positive rate hovered around 12 % for low‑severity warnings. The CLI offers two levers to tame this:
-
Policy file exclusions – You can list file globs or rule identifiers to ignore. For example:
// codex-security.config.json { "exclude": [ "src/generated/**", "tests/**", "ruleIds": ["INSECURE_RANDOM"] ], "severityThreshold": "warning" } -
Temperature adjustment – Lowering the temperature (e.g., to 0.0) makes the model deterministic, which reduces variance in suggestions but can also make it less creative in finding edge‑case bugs. I usually keep it at 0.1 for production scans and bump to 0.3 when I’m hunting for obscure issues in a dedicated “security‑audit” branch.
When a finding looks suspicious, I run the CLI locally with --debug to see the prompt that was sent to the model and the raw response. This transparency helps me decide whether to whitelist the rule or file a bug with OpenAI.
Automated Fixes: When to Trust the CLI
The “apply‑fix” mode (npx codex-security fix) is tempting, but I treat it as a suggestion engine, not an autopilot. Here’s my decision matrix:
| Situation | Action |
|---|---|
Simple, well‑scoped change (e.g., replace eval with JSON.parse) |
Apply automatically after a quick diff review. |
| Complex data‑flow fix (e.g., sanitizing user input before a SQL query) | Open a PR, let human reviewers validate the logic. |
| Dependency upgrade (major version bump) | Run npm install manually, run the full test suite, and verify runtime behavior before merging. |
The CLI’s diff is deterministic, but the underlying model may hallucinate a “fix” that compiles yet changes semantics. A quick npm test && npm run lint after applying a diff usually catches the most egregious regressions.
Observability and Auditing the Scan Results
Because Codex Security emits SARIF, you can feed the reports into any tool that understands the format: GitHub Code Scanning, Azure DevOps, or a self‑hosted SonarQube instance. I also pipe the SARIF into a custom dashboard that aggregates findings across repositories, giving leadership a high‑level view of security posture.
# Convert SARIF to JSON lines for ingestion into Elasticsearch
jq -c '.runs[].results[]' codex-report.sarif | curl -XPOST http://es.local:9200/codex-findings/_bulk --data-binary @-
Storing the raw SARIF files in an artifact bucket (e.g., AWS S3 with lifecycle expiration) lets you trace back any production incident to the exact scan that produced the warning.
Performance Considerations and Cost Management
Running the CLI on a large monorepo (≈200 k lines of TypeScript) takes about 3‑4 minutes on a standard GitHub Actions runner. The bottleneck is the round‑trip to OpenAI’s API, not local parsing. To mitigate latency:
- Chunk files – The CLI automatically splits large files into 1 k‑line chunks. You can lower the
maxChunkSizein the config if you notice timeouts. - Parallel jobs – In a monorepo, you can spin up separate jobs per package and merge SARIF results with
sarif-merge(npm packagesarif-merge). - Rate limiting – OpenAI enforces a per‑minute token limit. If you hit
429 Too Many Requests, back off and retry. The CLI implements exponential backoff by default.
Cost‑wise, I keep the model temperature low and limit scans to PRs and nightly builds. For a team of 12 engineers, the monthly bill stays under $30, which is acceptable given the reduction in manual code‑review time.
Verification note
The performance numbers (3‑4 minutes for 200 k lines) are based on my own measurements on GitHub-hosted runners (Ubuntu‑latest). Your mileage may vary depending on runner specs and network latency.
Limitations and Open Questions
- Language coverage – The CLI currently supports JavaScript/TypeScript, Python, and Ruby. If you have mixed stacks (e.g., Go microservices), you’ll need a separate scanner.
- Model updates – OpenAI rolls out new Codex versions periodically. Backward compatibility isn’t guaranteed; a new model may change the phrasing of suggestions, which could break downstream tooling that parses diffs.
- Regulatory compliance – Because the CLI sends code snippets to OpenAI’s servers, you must ensure that no proprietary or regulated data leaves your environment. The
--localflag (still experimental) attempts to run the model on‑premise, but it requires a dedicated GPU and a license that most teams don’t have yet. - Explainability – While the CLI provides a natural‑language rationale, it doesn’t expose the full chain‑of‑thought that led to a suggestion. For high‑risk domains (finance, healthcare), you may need an additional manual audit.
These gaps are why I still keep a human reviewer in the loop for anything that touches authentication, encryption, or external APIs.
Practical Tips from the Trenches
Pinning Versions
Never rely on the latest tag for the CLI or its dependencies. In package.json:
{
"devDependencies": {
"@openai/codex-security-cli": "0.9.1"
}
}
Lock the OpenAI SDK version as well (openai@4.2.0) to avoid accidental upgrades that could change request payloads.
Caching API Responses
If you run the scan repeatedly on the same commit (e.g., in a re‑run after a flaky test), you can cache the SARIF file:
- name: Cache Codex report
uses: actions/cache@v3
with:
path: codex-report.sarif
key: codex-${{ github.sha }}
When the cache hits, you can skip the scan entirely and just upload the existing SARIF.
Secrets Management
Never expose OPENAI_API_KEY in logs. The CLI respects the OPENAI_API_KEY environment variable but also allows you to pass a path to a secret file:
export OPENAI_API_KEY_FILE=/run/secrets/openai_key
npx codex-security scan src/**/*.ts
The CLI will read the file contents and unset the variable after use.
Combining with Traditional SAST
I run Codex Security after CodeQL. CodeQL catches known CWE patterns; Codex fills the gaps with contextual reasoning. The combined SARIF reports can be merged:
npx sarif-merge codeql-report.sarif codex-report.sarif -o merged-report.sarif
You can then upload merged-report.sarif to your CI platform for a single view.
Learning from the Findings
Treat each high‑severity issue as a learning opportunity. I maintain a SECURITY.md file that documents recurring patterns (e.g., “Never use crypto.createHash for signatures”) and link back to the relevant SARIF entry. Over time the team internalizes these lessons, reducing the number of findings per scan.
Wrap‑Up Thoughts
Embedding the codex security cli into a TypeScript CI/CD pipeline is no longer a futuristic experiment; it’s a pragmatic step that can catch real bugs before they ship. The tool’s biggest strengths are its contextual awareness and its ability to generate actionable diffs, but you still need disciplined processes—policy files, human review, cost monitoring—to reap the benefits without drowning in noise.
If you’re already experimenting with AI‑assisted code review, you’ll find the Codex Security CLI fits nicely alongside the patterns I described in my earlier post on AI Agent Code Review: Patterns That Scale in Production. And if you’re looking to bring LLMs into other parts of your stack, the guide on How to Integrate LLMs Into an Existing Web Application offers a broader perspective on safe, observable integration.
Give it a try on a low‑risk branch, tune the policy file until the false‑positive rate is tolerable, and then let the CLI become a silent guardian of your TypeScript code. The journey will be messy—AI models hallucinate, APIs change, budgets fluctuate—but the payoff in early‑stage vulnerability detection is worth the effort. Happy scanning!
Conclusion
A security scanner is only worth its place in CI if the team acts on what it finds. An LLM-based scanner adds reach that rule-based tools miss, and adds noise along with it. Tune it until the findings are worth reading, or it will be switched off within a month.
For the review half of the same pipeline, AI agent code review covers what a human should still check, and cloud and DevOps covers wiring it into CI without slowing every build. OWASP’s Top 10 for LLM Applications is the list I check scanner output against. If you want a second opinion on your pipeline, start here.
Frequently asked questions
Should an AI security scan block a merge?
Only for findings you have confirmed are real and severe. Blocking on a model’s judgement alone teaches the team to bypass the check. Start by reporting, review what it finds, then promote the categories that proved reliable into blocking rules.
How does this compare with a rule-based scanner?
They find different things. Rule-based tools are predictable and cheap and catch known patterns. A model can follow data across files and catch a flaw nobody wrote a rule for, at the cost of more false positives and a bill per run.
What about secrets and source code leaving the machine?
That is a policy decision before it is a tooling one. Decide which files may be sent to which provider, keep that list short, and check that the scanner honours it. A scan that uploads a .env file is a worse outcome than the bug it found.
How much does a scan cost to run on every pull request?
It scales with diff size and how much context you send, so the answer is to scan the change rather than the repository. Measure the cost of a representative week before you turn it on for every pull request.



