AI coding agents—Claude Code, Cursor, Codex, and Copilot—can now scaffold a full-stack feature, API route, Dockerfile, and GitHub Action in under a minute.
Every single line compiles. TypeScript is happy. ESLint passes with zero warnings.
And yet, after auditing dozens of AI-assisted TypeScript, Next.js, and Node.js repositories, the exact same 6 security bugs keep showing up in pull requests—not because models don't know syntax, but because they optimize for "boots quickly with zero local setup errors."
Here are the 6 silent traps to watch for, how to fix each one, and a free, zero-dependency CLI + 2 Open-Core Agent Skills (ai-code-audit-lite) I open-sourced so you can catch them automatically before merge.
1. Hardcoded Fallback Secrets (|| "dev-secret")
To make sure generated code doesn't crash on your laptop when .env is incomplete, LLMs love adding a fallback string:
// ❌ Vulnerable: if JWT_SECRET is missing in prod, anyone can forge tokens
const JWT_SECRET = process.env.JWT_SECRET || "dev-secret-do-not-use";
If a deployment pipeline drops or misnames JWT_SECRET in staging or production, your app silently boots using a string visible in your Git repository.
// ✅ Fix: fail closed at startup
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET || JWT_SECRET.length < 32) {
throw new Error("Missing or weak JWT_SECRET environment variable");
}
2. jwt.decode() Instead of jwt.verify()
When wiring quick auth middleware or extracting a userId from a Bearer token, coding agents occasionally reach for jwt.decode()—which parses Base64 JSON without checking the cryptographic signature:
// ❌ Vulnerable: accepts any self-signed or tampered JWT payload
export function getUserFromHeader(authHeader: string) {
const token = authHeader.replace("Bearer ", "");
return jwt.decode(token);
}
An attacker can take any JWT, change "role": "admin" or "sub": "victim-id", re-encode it in Base64, and walk straight in.
// ✅ Fix: verify signature, pin allowed algorithms, issuer & audience
export function getUserFromHeader(authHeader: string) {
const token = authHeader.replace(/^Bearer\s+/i, "");
return jwt.verify(token, JWT_PUBLIC_KEY, {
algorithms: ["RS256"],
issuer: "https://auth.example.com",
audience: "api.example.com",
});
}
3. NEXT_PUBLIC_ / VITE_ Prefixed Server Secrets
In Next.js and Vite apps, anything prefixed with NEXT_PUBLIC_ or VITE_ is inlined directly into client-side JavaScript bundles. When an AI agent hits an "env var is undefined in browser" error, its fastest "fix" is often adding NEXT_PUBLIC_ to the variable name:
// ❌ Vulnerable: shipped to every visitor's browser DevTools
export const config = {
supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY,
stripeSecret: process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY,
};
Exposing a Supabase service_role key completely bypasses Row-Level Security (RLS) across your entire database.
Fix: Keep private keys strictly server-side (Route Handlers, Server Actions, backend APIs) with no NEXT_PUBLIC_ / VITE_ prefix, and rotate any key that was ever bundled.
4. Permissive CORS + Credentials & Silent catch {} Blocks
Two classic "make the error go away" patches generated under time pressure:
// ❌ Vulnerable: lets any malicious origin send authenticated requests
app.use(cors({ origin: "*", credentials: true }));
// ❌ Vulnerable: silently swallows auth/webhook verification errors
try {
verifyWebhookSignature(req);
} catch (e) {}
// ✅ Fix: explicit origin allowlist + fail-closed error handling
const ALLOWED_ORIGINS = new Set(["https://app.example.com"]);
app.use(
cors({
origin: (origin, cb) =>
cb(null, !origin || ALLOWED_ORIGINS.has(origin)),
credentials: true,
})
);
Always return 401/403 (or rethrow) when verification throws—never swallow security exceptions in an empty catch.
5. Raw SQL & Shell Template Interpolation
ORMs like Prisma and Drizzle parameterize normal queries, which lulls teams into assuming SQL injection is extinct. Then an AI agent writes one complex reporting query or PDF helper:
// ❌ Vulnerable: SQL injection via $queryRawUnsafe
return prisma.$queryRawUnsafe(
`SELECT * FROM users WHERE email = '${email}'`
);
// ❌ Vulnerable: OS command injection via shell interpolation
exec(`wkhtmltopdf ${filename} out.pdf`);
// ✅ Fix: tagged-template parameterized SQL + shell-free execFile
return prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`;
// Validate filename strictly and pass args as an array (shell: false)
execFile("wkhtmltopdf", [safeFilename, "out.pdf"], { shell: false });
6. Dockerfile Secret Layers & GitHub Actions pull_request_target RCE
Security bugs don't stop in src/. AI-generated DevOps files routinely introduce two critical infrastructure flaws:
# ❌ Vulnerable: ARG values & COPY .env remain embedded in image layers
FROM node:22-alpine
ARG DATABASE_URL
COPY .env .env
And in .github/workflows/:
# ❌ Vulnerable: executes untrusted fork PR code with repo write secrets
on:
pull_request_target:
jobs:
triage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- run: echo "Auditing ${{ github.event.pull_request.title }}"
Fixes:
- Never bake secrets via
ARGorCOPY .env—add.env*to.dockerignore, inject secrets at runtime, or use BuildKit--mount=type=secret. - Use
on: pull_requestfor running PR code, and pass untrusted metadata (github.event.pull_request.title) through anenv:variable instead of interpolating${{ ... }}directly insiderun:.
Catch All of These in 100ms (npx ai-code-audit-lite)
To make pre-merge checks effortless, I open-sourced ai-code-audit-lite (Apache-2.0, zero npm dependencies, Node.js 20+).
Run a full scan or scan only your current git diff:
# Scan the whole repo
npx ai-code-audit-lite scan .
# Scan only changed files and fail CI on High/Critical findings
npx ai-code-audit-lite scan . --diff --fail-on high
# Output SARIF 2.1.0 for GitHub Code Scanning
npx ai-code-audit-lite scan . --sarif > ai-audit.sarif
Here's what it outputs on the intentionally vulnerable demo included in the repo:
ai-code-audit-lite — Fast Pre-Ship Security Scan
Target: .../examples/vulnerable-demo | Scanned: 4 file(s) | Rules: 18
[CRITICAL] ACA-017 (CWE-829) GitHub Actions pull_request_target Checkout (Pwn Request RCE)
Location : .github/workflows/pr-triage.yml:12
[CRITICAL] ACA-001 (CWE-798) Hardcoded Fallback Secret in Auth/Signing Expression
Location : api.ts:6
[CRITICAL] ACA-006 (CWE-347) JWT Decoded Without Signature Verification
Location : api.ts:14
[CRITICAL] ACA-009 (CWE-89) Unsafe Raw SQL Sink (Potential SQL Injection)
Location : api.ts:23
[CRITICAL] ACA-010 (CWE-78) OS Command Injection Sink (Shell Execution with Dynamic Input)
Location : api.ts:27
[CRITICAL] ACA-014 (CWE-798) Secret Baked into Dockerfile Image Layer (ARG / COPY .env)
Location : Dockerfile:2
Summary: 7 Critical | 6 High | 2 Medium | 0 Low
Bonus: 2 Free Open-Core Agent Skills for Claude Code, Cursor & Codex
Static rules catch fast single-line mistakes, while deeper issues (multi-tenant BOLA/IDOR, Supabase RLS policies, Next.js Server Actions, RAG/MCP boundaries) need an AI agent following a structured source-to-sink audit playbook.
You can install the 2 free Apache-2.0 Agent Skills (security-audit-orchestrator + ai-generated-code-audit) directly into your repo with one command:
npx ai-code-audit-lite init --target claude # or: cursor | codex | gemini | agents | all
GitHub repo (source, 18 built-in rules, GitHub Actions SARIF example & demo):
👉 https://github.com/aymenkani/ai-code-audit-lite
What sneaky AI-generated security bugs have you caught in PR reviews lately? Drop them in the comments—I'm actively adding the highest-signal patterns as new rules in ai-code-audit-lite.
Top comments (0)